diff --git a/PRODUCTION.md b/PRODUCTION.md index 1de880c..1adc814 100644 --- a/PRODUCTION.md +++ b/PRODUCTION.md @@ -44,8 +44,8 @@ Every command below was run against this codebase's Docker stack unless it is ma Persistent state lives in exactly two volumes: **`pgdata`** (the database) and **`pdfstore`** (approved DCR PDFs). `caddydata` holds certificates. Everything else is rebuilt from the code. -Roles: MR (medical representative), AM (area manager), GM (general manager), ADMIN. The MR -files daily call reports and company forms, the AM approves, the GM has read access across +Roles: MR (medical representative), ABM (Area Business Manager), AGM (Assistant General Manager), ADMIN. The MR +files daily call reports and company forms, the ABM approves, the AGM has read access across territories, the ADMIN maintains people, organisation and master data. ## 2. Requirements @@ -107,7 +107,7 @@ short-lived bootstrap and do the following **before the server is reachable by a changed later from the app, so choose them as final and hand them over securely. 4. Sign out, sign in as the **new** administrator, open **Users** and **deactivate all four demo accounts** (deactivation also revokes their sessions). Verify `adm001` can no longer sign in. -5. Assign an Area Manager to each headquarters, then assign doctors and chemists to MRs +5. Assign an Area Business Manager to each headquarters, then assign doctors and chemists to MRs (**Setup → Assignments**). If you would rather not keep the demo doctors, chemists and the `BBSR` headquarters, deactivate @@ -337,7 +337,7 @@ docker compose up -d 2. Real headquarters and users created; **all demo accounts deactivated** (section 4). 3. Reference data loaded (section 5): Products page shows 26 products; Sales Projection shows the product list. -4. One end-to-end pass with real accounts: MR files a DCR → AM approves → PDF downloads and +4. One end-to-end pass with real accounts: MR files a DCR → ABM approves → PDF downloads and opens; each company form downloads a PDF that matches the printed original. 5. HTTPS works on the final domain; HSTS enabled. 6. Firewall: only 80/443 (or the proxy) open. @@ -355,7 +355,7 @@ docker compose up -d there is no self-service recovery and no email flow. - **Company-form approval is per form, not per row.** Tour plan, standard tour plan and fare chart each have one approval state, stored on the server (`form_approval`): the MR sends a form that has - rows, the Area Manager approves it, and the PDF signature shows that name. Any change to the rows + rows, the Area Business Manager approves it, and the PDF signature shows that name. Any change to the rows withdraws the approval. The signature is decided by the server, never by the browser. - **Audit-log immutability is opt-in** (section 8) and untested with the shipped compose file. - **No built-in alerting or error tracking**; only health checks and logs. diff --git a/README.md b/README.md index 36b3d89..4d71d7a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > **Deploying to a server?** Use [PRODUCTION.md](PRODUCTION.md) — the operator's guide (first deployment, real users, backups, updates, runbook). This README is for development. -Field-force reporting for a pharmaceutical sales team (Celtic Life Science Pvt Ltd): Medical Representatives (MRs) file **Daily Call Reports**, Area Managers (AMs) review and approve them (the General Manager has a read-only overview), and approved reports are locked and rendered as PDFs. Alongside the DCR, the system manages the company's paper forms — tour plans, fare charts, stock statements and more — and prints each one on its own PDF layout. +Field-force reporting for a pharmaceutical sales team (Celtic Life Science Pvt Ltd): Medical Representatives (MRs) file **Daily Call Reports**, Area Business Managers (ABMs) review and approve them (the Assistant General Manager (AGM) has a read-only overview), and approved reports are locked and rendered as PDFs. Alongside the DCR, the system manages the company's paper forms — tour plans, fare charts, stock statements and more — and prints each one on its own PDF layout. - **Backend:** FastAPI · SQLAlchemy 2 (async) · PostgreSQL 16 · Alembic - **PDFs:** Jinja2 templates rendered by WeasyPrint @@ -35,11 +35,11 @@ Deliberately **not** in scope: HR, payroll, attendance, distributor management, | Area | What it does | |---|---| | Daily Call Reports | MR records doctor and chemist calls per day; one report per MR per date | -| Approval workflow | `DRAFT → PENDING_AM → APPROVED`, with a return-for-correction loop (the Area Manager is the final approver); approved reports are immutable | +| Approval workflow | `DRAFT → PENDING_ABM → APPROVED`, with a return-for-correction loop (the Area Business Manager is the final approver); approved reports are immutable | | Audit trail | Append-only log of every state change; approval history is a view over it | | PDFs | Approved DCRs are stored as PDFs; company forms download as PDFs on demand | | Company forms | Ten form tables (tour plan, fare chart, stock statement, …) with per-form PDF layouts | -| Masters | Users, headquarters, AM↔HQ mapping, doctors, chemists, products, with MR assignments | +| Masters | Users, headquarters, ABM↔HQ mapping, doctors, chemists, products, with MR assignments | | Security | JWT with refresh-token rotation, argon2 password hashing, role **and** scope checks | --- @@ -181,7 +181,7 @@ cd web && npm install && npm run dev **PDF rendering on a dev machine:** WeasyPrint needs Pango and HarfBuzz (`apt install libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz0b fonts-dejavu-core fonts-liberation fonts-crosextra-carlito` on Debian/Ubuntu). Without them the app still runs but produces plain-text PDFs and logs a warning; use the Docker image to see the real layout. -Seeded accounts (`scripts/seed.py`): `adm001@acmepharma.in` (System Admin), `gm001@acmepharma.in` (GM), `am001@acmepharma.in` (AM), `mr001@acmepharma.in` (MR) — one company, one headquarters (BBSR), 15 doctors (3 core) and 5 chemists assigned to the MR. +Seeded accounts (`scripts/seed.py`): `adm001@acmepharma.in` (System Admin), `gm001@acmepharma.in` (AGM), `am001@acmepharma.in` (ABM), `mr001@acmepharma.in` (MR) — one company, one headquarters (BBSR), 15 doctors (3 core) and 5 chemists assigned to the MR. --- @@ -245,7 +245,7 @@ web/src/ └── styles/ tokens.css · base.css · layout.css · components.css ``` -Screens are role-aware: MR / AM / GM get a dashboard with counts and a "waiting on you" queue; the Administrator gets an organisation overview. Routes use hash URLs (`#/reports/`), so every screen is linkable and the back button works behind any static file server. To add a page, create it under `pages/`, add a route in `App.tsx` and a menu entry in `lib/navigation.ts`. +Screens are role-aware: MR / ABM / AGM get a dashboard with counts and a "waiting on you" queue; the Administrator gets an organisation overview. Routes use hash URLs (`#/reports/`), so every screen is linkable and the back button works behind any static file server. To add a page, create it under `pages/`, add a route in `App.tsx` and a menu entry in `lib/navigation.ts`. ### Branding and theme @@ -268,9 +268,9 @@ The UI uses the Celtic logo and the colours taken from it. | Role | Can do | |---|---| | **MR** | File and edit own DCRs while `DRAFT`/`RETURNED`; submit; edit company forms | -| **AM** | Review DCRs of own headquarters: approve or return; sees only the approval forms (Tour Plan, Standard Tour Plan, Fare Chart) | -| **GM** | Read-only: view reports, users and headquarters across the company; no approval step | -| **ADMIN** | Provision users, headquarters and masters. **Cannot approve or read report content** | +| **ABM** | Review DCRs of own headquarters: approve or return; sees only the approval forms (Tour Plan, Standard Tour Plan, Fare Chart) | +| **AGM** | Read-only: view reports, users and headquarters across the company; no approval step | +| **ADMIN** | Provision users, headquarters and masters; monitor and read Daily Call Reports across the company. **Cannot approve reports** | Permissions are checked in two separate layers, because most RBAC bugs live in the gap between them: @@ -282,7 +282,7 @@ current_user: User = Depends(require_role(Role.MR)) await assert_can_view_dcr(db, current_user, dcr) ``` -"AM" is a role; "AM *of this headquarters*" is a scope. Both are mandatory on scoped endpoints, and each has a negative test asserting **403** — not 404 or an empty 200 — so a scope bug cannot hide behind an ambiguous response. +"ABM" is the stored role code for an ABM; "ABM *of this headquarters*" is a scope. Both are mandatory on scoped endpoints, and each has a negative test asserting **403** — not 404 or an empty 200 — so a scope bug cannot hide behind an ambiguous response. The System Administrator can never approve: `ADMIN` matches no transition in the state machine, so the audit trail stays evidence that a manager made the decision. @@ -291,13 +291,13 @@ The System Administrator can never approve: `ADMIN` matches no transition in the ## The approval workflow ``` -DRAFT ──submit(MR)──► PENDING_AM ──approve(AM)──► APPROVED (terminal, immutable) +DRAFT ──submit(MR)──► PENDING_ABM ──approve(ABM)──► APPROVED (terminal, immutable) ▲ │ - │ └──return(AM)──┐ + │ └──return(ABM)──┐ └──────submit(MR)───── RETURNED ◄───────┘ ``` -- `RETURNED` records who returned it in the `returned_by_role` column. There is no General Manager stage; the GM is a read-only role. +- `RETURNED` records who returned it in the `returned_by_role` column. There is no AGM stage; the AGM is a read-only role. - `APPROVED` is both "finally approved" and "locked": immutability is a property of the state, enforced in one guard, so there is no window where a report is approved but still editable. - Managers change state and add comments; they never edit another person's call rows. - Returning a report requires a reason (`MIN_RETURN_REASON_LENGTH`). @@ -323,9 +323,9 @@ The `csv_data` module exposes the company's paper forms as editable tables, impo | Weekly Report | `weekly_report` | One page per saved report | | Daily Call Report (CSV) | `daily_call_report_csv` | Doctor and chemist sections (not exposed in the UI) | -¹ *Approval forms* — the AM can only see these, and their PDF carries the AM approval signature line. +¹ *Approval forms* — the ABM can only see these, and their PDF carries the ABM approval signature line. -**Approval forms are per MR.** Tour Plan, Standard Tour Plan and Fare Chart rows belong to the MR who entered them (`owner_user_id`), each MR sees and numbers only their own, and the approval (`form_approval`) is kept per form *and* MR. A request goes only to the Area Manager who currently manages that MR's headquarters: any other Area Manager gets a 403 and never sees it in their list, and an MR whose headquarters has no Area Manager cannot send a form. Editing an MR's rows withdraws only that MR's approval. An admin fills a form in on behalf of one chosen MR and can never approve. +**Approval forms are per MR.** Tour Plan, Standard Tour Plan and Fare Chart rows belong to the MR who entered them (`owner_user_id`), each MR sees and numbers only their own, and the approval (`form_approval`) is kept per form *and* MR. A request goes only to the Area Business Manager who currently manages that MR's headquarters: any other Area Business Manager gets a 403 and never sees it in their list, and an MR whose headquarters has no Area Business Manager cannot send a form. Editing an MR's rows withdraws only that MR's approval. An admin fills a form in on behalf of one chosen MR and can never approve. **Monthly download.** Forms with a month (Sales Projection, Weekly Report, Field Activity Report, Core Doctor Call Conversion, Area Covered, Sales and Stock Statement) get a Month selector. The table and the PDF (`GET /csv-data/{form}/pdf?month=November`) then cover that month only; a month with no rows is refused rather than printed blank. @@ -347,7 +347,7 @@ Base path `/api/v1`; interactive documentation at `/docs` and `/redoc`, schema a |---|---|---| | auth | `/auth` | Login, refresh (rotating tokens), logout, current user | | users | `/users` | User administration and the MR profile | -| organization | `/headquarters` | Headquarters and AM↔HQ mapping | +| organization | `/headquarters` | Headquarters and ABM↔HQ mapping | | doctors, chemists | `/doctors`, `/chemists` | Masters and MR assignment | | products | `/products` | Product master and stock inventory list | | reports | `/dcr` | DCR CRUD, calls, submit / return / approve, PDF | @@ -395,7 +395,7 @@ ALTER TABLE daily_call_report ADD CONSTRAINT uq_dcr_mr_date UNIQUE (mr_user_id, -- No duplicate doctor call within one report ALTER TABLE doctor_call ADD CONSTRAINT uq_call_dcr_doctor UNIQUE (dcr_id, doctor_id); --- Exactly one active Area Manager per headquarters +-- Exactly one active Area Business Manager per headquarters CREATE UNIQUE INDEX uq_active_am_per_hq ON am_headquarters (headquarters_id) WHERE effective_to IS NULL; ``` @@ -447,7 +447,7 @@ pytest tests/unit -q # state machine, PDF layouts — s ## Known limitations -- **Company-form approval is per form, not per row.** The tour plan, standard tour plan and fare chart each have one server-stored approval state (`draft → pending → approved`). The MR sends a form that has rows, the Area Manager approves it, and the PDF signature is decided by the server. Any change to the rows withdraws the approval. +- **Company-form approval is per form, not per row.** The tour plan, standard tour plan and fare chart each have one server-stored approval state (`draft → pending → approved`). The MR sends a form that has rows, the Area Business Manager approves it, and the PDF signature is decided by the server. Any change to the rows withdraws the approval. - **`web/node_modules` and `web/dist` are committed** to the repository (with stale build output) and should be untracked; Docker builds the app from source. - The test suite needs a reachable PostgreSQL; some tests under `tests/unit` also need it. diff --git a/alembic/versions/a7e3f9b5c2d4_stockist_calls.py b/alembic/versions/a7e3f9b5c2d4_stockist_calls.py new file mode 100644 index 0000000..c82cde9 --- /dev/null +++ b/alembic/versions/a7e3f9b5c2d4_stockist_calls.py @@ -0,0 +1,56 @@ +"""stockist visits on the Daily Call Report + +Revision ID: a7e3f9b5c2d4 +Revises: z6d2e8f4a1b3 +Create Date: 2026-11-03 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "a7e3f9b5c2d4" +down_revision: str | None = "z6d2e8f4a1b3" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.create_table( + "stockist_call", + sa.Column("id", sa.UUID(), nullable=False), + sa.Column("dcr_id", sa.UUID(), nullable=False), + sa.Column("stockist_id", sa.UUID(), nullable=False), + sa.Column("visit_time", sa.Time(), nullable=False), + sa.Column("pob", sa.String(length=100), nullable=True), + sa.Column("remarks", sa.Text(), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False), + sa.ForeignKeyConstraint(["dcr_id"], ["daily_call_report.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["stockist_id"], ["stockist.id"], ondelete="RESTRICT"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("dcr_id", "stockist_id", name="uq_call_dcr_stockist"), + ) + + op.add_column("missed_visit", sa.Column("stockist_id", sa.UUID(), nullable=True)) + op.create_foreign_key( + "missed_visit_stockist_id_fkey", "missed_visit", "stockist", ["stockist_id"], ["id"], ondelete="RESTRICT" + ) + op.create_unique_constraint("uq_missed_dcr_stockist", "missed_visit", ["dcr_id", "stockist_id"]) + op.drop_constraint("ck_missed_one_target", "missed_visit", type_="check") + op.create_check_constraint( + "ck_missed_one_target", "missed_visit", "num_nonnulls(doctor_id, chemist_id, stockist_id) = 1" + ) + + +def downgrade() -> None: + op.execute("DELETE FROM missed_visit WHERE stockist_id IS NOT NULL") + op.drop_constraint("ck_missed_one_target", "missed_visit", type_="check") + op.create_check_constraint( + "ck_missed_one_target", "missed_visit", "(doctor_id IS NULL) <> (chemist_id IS NULL)" + ) + op.drop_constraint("uq_missed_dcr_stockist", "missed_visit", type_="unique") + op.drop_constraint("missed_visit_stockist_id_fkey", "missed_visit", type_="foreignkey") + op.drop_column("missed_visit", "stockist_id") + op.drop_table("stockist_call") diff --git a/alembic/versions/b8f4a1c6d2e9_abm_agm_role_codes.py b/alembic/versions/b8f4a1c6d2e9_abm_agm_role_codes.py new file mode 100644 index 0000000..042f0ba --- /dev/null +++ b/alembic/versions/b8f4a1c6d2e9_abm_agm_role_codes.py @@ -0,0 +1,43 @@ +"""Rename the AM/GM role and pending-status codes to ABM/AGM + +Revision ID: b8f4a1c6d2e9 +Revises: a7e3f9b5c2d4 +Create Date: 2026-11-04 +""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "b8f4a1c6d2e9" +down_revision: str | None = "a7e3f9b5c2d4" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.execute("UPDATE \"user\" SET role = 'ABM' WHERE role = 'AM'") + op.execute("UPDATE \"user\" SET role = 'AGM' WHERE role = 'GM'") + op.execute( + "UPDATE daily_call_report SET returned_by_role = 'ABM' WHERE returned_by_role = 'AM'" + ) + op.execute( + "UPDATE daily_call_report SET returned_by_role = 'AGM' WHERE returned_by_role = 'GM'" + ) + op.execute( + "UPDATE daily_call_report SET status = 'PENDING_ABM' WHERE status = 'PENDING_AM'" + ) + + +def downgrade() -> None: + op.execute( + "UPDATE daily_call_report SET status = 'PENDING_AM' WHERE status = 'PENDING_ABM'" + ) + op.execute( + "UPDATE daily_call_report SET returned_by_role = 'AM' WHERE returned_by_role = 'ABM'" + ) + op.execute( + "UPDATE daily_call_report SET returned_by_role = 'GM' WHERE returned_by_role = 'AGM'" + ) + op.execute("UPDATE \"user\" SET role = 'AM' WHERE role = 'ABM'") + op.execute("UPDATE \"user\" SET role = 'GM' WHERE role = 'AGM'") diff --git a/alembic/versions/z6d2e8f4a1b3_add_stockist_table.py b/alembic/versions/z6d2e8f4a1b3_add_stockist_table.py new file mode 100644 index 0000000..7501b2a --- /dev/null +++ b/alembic/versions/z6d2e8f4a1b3_add_stockist_table.py @@ -0,0 +1,44 @@ +"""add stockist master table + +Revision ID: z6d2e8f4a1b3 +Revises: y5c1e7a3b0d2 +Create Date: 2026-11-03 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +revision: str = "z6d2e8f4a1b3" +down_revision: str | None = "y5c1e7a3b0d2" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.create_table( + "stockist", + sa.Column("id", sa.UUID(), nullable=False), + sa.Column("headquarters_id", sa.UUID(), nullable=False), + sa.Column("name", sa.String(length=200), nullable=False), + sa.Column("address", sa.String(length=500), nullable=False), + sa.Column("contact_number", sa.String(length=20), nullable=True), + sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.text("true")), + sa.Column("approval_status", sa.String(length=10), nullable=False, server_default="APPROVED"), + sa.Column("requested_by_user_id", sa.UUID(), nullable=True), + sa.Column("rejection_reason", sa.String(length=500), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False), + sa.ForeignKeyConstraint(["headquarters_id"], ["headquarters.id"], ondelete="RESTRICT"), + sa.ForeignKeyConstraint(["requested_by_user_id"], ["user.id"], ondelete="SET NULL"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("headquarters_id", "name", "address", name="uq_stockist_hq_name_address"), + ) + op.create_index("ix_stockist_approval_status", "stockist", ["approval_status"]) + + +def downgrade() -> None: + op.drop_index("ix_stockist_approval_status", table_name="stockist") + op.drop_table("stockist") + diff --git a/app/api/v1/router.py b/app/api/v1/router.py index b9fc382..1bc319a 100644 --- a/app/api/v1/router.py +++ b/app/api/v1/router.py @@ -12,8 +12,10 @@ from app.chemists.router import router as chemists_router from app.csv_data.router import router as csv_data_router from app.doctors.router import router as doctors_router from app.organization.router import router as organization_router +from app.pdf.router import router as directory_pdf_router from app.products.router import router as products_router from app.reports.router import router as reports_router +from app.stockists.router import router as stockists_router from app.users.router import router as users_router api_router = APIRouter() @@ -22,7 +24,9 @@ api_router.include_router(users_router) api_router.include_router(organization_router) api_router.include_router(doctors_router) api_router.include_router(chemists_router) +api_router.include_router(stockists_router) api_router.include_router(csv_data_router) api_router.include_router(products_router) api_router.include_router(reports_router) api_router.include_router(audit_router) +api_router.include_router(directory_pdf_router) diff --git a/app/approvals/state_machine.py b/app/approvals/state_machine.py index a563a7b..041f15d 100644 --- a/app/approvals/state_machine.py +++ b/app/approvals/state_machine.py @@ -1,11 +1,11 @@ """The approval workflow for the revised business requirement. - DRAFT --submit(MR)--> PENDING_AM - RETURNED --submit(MR)--> PENDING_AM - PENDING_AM --approve(AM)--> APPROVED (terminal, immutable) - PENDING_AM --return(AM)--> RETURNED + DRAFT --submit(MR)--> PENDING_ABM + RETURNED --submit(MR)--> PENDING_ABM + PENDING_ABM --approve(ABM)--> APPROVED (terminal, immutable) + PENDING_ABM --return(ABM)--> RETURNED -The Area Manager is the final approver; there is no General Manager stage. +The Area Business Manager is the final approver; there is no Assistant General Manager stage. """ from dataclasses import dataclass @@ -24,11 +24,11 @@ class Transition: TRANSITIONS: tuple[Transition, ...] = ( - Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR), - Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR), - Transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.AM), + Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_ABM, Role.MR), + Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_ABM, Role.MR), + Transition(DCRStatus.PENDING_ABM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.ABM), Transition( - DCRStatus.PENDING_AM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.AM, + DCRStatus.PENDING_ABM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.ABM, requires_reason=True, ), ) diff --git a/app/audit/router.py b/app/audit/router.py index 69f7959..734a8b2 100644 --- a/app/audit/router.py +++ b/app/audit/router.py @@ -32,10 +32,10 @@ async def get_audit_history( if dcr is None: raise NotFoundError("Report not found") await assert_can_view_dcr(db, current_user, dcr) - elif current_user.role not in (Role.ADMIN, Role.GM): + elif current_user.role not in (Role.ADMIN, Role.AGM): from app.common.exceptions import ForbiddenError - raise ForbiddenError("Only ADMIN or GM may read non-report audit history") + raise ForbiddenError("Only ADMIN or AGM may read non-report audit history") return await AuditService(db).history_for(entity_type, entity_id) diff --git a/app/auth/dependencies.py b/app/auth/dependencies.py index 9af4705..8c1d525 100644 --- a/app/auth/dependencies.py +++ b/app/auth/dependencies.py @@ -3,8 +3,8 @@ Layer 1 (`require_role`) answers "WHAT may this role do?". Layer 2 (`assert_can_*`) answers "WHOSE data may this specific user touch?". -Most RBAC bugs live in the gap between those two questions: "AM" is a role, but -"AM *of this headquarters*" is a scope. Both checks are mandatory on scoped +Most RBAC bugs live in the gap between those two questions: "ABM" is the stored role code +for an ABM, but "ABM *of this headquarters*" is a scope. Both checks are mandatory on scoped endpoints, and every one has a negative test asserting 403 (X1-X3). """ @@ -64,7 +64,7 @@ def require_role(*allowed: Role): async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[uuid.UUID]: - """Headquarters this Area Manager currently manages (`effective_to IS NULL`).""" + """Headquarters this Area Business Manager currently manages (`effective_to IS NULL`).""" stmt = select(AMHeadquarters.headquarters_id).where( AMHeadquarters.area_manager_user_id == am_user_id, AMHeadquarters.effective_to.is_(None), @@ -73,10 +73,10 @@ async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[u async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None: - """Headquarters the user may see. `None` means "all" (GM and ADMIN).""" - if user.role in (Role.GM, Role.ADMIN): + """Headquarters the user may see. `None` means "all" (AGM and ADMIN).""" + if user.role in (Role.AGM, Role.ADMIN): return None - if user.role == Role.AM: + if user.role == Role.ABM: return await active_hq_ids_for_am(db, user.id) if user.role in FIELD_ROLES: return user.covered_headquarter_ids @@ -94,13 +94,13 @@ async def assert_can_view_dcr(db: AsyncSession, user: User, dcr) -> None: """Layer 2 for reports. ADMIN may inspect report content for support and administration, but cannot act on - reports because every transition endpoint still requires the AM role. + reports because every transition endpoint still requires the ABM role code (ABM). """ - if user.role in (Role.GM, Role.ADMIN): + if user.role in (Role.AGM, Role.ADMIN): return if user.role in FIELD_ROLES and dcr.mr_user_id == user.id: return - if user.role == Role.AM: + if user.role == Role.ABM: if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id): return raise ForbiddenError("Report outside your data scope") diff --git a/app/chemists/models.py b/app/chemists/models.py index 2fc2272..56412df 100644 --- a/app/chemists/models.py +++ b/app/chemists/models.py @@ -26,7 +26,7 @@ class Chemist(Base, UUIDMixin, TimestampMixin): shop_address: Mapped[str] = mapped_column(String(500), nullable=False) contact_number: Mapped[str | None] = mapped_column(String(20)) is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) - #: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited. + #: PENDING until the Area Business Manager approves one an MR added; only APPROVED ones are listed or visited. approval_status: Mapped[str] = mapped_column( String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False ) diff --git a/app/chemists/router.py b/app/chemists/router.py index e87a324..1dc7567 100644 --- a/app/chemists/router.py +++ b/app/chemists/router.py @@ -18,8 +18,19 @@ router = APIRouter(prefix="/chemists", tags=["chemists"]) @router.get("", response_model=list[ChemistRead]) async def list_chemists( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) -) -> list[Chemist]: - return await ChemistService(db).list_for(current_user) +) -> list[ChemistRead]: + service = ChemistService(db) + chemists = await service.list_for(current_user) + names = await service.assigned_mr_names([c.id for c in chemists]) + return [ + ChemistRead.model_validate(c).model_copy( + update={ + "assigned_mr_id": names[c.id][0] if c.id in names else None, + "assigned_mr_name": names[c.id][1] if c.id in names else None, + } + ) + for c in chemists + ] @router.post("", response_model=ChemistRead, status_code=status.HTTP_201_CREATED) @@ -29,7 +40,7 @@ async def create_chemist( current_user: User = Depends(require_role(Role.ADMIN, Role.MR)), db: AsyncSession = Depends(get_db), ) -> Chemist: - """An Administrator, or an MR within their own headquarters (AM and GM cannot).""" + """An Administrator, or an MR within their own headquarters (ABM and AGM cannot).""" return await ChemistService(db).create(payload, current_user, client_ip(request)) @@ -44,12 +55,23 @@ async def update_chemist( return await ChemistService(db).update(chemist_id, payload, current_user, client_ip(request)) +@router.delete("/{chemist_id}/assign", status_code=status.HTTP_204_NO_CONTENT) +async def unassign_chemist( + chemist_id: uuid.UUID, + request: Request, + current_user: User = Depends(require_role(Role.ADMIN)), + db: AsyncSession = Depends(get_db), +) -> None: + """Administrator only: leave the chemist with no MR.""" + await ChemistService(db).unassign(chemist_id, current_user, client_ip(request)) + + @router.post("/{chemist_id}/assign", status_code=status.HTTP_201_CREATED) async def assign_chemist( chemist_id: uuid.UUID, payload: AssignToMR, request: Request, - current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)), + current_user: User = Depends(require_role(Role.ADMIN, Role.AGM, Role.ABM)), db: AsyncSession = Depends(get_db), ): assignment = await ChemistService(db).assign_to_mr( @@ -67,8 +89,8 @@ async def assign_chemist( async def list_chemist_requests( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> list[Chemist]: - """Chemists an MR added that wait for the Area Manager: an MR sees their own (with any - rejected and why), an Area Manager what waits for them, the administrator and GM all.""" + """Chemists an MR added that wait for the Area Business Manager: an MR sees their own (with any + rejected and why), an Area Business Manager what waits for them, the administrator and AGM all.""" return await ChemistService(db).requests_for(current_user) @@ -76,10 +98,10 @@ async def list_chemist_requests( async def approve_chemist( chemist_id: uuid.UUID, request: Request, - current_user: User = Depends(require_role(Role.AM, Role.ADMIN)), + current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)), db: AsyncSession = Depends(get_db), ) -> Chemist: - """The Area Manager of its headquarters adds it to the list, assigned to the MR who asked.""" + """The Area Business Manager of its headquarters adds it to the list, assigned to the MR who asked.""" return await ChemistService(db).review(chemist_id, True, None, current_user, client_ip(request)) @@ -88,7 +110,7 @@ async def reject_chemist( chemist_id: uuid.UUID, payload: RejectMaster, request: Request, - current_user: User = Depends(require_role(Role.AM, Role.ADMIN)), + current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)), db: AsyncSession = Depends(get_db), ) -> Chemist: return await ChemistService(db).review(chemist_id, False, payload.reason, current_user, client_ip(request)) diff --git a/app/chemists/schemas.py b/app/chemists/schemas.py index 981cf13..e5cb581 100644 --- a/app/chemists/schemas.py +++ b/app/chemists/schemas.py @@ -12,6 +12,7 @@ class ChemistCreate(BaseModel): class ChemistUpdate(BaseModel): + headquarters_id: uuid.UUID | None = None name: str | None = Field(default=None, min_length=2, max_length=200) shop_address: str | None = Field(default=None, min_length=2, max_length=500) contact_number: str | None = Field(default=None, max_length=20) @@ -32,4 +33,7 @@ class ChemistRead(BaseModel): rejection_reason: str | None requested_by_name: str | None created_at: datetime + #: Filled by the list endpoint only. + assigned_mr_name: str | None = None + assigned_mr_id: uuid.UUID | None = None diff --git a/app/chemists/service.py b/app/chemists/service.py index 0355bfb..ef000a1 100644 --- a/app/chemists/service.py +++ b/app/chemists/service.py @@ -10,12 +10,13 @@ from app.auth.dependencies import assert_can_view_hq, visible_hq_ids from app.chemists.models import Chemist, ChemistAssignment from app.chemists.schemas import ChemistCreate, ChemistUpdate from app.common import master_approval +from app.common.master_edit import commit_unique, end_assignments, move_headquarters from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES from app.common.exceptions import ConflictError, NotFoundError, ValidationError from app.common.utils import snapshot from app.users.models import User -_AUDIT_FIELDS = ["name", "shop_address", "contact_number", "is_active"] +_AUDIT_FIELDS = ["headquarters_id", "name", "shop_address", "contact_number", "is_active"] class ChemistService: @@ -27,7 +28,7 @@ class ChemistService: await assert_can_view_hq(self.db, actor, data.headquarters_id) values = data.model_dump() - # Added by an MR: it waits for the Area Manager. One they were refused is sent again. + # Added by an MR: it waits for the Area Business Manager. One they were refused is sent again. twin = None if actor.role in FIELD_ROLES: twin = await master_approval.rejected_twin( @@ -97,7 +98,11 @@ class ChemistService: await assert_can_view_hq(self.db, actor, chemist.headquarters_id) before = snapshot(chemist, _AUDIT_FIELDS) - for field, value in data.model_dump(exclude_unset=True).items(): + changes = data.model_dump(exclude_unset=True) + new_hq = changes.pop("headquarters_id", None) + if new_hq is not None: + await move_headquarters(self.db, actor, chemist, new_hq, ChemistAssignment, "chemist_id") + for field, value in changes.items(): setattr(chemist, field, value) await self.audit.log( @@ -109,7 +114,7 @@ class ChemistService: after=snapshot(chemist, _AUDIT_FIELDS), ip_address=ip, ) - await self.db.commit() + await commit_unique(self.db, "A chemist with this name already exists at this address in this headquarters") return chemist async def list_for(self, actor: User) -> list[Chemist]: @@ -133,6 +138,34 @@ class ChemistService: stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None])) return list((await self.db.execute(stmt)).scalars().all()) + async def assigned_mr_names(self, chemist_ids: list[uuid.UUID]) -> dict[uuid.UUID, tuple[uuid.UUID, str]]: + """The MR (id, name) each chemist is currently assigned to, by chemist id.""" + if not chemist_ids: + return {} + stmt = ( + select(ChemistAssignment.chemist_id, User.id, User.full_name) + .join(User, User.id == ChemistAssignment.mr_user_id) + .where(ChemistAssignment.chemist_id.in_(chemist_ids), ChemistAssignment.effective_to.is_(None)) + ) + return {chemist_id: (mr_id, name) for chemist_id, mr_id, name in (await self.db.execute(stmt)).all()} + + async def unassign(self, chemist_id: uuid.UUID, actor: User, ip: str | None = None) -> None: + """Take the chemist away from its MR, leaving it unassigned.""" + chemist = await self.db.get(Chemist, chemist_id) + if chemist is None: + raise NotFoundError("Chemist not found") + await assert_can_view_hq(self.db, actor, chemist.headquarters_id) + if await end_assignments(self.db, ChemistAssignment, "chemist_id", chemist_id): + await self.audit.log( + actor_user_id=actor.id, + entity_type=EntityType.CHEMIST, + entity_id=chemist_id, + action=AuditAction.UPDATE, + after={"unassigned": True}, + ip_address=ip, + ) + await self.db.commit() + async def assign_to_mr( self, chemist_id: uuid.UUID, @@ -146,7 +179,7 @@ class ChemistService: raise NotFoundError("Chemist not found") await assert_can_view_hq(self.db, actor, chemist.headquarters_id) if chemist.approval_status != MasterApproval.APPROVED: - raise ValidationError("This chemist is still waiting for the Area Manager's approval") + raise ValidationError("This chemist is still waiting for the Area Business Manager's approval") mr = await self.db.get(User, mr_user_id) if mr is None: diff --git a/app/common/enums.py b/app/common/enums.py index beea06c..42d5128 100644 --- a/app/common/enums.py +++ b/app/common/enums.py @@ -9,18 +9,18 @@ from enum import StrEnum class Role(StrEnum): - """Operational roles (MR/AM/GM) plus the technical ADMIN role. + """Operational roles (MR, ABM, AGM; stored as MR/ABM/AGM) plus technical ADMIN. - 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 sits OUTSIDE the business hierarchy. It provisions users and masters and + may monitor reports, but can never approve one (report §8, SEC-2). """ ADMIN = "ADMIN" - GM = "GM" - AM = "AM" + AGM = "AGM" + ABM = "ABM" MR = "MR" #: Senior Field Executive: does an MR's work (daily reports, forms, doctors, chemists) and - #: reports to the same Area Manager, but may cover several headquarters. + #: reports to the same Area Business Manager, but may cover several headquarters. SFE = "SFE" @@ -29,25 +29,25 @@ FIELD_ROLES: frozenset[Role] = frozenset({Role.MR, Role.SFE}) class DCRStatus(StrEnum): - """MR submits, the Area Manager approves or returns it. + """MR submits, the Area Business Manager approves or returns it. `RETURNED` captures the correction loop, and `APPROVED` remains terminal and - immutable. There is no General Manager step. + immutable. There is no Assistant General Manager step. """ DRAFT = "DRAFT" - PENDING_AM = "PENDING_AM" + PENDING_ABM = "PENDING_ABM" RETURNED = "RETURNED" APPROVED = "APPROVED" class ReportType(StrEnum): - """An MR files two reports a day, each approved by the Area Manager on its own. + """An MR files two reports a day, each approved by the Area Business Manager on its own. PLAN — in the morning: which doctors and chemists the MR intends to visit, and when. ACTUAL — at the end of the day: the visits that happened, plus a short note for every planned visit that did not. It can be started only once the plan is approved. - SELF — an Area Manager's own end-of-day report of the visits they made. It needs no + SELF — an Area Business Manager's own end-of-day report of the visits they made. It needs no plan and no approval: submitting it makes it final. """ @@ -84,7 +84,7 @@ class ConversionStatus(StrEnum): class MasterApproval(StrEnum): - """A doctor or chemist an MR adds waits for their Area Manager before anyone can use it.""" + """A doctor or chemist an MR adds waits for their Area Business Manager before anyone can use it.""" PENDING = "PENDING" APPROVED = "APPROVED" @@ -109,6 +109,7 @@ class EntityType(StrEnum): HEADQUARTERS = "headquarters" DOCTOR = "doctor" CHEMIST = "chemist" + STOCKIST = "stockist" DCR = "dcr" PRODUCT = "product" #: A row of a company form (the table is named in the entry's data). diff --git a/app/common/master_approval.py b/app/common/master_approval.py index 2dce427..4cfeeb9 100644 --- a/app/common/master_approval.py +++ b/app/common/master_approval.py @@ -1,11 +1,11 @@ -"""Approval of the doctors and chemists an MR adds. +"""Approval of the doctors, chemists and stockists an MR adds. - MR adds one --> PENDING --approve(AM)--> APPROVED (listed, and visitable by that MR) - --reject(AM)---> REJECTED (the MR sees why; adding it again re-sends it) + MR adds one --> PENDING --approve(ABM)--> APPROVED (listed, and visitable by that MR) + --reject(ABM)---> REJECTED (the MR sees why; adding it again re-sends it) Only APPROVED masters are listed or may be visited. The administrator's own additions are -APPROVED at once. The reviewer is the Area Manager of the master's headquarters (or the -administrator); the General Manager may look but not act. +APPROVED at once. The reviewer is the Area Business Manager of the master's headquarters (or the +administrator); the Assistant General Manager may look but not act. """ import uuid @@ -34,14 +34,22 @@ async def rejected_twin(db: AsyncSession, model: Any, match: dict[str, Any]) -> async def resubmit( - db: AsyncSession, record: Any, values: dict[str, Any], actor: User, assignment_model: Any, fk: str + db: AsyncSession, + record: Any, + values: dict[str, Any], + actor: User, + assignment_model: Any | None = None, + fk: str | None = None, ) -> None: - """Re-send a rejected record with the MR's new details, assigned to that MR.""" + """Re-send a rejected record with the MR's new details, assigned to that MR (stockists have no + per-MR assignment: they belong to the headquarters).""" for field, value in values.items(): setattr(record, field, value) record.approval_status = MasterApproval.PENDING record.requested_by_user_id = actor.id record.rejection_reason = None + if assignment_model is None or fk is None: + return today = date.today() current = ( await db.execute( @@ -59,7 +67,7 @@ async def resubmit( async def requests_for(db: AsyncSession, model: Any, actor: User) -> list[Any]: """An MR: what they asked for that is still waiting or was rejected. - An Area Manager: what waits for them. Administrator and GM: everything waiting.""" + An Area Business Manager: what waits for them. Administrator and AGM: everything waiting.""" stmt = select(model).order_by(model.created_at.desc()) if actor.role in FIELD_ROLES: return list( @@ -92,8 +100,8 @@ async def review( record = await db.get(model, record_id) if record is None: raise NotFoundError(f"{entity_type.value.capitalize()} not found") - if actor.role not in (Role.AM, Role.ADMIN): - raise ForbiddenError("Only the Area Manager approves a new doctor or chemist") + if actor.role not in (Role.ABM, Role.ADMIN): + raise ForbiddenError("Only the Area Business Manager approves a new doctor, chemist or stockist") await assert_can_view_hq(db, actor, record.headquarters_id) target = MasterApproval.APPROVED if approve else MasterApproval.REJECTED if record.approval_status == target: diff --git a/app/common/master_edit.py b/app/common/master_edit.py new file mode 100644 index 0000000..bfbab21 --- /dev/null +++ b/app/common/master_edit.py @@ -0,0 +1,69 @@ +"""Shared rules for an administrator editing a doctor, chemist or stockist.""" + +import uuid +from datetime import date + +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth.dependencies import assert_can_view_hq +from app.common.exceptions import ConflictError, NotFoundError +from app.organization.models import Headquarters +from app.users.models import User + + +async def move_headquarters( + db: AsyncSession, + actor: User, + item, + new_hq_id: uuid.UUID, + assignment_model=None, + fk_field: str | None = None, +) -> None: + """Move ``item`` to another headquarters. A current MR assignment ends when that MR does not + work the new headquarters, since an MR may only hold masters of the headquarters they cover.""" + if new_hq_id == item.headquarters_id: + return + if await db.get(Headquarters, new_hq_id) is None: + raise NotFoundError("Headquarters not found") + await assert_can_view_hq(db, actor, new_hq_id) + item.headquarters_id = new_hq_id + if assignment_model is None: + return + current = ( + await db.execute( + select(assignment_model).where( + getattr(assignment_model, fk_field) == item.id, + assignment_model.effective_to.is_(None), + ) + ) + ).scalars().all() + for row in current: + mr = await db.get(User, row.mr_user_id) + if mr is None or new_hq_id not in mr.covered_headquarter_ids: + row.effective_to = date.today() + + +async def end_assignments(db: AsyncSession, assignment_model, fk_field: str, item_id: uuid.UUID) -> int: + """Close every current MR assignment of one master; returns how many were closed.""" + current = ( + await db.execute( + select(assignment_model).where( + getattr(assignment_model, fk_field) == item_id, + assignment_model.effective_to.is_(None), + ) + ) + ).scalars().all() + for row in current: + row.effective_to = date.today() + return len(current) + + +async def commit_unique(db: AsyncSession, message: str) -> None: + """Commit, turning a unique-constraint clash (same name and address in a headquarters) into a 409.""" + try: + await db.commit() + except IntegrityError as exc: + await db.rollback() + raise ConflictError(message) from exc diff --git a/app/csv_data/approval.py b/app/csv_data/approval.py index 013edd4..42a8423 100644 --- a/app/csv_data/approval.py +++ b/app/csv_data/approval.py @@ -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 diff --git a/app/csv_data/models.py b/app/csv_data/models.py index ae0b4f3..fb34ce1 100644 --- a/app/csv_data/models.py +++ b/app/csv_data/models.py @@ -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") diff --git a/app/csv_data/router.py b/app/csv_data/router.py index 33d81f4..38edd34 100644 --- a/app/csv_data/router.py +++ b/app/csv_data/router.py @@ -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) diff --git a/app/database/all_models.py b/app/database/all_models.py index 5aa03a7..bee0a5c 100644 --- a/app/database/all_models.py +++ b/app/database/all_models.py @@ -13,7 +13,8 @@ from app.database.base import Base from app.doctors.models import Doctor, DoctorAssignment from app.organization.models import AMHeadquarters, Company, Headquarters from app.products.models import Product -from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit +from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit, StockistCall +from app.stockists.models import Stockist from app.users.models import User, UserExtraHeadquarters # noqa: F401 __all__ = [ @@ -32,6 +33,8 @@ __all__ = [ "DailyCallReport", "DoctorCall", "MissedVisit", + "StockistCall", "User", "Product", + "Stockist", ] diff --git a/app/doctors/models.py b/app/doctors/models.py index 9b35915..6b28956 100644 --- a/app/doctors/models.py +++ b/app/doctors/models.py @@ -40,7 +40,7 @@ class Doctor(Base, UUIDMixin, TimestampMixin): #: Core doctors are the high-value targets tracked for conversion. is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) - #: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited. + #: PENDING until the Area Business Manager approves one an MR added; only APPROVED ones are listed or visited. approval_status: Mapped[str] = mapped_column( String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False ) diff --git a/app/doctors/router.py b/app/doctors/router.py index 82da814..990476e 100644 --- a/app/doctors/router.py +++ b/app/doctors/router.py @@ -17,9 +17,15 @@ router = APIRouter(prefix="/doctors", tags=["doctors"]) @router.get("", response_model=list[DoctorRead]) async def list_doctors( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) -) -> list[Doctor]: +) -> list[DoctorRead]: """S5 — an MR gets only their assigned doctors; managers get their HQ scope.""" - return await DoctorService(db).list_for(current_user) + rows = await DoctorService(db).list_for(current_user) + return [ + DoctorRead.model_validate(doctor).model_copy( + update={"assigned_mr_name": assigned_mr_name, "assigned_mr_id": mr_id} + ) + for doctor, assigned_mr_name, mr_id in rows + ] @router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED) @@ -29,7 +35,7 @@ async def create_doctor( current_user: User = Depends(require_role(Role.ADMIN, Role.MR)), db: AsyncSession = Depends(get_db), ) -> Doctor: - """An Administrator, or an MR within their own headquarters (AM and GM cannot).""" + """An Administrator, or an MR within their own headquarters (ABM and AGM cannot).""" return await DoctorService(db).create(payload, current_user, client_ip(request)) @@ -44,15 +50,26 @@ async def update_doctor( return await DoctorService(db).update(doctor_id, payload, current_user, client_ip(request)) +@router.delete("/{doctor_id}/assign", status_code=status.HTTP_204_NO_CONTENT) +async def unassign_doctor( + doctor_id: uuid.UUID, + request: Request, + current_user: User = Depends(require_role(Role.ADMIN)), + db: AsyncSession = Depends(get_db), +) -> None: + """Administrator only: leave the doctor with no MR.""" + await DoctorService(db).unassign(doctor_id, current_user, client_ip(request)) + + @router.post("/{doctor_id}/assign", status_code=status.HTTP_201_CREATED) async def assign_doctor( doctor_id: uuid.UUID, payload: AssignToMR, request: Request, - current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)), + current_user: User = Depends(require_role(Role.ADMIN, Role.AGM, Role.ABM)), db: AsyncSession = Depends(get_db), ): - """An AM may assign only within their own headquarters — enforced by data scope.""" + """An ABM may assign only within their own headquarters — enforced by data scope.""" assignment = await DoctorService(db).assign_to_mr( doctor_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request) ) @@ -68,8 +85,8 @@ async def assign_doctor( async def list_doctor_requests( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> list[Doctor]: - """Doctors an MR added that wait for the Area Manager: an MR sees their own (with any - rejected and why), an Area Manager what waits for them, the administrator and GM all.""" + """Doctors an MR added that wait for the Area Business Manager: an MR sees their own (with any + rejected and why), an Area Business Manager what waits for them, the administrator and AGM all.""" return await DoctorService(db).requests_for(current_user) @@ -77,10 +94,10 @@ async def list_doctor_requests( async def approve_doctor( doctor_id: uuid.UUID, request: Request, - current_user: User = Depends(require_role(Role.AM, Role.ADMIN)), + current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)), db: AsyncSession = Depends(get_db), ) -> Doctor: - """The Area Manager of its headquarters adds it to the list, assigned to the MR who asked.""" + """The Area Business Manager of its headquarters adds it to the list, assigned to the MR who asked.""" return await DoctorService(db).review(doctor_id, True, None, current_user, client_ip(request)) @@ -89,7 +106,7 @@ async def reject_doctor( doctor_id: uuid.UUID, payload: RejectMaster, request: Request, - current_user: User = Depends(require_role(Role.AM, Role.ADMIN)), + current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)), db: AsyncSession = Depends(get_db), ) -> Doctor: return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request)) diff --git a/app/doctors/schemas.py b/app/doctors/schemas.py index 123d720..91aa04c 100644 --- a/app/doctors/schemas.py +++ b/app/doctors/schemas.py @@ -24,6 +24,7 @@ class DoctorCreate(BaseModel): class DoctorUpdate(BaseModel): + headquarters_id: uuid.UUID | None = None name: str | None = Field(default=None, min_length=2, max_length=200) clinic_address: str | None = Field(default=None, min_length=2, max_length=500) speciality: str | None = Field(default=None, max_length=100) @@ -49,6 +50,8 @@ class DoctorRead(BaseModel): date_of_birth: date | None is_core_doctor: bool is_active: bool + assigned_mr_name: str | None = None + assigned_mr_id: uuid.UUID | None = None #: PENDING / APPROVED / REJECTED — see app/common/master_approval.py. approval_status: str rejection_reason: str | None @@ -62,6 +65,6 @@ class AssignToMR(BaseModel): class RejectMaster(BaseModel): - """Why the Area Manager refused a doctor or chemist an MR added — shown to that MR.""" + """Why the Area Business Manager refused a doctor or chemist an MR added — shown to that MR.""" reason: str = Field(min_length=3, max_length=500) diff --git a/app/doctors/service.py b/app/doctors/service.py index c3a4f16..ce6c96c 100644 --- a/app/doctors/service.py +++ b/app/doctors/service.py @@ -1,13 +1,14 @@ import uuid from datetime import date -from sqlalchemy import select +from sqlalchemy import and_, select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncSession from app.audit.service import AuditService from app.auth.dependencies import assert_can_view_hq, visible_hq_ids from app.common import master_approval +from app.common.master_edit import commit_unique, end_assignments, move_headquarters from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES from app.common.exceptions import ConflictError, NotFoundError, ValidationError from app.common.utils import snapshot @@ -16,6 +17,7 @@ from app.doctors.schemas import DoctorCreate, DoctorUpdate from app.users.models import User _AUDIT_FIELDS = [ + "headquarters_id", "name", "clinic_address", "speciality", @@ -35,7 +37,7 @@ class DoctorService: await assert_can_view_hq(self.db, actor, data.headquarters_id) values = data.model_dump() - # Added by an MR: it waits for the Area Manager. One they were refused is sent again. + # Added by an MR: it waits for the Area Business Manager. One they were refused is sent again. twin = None if actor.role in FIELD_ROLES: twin = await master_approval.rejected_twin( @@ -105,7 +107,11 @@ class DoctorService: await assert_can_view_hq(self.db, actor, doctor.headquarters_id) before = snapshot(doctor, _AUDIT_FIELDS) - for field, value in data.model_dump(exclude_unset=True).items(): + changes = data.model_dump(exclude_unset=True) + new_hq = changes.pop("headquarters_id", None) + if new_hq is not None: + await move_headquarters(self.db, actor, doctor, new_hq, DoctorAssignment, "doctor_id") + for field, value in changes.items(): setattr(doctor, field, value) await self.audit.log( @@ -117,30 +123,52 @@ class DoctorService: after=snapshot(doctor, _AUDIT_FIELDS), ip_address=ip, ) - await self.db.commit() + await commit_unique(self.db, "A doctor with this name already exists at this clinic in this headquarters") return doctor - async def list_for(self, actor: User) -> list[Doctor]: + async def list_for(self, actor: User) -> list[tuple[Doctor, str | None, uuid.UUID | None]]: """An MR sees ONLY doctors currently assigned to them (R5).""" - if actor.role in FIELD_ROLES: - stmt = ( - select(Doctor) - .join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id) - .where( - DoctorAssignment.mr_user_id == actor.id, + stmt = ( + select(Doctor, User.full_name, User.id) + .outerjoin( + DoctorAssignment, + and_( + DoctorAssignment.doctor_id == Doctor.id, DoctorAssignment.effective_to.is_(None), - Doctor.is_active.is_(True), - Doctor.approval_status == MasterApproval.APPROVED, - ) - .order_by(Doctor.name) + ), ) - return list((await self.db.execute(stmt)).scalars().all()) + .outerjoin(User, User.id == DoctorAssignment.mr_user_id) + .where(Doctor.approval_status == MasterApproval.APPROVED) + .order_by(Doctor.name) + ) + if actor.role in FIELD_ROLES: + stmt = stmt.where( + DoctorAssignment.mr_user_id == actor.id, + Doctor.is_active.is_(True), + ) + else: + allowed = await visible_hq_ids(self.db, actor) + if allowed is not None: + stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None])) + rows = (await self.db.execute(stmt)).all() + return [(doctor, assigned_mr_name, mr_id) for doctor, assigned_mr_name, mr_id in rows] - allowed = await visible_hq_ids(self.db, actor) - stmt = select(Doctor).where(Doctor.approval_status == MasterApproval.APPROVED).order_by(Doctor.name) - if allowed is not None: - stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None])) - return list((await self.db.execute(stmt)).scalars().all()) + async def unassign(self, doctor_id: uuid.UUID, actor: User, ip: str | None = None) -> None: + """Take the doctor away from its MR, leaving it unassigned.""" + doctor = await self.db.get(Doctor, doctor_id) + if doctor is None: + raise NotFoundError("Doctor not found") + await assert_can_view_hq(self.db, actor, doctor.headquarters_id) + if await end_assignments(self.db, DoctorAssignment, "doctor_id", doctor_id): + await self.audit.log( + actor_user_id=actor.id, + entity_type=EntityType.DOCTOR, + entity_id=doctor_id, + action=AuditAction.UPDATE, + after={"unassigned": True}, + ip_address=ip, + ) + await self.db.commit() async def assign_to_mr( self, @@ -155,7 +183,7 @@ class DoctorService: raise NotFoundError("Doctor not found") await assert_can_view_hq(self.db, actor, doctor.headquarters_id) if doctor.approval_status != MasterApproval.APPROVED: - raise ValidationError("This doctor is still waiting for the Area Manager's approval") + raise ValidationError("This doctor is still waiting for the Area Business Manager's approval") mr = await self.db.get(User, mr_user_id) if mr is None: diff --git a/app/main.py b/app/main.py index 320a5a2..677c9b7 100644 --- a/app/main.py +++ b/app/main.py @@ -50,7 +50,7 @@ def create_app() -> FastAPI: version="0.1.0", description=( "Pharmaceutical field-force reporting — MVP. " - "Daily Call Reports with AM final approval, GM monitoring, " + "Daily Call Reports with ABM final approval, AGM monitoring, " "locked PDFs and audit trails." ), docs_url="/docs", diff --git a/app/organization/models.py b/app/organization/models.py index 626f203..363830a 100644 --- a/app/organization/models.py +++ b/app/organization/models.py @@ -3,7 +3,7 @@ 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 MR's Area Business 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. """ @@ -54,10 +54,10 @@ class Headquarters(Base, UUIDMixin, TimestampMixin): class AMHeadquarters(Base, UUIDMixin, TimestampMixin): - """Which Area Manager currently manages which headquarters. + """Which Area Business Manager currently manages which headquarters. - `effective_to IS NULL` means "current". A headquarters may have several Area Managers - and an Area Manager several headquarters; the partial unique index only stops the same + `effective_to IS NULL` means "current". A headquarters may have several Area Business Managers + and an Area Business Manager several headquarters; the partial unique index only stops the same pair being active twice. """ diff --git a/app/organization/router.py b/app/organization/router.py index c6e484a..c9ebe53 100644 --- a/app/organization/router.py +++ b/app/organization/router.py @@ -24,16 +24,16 @@ router = APIRouter(prefix="/headquarters", tags=["organization"]) 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.""" + """Scoped: an MR sees their own HQ, an ABM sees theirs, AGM/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)), + current_user: User = Depends(require_role(Role.ADMIN, Role.AGM)), db: AsyncSession = Depends(get_db), ): - """Which Area Manager currently manages which headquarters (one row per pair).""" + """Which Area Business Manager currently manages which headquarters (one row per pair).""" return await OrganizationService(db).list_area_manager_mappings(current_user) @@ -45,7 +45,7 @@ async def set_area_manager_headquarters( current_user: User = Depends(require_role(Role.ADMIN)), db: AsyncSession = Depends(get_db), ): - """Replace the set of headquarters an Area Manager manages (any number).""" + """Replace the set of headquarters an Area Business Manager manages (any number).""" return await OrganizationService(db).set_area_manager_headquarters( area_manager_user_id, payload.headquarters_ids, diff --git a/app/organization/schemas.py b/app/organization/schemas.py index f7a4e6f..a0fd635 100644 --- a/app/organization/schemas.py +++ b/app/organization/schemas.py @@ -43,7 +43,7 @@ class AssignAreaManager(BaseModel): class SetAreaManagerHeadquarters(BaseModel): - """The complete list of headquarters an Area Manager should manage (may be empty).""" + """The complete list of headquarters an Area Business Manager should manage (may be empty).""" headquarters_ids: list[uuid.UUID] = Field(default_factory=list, max_length=500) effective_from: date | None = None diff --git a/app/organization/service.py b/app/organization/service.py index f6d5a63..89a36f8 100644 --- a/app/organization/service.py +++ b/app/organization/service.py @@ -60,7 +60,7 @@ class OrganizationService: 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.""" + """Current (open) Area Business Manager to headquarters mappings, for display.""" stmt = ( select(AMHeadquarters) .join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id) @@ -79,7 +79,7 @@ class OrganizationService: actor: User, ip: str | None = None, ) -> list[AMHeadquarters]: - """Make `headquarters_ids` exactly the set of headquarters this AM manages. + """Make `headquarters_ids` exactly the set of headquarters this ABM manages. Headquarters missing from the list are released, new ones are added. Other Area Managers of the same headquarters keep it: a headquarters may have several. @@ -87,9 +87,9 @@ class OrganizationService: 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: + if manager.role != Role.ABM: raise ValidationError( - "Only a user with the AM role can manage a headquarters", + "Only an ABM can manage a headquarters", {"user_role": manager.role.value}, ) @@ -165,7 +165,7 @@ class OrganizationService: actor: User, ip: str | None = None, ) -> AMHeadquarters: - """Add an Area Manager to a headquarters, beside any it already has. + """Add an Area Business Manager to a headquarters, beside any it already has. Assigning the same pair twice changes nothing (`uq_active_am_hq_pair`). """ @@ -176,9 +176,9 @@ class OrganizationService: manager = await self.db.get(User, am_user_id) if manager is None: raise NotFoundError("User not found") - if manager.role != Role.AM: + if manager.role != Role.ABM: raise ValidationError( - "Only a user with the AM role can manage a headquarters", + "Only an ABM can manage a headquarters", {"user_role": manager.role.value}, ) diff --git a/app/pdf/forms.py b/app/pdf/forms.py index 3e56f0a..97e9ad6 100644 --- a/app/pdf/forms.py +++ b/app/pdf/forms.py @@ -80,7 +80,7 @@ FORMS: dict[str, FormSpec] = { Col("From", "from_location", 25.0), Col("To", "to_location", 23.2), Col("POB", "pob", 15.3, "center"), - Col("Stockiest Visit", "stockiest_visit", 15.2, "center"), + Col("Stockist Visit", "stockiest_visit", 15.2, "center"), ), serial_field="serial_no", serial_dot=True, @@ -231,6 +231,17 @@ _PLAN_CHEMIST_COLS = ( Col("NAME OF THE CHEMIST", "chemist_name", 52.8), Col("PLANNED TIME", "planned_time", 37.0, "center"), ) +# Stockist visits: printed only when the report has any, so other reports keep their layout. +_STOCKIST_COLS = ( + _serial("SR. NO.", 10.2), + Col("NAME OF THE STOCKIST", "stockist_name", 32.8), + Col("POB", "pob", 57.0), +) +_PLAN_STOCKIST_COLS = ( + _serial("SR. NO.", 10.2), + Col("NAME OF THE STOCKIST", "stockist_name", 52.8), + Col("PLANNED TIME", "planned_time", 37.0, "center"), +) # End-of-day report: the planned visits that were not made, and why. _MISSED_COLS = ( _serial("SR. NO.", 8.6), @@ -576,13 +587,14 @@ def build_dcr_context( chemist_calls, approval: dict[str, str] | None = None, missed: list[Row] | None = None, + stockist_calls=(), ) -> dict[str, object]: """The approved Daily Call Report, laid out exactly like the printed company form. Same template family, headings, column widths and number of ruled lines as the ``daily_call_report_csv`` company form: 10 doctor lines and 5 chemist lines, filled from the top in visit order; more visits simply continue on the next page. The only - additions are the signatures: the MR's name, and (once approved) the Area Manager's + additions are the signatures: the MR's name, and (once approved) the Area Business Manager's approval signature with its date and time. A morning day plan uses the same form with a PLANNED TIME column in place of the @@ -592,8 +604,8 @@ def build_dcr_context( report_type = getattr(dcr, "report_type", None) report_type = getattr(report_type, "value", report_type) if report_type == "PLAN": - return _build_plan_context(dcr, doctor_calls, chemist_calls, approval) - is_self = report_type == "SELF" # an Area Manager's own report: no approval signature + return _build_plan_context(dcr, doctor_calls, chemist_calls, approval, stockist_calls) + is_self = report_type == "SELF" # an Area Business Manager's own report: no approval signature doctors = [ { "doctor_name": c.doctor.name, @@ -605,6 +617,7 @@ def build_dcr_context( for c in doctor_calls ] chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_calls] + stockists = [{"stockist_name": c.stockist.name, "pob": c.pob or ""} for c in stockist_calls] meta = [ [("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))], [("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))], @@ -619,12 +632,17 @@ def build_dcr_context( "grids": { "doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10), "chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84), + **( + {"stockists": _grid(_STOCKIST_COLS, stockists, min_rows=0, table_width=84)} + if stockists + else {} + ), **({"missed": _grid(_MISSED_COLS, missed, min_rows=0)} if missed else {}), }, "is_plan": False, "stockist_visit": dcr.stockist_visit or "", "order_value": dcr.order_value or "", - "signer_label": "Area Manager Signature" if is_self else "MR Signature", + "signer_label": "Area Business Manager Signature" if is_self else "MR Signature", "mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})", "approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None } @@ -635,7 +653,9 @@ def _products(names: list[str] | str | None) -> str: return names if isinstance(names, str) else ", ".join(names or []) -def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str, object]: +def _build_plan_context( + dcr, doctor_calls, chemist_calls, approval, stockist_calls=() +) -> dict[str, object]: doctors = [ { "doctor_name": c.doctor.name, @@ -649,6 +669,10 @@ def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str, {"chemist_name": c.chemist.name, "planned_time": c.visit_time.strftime("%H:%M")} for c in chemist_calls ] + stockists = [ + {"stockist_name": c.stockist.name, "planned_time": c.visit_time.strftime("%H:%M")} + for c in stockist_calls + ] meta = [ [("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))], [("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))], @@ -663,6 +687,11 @@ def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str, "grids": { "doctors": _grid(_PLAN_DOCTOR_COLS, doctors, min_rows=10), "chemists": _grid(_PLAN_CHEMIST_COLS, chemists, min_rows=5, table_width=84), + **( + {"stockists": _grid(_PLAN_STOCKIST_COLS, stockists, min_rows=0, table_width=84)} + if stockists + else {} + ), }, "is_plan": True, "stockist_visit": "", diff --git a/app/pdf/router.py b/app/pdf/router.py new file mode 100644 index 0000000..3ec7be6 --- /dev/null +++ b/app/pdf/router.py @@ -0,0 +1,31 @@ +"""Printable list of the Doctors & Chemists directory. + +The browser sends the rows it already shows (the user's own scope, filters and search), so +this prints nothing the user cannot already see; it only lays them out on the company letterhead.""" + +from fastapi import APIRouter, Depends, Response +from pydantic import BaseModel, Field + +from app.auth.dependencies import get_current_user +from app.pdf.service import csv_table_pdf_bytes +from app.users.models import User + +router = APIRouter(prefix="/directory", tags=["directory"]) + + +class DirectoryPdf(BaseModel): + title: str = Field(min_length=1, max_length=60) + columns: list[str] = Field(min_length=1, max_length=12) + rows: list[dict[str, str]] = Field(max_length=5000) + + +@router.post("/pdf") +async def directory_pdf(payload: DirectoryPdf, _: User = Depends(get_current_user)) -> Response: + columns = tuple(c for c in payload.columns if c.isidentifier()) + rows = [{c: r.get(c, "") for c in columns} for r in payload.rows] + name = "".join(ch for ch in payload.title.lower() if ch.isalnum()) or "directory" + return Response( + csv_table_pdf_bytes(f"directory_{name}", payload.title, columns, rows), + media_type="application/pdf", + headers={"Content-Disposition": f'inline; filename="{name}.pdf"'}, + ) diff --git a/app/pdf/service.py b/app/pdf/service.py index 4595b8e..c89baf2 100644 --- a/app/pdf/service.py +++ b/app/pdf/service.py @@ -142,7 +142,7 @@ def _approval_signature_line( table_name: str, approval_status: str | None = None, am_name: str | None = None, - am_role: str = "Area Manager", + am_role: str = "Area Business Manager", ) -> str: return approval_signature_line(table_name, approval_status, am_name) @@ -154,7 +154,7 @@ def csv_table_pdf_bytes( rows: list[dict[str, object]], approval_status: str | None = None, am_name: str | None = None, - am_role: str = "Area Manager", + am_role: str = "Area Business Manager", approved_at: str | None = None, renumber: bool = False, ) -> bytes: @@ -210,6 +210,7 @@ class PDFService: sorted(dcr.chemist_calls, key=lambda c: c.visit_time), await self._approval(dcr), missed, + sorted(dcr.stockist_calls, key=lambda c: c.visit_time), ) async def render_bytes(self, dcr: DailyCallReport) -> bytes: diff --git a/app/pdf/templates/dcr.html b/app/pdf/templates/dcr.html index 97a2327..c055f08 100644 --- a/app/pdf/templates/dcr.html +++ b/app/pdf/templates/dcr.html @@ -21,6 +21,10 @@ {{ grid(grids.doctors, left=True) }}

{{ "CHEMISTS TO VISIT" if is_plan else "CHEMIST VISIT" }}

{{ grid(grids.chemists, left=True) }} + {% if grids.stockists %} +

{{ "STOCKISTS TO VISIT" if is_plan else "STOCKIST VISIT" }}

+ {{ grid(grids.stockists, left=True) }} + {% endif %} {% if is_plan %} {% if mr_remarks %}
REMARKS : {{ mr_remarks }}
{% endif %} {% else %} @@ -46,7 +50,7 @@ {% if approval %}
APPROVAL SIGNATURE:
{{ approval.name }}
-
Area Manager · {{ approval.at }}
+
Area Business Manager · {{ approval.at }}
{% endif %} diff --git a/app/pdf/templates/dcr.txt b/app/pdf/templates/dcr.txt index 01a5998..0fd0bd6 100644 --- a/app/pdf/templates/dcr.txt +++ b/app/pdf/templates/dcr.txt @@ -11,7 +11,11 @@ Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_p {{ grids.chemists.headers | join(' | ') }} {% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }} {% endfor %} -{% if grids.missed %}PLANNED VISITS NOT MADE +{% if grids.stockists %}{{ "STOCKISTS TO VISIT" if is_plan else "STOCKIST VISIT" }} +{{ grids.stockists.headers | join(' | ') }} +{% for r in grids.stockists.rows %}{{ r.cells | join(' | ') }} +{% endfor %} +{% endif %}{% if grids.missed %}PLANNED VISITS NOT MADE {{ grids.missed.headers | join(' | ') }} {% for r in grids.missed.rows %}{{ r.cells | join(' | ') }} {% endfor %} diff --git a/app/pdf/templates/forms/_macros.html b/app/pdf/templates/forms/_macros.html index cd49c85..aa0c824 100644 --- a/app/pdf/templates/forms/_macros.html +++ b/app/pdf/templates/forms/_macros.html @@ -45,7 +45,7 @@
{{ text }}
{% endmacro %} -{# Tour plan, standard tour plan and fare chart: MR signature plus the AM approval. #} +{# Tour plan, standard tour plan and fare chart: MR signature plus the ABM approval. #} {% macro sign_approval(approval) %} diff --git a/app/reports/models.py b/app/reports/models.py index 67c2cfc..c537d67 100644 --- a/app/reports/models.py +++ b/app/reports/models.py @@ -5,8 +5,8 @@ doctors and chemists they intend to visit, and an end-of-day ACTUAL report of th that happened. Both share this table and its call rows; the ACTUAL report points at its plan, and records why any planned visit was missed in ``missed_visit``. -An Area Manager files a SELF report of their own visits in the same table; ``mr_user_id`` -is then the Area Manager (the report's owner), and submitting it makes it final.""" +An Area Business Manager files a SELF report of their own visits in the same table; ``mr_user_id`` +is then the Area Business Manager (the report's owner), and submitting it makes it final.""" import uuid from datetime import date, datetime, time @@ -73,7 +73,7 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin): nullable=False, ) - #: SNAPSHOT of the reviewing AM / approving GM, so an HQ handover never rewrites + #: SNAPSHOT of the reviewing ABM / overseeing AGM, so an HQ handover never rewrites #: history (report §5.5). current_am_user_id: Mapped[uuid.UUID | None] = mapped_column( PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT") @@ -104,6 +104,9 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin): chemist_calls: Mapped[list["ChemistCall"]] = relationship( back_populates="dcr", cascade="all, delete-orphan", lazy="selectin" ) + stockist_calls: Mapped[list["StockistCall"]] = relationship( + back_populates="dcr", cascade="all, delete-orphan", lazy="selectin" + ) missed_visits: Mapped[list["MissedVisit"]] = relationship( back_populates="dcr", cascade="all, delete-orphan", lazy="selectin" ) @@ -184,18 +187,42 @@ class ChemistCall(Base, UUIDMixin, TimestampMixin): chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821 -class MissedVisit(Base, UUIDMixin, TimestampMixin): - """Why a doctor or chemist on the approved plan was not visited that day. +class StockistCall(Base, UUIDMixin, TimestampMixin): + __tablename__ = "stockist_call" + __table_args__ = ( + UniqueConstraint("dcr_id", "stockist_id", name="uq_call_dcr_stockist"), + ) - Belongs to the end-of-day report; exactly one of doctor/chemist is set. + dcr_id: Mapped[uuid.UUID] = mapped_column( + PGUUID(as_uuid=True), + ForeignKey("daily_call_report.id", ondelete="CASCADE"), + nullable=False, + ) + stockist_id: Mapped[uuid.UUID] = mapped_column( + PGUUID(as_uuid=True), ForeignKey("stockist.id", ondelete="RESTRICT"), nullable=False + ) + visit_time: Mapped[time] = mapped_column(Time, nullable=False) + #: Order booked with the stockist on this visit. + pob: Mapped[str | None] = mapped_column(String(100)) + remarks: Mapped[str | None] = mapped_column(Text) + + dcr: Mapped["DailyCallReport"] = relationship(back_populates="stockist_calls") + stockist: Mapped["Stockist"] = relationship(lazy="selectin") # noqa: F821 + + +class MissedVisit(Base, UUIDMixin, TimestampMixin): + """Why a doctor, chemist or stockist on the approved plan was not visited that day. + + Belongs to the end-of-day report; exactly one of doctor/chemist/stockist is set. """ __tablename__ = "missed_visit" __table_args__ = ( UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"), UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"), + UniqueConstraint("dcr_id", "stockist_id", name="uq_missed_dcr_stockist"), CheckConstraint( - "(doctor_id IS NULL) <> (chemist_id IS NULL)", name="ck_missed_one_target" + "num_nonnulls(doctor_id, chemist_id, stockist_id) = 1", name="ck_missed_one_target" ), ) @@ -210,6 +237,9 @@ class MissedVisit(Base, UUIDMixin, TimestampMixin): chemist_id: Mapped[uuid.UUID | None] = mapped_column( PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT") ) + stockist_id: Mapped[uuid.UUID | None] = mapped_column( + PGUUID(as_uuid=True), ForeignKey("stockist.id", ondelete="RESTRICT") + ) reason: Mapped[str] = mapped_column(Text, nullable=False) dcr: Mapped["DailyCallReport"] = relationship(back_populates="missed_visits") diff --git a/app/reports/repository.py b/app/reports/repository.py index 3d37513..21133a1 100644 --- a/app/reports/repository.py +++ b/app/reports/repository.py @@ -6,7 +6,7 @@ from sqlalchemy.orm import selectinload from app.common.enums import DCRStatus, ReportType from app.common.repository import BaseRepository -from app.reports.models import ChemistCall, DailyCallReport, DoctorCall +from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, StockistCall class DCRRepository(BaseRepository[DailyCallReport]): @@ -19,6 +19,7 @@ class DCRRepository(BaseRepository[DailyCallReport]): .options( selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor), selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist), + selectinload(DailyCallReport.stockist_calls).selectinload(StockistCall.stockist), selectinload(DailyCallReport.missed_visits), selectinload(DailyCallReport.mr), selectinload(DailyCallReport.headquarters), @@ -29,6 +30,9 @@ class DCRRepository(BaseRepository[DailyCallReport]): selectinload(DailyCallReport.plan) .selectinload(DailyCallReport.chemist_calls) .selectinload(ChemistCall.chemist), + selectinload(DailyCallReport.plan) + .selectinload(DailyCallReport.stockist_calls) + .selectinload(StockistCall.stockist), selectinload(DailyCallReport.actual), ) # The session keeps objects after commit (expire_on_commit=False), so without this the diff --git a/app/reports/router.py b/app/reports/router.py index 4cf5857..880aa03 100644 --- a/app/reports/router.py +++ b/app/reports/router.py @@ -12,6 +12,7 @@ from app.pdf.service import PDFService from app.reports.schemas import ( ApproveRequest, ChemistCallCreate, + StockistCallCreate, DCRCreate, DCRListItem, DCRRead, @@ -111,7 +112,7 @@ async def download_pdf( async def create_report( payload: DCRCreate, request: Request, - current_user: User = Depends(require_role(Role.MR, Role.AM)), + current_user: User = Depends(require_role(Role.MR, Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read(await DCRService(db).create(payload, current_user, client_ip(request))) @@ -122,7 +123,7 @@ async def update_report( dcr_id: uuid.UUID, payload: DCRUpdate, request: Request, - current_user: User = Depends(require_role(Role.MR, Role.AM)), + current_user: User = Depends(require_role(Role.MR, Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( @@ -137,7 +138,7 @@ async def add_doctor_call( dcr_id: uuid.UUID, payload: DoctorCallCreate, request: Request, - current_user: User = Depends(require_role(Role.MR, Role.AM)), + current_user: User = Depends(require_role(Role.MR, Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( @@ -150,7 +151,7 @@ async def add_chemist_call( dcr_id: uuid.UUID, payload: ChemistCallCreate, request: Request, - current_user: User = Depends(require_role(Role.MR, Role.AM)), + current_user: User = Depends(require_role(Role.MR, Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( @@ -158,12 +159,25 @@ async def add_chemist_call( ) +@router.post("/{dcr_id}/calls/stockist", response_model=DCRRead, status_code=201) +async def add_stockist_call( + dcr_id: uuid.UUID, + payload: StockistCallCreate, + request: Request, + current_user: User = Depends(require_role(Role.MR, Role.ABM)), + db: AsyncSession = Depends(get_db), +) -> DCRRead: + return to_read( + await DCRService(db).add_stockist_call(dcr_id, payload, current_user, client_ip(request)) + ) + + @router.delete("/{dcr_id}/calls/{call_id}", response_model=DCRRead) async def delete_call( dcr_id: uuid.UUID, call_id: uuid.UUID, request: Request, - current_user: User = Depends(require_role(Role.MR, Role.AM)), + current_user: User = Depends(require_role(Role.MR, Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( @@ -207,7 +221,7 @@ async def clear_missed_reason( async def submit( dcr_id: uuid.UUID, request: Request, - current_user: User = Depends(require_role(Role.MR, Role.AM)), + current_user: User = Depends(require_role(Role.MR, Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request))) @@ -218,7 +232,7 @@ async def return_report( dcr_id: uuid.UUID, payload: ReturnRequest, request: Request, - current_user: User = Depends(require_role(Role.AM)), + current_user: User = Depends(require_role(Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: return to_read( @@ -233,10 +247,10 @@ async def approve( dcr_id: uuid.UUID, payload: ApproveRequest, request: Request, - current_user: User = Depends(require_role(Role.AM)), + current_user: User = Depends(require_role(Role.ABM)), db: AsyncSession = Depends(get_db), ) -> DCRRead: - """Area Manager final approval (headquarters scope is enforced by the service).""" + """Area Business Manager final approval (headquarters scope is enforced by the service).""" return to_read( await DCRService(db).approve(dcr_id, payload.comment, current_user, client_ip(request)) ) diff --git a/app/reports/schemas.py b/app/reports/schemas.py index 1ee7bb6..5db2a08 100644 --- a/app/reports/schemas.py +++ b/app/reports/schemas.py @@ -52,6 +52,13 @@ class ChemistCallCreate(BaseModel): remarks: str | None = Field(default=None, max_length=2000) +class StockistCallCreate(BaseModel): + stockist_id: uuid.UUID + visit_time: time + pob: str | None = Field(default=None, max_length=100) + remarks: str | None = Field(default=None, max_length=2000) + + class DoctorCallRead(BaseModel): model_config = ConfigDict(from_attributes=True) @@ -80,10 +87,21 @@ class ChemistCallRead(BaseModel): remarks: str | None +class StockistCallRead(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: uuid.UUID + stockist_id: uuid.UUID + stockist_name: str + visit_time: time + pob: str | None + remarks: str | None + + class DCRCreate(BaseModel): report_date: date report_type: ReportType = ReportType.ACTUAL - #: SELF reports only: which of the Area Manager's headquarters the visits were in. + #: SELF reports only: which of the Area Business Manager's headquarters the visits were in. headquarters_id: uuid.UUID | None = None mr_remarks: str | None = Field(default=None, max_length=2000) doctor_calls: list[DoctorCallCreate] = Field(default_factory=list) @@ -97,10 +115,11 @@ class DCRUpdate(BaseModel): class MissedVisitSet(BaseModel): - """Why one planned doctor OR chemist was not visited (end-of-day report only).""" + """Why one planned doctor, chemist OR stockist was not visited (end-of-day report only).""" doctor_id: uuid.UUID | None = None chemist_id: uuid.UUID | None = None + stockist_id: uuid.UUID | None = None reason: str = Field(min_length=3, max_length=500) @@ -111,7 +130,7 @@ class PlannedVisitRead(BaseModel): PENDING — neither yet (the report cannot be submitted while any remain). """ - kind: Literal["DOCTOR", "CHEMIST"] + kind: Literal["DOCTOR", "CHEMIST", "STOCKIST"] target_id: uuid.UUID name: str is_core_doctor: bool @@ -176,6 +195,7 @@ class DCRRead(BaseModel): approved_at: datetime | None doctor_calls: list[DoctorCallRead] chemist_calls: list[ChemistCallRead] + stockist_calls: list[StockistCallRead] #: End-of-day report only: the approved plan, line by line, with what became of it. planned_visits: list[PlannedVisitRead] @@ -184,6 +204,6 @@ class StatusCounts(BaseModel): """Header counts on the list screens — the cheap replacement for dashboards.""" DRAFT: int = 0 - PENDING_AM: int = 0 + PENDING_ABM: int = 0 RETURNED: int = 0 APPROVED: int = 0 diff --git a/app/reports/serializers.py b/app/reports/serializers.py index 9712be2..2940f0a 100644 --- a/app/reports/serializers.py +++ b/app/reports/serializers.py @@ -7,6 +7,7 @@ from app.reports.schemas import ( DCRRead, DoctorCallRead, PlannedVisitRead, + StockistCallRead, ) @@ -15,8 +16,12 @@ def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]: plan = dcr.plan if plan is None: return [] - visited = {c.doctor_id for c in dcr.doctor_calls} | {c.chemist_id for c in dcr.chemist_calls} - missed = {m.doctor_id or m.chemist_id: m for m in dcr.missed_visits} + visited = ( + {c.doctor_id for c in dcr.doctor_calls} + | {c.chemist_id for c in dcr.chemist_calls} + | {c.stockist_id for c in dcr.stockist_calls} + ) + missed = {m.doctor_id or m.chemist_id or m.stockist_id: m for m in dcr.missed_visits} def line(kind, target_id, name, is_core, planned_time) -> PlannedVisitRead: note = missed.get(target_id) @@ -38,6 +43,9 @@ def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]: ] + [ line("CHEMIST", c.chemist_id, c.chemist.name, False, c.visit_time) for c in plan.chemist_calls + ] + [ + line("STOCKIST", c.stockist_id, c.stockist.name, False, c.visit_time) + for c in plan.stockist_calls ] return sorted(lines, key=lambda x: x.planned_time) @@ -91,6 +99,17 @@ def to_read(dcr: DailyCallReport) -> DCRRead: ) for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time) ], + stockist_calls=[ + StockistCallRead( + id=c.id, + stockist_id=c.stockist_id, + stockist_name=c.stockist.name, + visit_time=c.visit_time, + pob=c.pob, + remarks=c.remarks, + ) + for c in sorted(dcr.stockist_calls, key=lambda x: x.visit_time) + ], planned_visits=planned_visits(dcr), ) diff --git a/app/reports/service.py b/app/reports/service.py index 31032f5..4e284be 100644 --- a/app/reports/service.py +++ b/app/reports/service.py @@ -7,16 +7,19 @@ Plan / end-of-day rules (P1-P5): P1 A PLAN lists the visits the MR intends to make; it carries no outcomes, and its times are planned times, so they may be later than "now". P2 An ACTUAL (end-of-day) report can be created only once the PLAN for that date is - APPROVED by the Area Manager; it is linked to that plan. - P3 Every planned doctor/chemist must, before submit, either have a visit recorded on + APPROVED by the Area Business Manager; it is linked to that plan. + P3 Every planned doctor/chemist/stockist must, before submit, either have a visit recorded on the end-of-day report or a short note saying why it was missed. P4 Recording a visit for a doctor/chemist drops any "missed" note for them. P5 Visits not on the plan may still be added to the end-of-day report. -Area Manager's own report (S1-S3): - S1 An Area Manager files one SELF report per date, for one headquarters they manage; +Area Business Manager's own report (S1-S3): + S1 An Area Business Manager files one SELF report per date, for one headquarters they manage; it needs no plan. - S2 Its visits may be to any active doctor or chemist of that headquarters. + S2 Its visits may be to any active doctor, chemist or stockist of that headquarters. + +Stockists are not assigned to an MR: an MR (or SFE) may visit any active stockist of the +headquarters they cover. S3 There is no approval: submitting it makes it final (APPROVED, locked, PDF stored). """ @@ -51,9 +54,16 @@ from app.common.exceptions import ( from app.common.utils import local_now, local_today, snapshot, utcnow from app.config.settings import settings from app.doctors.models import Doctor, DoctorAssignment -from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit +from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit, StockistCall from app.reports.repository import DCRRepository -from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate, MissedVisitSet +from app.reports.schemas import ( + ChemistCallCreate, + DCRCreate, + DoctorCallCreate, + MissedVisitSet, + StockistCallCreate, +) +from app.stockists.models import Stockist from app.reports.serializers import planned_visits from app.users.models import User @@ -73,7 +83,7 @@ _AUDIT_FIELDS = [ #: Who files (and alone may edit or submit) each type of report. -_OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.AM})} +_OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.ABM})} _LABEL = { ReportType.PLAN: "Daily Call Report (Plan)", ReportType.ACTUAL: "Daily Call Report (Done)", @@ -146,8 +156,23 @@ class DCRService: ) return set((await self.db.execute(stmt)).scalars().all()) + async def _allowed_stockist_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]: + """Active stockists of the report's headquarters (SELF), or of every headquarters + the MR / SFE covers.""" + hq_ids = ( + {dcr.headquarters_id} + if dcr.report_type == ReportType.SELF + else dcr.mr.covered_headquarter_ids or {dcr.headquarters_id} + ) + stmt = select(Stockist.id).where( + Stockist.headquarters_id.in_(hq_ids), + Stockist.is_active.is_(True), + Stockist.approval_status == MasterApproval.APPROVED, + ) + return set((await self.db.execute(stmt)).scalars().all()) + async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]: - # A doctor the MR added is visitable only once the Area Manager has approved it. + # A doctor the MR added is visitable only once the Area Business Manager has approved it. stmt = ( select(DoctorAssignment.doctor_id) .join(Doctor, Doctor.id == DoctorAssignment.doctor_id) @@ -230,6 +255,25 @@ class DCRService: remarks=payload.remarks, ) + async def _build_stockist_call( + self, dcr: DailyCallReport, payload: StockistCallCreate, allowed: set[uuid.UUID] + ) -> StockistCall: + if payload.stockist_id not in allowed: + raise ValidationError( + "Stockist is not in this report's headquarters" + if dcr.report_type == ReportType.SELF + else "Stockist is not in a headquarters you cover", + {"stockist_id": str(payload.stockist_id)}, + ) + is_plan = dcr.report_type == ReportType.PLAN + return StockistCall( + dcr_id=dcr.id, + stockist_id=payload.stockist_id, + visit_time=payload.visit_time, + pob=None if is_plan else _clean(payload.pob), + remarks=payload.remarks, + ) + # ------------------------------------------------------------------ # Commands # ------------------------------------------------------------------ @@ -238,8 +282,8 @@ class DCRService: self, data: DCRCreate, actor: User, ip: str | None = None ) -> DailyCallReport: if data.report_type == ReportType.SELF: - if actor.role != Role.AM: - raise ForbiddenError("Only an Area Manager files a Daily Call Report (Self)") + if actor.role != Role.ABM: + raise ForbiddenError("Only an Area Business Manager files a Daily Call Report (Self)") headquarters_id = await self._self_report_hq(actor, data.headquarters_id) elif actor.role not in FIELD_ROLES: raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)") @@ -403,6 +447,36 @@ class DCRService: await self.db.commit() return await self.repo.get_full(dcr.id) + async def add_stockist_call( + self, dcr_id: uuid.UUID, payload: StockistCallCreate, actor: User, ip: str | None = None + ) -> DailyCallReport: + dcr = await self._get_owned_editable(dcr_id, actor) + allowed = await self._allowed_stockist_ids(dcr) + call = await self._build_stockist_call(dcr, payload, allowed) + self._validate_visit_time(dcr, payload.visit_time) + self.db.add(call) + + try: + await self.db.flush() + except IntegrityError as exc: + await self.db.rollback() + raise ConflictError( + "This stockist has already been called on this report", + {"stockist_id": str(payload.stockist_id), "cause": "uq_call_dcr_stockist"}, + ) from exc + + await self._drop_missed_note(dcr, stockist_id=payload.stockist_id) + await self.audit.log( + actor_user_id=actor.id, + entity_type=EntityType.DCR, + entity_id=dcr.id, + action=AuditAction.UPDATE, + after={"added_stockist_call": str(payload.stockist_id)}, + ip_address=ip, + ) + await self.db.commit() + return await self.repo.get_full(dcr.id) + def _validate_visit_time(self, dcr: DailyCallReport, visit_time) -> None: """V11 — a visit time on today's report cannot be in the future (P1: plans excepted).""" if dcr.report_type != ReportType.PLAN and dcr.report_date == local_today(): @@ -417,7 +491,11 @@ class DCRService: self, dcr_id: uuid.UUID, call_id: uuid.UUID, actor: User, ip: str | None = None ) -> DailyCallReport: dcr = await self._get_owned_editable(dcr_id, actor) - call = await self.db.get(DoctorCall, call_id) or await self.db.get(ChemistCall, call_id) + call = ( + await self.db.get(DoctorCall, call_id) + or await self.db.get(ChemistCall, call_id) + or await self.db.get(StockistCall, call_id) + ) if call is None or call.dcr_id != dcr.id: raise NotFoundError("Call not found on this report", {"call_id": str(call_id)}) await self.db.delete(call) @@ -435,30 +513,36 @@ class DCRService: async def set_missed_reason( self, dcr_id: uuid.UUID, payload: MissedVisitSet, actor: User, ip: str | None = None ) -> DailyCallReport: - """P3 — record (or reword) why a planned doctor/chemist was not visited.""" + """P3 — record (or reword) why a planned doctor/chemist/stockist was not visited.""" dcr = await self._get_owned_editable(dcr_id, actor) if dcr.report_type != ReportType.ACTUAL or dcr.plan is None: raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)") - if (payload.doctor_id is None) == (payload.chemist_id is None): - raise ValidationError("Give exactly one of doctor_id or chemist_id") + targets = [t for t in (payload.doctor_id, payload.chemist_id, payload.stockist_id) if t] + if len(targets) != 1: + raise ValidationError("Give exactly one of doctor_id, chemist_id or stockist_id") reason = _clean(payload.reason) if reason is None: raise ValidationError("Say briefly why the visit was missed") - target_id = payload.doctor_id or payload.chemist_id + target_id = targets[0] line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None) if line is None: raise ValidationError( - "This doctor or chemist is not on the plan", {"target_id": str(target_id)} + "This doctor, chemist or stockist is not on the plan", {"target_id": str(target_id)} ) if line.status == "VISITED": raise ConflictError( - "A visit is already recorded for this doctor or chemist; remove it first", + "A visit is already recorded for this doctor, chemist or stockist; remove it first", {"target_id": str(target_id)}, ) note = next( - (m for m in dcr.missed_visits if (m.doctor_id or m.chemist_id) == target_id), None + ( + m + for m in dcr.missed_visits + if (m.doctor_id or m.chemist_id or m.stockist_id) == target_id + ), + None, ) before = {"reason": note.reason} if note else None if note is None: @@ -467,6 +551,7 @@ class DCRService: dcr_id=dcr.id, doctor_id=payload.doctor_id, chemist_id=payload.chemist_id, + stockist_id=payload.stockist_id, reason=reason, ) ) @@ -499,7 +584,10 @@ class DCRService: entity_type=EntityType.DCR, entity_id=dcr.id, action=AuditAction.DELETE, - before={"missed_visit": str(note.doctor_id or note.chemist_id), "reason": note.reason}, + before={ + "missed_visit": str(note.doctor_id or note.chemist_id or note.stockist_id), + "reason": note.reason, + }, ip_address=ip, ) await self.db.commit() @@ -522,7 +610,7 @@ class DCRService: if dcr.report_type == ReportType.SELF: return await self._finalise_self_report(dcr, actor, ip) - if dcr.status == DCRStatus.PENDING_AM: + if dcr.status == DCRStatus.PENDING_ABM: return dcr # already submitted (a double click): nothing more to do transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role) @@ -552,7 +640,7 @@ class DCRService: async def _finalise_self_report( self, dcr: DailyCallReport, actor: User, ip: str | None ) -> DailyCallReport: - """S3 — an Area Manager's own report is final once submitted; nobody approves it.""" + """S3 — an Area Business Manager's own report is final once submitted; nobody approves it.""" if dcr.status == DCRStatus.APPROVED: return dcr # already submitted (a double click) assert_editable(dcr.status) @@ -606,9 +694,9 @@ class DCRService: async def approve( self, dcr_id: uuid.UUID, comment: str | None, actor: User, ip: str | None = None ) -> DailyCallReport: - """Area Manager final approval. APPROVED is terminal and immutable.""" + """Area Business Manager final approval. APPROVED is terminal and immutable.""" dcr = await self._get_in_scope(dcr_id, actor) - if dcr.status == DCRStatus.APPROVED and actor.role == Role.AM: + if dcr.status == DCRStatus.APPROVED and actor.role == Role.ABM: return dcr # already approved (a double click): the report stays as it is transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role) @@ -661,9 +749,9 @@ class DCRService: async def list_for( self, actor: User, headquarters_id: uuid.UUID | None = None, **filters ) -> list[DailyCallReport]: - # An Area Manager's SELF list is their own reports, not their headquarters'. + # An Area Business Manager's SELF list is their own reports, not their headquarters'. if actor.role in FIELD_ROLES or ( - actor.role == Role.AM and filters.get("report_type") == ReportType.SELF + actor.role == Role.ABM and filters.get("report_type") == ReportType.SELF ): return await self.repo.list_scoped(mr_user_id=actor.id, **filters) hq_ids = await self._hq_scope(actor, headquarters_id) @@ -692,7 +780,7 @@ class DCRService: return dcr async def _self_report_hq(self, actor: User, headquarters_id: uuid.UUID | None) -> uuid.UUID: - """S1 — one of the headquarters this Area Manager manages; implied when there is one.""" + """S1 — one of the headquarters this Area Business Manager manages; implied when there is one.""" managed = await active_hq_ids_for_am(self.db, actor.id) if headquarters_id is None and len(managed) == 1: return next(iter(managed)) @@ -711,14 +799,14 @@ class DCRService: def _check_submit_contents(self, dcr: DailyCallReport) -> None: if dcr.report_type == ReportType.PLAN: - if not dcr.doctor_calls and not dcr.chemist_calls: - raise ValidationError("Plan at least one doctor or chemist visit to submit") + if not dcr.doctor_calls and not dcr.chemist_calls and not dcr.stockist_calls: + raise ValidationError("Plan at least one doctor, chemist or stockist visit to submit") return # P3 — every planned visit is either recorded or explained. pending = [p for p in planned_visits(dcr) if p.status == "PENDING"] if pending: raise ValidationError( - "Record a visit or add a missed-visit note for every planned doctor and chemist", + "Record a visit or add a missed-visit note for every planned doctor, chemist and stockist", {"pending": [p.name for p in pending]}, ) # V4 — at least one doctor call, unless the planned visits were all explained. @@ -737,7 +825,7 @@ class DCRService: if plan.status != DCRStatus.APPROVED: raise ValidationError( "Your Daily Call Report (Plan) for this date must be approved " - "by the Area Manager first", + "by the Area Business Manager first", {"report_date": report_date.isoformat(), "plan_status": plan.status.value}, ) return plan @@ -747,18 +835,21 @@ class DCRService: dcr: DailyCallReport, doctor_id: uuid.UUID | None = None, chemist_id: uuid.UUID | None = None, + stockist_id: uuid.UUID | None = None, ) -> None: """P4 — a recorded visit replaces any note saying it was missed.""" for note in dcr.missed_visits: - if (doctor_id and note.doctor_id == doctor_id) or ( - chemist_id and note.chemist_id == chemist_id + if ( + (doctor_id and note.doctor_id == doctor_id) + or (chemist_id and note.chemist_id == chemist_id) + or (stockist_id and note.stockist_id == stockist_id) ): await self.db.delete(note) async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None: from app.organization.models import AMHeadquarters - # Recorded only; any Area Manager of the headquarters may act on the report. + # Recorded only; any Area Business Manager of the headquarters may act on the report. stmt = ( select(AMHeadquarters.area_manager_user_id) .where( diff --git a/app/stockists/__init__.py b/app/stockists/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/app/stockists/__init__.py @@ -0,0 +1 @@ + diff --git a/app/stockists/models.py b/app/stockists/models.py new file mode 100644 index 0000000..6920a11 --- /dev/null +++ b/app/stockists/models.py @@ -0,0 +1,46 @@ +"""Stockist master data.""" + +import uuid + +from sqlalchemy import Boolean, ForeignKey, String, UniqueConstraint +from sqlalchemy.dialects.postgresql import UUID as PGUUID +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.common.enums import MasterApproval +from app.database.base import Base, TimestampMixin, UUIDMixin + + +class Stockist(Base, UUIDMixin, TimestampMixin): + __tablename__ = "stockist" + __table_args__ = ( + UniqueConstraint( + "headquarters_id", "name", "address", name="uq_stockist_hq_name_address" + ), + ) + + headquarters_id: Mapped[uuid.UUID] = mapped_column( + PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False + ) + name: Mapped[str] = mapped_column(String(200), nullable=False) + address: Mapped[str] = mapped_column(String(500), nullable=False) + contact_number: Mapped[str | None] = mapped_column(String(20)) + is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) + approval_status: Mapped[str] = mapped_column( + String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False + ) + requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column( + PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL") + ) + rejection_reason: Mapped[str | None] = mapped_column(String(500)) + requested_by: Mapped["User | None"] = relationship( # noqa: F821 + lazy="selectin", foreign_keys=[requested_by_user_id] + ) + + @property + def requested_by_name(self) -> str | None: + return self.requested_by.full_name if self.requested_by else None + + @property + def shop_address(self) -> str: + return self.address + diff --git a/app/stockists/router.py b/app/stockists/router.py new file mode 100644 index 0000000..b63b1c7 --- /dev/null +++ b/app/stockists/router.py @@ -0,0 +1,82 @@ +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.doctors.schemas import RejectMaster +from app.stockists.models import Stockist +from app.stockists.schemas import StockistCreate, StockistRead, StockistUpdate +from app.stockists.service import StockistService +from app.users.models import User + +router = APIRouter(prefix="/stockists", tags=["stockists"]) + + +@router.get("", response_model=list[StockistRead]) +async def list_stockists( + current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) +) -> list[StockistRead]: + service = StockistService(db) + stockists = await service.list_for(current_user) + names = await service.mr_names_by_hq({s.headquarters_id for s in stockists}) + return [ + StockistRead.model_validate(s).model_copy(update={"assigned_mr_name": names.get(s.headquarters_id)}) + for s in stockists + ] + + +@router.post("", response_model=StockistRead, status_code=status.HTTP_201_CREATED) +async def create_stockist( + payload: StockistCreate, + request: Request, + current_user: User = Depends(require_role(Role.ADMIN, Role.MR)), + db: AsyncSession = Depends(get_db), +) -> Stockist: + """An Administrator (listed at once), or an MR within their own headquarters (waits for the + Area Business Manager).""" + return await StockistService(db).create(payload, current_user, client_ip(request)) + + +@router.patch("/{stockist_id}", response_model=StockistRead) +async def update_stockist( + stockist_id: uuid.UUID, + payload: StockistUpdate, + request: Request, + current_user: User = Depends(require_role(Role.ADMIN)), + db: AsyncSession = Depends(get_db), +) -> Stockist: + return await StockistService(db).update(stockist_id, payload, current_user, client_ip(request)) + + + +@router.get("/requests", response_model=list[StockistRead]) +async def list_stockist_requests( + current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) +) -> list[Stockist]: + """Stockists an MR added that wait for the Area Business Manager: an MR sees their own (with any + rejected and why), an Area Business Manager what waits for them, the administrator and AGM all.""" + return await StockistService(db).requests_for(current_user) + + +@router.post("/{stockist_id}/approve", response_model=StockistRead) +async def approve_stockist( + stockist_id: uuid.UUID, + request: Request, + current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)), + db: AsyncSession = Depends(get_db), +) -> Stockist: + return await StockistService(db).review(stockist_id, True, None, current_user, client_ip(request)) + + +@router.post("/{stockist_id}/reject", response_model=StockistRead) +async def reject_stockist( + stockist_id: uuid.UUID, + payload: RejectMaster, + request: Request, + current_user: User = Depends(require_role(Role.ABM, Role.ADMIN)), + db: AsyncSession = Depends(get_db), +) -> Stockist: + return await StockistService(db).review(stockist_id, False, payload.reason, current_user, client_ip(request)) diff --git a/app/stockists/schemas.py b/app/stockists/schemas.py new file mode 100644 index 0000000..fecffff --- /dev/null +++ b/app/stockists/schemas.py @@ -0,0 +1,58 @@ +import uuid +from datetime import datetime + +from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator + + +class StockistCreate(BaseModel): + headquarters_id: uuid.UUID + name: str = Field(min_length=2, max_length=200) + address: str | None = Field(default=None, min_length=2, max_length=500) + shop_address: str | None = Field(default=None, min_length=2, max_length=500) + contact_number: str | None = Field(default=None, max_length=20) + + @model_validator(mode="after") + def resolve_address(self) -> "StockistCreate": + if not self.address and not self.shop_address: + raise ValueError("Address is required") + if not self.address: + self.address = self.shop_address + return self + + +class StockistUpdate(BaseModel): + headquarters_id: uuid.UUID | None = None + name: str | None = Field(default=None, min_length=2, max_length=200) + address: str | None = Field(default=None, min_length=2, max_length=500) + shop_address: str | None = Field(default=None, min_length=2, max_length=500) + contact_number: str | None = Field(default=None, max_length=20) + is_active: bool | None = None + + @model_validator(mode="after") + def resolve_address(self) -> "StockistUpdate": + if self.address is None and self.shop_address is not None: + self.address = self.shop_address + return self + + +class StockistRead(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: uuid.UUID + headquarters_id: uuid.UUID + name: str + address: str + contact_number: str | None + is_active: bool + approval_status: str + rejection_reason: str | None + requested_by_name: str | None + created_at: datetime + #: Filled by the list endpoint only: the MRs working this stockist's headquarters. + assigned_mr_name: str | None = None + + @computed_field + @property + def shop_address(self) -> str: + return self.address + diff --git a/app/stockists/service.py b/app/stockists/service.py new file mode 100644 index 0000000..f9227cf --- /dev/null +++ b/app/stockists/service.py @@ -0,0 +1,154 @@ +import uuid + +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 assert_can_view_hq, visible_hq_ids +from app.common import master_approval +from app.common.enums import FIELD_ROLES, AuditAction, EntityType, MasterApproval +from app.common.exceptions import ConflictError, NotFoundError +from app.common.master_edit import commit_unique, move_headquarters +from app.common.utils import snapshot +from app.stockists.models import Stockist +from app.stockists.schemas import StockistCreate, StockistUpdate +from app.users.models import User, UserExtraHeadquarters + +_AUDIT_FIELDS = ["headquarters_id", "name", "address", "contact_number", "is_active"] + + +class StockistService: + def __init__(self, db: AsyncSession) -> None: + self.db = db + self.audit = AuditService(db) + + async def create(self, data: StockistCreate, actor: User, ip: str | None = None) -> Stockist: + await assert_can_view_hq(self.db, actor, data.headquarters_id) + + values = data.model_dump(exclude_unset=True) + if "address" not in values and "shop_address" in values: + values["address"] = values.pop("shop_address") + else: + values.pop("shop_address", None) + + # Added by an MR: it waits for the Area Business Manager. One they were refused is sent again. + if actor.role in FIELD_ROLES: + twin = await master_approval.rejected_twin( + self.db, Stockist, {k: values[k] for k in ("headquarters_id", "name", "address")} + ) + if twin is not None: + await master_approval.resubmit(self.db, twin, values, actor) + await self.audit.log( + actor_user_id=actor.id, + entity_type=EntityType.STOCKIST, + entity_id=twin.id, + action=AuditAction.SUBMIT, + after=snapshot(twin, _AUDIT_FIELDS), + ip_address=ip, + ) + await self.db.commit() + await self.db.refresh(twin) + return twin + + stockist = Stockist( + **values, + approval_status=master_approval.initial_status(actor), + requested_by_user_id=actor.id if actor.role in FIELD_ROLES else None, + ) + self.db.add(stockist) + try: + await self.db.flush() + except IntegrityError as exc: + await self.db.rollback() + raise ConflictError( + "A stockist with this name already exists at this address in this headquarters", + {"cause": "uq_stockist_hq_name_address"}, + ) from exc + + await self.audit.log( + actor_user_id=actor.id, + entity_type=EntityType.STOCKIST, + entity_id=stockist.id, + action=AuditAction.CREATE, + after=snapshot(stockist, _AUDIT_FIELDS), + ip_address=ip, + ) + await self.db.commit() + await self.db.refresh(stockist) + return stockist + + async def update( + self, stockist_id: uuid.UUID, data: StockistUpdate, actor: User, ip: str | None = None + ) -> Stockist: + stockist = await self.db.get(Stockist, stockist_id) + if stockist is None: + raise NotFoundError("Stockist not found") + await assert_can_view_hq(self.db, actor, stockist.headquarters_id) + + before = snapshot(stockist, _AUDIT_FIELDS) + update_data = data.model_dump(exclude_unset=True) + new_hq = update_data.pop("headquarters_id", None) + if new_hq is not None: + await move_headquarters(self.db, actor, stockist, new_hq) + if "shop_address" in update_data and "address" not in update_data: + update_data["address"] = update_data.pop("shop_address") + else: + update_data.pop("shop_address", None) + + for field, value in update_data.items(): + setattr(stockist, field, value) + + await self.audit.log( + actor_user_id=actor.id, + entity_type=EntityType.STOCKIST, + entity_id=stockist.id, + action=AuditAction.UPDATE, + before=before, + after=snapshot(stockist, _AUDIT_FIELDS), + ip_address=ip, + ) + await commit_unique(self.db, "A stockist with this name already exists at this address in this headquarters") + return stockist + + async def mr_names_by_hq(self, hq_ids: set[uuid.UUID]) -> dict[uuid.UUID, str]: + """Stockists are not assigned to one MR: the active MRs / SFEs working each headquarters + (their own headquarters or an extra one), comma-joined, by headquarters id.""" + if not hq_ids: + return {} + field = (User.is_active.is_(True), User.role.in_(list(FIELD_ROLES))) + primary = select(User.headquarters_id, User.full_name).where(User.headquarters_id.in_(hq_ids), *field) + extra = ( + select(UserExtraHeadquarters.headquarters_id, User.full_name) + .join(User, User.id == UserExtraHeadquarters.user_id) + .where(UserExtraHeadquarters.headquarters_id.in_(hq_ids), *field) + ) + names: dict[uuid.UUID, set[str]] = {} + for stmt in (primary, extra): + for hq_id, name in (await self.db.execute(stmt)).all(): + names.setdefault(hq_id, set()).add(name) + return {hq_id: ", ".join(sorted(n)) for hq_id, n in names.items()} + + async def list_for(self, actor: User) -> list[Stockist]: + allowed = await visible_hq_ids(self.db, actor) + stmt = ( + select(Stockist) + .where(Stockist.approval_status == MasterApproval.APPROVED) + .order_by(Stockist.name) + ) + if actor.role in FIELD_ROLES: + stmt = stmt.where(Stockist.is_active.is_(True)) + if allowed is not None: + stmt = stmt.where(Stockist.headquarters_id.in_(allowed or [None])) + return list((await self.db.execute(stmt)).scalars().all()) + + + async def requests_for(self, actor: User) -> list[Stockist]: + return await master_approval.requests_for(self.db, Stockist, actor) + + async def review( + self, stockist_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None + ) -> Stockist: + return await master_approval.review( + self.db, Stockist, EntityType.STOCKIST, stockist_id, approve, reason, actor, ip + ) diff --git a/app/users/overview.py b/app/users/overview.py index 6ce8c4a..f71ffa9 100644 --- a/app/users/overview.py +++ b/app/users/overview.py @@ -1,4 +1,4 @@ -"""One person's whole picture for the General Manager and Admin: who they are, where they +"""One person's whole picture for the Assistant General Manager and Admin: who they are, where they work, who they report to, their doctors and chemists, their reports and their company forms.""" import uuid @@ -139,7 +139,7 @@ async def user_overview(db: AsyncSession, actor: User, user_id: uuid.UUID) -> di data["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in recent] data["forms"] = await _forms(db, user) - elif user.role == Role.AM: + elif user.role == Role.ABM: managed = ( await db.execute( select(Headquarters) diff --git a/app/users/router.py b/app/users/router.py index 2dbcf9e..eaf3d5e 100644 --- a/app/users/router.py +++ b/app/users/router.py @@ -24,17 +24,17 @@ async def my_profile( @router.get("/{user_id}/overview") async def user_overview( user_id: uuid.UUID, - current_user: User = Depends(require_role(Role.ADMIN, Role.GM)), + current_user: User = Depends(require_role(Role.ADMIN, Role.AGM)), db: AsyncSession = Depends(get_db), ) -> dict: - """The whole picture of one person, for the General Manager and Admin.""" + """The whole picture of one person, for the Assistant General Manager and Admin.""" return await overview.user_overview(db, current_user, user_id) @router.get("", response_model=list[UserRead]) async def list_users( role: Role | None = None, - current_user: User = Depends(require_role(Role.ADMIN, Role.GM)), + current_user: User = Depends(require_role(Role.ADMIN, Role.AGM)), db: AsyncSession = Depends(get_db), ) -> list[User]: return await UserService(db).list_users(current_user, role) diff --git a/app/users/schemas.py b/app/users/schemas.py index a8cfbd2..7b82cae 100644 --- a/app/users/schemas.py +++ b/app/users/schemas.py @@ -36,7 +36,7 @@ class UserUpdate(BaseModel): #: A new password. Signs the user out everywhere and clears a lockout. password: str | None = Field(default=None, min_length=8, max_length=128) phone: str | None = Field(default=None, max_length=20) - #: Admin-only. Moving to MR needs `headquarters_id`; leaving MR or AM ends that role's + #: Admin-only. Moving to MR needs `headquarters_id`; leaving MR or ABM ends that role's #: assignments, and the user is signed out so they sign in again with the new role. role: Role | None = None headquarters_id: uuid.UUID | None = None @@ -61,7 +61,7 @@ class UserRead(BaseModel): class MyProfile(BaseModel): - """S4 — the MR profile screen. Includes the DERIVED reporting Area Manager.""" + """S4 — the MR profile screen. Includes the DERIVED reporting Area Business Manager.""" id: uuid.UUID full_name: str diff --git a/app/users/service.py b/app/users/service.py index 364684a..89da0cf 100644 --- a/app/users/service.py +++ b/app/users/service.py @@ -175,14 +175,14 @@ class UserService: return user async def _end_role_assignments(self, user_id: uuid.UUID, old_role: Role) -> dict[str, int]: - """Close what the old role held: an MR's doctors and chemists, an AM's headquarters.""" + """Close what the old role held: an MR's doctors and chemists, an ABM's headquarters.""" today = date.today() if old_role in FIELD_ROLES: targets = [ ("doctors", DoctorAssignment, DoctorAssignment.mr_user_id), ("chemists", ChemistAssignment, ChemistAssignment.mr_user_id), ] - elif old_role == Role.AM: + elif old_role == Role.ABM: targets = [("headquarters", AMHeadquarters, AMHeadquarters.area_manager_user_id)] else: return {} @@ -204,7 +204,7 @@ class UserService: return list((await self.db.execute(stmt)).scalars().all()) async def my_profile(self, user: User) -> MyProfile: - """S4 — includes the reporting Area Manager DERIVED through the headquarters.""" + """S4 — includes the reporting Area Business Manager DERIVED through the headquarters.""" hq_code = hq_name = None manager_id = manager_name = None @@ -221,7 +221,7 @@ class UserService: AMHeadquarters.effective_to.is_(None), ) ) - # A headquarters may have several Area Managers: name every one. + # A headquarters may have several Area Business Managers: name every one. managers = list((await self.db.execute(stmt.order_by(User.full_name))).scalars()) if managers: manager_id = managers[0].id diff --git a/openapi.json b/openapi.json index fe53d0b..6a947b2 100644 --- a/openapi.json +++ b/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "Pharma Field Force Reporting", - "description": "Pharmaceutical field-force reporting \u2014 MVP. One MR, Daily Call Report, AM review, GM approval, locked PDF, audit trail.", + "description": "Pharmaceutical field-force reporting \u2014 MVP. MRs file Daily Call Reports, ABMs review and approve them, and AGMs have a read-only overview.", "version": "0.1.0" }, "paths": { @@ -325,7 +325,7 @@ "organization" ], "summary": "List Headquarters", - "description": "Scoped: an MR sees their own HQ, an AM sees theirs, GM/Admin see all.", + "description": "Scoped: an MR sees their own HQ, an ABM sees theirs, AGM/Admin see all.", "operationId": "list_headquarters_api_v1_headquarters_get", "responses": { "200": { @@ -399,7 +399,7 @@ "tags": [ "organization" ], - "summary": "Assign Area Manager", + "summary": "Assign Area Business Manager", "operationId": "assign_area_manager_api_v1_headquarters__headquarters_id__area_manager_post", "security": [ { @@ -592,7 +592,7 @@ "doctors" ], "summary": "Assign Doctor", - "description": "An AM may assign only within their own headquarters \u2014 enforced by data scope.", + "description": "An ABM may assign only within their own headquarters \u2014 enforced by data scope.", "operationId": "assign_doctor_api_v1_doctors__doctor_id__assign_post", "security": [ { @@ -1397,7 +1397,7 @@ "reports" ], "summary": "Forward", - "description": "The Area Manager forwards or returns \u2014 it does NOT approve (A4/Q4).", + "description": "The Area Business Manager forwards or returns \u2014 it does NOT approve (A4/Q4).", "operationId": "forward_api_v1_dcr__dcr_id__forward_post", "security": [ { @@ -1514,7 +1514,7 @@ "reports" ], "summary": "Approve", - "description": "GM only. SEC-2: ADMIN is absent from this dependency by design.", + "description": "AGM only. SEC-2: ADMIN is absent from this dependency by design.", "operationId": "approve_api_v1_dcr__dcr_id__approve_post", "security": [ { @@ -1719,7 +1719,7 @@ "area_manager_user_id": { "type": "string", "format": "uuid", - "title": "Area Manager User Id" + "title": "Area Business Manager User Id" }, "headquarters_id": { "type": "string", @@ -1818,7 +1818,7 @@ "area_manager_user_id": { "type": "string", "format": "uuid", - "title": "Area Manager User Id" + "title": "Area Business Manager User Id" }, "effective_from": { "anyOf": [ @@ -2530,13 +2530,13 @@ "type": "string", "enum": [ "DRAFT", - "PENDING_AM", + "PENDING_ABM", "PENDING_GM", "RETURNED", "APPROVED" ], "title": "DCRStatus", - "description": "5 states, down from the 7 originally proposed.\n\n- \"Returned by AM\" and \"Returned by GM\" collapse into RETURNED; who returned it\n is stored in `returned_by_role`, which is data, not state.\n- \"Finally Approved\" and \"Locked\" collapse into APPROVED. Immutability is a\n property of APPROVED enforced in one guard, not a second status." + "description": "5 states, down from the 7 originally proposed.\n\n- \"Returned by ABM\" and \"Returned by AGM\" collapse into RETURNED; who returned it\n is stored in `returned_by_role`, which is data, not state.\n- \"Finally Approved\" and \"Locked\" collapse into APPROVED. Immutability is a\n property of APPROVED enforced in one guard, not a second status." }, "DCRUpdate": { "properties": { @@ -2806,6 +2806,17 @@ "is_active": { "type": "boolean", "title": "Is Active" + }, + "assigned_mr_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Assigned Mr Name" } }, "type": "object", @@ -3185,7 +3196,7 @@ "reporting_manager_name" ], "title": "MyProfile", - "description": "S4 \u2014 the MR profile screen. Includes the DERIVED reporting Area Manager." + "description": "S4 \u2014 the MR profile screen. Includes the DERIVED reporting Area Business Manager." }, "RefreshRequest": { "properties": { @@ -3220,12 +3231,12 @@ "type": "string", "enum": [ "ADMIN", - "GM", - "AM", + "AGM", + "ABM", "MR" ], "title": "Role", - "description": "Operational roles (MR/AM/GM) plus the technical ADMIN role.\n\nADMIN sits OUTSIDE the business hierarchy. It provisions users and masters but\ncan never approve a report or read report content (report \u00a78, SEC-2)." + "description": "Operational roles (MR/ABM/AGM) plus the technical ADMIN role.\n\nADMIN sits OUTSIDE the business hierarchy. It provisions users and masters, may monitor and read reports, but can never approve one (report \u00a78, SEC-2)." }, "StatusCounts": { "properties": { @@ -3234,7 +3245,7 @@ "title": "Draft", "default": 0 }, - "PENDING_AM": { + "PENDING_ABM": { "type": "integer", "title": "Pending Am", "default": 0 diff --git a/scripts/seed.py b/scripts/seed.py index 4fba7e9..5da48f1 100644 --- a/scripts/seed.py +++ b/scripts/seed.py @@ -1,6 +1,6 @@ """Seed the minimum MVP system described in report §10.2. -Creates: 1 company, 1 headquarters, 1 GM, 1 AM, 1 MR, 1 System Admin, +Creates: 1 company, 1 headquarters, 1 AGM, 1 ABM, 1 MR, 1 System Admin, 15 doctors (3 flagged as core) and 5 chemists, all assigned to the MR. python -m scripts.seed @@ -64,8 +64,8 @@ async def seed() -> None: ) admin = make(Role.ADMIN, "System Administrator", "ADM001") - gm = make(Role.GM, "Anita Mohanty", "GM001") - am = make(Role.AM, "Suresh Behera", "AM001") + gm = make(Role.AGM, "Anita Mohanty", "GM001") + am = make(Role.ABM, "Suresh Behera", "AM001") mr = make(Role.MR, "Ravi Das", "MR001", hq.id) db.add_all([admin, gm, am, mr]) await db.flush() @@ -113,8 +113,8 @@ async def seed() -> None: print("Seeded the minimum MVP system.\n") print(f" Password for every account: {DEMO_PASSWORD}\n") print(" System Admin adm001@acmepharma.in") - print(" General Mgr gm001@acmepharma.in") - print(" Area Manager am001@acmepharma.in") + print(" Assistant General Manager (AGM) gm001@acmepharma.in") + print(" Area Business Manager (ABM) am001@acmepharma.in") print(" MR mr001@acmepharma.in") print("\n 1 headquarters (BBSR), 15 doctors (3 core), 5 chemists — all assigned to MR001.") print("\n CHANGE THESE PASSWORDS before any real use.") diff --git a/tests/conftest.py b/tests/conftest.py index a2fb757..deb1283 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -104,8 +104,8 @@ async def client(session_factory, tmp_path) -> AsyncGenerator[AsyncClient, None] # --------------------------------------------------------------------------- -# Organisation fixture: the minimum MVP system — 1 company, 2 HQs, GM, 2 AMs, 2 MRs. -# The second HQ/AM/MR exist purely so the negative-scope tests (X1, X2) have someone +# Organisation fixture: the minimum MVP system — 1 company, 2 HQs, AGM, 2 AMs, 2 MRs. +# The second HQ/ABM/MR exist purely so the negative-scope tests (X1, X2) have someone # to be denied. # --------------------------------------------------------------------------- @@ -142,9 +142,9 @@ async def org(db: AsyncSession) -> dict: ) admin = make(Role.ADMIN, "System Admin", "ADM001") - gm = make(Role.GM, "Anita Mohanty", "GM001") - am1 = make(Role.AM, "Suresh Behera", "AM001") - am2 = make(Role.AM, "Rakesh Sahu", "AM002") + gm = make(Role.AGM, "Anita Mohanty", "GM001") + am1 = make(Role.ABM, "Suresh Behera", "AM001") + am2 = make(Role.ABM, "Rakesh Sahu", "AM002") mr1 = make(Role.MR, "Ravi Das", "MR001", hq1.id) mr2 = make(Role.MR, "Priya Nayak", "MR002", hq2.id) db.add_all([admin, gm, am1, am2, mr1, mr2]) diff --git a/tests/e2e/test_area_manager_headquarters.py b/tests/e2e/test_area_manager_headquarters.py index b739279..d2c5d42 100644 --- a/tests/e2e/test_area_manager_headquarters.py +++ b/tests/e2e/test_area_manager_headquarters.py @@ -1,4 +1,4 @@ -"""An Area Manager can manage any number of headquarters; only an Admin can change that.""" +"""An Area Business Manager can manage any number of headquarters; only an Admin can change that.""" import uuid @@ -104,7 +104,7 @@ class TestAreaManagerHeadquarters: for who in ("gm", "am1", "mr1"): put = await client.put(f"{API}/area-managers/{org['am1'].id}", headers=auth[who], json=body) assert put.status_code == 403, (who, put.text) - # GM may read the mappings (to see who manages what), AM and MR may not. + # AGM may read the mappings (to see who manages what), ABM and MR may not. assert (await client.get(f"{API}/area-managers", headers=auth["gm"])).status_code == 200 for who in ("am1", "mr1"): assert (await client.get(f"{API}/area-managers", headers=auth[who])).status_code == 403 diff --git a/tests/e2e/test_day_plan.py b/tests/e2e/test_day_plan.py index b9a336c..4f04533 100644 --- a/tests/e2e/test_day_plan.py +++ b/tests/e2e/test_day_plan.py @@ -1,4 +1,4 @@ -"""Morning day plan → Area Manager approval → end-of-day report against it (rules P1-P5).""" +"""Morning day plan → Area Business Manager approval → end-of-day report against it (rules P1-P5).""" from datetime import date @@ -99,7 +99,7 @@ class TestEndOfDayNeedsAnApprovedPlan: await _plan(client, auth, doctors, [], approve=False) resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"}) assert resp.status_code == 422 - assert "approved by the Area Manager" in resp.json()["error"]["message"] + assert "approved by the Area Business Manager" in resp.json()["error"]["message"] async def test_once_approved_it_is_linked_to_the_plan(self, client, auth, org): doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1) diff --git a/tests/e2e/test_duplicate_requests.py b/tests/e2e/test_duplicate_requests.py index f27f938..6090f8d 100644 --- a/tests/e2e/test_duplicate_requests.py +++ b/tests/e2e/test_duplicate_requests.py @@ -48,7 +48,7 @@ class TestReports: first = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"]) second = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"]) assert first.status_code == second.status_code == 200 - assert second.json()["status"] == "PENDING_AM" + assert second.json()["status"] == "PENDING_ABM" assert second.json()["submitted_at"] == first.json()["submitted_at"] assert await _audit_count(db, dcr, "SUBMIT") == 1 @@ -93,7 +93,7 @@ class TestSetup: assert (await client.post(f"{API}/products", headers=auth["admin"], json=product)).status_code == 201 assert (await client.post(f"{API}/products", headers=auth["admin"], json=product)).status_code == 409 - user = {"email": "dup@acmepharma.in", "password": "Str0ngPass9", "full_name": "Dup User", "employee_code": "D1", "role": "GM"} + user = {"email": "dup@acmepharma.in", "password": "Str0ngPass9", "full_name": "Dup User", "employee_code": "D1", "role": "AGM"} assert (await client.post(f"{API}/users", headers=auth["admin"], json=user)).status_code == 201 assert (await client.post(f"{API}/users", headers=auth["admin"], json=user)).status_code == 409 diff --git a/tests/e2e/test_form_approval.py b/tests/e2e/test_form_approval.py index 2e79f6e..2c9ca34 100644 --- a/tests/e2e/test_form_approval.py +++ b/tests/e2e/test_form_approval.py @@ -30,7 +30,7 @@ def _by_table(resp): class TestFormApproval: async def test_every_approval_form_starts_as_draft_for_everyone(self, client, auth): - # An MR sees all three forms as drafts; an Area Manager or admin has nothing to act on yet. + # An MR sees all three forms as drafts; an Area Business Manager or admin has nothing to act on yet. forms = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"])) assert set(forms) == {"tour_plan", "standard_tour_plan", "fare_chart", "expense_statement"} assert {f["status"] for f in forms.values()} == {"draft"} @@ -47,7 +47,7 @@ class TestFormApproval: done = await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"]) assert done.status_code == 200, done.text assert done.json()["status"] == "approved" and done.json()["approved_by_name"] == "Suresh Behera" - # The MR's very next read shows the AM's approval — no shared browser needed. + # The MR's very next read shows the ABM's approval — no shared browser needed. seen = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"] assert (seen["status"], seen["approved_by_name"]) == ("approved", "Suresh Behera") @@ -61,7 +61,7 @@ class TestFormApproval: early = await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"]) assert early.status_code == 409, early.text assert _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]["status"] == "draft" - assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # a draft is nothing for the AM to act on + assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # a draft is nothing for the ABM to act on async def test_double_clicks_are_harmless(self, client, auth, org, fare_chart): await _add_row(client, auth) @@ -93,11 +93,11 @@ class TestFormApproval: assert (await change()).status_code in (200, 201) state = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"] assert state["status"] == "draft" and state["approved_by_name"] is None - # A pending (not yet approved) form is withdrawn too, so the AM never signs stale data. + # A pending (not yet approved) form is withdrawn too, so the ABM never signs stale data. # An MR may remove a row they entered by mistake; that too withdraws the request. await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"]) assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["mr1"])).status_code == 204 - assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # withdrawn: nothing left for the AM + assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # withdrawn: nothing left for the ABM async def test_the_pdf_signature_comes_from_the_server_not_the_browser(self, client, auth, org, db, fare_chart): # Not approved: a browser claiming otherwise changes nothing. diff --git a/tests/e2e/test_form_gm_oversight.py b/tests/e2e/test_form_gm_oversight.py index edf5d38..1cabb70 100644 --- a/tests/e2e/test_form_gm_oversight.py +++ b/tests/e2e/test_form_gm_oversight.py @@ -1,4 +1,4 @@ -"""Company forms: listed in the company's order, and readable (never writable) by the GM.""" +"""Company forms: listed in the company's order, and readable (never writable) by the AGM.""" from tests.e2e.test_form_ownership import forms # noqa: F401 - creates the form tables diff --git a/tests/e2e/test_form_ownership.py b/tests/e2e/test_form_ownership.py index 00e7875..8014f00 100644 --- a/tests/e2e/test_form_ownership.py +++ b/tests/e2e/test_form_ownership.py @@ -1,4 +1,4 @@ -"""Company forms belong to one MR; only that MR's own Area Manager receives and signs the request.""" +"""Company forms belong to one MR; only that MR's own Area Business Manager receives and signs the request.""" import pytest from sqlalchemy import text @@ -110,7 +110,7 @@ class TestOnlyTheAssignedAreaManagerGetsTheRequest: await db.execute(text("UPDATE am_headquarters SET effective_to = current_date WHERE headquarters_id = :h"), {"h": org["hq1"].id}) await db.commit() resp = await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"]) - assert resp.status_code == 422 and "Area Manager" in resp.text + assert resp.status_code == 422 and "Area Business Manager" in resp.text async def test_the_pdf_is_signed_by_the_approver_of_that_mr_only(self, client, auth, org, db, forms): from app.csv_data.router import _signature diff --git a/tests/e2e/test_full_approval_flow.py b/tests/e2e/test_full_approval_flow.py index e3db0c8..6cade99 100644 --- a/tests/e2e/test_full_approval_flow.py +++ b/tests/e2e/test_full_approval_flow.py @@ -77,7 +77,7 @@ async def _create_masters(client, auth, org, n_doctors=15, n_chemists=5): class TestStep1And2Setup: async def test_admin_creates_user_and_org_mapping(self, client, auth, org): """Step 1-2: users exist with correct roles, and the MR's profile resolves - both its headquarters and its DERIVED reporting Area Manager.""" + both its headquarters and its DERIVED reporting Area Business Manager.""" resp = await client.get(f"{API}/users/me/profile", headers=auth["mr1"]) assert resp.status_code == 200, resp.text profile = resp.json() @@ -120,6 +120,15 @@ class TestStep1And2Setup: class TestStep3And5Masters: + async def test_admin_and_agm_see_doctor_mr_assignment(self, client, auth, org): + doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=0) + + for who in ("admin", "gm"): + resp = await client.get(f"{API}/doctors", headers=auth[who]) + assert resp.status_code == 200, resp.text + row = next(item for item in resp.json() if item["id"] == doctors[0]["id"]) + assert row["assigned_mr_name"] == org["mr1"].full_name + async def test_mr_sees_exactly_the_assigned_doctors(self, client, auth, org): """Step 3 + Step 5 (S5): 15 doctors created and assigned → MR sees 15.""" await _create_masters(client, auth, org) @@ -288,11 +297,11 @@ class TestFullApprovalFlow: # --- Step 8: MR submits --------------------------------------- resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) assert resp.status_code == 200, resp.text - assert resp.json()["status"] == DCRStatus.PENDING_AM.value + assert resp.json()["status"] == DCRStatus.PENDING_ABM.value assert resp.json()["submitted_at"] is not None - # --- Step 9a: AM returns it ----------------------------------- - queue = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am1"]) + # --- Step 9a: ABM returns it ----------------------------------- + queue = await client.get(f"{API}/dcr?status=PENDING_ABM", headers=auth["am1"]) assert [r["id"] for r in queue.json()] == [dcr_id] # A reason is mandatory (V8). @@ -309,7 +318,7 @@ class TestFullApprovalFlow: assert resp.status_code == 200, resp.text returned = resp.json() assert returned["status"] == DCRStatus.RETURNED.value - assert returned["returned_by_role"] == "AM" + assert returned["returned_by_role"] == "ABM" assert "chemist visits" in returned["return_reason"] # The MR can edit again once returned. @@ -322,12 +331,12 @@ class TestFullApprovalFlow: # --- Step 9b: MR resubmits ------------------------------------ resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) - assert resp.json()["status"] == DCRStatus.PENDING_AM.value + assert resp.json()["status"] == DCRStatus.PENDING_ABM.value # Resubmission clears the previous return. assert resp.json()["return_reason"] is None - # --- Step 10: the Area Manager gives the final approval ------- - # There is no General Manager stage, and the GM cannot approve. + # --- Step 10: the Area Business Manager gives the final approval ------- + # There is no AGM stage, and the AGM cannot approve. gm_try = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["gm"], json={}) assert gm_try.status_code == 403, gm_try.text gone = await client.post(f"{API}/dcr/{dcr_id}/forward", headers=auth["am1"], json={}) @@ -371,7 +380,7 @@ class TestFullApprovalFlow: for role in ("gm", "admin"): again = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth[role], json={}) assert again.status_code in (403, 409) - # The approving AM repeating the click changes nothing (idempotent), and is not an error. + # The approving ABM repeating the click changes nothing (idempotent), and is not an error. repeat = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={}) assert repeat.status_code == 200 and repeat.json()["approved_at"] == approved["approved_at"] # ...but an approved report can still not be returned or reopened by anybody. @@ -379,7 +388,7 @@ class TestFullApprovalFlow: back = await client.post(f"{API}/dcr/{dcr_id}/return", headers=auth[role], json={"reason": "reopen it please"}) assert back.status_code in (403, 409), role - # --- Step 12: MR, AM and GM each download the PDF ------------- + # --- Step 12: MR, ABM and AGM each download the PDF ------------- for role in ("mr1", "am1", "gm"): pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth[role]) assert pdf.status_code == 200, f"{role}: {pdf.text}" @@ -399,11 +408,11 @@ class TestFullApprovalFlow: entries = history.json() assert entries[2]["actor_name"] == "Suresh Behera" - assert entries[2]["actor_role"] == "AM" + assert entries[2]["actor_role"] == "ABM" assert "chemist visits" in entries[2]["comment"] - # The final entry is the Area Manager's approval. + # The final entry is the Area Business Manager's approval. assert entries[-1]["actor_name"] == "Suresh Behera" - assert entries[-1]["actor_role"] == "AM" + assert entries[-1]["actor_role"] == "ABM" assert entries[-1]["comment"] == "Approved for the month." assert all(e["at"] for e in entries) @@ -456,7 +465,7 @@ class TestNegativeScope: await client.post(f"{API}/dcr/{dcr_id}/{action}", headers=auth["am2"], json=body) ).status_code == 403 - listing = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am2"]) + listing = await client.get(f"{API}/dcr?status=PENDING_ABM", headers=auth["am2"]) assert listing.json() == [] async def test_x3_admin_cannot_approve(self, client, auth, org, approved_plan): @@ -470,6 +479,9 @@ class TestNegativeScope: assert ( await client.get(f"{API}/dcr/{dcr_id}", headers=auth["admin"]) ).status_code == 200 + listing = await client.get(f"{API}/dcr", headers=auth["admin"]) + assert listing.status_code == 200, listing.text + assert dcr_id in {report["id"] for report in listing.json()} async def test_admin_cannot_create_a_report(self, client, auth): resp = await client.post( diff --git a/tests/e2e/test_master_approval.py b/tests/e2e/test_master_approval.py index 9c858c7..1c87fd0 100644 --- a/tests/e2e/test_master_approval.py +++ b/tests/e2e/test_master_approval.py @@ -1,4 +1,4 @@ -"""A doctor or chemist an MR adds waits for their Area Manager; a doctor visit records a gift.""" +"""A doctor, chemist or stockist an MR adds waits for their Area Business Manager; a doctor visit records a gift.""" from datetime import date @@ -80,6 +80,37 @@ class TestAnMrsChemistWaitsToo: assert "New Pharmacy" in await _names(client, auth["mr1"], "/chemists") +class TestAnMrsStockistWaitsToo: + async def _add(self, client, auth, org, who="mr1"): + resp = await client.post( + f"{API}/stockists", headers=auth[who], + json={"headquarters_id": str(org["hq1"].id), "name": "New Distributors", "address": "Unit 4, Bhubaneswar"}, + ) + assert resp.status_code == 201, resp.text + return resp.json() + + async def test_it_is_pending_until_the_area_manager_approves(self, client, auth, org): + stockist = await self._add(client, auth, org) + assert stockist["approval_status"] == "PENDING" and stockist["requested_by_name"] == "Ravi Das" + assert "New Distributors" not in await _names(client, auth["mr1"], "/stockists") + assert await _names(client, auth["mr1"], "/stockists/requests") == ["New Distributors"] + assert await _names(client, auth["am1"], "/stockists/requests") == ["New Distributors"] + assert await _names(client, auth["am2"], "/stockists/requests") == [] + assert (await client.post(f"{API}/stockists/{stockist['id']}/approve", headers=auth["am2"])).status_code == 403 + assert (await client.post(f"{API}/stockists/{stockist['id']}/approve", headers=auth["am1"])).status_code == 200 + assert "New Distributors" in await _names(client, auth["mr1"], "/stockists") + + async def test_a_rejected_one_is_resent_by_adding_it_again(self, client, auth, org): + stockist = await self._add(client, auth, org) + rejected = await client.post(f"{API}/stockists/{stockist['id']}/reject", headers=auth["am1"], json={"reason": "Duplicate"}) + assert rejected.status_code == 200 and rejected.json()["rejection_reason"] == "Duplicate" + again = await self._add(client, auth, org) + assert again["id"] == stockist["id"] and again["approval_status"] == "PENDING" + + async def test_the_admins_own_stockist_is_approved_at_once(self, client, auth, org): + assert (await self._add(client, auth, org, who="admin"))["approval_status"] == "APPROVED" + + class TestGift: async def test_a_doctor_visit_records_the_gift_and_the_pdf_notes_it(self, client, auth, org, approved_plan): doctor = await _add_doctor(client, auth, org, who="admin", name="Dr Gifted") diff --git a/tests/e2e/test_self_report.py b/tests/e2e/test_self_report.py index d137928..5325312 100644 --- a/tests/e2e/test_self_report.py +++ b/tests/e2e/test_self_report.py @@ -1,4 +1,4 @@ -"""An Area Manager's own Daily Call Report (Self): no plan, no approval, final on submit.""" +"""An Area Business Manager's own Daily Call Report (Self): no plan, no approval, final on submit.""" from datetime import date @@ -26,7 +26,7 @@ class TestSelfReport: assert report["headquarters_id"] == str(org["hq1"].id) # the one HQ am1 manages dcr_id = report["id"] - # Any doctor of the headquarters, though it is assigned to an MR, not to the AM. + # Any doctor of the headquarters, though it is assigned to an MR, not to the ABM. visit = await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["am1"], diff --git a/tests/e2e/test_user_role_change.py b/tests/e2e/test_user_role_change.py index c115700..722ce76 100644 --- a/tests/e2e/test_user_role_change.py +++ b/tests/e2e/test_user_role_change.py @@ -23,9 +23,9 @@ class TestAdminChangesRole: ) assert doctor.status_code == 201 - resp = await _patch(client, auth, org["mr1"], {"role": "AM"}) + resp = await _patch(client, auth, org["mr1"], {"role": "ABM"}) assert resp.status_code == 200, resp.text - assert resp.json()["role"] == "AM" + assert resp.json()["role"] == "ABM" assert resp.json()["headquarters_id"] is None # The doctor stays in the headquarters but is no longer assigned to anyone. @@ -48,16 +48,16 @@ class TestAdminChangesRole: assert str(org["am1"].id) not in {m["area_manager_user_id"] for m in mappings.json()} async def test_gm_becomes_am(self, client, auth, org): - resp = await _patch(client, auth, org["gm"], {"role": "AM"}) + resp = await _patch(client, auth, org["gm"], {"role": "ABM"}) assert resp.status_code == 200, resp.text - assert resp.json()["role"] == "AM" + assert resp.json()["role"] == "ABM" async def test_role_change_signs_the_user_out(self, client, auth, org): login = await client.post( f"{API}/auth/login", json={"email": org["gm"].email, "password": DEFAULT_PASSWORD}, ) - await _patch(client, auth, org["gm"], {"role": "AM"}) + await _patch(client, auth, org["gm"], {"role": "ABM"}) again = await client.post( f"{API}/auth/refresh", json={"refresh_token": login.json()["refresh_token"]} ) @@ -68,9 +68,9 @@ class TestAdminChangesRole: assert resp.status_code == 422 async def test_admin_cannot_change_own_role(self, client, auth, org): - resp = await _patch(client, auth, org["admin"], {"role": "GM"}) + resp = await _patch(client, auth, org["admin"], {"role": "AGM"}) assert resp.status_code == 422 async def test_only_admin_can_change_a_role(self, client, auth, org): - resp = await _patch(client, auth, org["mr1"], {"role": "AM"}, as_="gm") + resp = await _patch(client, auth, org["mr1"], {"role": "ABM"}, as_="gm") assert resp.status_code == 403 diff --git a/tests/integration/test_db_constraints.py b/tests/integration/test_db_constraints.py index bbdbebb..d5eacf3 100644 --- a/tests/integration/test_db_constraints.py +++ b/tests/integration/test_db_constraints.py @@ -169,9 +169,9 @@ class TestMRRequiresHeadquarters: company_id=org["company"].id, email="gm2@acmepharma.in", password_hash=hash_password("x" * 12), - full_name="Wrong GM", + full_name="Wrong AGM", employee_code="GM999", - role=Role.GM, + role=Role.AGM, headquarters_id=org["hq1"].id, ) ) diff --git a/tests/unit/test_csv_form_pdfs.py b/tests/unit/test_csv_form_pdfs.py index 34c0c53..21c8582 100644 --- a/tests/unit/test_csv_form_pdfs.py +++ b/tests/unit/test_csv_form_pdfs.py @@ -43,7 +43,7 @@ def test_identity_is_gathered_from_all_rows_not_just_the_first(): # Headings exactly as printed on the company forms, in printed order. PRINTED_HEADERS = { - "tour_plan": ["Sl.No.", "Date", "From", "To", "POB", "Stockiest Visit"], + "tour_plan": ["Sl.No.", "Date", "From", "To", "POB", "Stockist Visit"], "standard_tour_plan": ["Sl.No.", "PLACE"], "fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)\n(One Way)"], "area_covered": ["AREA TO COVER", "SALE OBJECTIVE", "STATUS"], diff --git a/tests/unit/test_dcr_pdf_layout.py b/tests/unit/test_dcr_pdf_layout.py index 4c93269..6c46cc7 100644 --- a/tests/unit/test_dcr_pdf_layout.py +++ b/tests/unit/test_dcr_pdf_layout.py @@ -98,3 +98,18 @@ class TestSignatures: def test_user_text_is_escaped(self): html = _render(_context([_doctor("")])) assert "