Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during server cleanup. .env files, node_modules, builds, logs and media were excluded.
This commit is contained in:
+10
-10
@@ -1,6 +1,6 @@
|
||||
"""Approval workflow for the company forms that carry an Area Manager signature.
|
||||
"""Approval workflow for the company forms that carry an Area Business Manager signature.
|
||||
|
||||
draft --request(MR)--> pending --approve(AM)--> approved
|
||||
draft --request(MR)--> pending --approve(ABM)--> approved
|
||||
pending / approved --any change to the rows--> draft (a signature never covers edited data)
|
||||
|
||||
Every MR has their own copy of each form, so approval is per (form, MR). The request goes to the Area
|
||||
@@ -24,13 +24,13 @@ APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart", "expense_sta
|
||||
|
||||
|
||||
async def owners_in_scope(db: AsyncSession, user: User) -> list[User]:
|
||||
"""The MRs whose forms this user may see: themselves, their headquarters' MRs, or (admin, GM) all."""
|
||||
"""The MRs whose forms this user may see: themselves, their headquarters' MRs, or (admin, AGM) all."""
|
||||
stmt = select(User).where(User.role.in_(FIELD_ROLES), User.is_active.is_(True)).order_by(User.full_name)
|
||||
if user.role in FIELD_ROLES:
|
||||
stmt = stmt.where(User.id == user.id)
|
||||
elif user.role == Role.AM:
|
||||
elif user.role == Role.ABM:
|
||||
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
|
||||
elif user.role not in (Role.ADMIN, Role.GM):
|
||||
elif user.role not in (Role.ADMIN, Role.AGM):
|
||||
return []
|
||||
return list((await db.execute(stmt)).scalars())
|
||||
|
||||
@@ -49,7 +49,7 @@ async def assert_owner_in_scope(db: AsyncSession, user: User, owner_id: uuid.UUI
|
||||
for owner in await owners_in_scope(db, user):
|
||||
if owner.id == owner_id:
|
||||
return owner
|
||||
if user.role in (Role.ADMIN, Role.GM) or (await db.get(User, owner_id)) is None:
|
||||
if user.role in (Role.ADMIN, Role.AGM) or (await db.get(User, owner_id)) is None:
|
||||
raise NotFoundError("Medical representative not found", {"id": str(owner_id)})
|
||||
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
|
||||
|
||||
@@ -70,7 +70,7 @@ async def _get_or_create(db: AsyncSession, table_name: str, owner_id: uuid.UUID)
|
||||
async def list_approvals(db: AsyncSession, user: User) -> list[tuple[FormApproval, User, str | None]]:
|
||||
"""(approval, MR, headquarters name) for what `user` can see.
|
||||
|
||||
An MR always gets all three forms ("draft" until they act); an Area Manager or admin only
|
||||
An MR always gets all three forms ("draft" until they act); an Area Business Manager or admin only
|
||||
gets forms that have been sent, since a draft is nothing for them to act on.
|
||||
"""
|
||||
owners = {o.id: o for o in await owners_in_scope(db, user)}
|
||||
@@ -99,10 +99,10 @@ async def _row_count(db: AsyncSession, table_name: str, owner_id: uuid.UUID) ->
|
||||
|
||||
async def request_approval(db: AsyncSession, table_name: str, actor: User) -> FormApproval:
|
||||
if await assigned_area_manager(db, actor) is None:
|
||||
raise ValidationError("No Area Manager is assigned to your headquarters yet. Ask the administrator to assign one.")
|
||||
raise ValidationError("No Area Business Manager is assigned to your headquarters yet. Ask the administrator to assign one.")
|
||||
row = await _get_or_create(db, table_name, actor.id)
|
||||
if row.status == "pending":
|
||||
return row # already with the Area Manager — a second click changes nothing
|
||||
return row # already with the Area Business Manager — a second click changes nothing
|
||||
if row.status == "approved":
|
||||
raise ConflictError("This form is already approved. Change a row to send it again.")
|
||||
if await _row_count(db, table_name, actor.id) == 0:
|
||||
@@ -115,7 +115,7 @@ async def request_approval(db: AsyncSession, table_name: str, actor: User) -> Fo
|
||||
|
||||
|
||||
async def approve(db: AsyncSession, table_name: str, owner_id: uuid.UUID, actor: User) -> FormApproval:
|
||||
await assert_owner_in_scope(db, actor, owner_id) # only the Area Manager assigned to this MR's headquarters
|
||||
await assert_owner_in_scope(db, actor, owner_id) # only the Area Business Manager assigned to this MR's headquarters
|
||||
row = await _get_or_create(db, table_name, owner_id)
|
||||
if row.status == "approved":
|
||||
return row # a double click
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Approval state of the company forms that carry an Area Manager signature."""
|
||||
"""Approval state of the company forms that carry an Area Business Manager signature."""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
@@ -9,7 +9,7 @@ from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database.base import Base
|
||||
|
||||
#: draft = not sent yet, pending = the MR asked for approval, approved = the Area Manager signed.
|
||||
#: draft = not sent yet, pending = the MR asked for approval, approved = the Area Business Manager signed.
|
||||
FORM_APPROVAL_STATUSES = ("draft", "pending", "approved")
|
||||
|
||||
|
||||
|
||||
+58
-23
@@ -24,7 +24,7 @@ SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
|
||||
IDENTITY_COLUMNS = {"name", "employee_name", "headquarter"}
|
||||
APPROVAL_TABLES = approvals.APPROVAL_TABLES
|
||||
HIDDEN_TABLES = {"daily_call_report_csv"}
|
||||
#: Forms where every row belongs to one MR (and is approved by that MR's Area Manager).
|
||||
#: Forms where every row belongs to one MR (and is approved by that MR's Area Business Manager).
|
||||
OWNED_TABLES = APPROVAL_TABLES
|
||||
|
||||
|
||||
@@ -60,6 +60,10 @@ async def _reject_repeat(
|
||||
raise ConflictError("An identical row already exists in this form")
|
||||
|
||||
|
||||
#: Forms where the same row may legitimately be added again (e.g. a place visited repeatedly).
|
||||
REPEATABLE_ROW_TABLES = {"standard_tour_plan"}
|
||||
|
||||
|
||||
#: Tables whose printed Sl. No. starts over at 1 for each month rather than running on
|
||||
#: forever — a shared master list (e.g. Sales Projection's product list) refilled every
|
||||
#: month, not one MR's own running form.
|
||||
@@ -173,6 +177,35 @@ async def _apply_sales_projection_product(
|
||||
return values
|
||||
|
||||
|
||||
#: Sales and Stock Statement products spelt differently from the Sales Projection list (compared as _pts_key).
|
||||
_STOCK_PRODUCT_ALIASES = {"AMOCLODAXCV625": "AMOCLADOXCV625", "BONTRASTRONG": "BONETRASTRONG", "BONTRAMAX+": "BONETRAMAX+"}
|
||||
|
||||
|
||||
def _pts_key(name: object) -> str:
|
||||
"""A product name compared without case, spaces or hyphens ("Penorenz-MR-4" = "PENORENZ-MR 4")."""
|
||||
key = re.sub(r"[^A-Z0-9+]", "", str(name or "").upper())
|
||||
return _STOCK_PRODUCT_ALIASES.get(key, key)
|
||||
|
||||
|
||||
async def _with_product_pts(
|
||||
table_name: str, rows: list[dict[str, object]], db: AsyncSession
|
||||
) -> list[dict[str, object]]:
|
||||
"""Sales and Stock Statement: VALUE IN PTS shows the product's PTS from the Sales Projection list."""
|
||||
if table_name != "sales_and_stock_statement" or not rows:
|
||||
return rows
|
||||
result = await db.execute(
|
||||
text('SELECT product_name, pts FROM "sales_projection" WHERE COALESCE(btrim(pts), \'\') <> \'\' ORDER BY source_row_number')
|
||||
)
|
||||
prices: dict[str, str] = {}
|
||||
for product_name, pts in result.all():
|
||||
prices.setdefault(_pts_key(product_name), str(pts).strip())
|
||||
for row in rows:
|
||||
pts = prices.get(_pts_key(row.get("product_name")))
|
||||
if pts is not None:
|
||||
row["value_in_pts"] = pts
|
||||
return rows
|
||||
|
||||
|
||||
#: Expense Statement: the TOTAL column is always fare + daily allowance + postage + other expenses.
|
||||
EXPENSE_AMOUNTS = ("fare", "da_hq", "da_ex", "da_out", "postage", "other_expense")
|
||||
|
||||
@@ -201,7 +234,7 @@ async def _owner_condition(
|
||||
table_name: str, current_user: User, db: AsyncSession, owner_id: uuid.UUID | None
|
||||
) -> tuple[list[str], dict[str, object]]:
|
||||
"""Limit an approval form's rows to the MRs this user may see: an MR sees only their own,
|
||||
an Area Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
|
||||
an Area Business Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
|
||||
if table_name not in OWNED_TABLES:
|
||||
return [], {}
|
||||
if current_user.role in FIELD_ROLES:
|
||||
@@ -211,7 +244,7 @@ async def _owner_condition(
|
||||
if owner_id is not None:
|
||||
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||
return ["owner_user_id = :owner"], {"owner": owner_id}
|
||||
if current_user.role == Role.AM:
|
||||
if current_user.role == Role.ABM:
|
||||
return ["owner_user_id = ANY(:owners)"], {"owners": [o.id for o in await approvals.owners_in_scope(db, current_user)]}
|
||||
return [], {}
|
||||
|
||||
@@ -231,7 +264,7 @@ async def _row_owner(table_name: str, row_id: uuid.UUID, current_user: User, db:
|
||||
return owner_id
|
||||
if current_user.role in FIELD_ROLES and owner_id != current_user.id:
|
||||
raise ForbiddenError("This row belongs to another medical representative")
|
||||
if current_user.role == Role.AM:
|
||||
if current_user.role == Role.ABM:
|
||||
if owner_id is None:
|
||||
raise ForbiddenError("This row is outside your headquarters")
|
||||
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||
@@ -343,7 +376,7 @@ async def _load_per_mr_rows(
|
||||
if who in people:
|
||||
item["name"], item["headquarter"] = people[who][0], people[who][1] or ""
|
||||
out.append(item)
|
||||
return await _present_rows_for_user(out, current_user, db)
|
||||
return await _with_product_pts(table_name, await _present_rows_for_user(out, current_user, db), db)
|
||||
|
||||
|
||||
def _month_of_every_product(rows: list[dict[str, object]], month: str, columns: Iterable[str]) -> list[dict[str, object]]:
|
||||
@@ -369,7 +402,7 @@ def _month_of_every_product(rows: list[dict[str, object]], month: str, columns:
|
||||
|
||||
def _available_csv_tables(current_user: User) -> list[str]:
|
||||
visible = [name for name in FORM_ORDER if name not in HIDDEN_TABLES]
|
||||
if current_user.role == Role.AM:
|
||||
if current_user.role == Role.ABM:
|
||||
return [name for name in visible if name in APPROVAL_TABLES]
|
||||
return visible
|
||||
|
||||
@@ -377,12 +410,12 @@ def _available_csv_tables(current_user: User) -> list[str]:
|
||||
def _ensure_table_access(table_name: str, current_user: User) -> None:
|
||||
if table_name in HIDDEN_TABLES:
|
||||
raise ForbiddenError("This CSV form is not available for export.", {"table": table_name})
|
||||
if current_user.role == Role.AM and table_name not in APPROVAL_TABLES:
|
||||
raise ForbiddenError("Area Manager can only access approval forms.", {"table": table_name})
|
||||
if current_user.role == Role.ABM and table_name not in APPROVAL_TABLES:
|
||||
raise ForbiddenError("Area Business Manager can only access approval forms.", {"table": table_name})
|
||||
|
||||
|
||||
@router.get("/tables")
|
||||
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM))) -> list[dict[str, object]]:
|
||||
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM))) -> list[dict[str, object]]:
|
||||
return [{"name": name, "label": CSV_LABELS[name], "columns": list(TABLES[name])} for name in _available_csv_tables(current_user)]
|
||||
|
||||
|
||||
@@ -427,16 +460,16 @@ def _approval_table(table_name: str) -> str:
|
||||
@router.get("/approvals")
|
||||
async def list_form_approvals(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
|
||||
) -> list[dict[str, object]]:
|
||||
"""Approval state of the forms that carry an Area Manager signature, limited to the MRs this user may see."""
|
||||
"""Approval state of the forms that carry an Area Business Manager signature, limited to the MRs this user may see."""
|
||||
return [_approval_out(r, owner, hq) for r, owner, hq in await approvals.list_approvals(db, current_user)]
|
||||
|
||||
|
||||
@router.get("/owners")
|
||||
async def list_form_owners(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
|
||||
) -> list[dict[str, object]]:
|
||||
"""The medical representatives whose forms this user may open."""
|
||||
hq = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
|
||||
@@ -452,7 +485,7 @@ async def request_form_approval(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.MR)),
|
||||
) -> dict[str, object]:
|
||||
"""The MR sends a form to the Area Manager."""
|
||||
"""The MR sends a form to the Area Business Manager."""
|
||||
row = await approvals.request_approval(db, _approval_table(table_name), current_user)
|
||||
return _approval_out(row, current_user, await _hq_name(db, current_user))
|
||||
|
||||
@@ -462,9 +495,9 @@ async def approve_form(
|
||||
table_name: str,
|
||||
owner_id: uuid.UUID = Query(description="The MR whose form is being approved"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.AM)),
|
||||
current_user: User = Depends(require_role(Role.ABM)),
|
||||
) -> dict[str, object]:
|
||||
"""The Area Manager signs an MR's form — only the one who manages that MR's headquarters."""
|
||||
"""The Area Business Manager signs an MR's form — only the one who manages that MR's headquarters."""
|
||||
row = await approvals.approve(db, _approval_table(table_name), owner_id, current_user)
|
||||
owner = await db.get(User, owner_id)
|
||||
return _approval_out(row, owner, await _hq_name(db, owner))
|
||||
@@ -475,7 +508,7 @@ async def list_csv_rows(
|
||||
table_name: str,
|
||||
owner_id: uuid.UUID | None = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
|
||||
) -> list[dict[str, object]]:
|
||||
_ensure_table_access(table_name, current_user)
|
||||
return await _load_rows(table_name, db, current_user, owner_id)
|
||||
@@ -508,7 +541,9 @@ async def create_csv_row(
|
||||
values = _apply_expense_total(values)
|
||||
if not _has_user_data(table_name, values):
|
||||
raise ValidationError("Add at least one value before creating a row")
|
||||
await _reject_repeat(table_name, values, db, owner.id if owner else None)
|
||||
# An MR may list the same place in the Standard Tour Plan more than once.
|
||||
if table_name not in REPEATABLE_ROW_TABLES:
|
||||
await _reject_repeat(table_name, values, db, owner.id if owner else None)
|
||||
next_row = (await db.execute(text(f'SELECT COALESCE(MAX(source_row_number), 0) + 1 FROM "{table_name}"'))).scalar_one()
|
||||
for column in columns:
|
||||
if column in SERIAL_COLUMNS:
|
||||
@@ -524,7 +559,7 @@ async def create_csv_row(
|
||||
await _renumber_rows(table_name, db)
|
||||
await approvals.invalidate(db, table_name, owner.id if owner else None)
|
||||
await db.commit()
|
||||
return await _get_row(table_name, row_id, db)
|
||||
return (await _with_product_pts(table_name, [await _get_row(table_name, row_id, db)], db))[0]
|
||||
|
||||
|
||||
async def _stored_owner(table_name: str, row_id: uuid.UUID, db: AsyncSession) -> uuid.UUID | None:
|
||||
@@ -562,7 +597,7 @@ async def _start_own_row(
|
||||
)
|
||||
await _renumber_rows(table_name, db)
|
||||
await db.commit()
|
||||
return await _get_row(table_name, row_id, db)
|
||||
return (await _with_product_pts(table_name, [await _get_row(table_name, row_id, db)], db))[0]
|
||||
|
||||
|
||||
@router.patch("/{table_name}/rows/{row_id}")
|
||||
@@ -596,7 +631,7 @@ async def update_csv_row(table_name: str, row_id: uuid.UUID, payload: dict[str,
|
||||
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||
await approvals.invalidate(db, table_name, row_owner)
|
||||
await db.commit()
|
||||
return await _get_row(table_name, row_id, db)
|
||||
return (await _with_product_pts(table_name, [await _get_row(table_name, row_id, db)], db))[0]
|
||||
|
||||
|
||||
@router.delete("/{table_name}/rows/{row_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -689,12 +724,12 @@ async def download_csv_row_pdf(
|
||||
table_name: str,
|
||||
row_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
|
||||
) -> Response:
|
||||
_ensure_table_access(table_name, current_user)
|
||||
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||
row = await _get_row(table_name, row_id, db)
|
||||
row = (await _present_rows_for_user([row], current_user, db))[0]
|
||||
row = (await _with_product_pts(table_name, await _present_rows_for_user([row], current_user, db), db))[0]
|
||||
approval_status, am_name, approved_at = await _signature(table_name, row_owner, db)
|
||||
return Response(
|
||||
_pdf_bytes(table_name, CSV_LABELS[table_name], row, approval_status, am_name, approved_at),
|
||||
@@ -709,7 +744,7 @@ async def download_csv_table_pdfs(
|
||||
owner_id: uuid.UUID | None = None,
|
||||
month: str | None = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.ABM, Role.AGM)),
|
||||
) -> Response:
|
||||
"""The whole form, or only one month of it (for the forms that have a month)."""
|
||||
_ensure_table_access(table_name, current_user)
|
||||
|
||||
Reference in New Issue
Block a user