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:
Shubhankar45
2026-11-07 05:43:12 +00:00
parent b001e2d03c
commit 0d30c58bf0
98 changed files with 1878 additions and 573 deletions
+58 -23
View File
@@ -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)