Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0d30c58bf0 | |||
| b001e2d03c |
+5
-5
@@ -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`**
|
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.
|
(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
|
Roles: MR (medical representative), ABM (Area Business Manager), AGM (Assistant General Manager), ADMIN. The MR
|
||||||
files daily call reports and company forms, the AM approves, the GM has read access across
|
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.
|
territories, the ADMIN maintains people, organisation and master data.
|
||||||
|
|
||||||
## 2. Requirements
|
## 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.
|
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
|
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.
|
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**).
|
(**Setup → Assignments**).
|
||||||
|
|
||||||
If you would rather not keep the demo doctors, chemists and the `BBSR` headquarters, deactivate
|
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).
|
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
|
3. Reference data loaded (section 5): Products page shows 26 products; Sales Projection shows the
|
||||||
product list.
|
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.
|
opens; each company form downloads a PDF that matches the printed original.
|
||||||
5. HTTPS works on the final domain; HSTS enabled.
|
5. HTTPS works on the final domain; HSTS enabled.
|
||||||
6. Firewall: only 80/443 (or the proxy) open.
|
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.
|
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
|
- **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
|
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.
|
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.
|
- **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.
|
- **No built-in alerting or error tracking**; only health checks and logs.
|
||||||
|
|||||||
@@ -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.
|
> **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
|
- **Backend:** FastAPI · SQLAlchemy 2 (async) · PostgreSQL 16 · Alembic
|
||||||
- **PDFs:** Jinja2 templates rendered by WeasyPrint
|
- **PDFs:** Jinja2 templates rendered by WeasyPrint
|
||||||
@@ -35,11 +35,11 @@ Deliberately **not** in scope: HR, payroll, attendance, distributor management,
|
|||||||
| Area | What it does |
|
| Area | What it does |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Daily Call Reports | MR records doctor and chemist calls per day; one report per MR per date |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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.
|
**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
|
└── 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/<id>`), 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/<id>`), 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
|
### Branding and theme
|
||||||
|
|
||||||
@@ -268,9 +268,9 @@ The UI uses the Celtic logo and the colours taken from it.
|
|||||||
| Role | Can do |
|
| Role | Can do |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **MR** | File and edit own DCRs while `DRAFT`/`RETURNED`; submit; edit company forms |
|
| **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) |
|
| **ABM** | 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 |
|
| **AGM** | 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** |
|
| **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:
|
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)
|
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.
|
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
|
## 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 ◄───────┘
|
└──────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.
|
- `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.
|
- Managers change state and add comments; they never edit another person's call rows.
|
||||||
- Returning a report requires a reason (`MIN_RETURN_REASON_LENGTH`).
|
- 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 |
|
| 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) |
|
| 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.
|
**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 |
|
| auth | `/auth` | Login, refresh (rotating tokens), logout, current user |
|
||||||
| users | `/users` | User administration and the MR profile |
|
| 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 |
|
| doctors, chemists | `/doctors`, `/chemists` | Masters and MR assignment |
|
||||||
| products | `/products` | Product master and stock inventory list |
|
| products | `/products` | Product master and stock inventory list |
|
||||||
| reports | `/dcr` | DCR CRUD, calls, submit / return / approve, PDF |
|
| 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
|
-- No duplicate doctor call within one report
|
||||||
ALTER TABLE doctor_call ADD CONSTRAINT uq_call_dcr_doctor UNIQUE (dcr_id, doctor_id);
|
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)
|
CREATE UNIQUE INDEX uq_active_am_per_hq ON am_headquarters (headquarters_id)
|
||||||
WHERE effective_to IS NULL;
|
WHERE effective_to IS NULL;
|
||||||
```
|
```
|
||||||
@@ -447,7 +447,7 @@ pytest tests/unit -q # state machine, PDF layouts — s
|
|||||||
|
|
||||||
## Known limitations
|
## 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.
|
- **`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.
|
- The test suite needs a reachable PostgreSQL; some tests under `tests/unit` also need it.
|
||||||
|
|
||||||
|
|||||||
@@ -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")
|
||||||
@@ -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'")
|
||||||
@@ -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")
|
||||||
|
|
||||||
@@ -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.csv_data.router import router as csv_data_router
|
||||||
from app.doctors.router import router as doctors_router
|
from app.doctors.router import router as doctors_router
|
||||||
from app.organization.router import router as organization_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.products.router import router as products_router
|
||||||
from app.reports.router import router as reports_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
|
from app.users.router import router as users_router
|
||||||
|
|
||||||
api_router = APIRouter()
|
api_router = APIRouter()
|
||||||
@@ -22,7 +24,9 @@ api_router.include_router(users_router)
|
|||||||
api_router.include_router(organization_router)
|
api_router.include_router(organization_router)
|
||||||
api_router.include_router(doctors_router)
|
api_router.include_router(doctors_router)
|
||||||
api_router.include_router(chemists_router)
|
api_router.include_router(chemists_router)
|
||||||
|
api_router.include_router(stockists_router)
|
||||||
api_router.include_router(csv_data_router)
|
api_router.include_router(csv_data_router)
|
||||||
api_router.include_router(products_router)
|
api_router.include_router(products_router)
|
||||||
api_router.include_router(reports_router)
|
api_router.include_router(reports_router)
|
||||||
api_router.include_router(audit_router)
|
api_router.include_router(audit_router)
|
||||||
|
api_router.include_router(directory_pdf_router)
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
"""The approval workflow for the revised business requirement.
|
"""The approval workflow for the revised business requirement.
|
||||||
|
|
||||||
DRAFT --submit(MR)--> PENDING_AM
|
DRAFT --submit(MR)--> PENDING_ABM
|
||||||
RETURNED --submit(MR)--> PENDING_AM
|
RETURNED --submit(MR)--> PENDING_ABM
|
||||||
PENDING_AM --approve(AM)--> APPROVED (terminal, immutable)
|
PENDING_ABM --approve(ABM)--> APPROVED (terminal, immutable)
|
||||||
PENDING_AM --return(AM)--> RETURNED
|
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
|
from dataclasses import dataclass
|
||||||
@@ -24,11 +24,11 @@ class Transition:
|
|||||||
|
|
||||||
|
|
||||||
TRANSITIONS: tuple[Transition, ...] = (
|
TRANSITIONS: tuple[Transition, ...] = (
|
||||||
Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR),
|
Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_ABM, Role.MR),
|
||||||
Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR),
|
Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_ABM, Role.MR),
|
||||||
Transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.AM),
|
Transition(DCRStatus.PENDING_ABM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.ABM),
|
||||||
Transition(
|
Transition(
|
||||||
DCRStatus.PENDING_AM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.AM,
|
DCRStatus.PENDING_ABM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.ABM,
|
||||||
requires_reason=True,
|
requires_reason=True,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
+2
-2
@@ -32,10 +32,10 @@ async def get_audit_history(
|
|||||||
if dcr is None:
|
if dcr is None:
|
||||||
raise NotFoundError("Report not found")
|
raise NotFoundError("Report not found")
|
||||||
await assert_can_view_dcr(db, current_user, dcr)
|
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
|
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)
|
return await AuditService(db).history_for(entity_type, entity_id)
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
Layer 1 (`require_role`) answers "WHAT may this role do?".
|
Layer 1 (`require_role`) answers "WHAT may this role do?".
|
||||||
Layer 2 (`assert_can_*`) answers "WHOSE data may this specific user touch?".
|
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
|
Most RBAC bugs live in the gap between those two questions: "ABM" is the stored role code
|
||||||
"AM *of this headquarters*" is a scope. Both checks are mandatory on scoped
|
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).
|
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]:
|
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(
|
stmt = select(AMHeadquarters.headquarters_id).where(
|
||||||
AMHeadquarters.area_manager_user_id == am_user_id,
|
AMHeadquarters.area_manager_user_id == am_user_id,
|
||||||
AMHeadquarters.effective_to.is_(None),
|
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:
|
async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None:
|
||||||
"""Headquarters the user may see. `None` means "all" (GM and ADMIN)."""
|
"""Headquarters the user may see. `None` means "all" (AGM and ADMIN)."""
|
||||||
if user.role in (Role.GM, Role.ADMIN):
|
if user.role in (Role.AGM, Role.ADMIN):
|
||||||
return None
|
return None
|
||||||
if user.role == Role.AM:
|
if user.role == Role.ABM:
|
||||||
return await active_hq_ids_for_am(db, user.id)
|
return await active_hq_ids_for_am(db, user.id)
|
||||||
if user.role in FIELD_ROLES:
|
if user.role in FIELD_ROLES:
|
||||||
return user.covered_headquarter_ids
|
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.
|
"""Layer 2 for reports.
|
||||||
|
|
||||||
ADMIN may inspect report content for support and administration, but cannot act on
|
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
|
return
|
||||||
if user.role in FIELD_ROLES and dcr.mr_user_id == user.id:
|
if user.role in FIELD_ROLES and dcr.mr_user_id == user.id:
|
||||||
return
|
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):
|
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
|
||||||
return
|
return
|
||||||
raise ForbiddenError("Report outside your data scope")
|
raise ForbiddenError("Report outside your data scope")
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ class Chemist(Base, UUIDMixin, TimestampMixin):
|
|||||||
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
contact_number: Mapped[str | None] = mapped_column(String(20))
|
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, 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(
|
approval_status: Mapped[str] = mapped_column(
|
||||||
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
||||||
)
|
)
|
||||||
|
|||||||
+31
-9
@@ -18,8 +18,19 @@ router = APIRouter(prefix="/chemists", tags=["chemists"])
|
|||||||
@router.get("", response_model=list[ChemistRead])
|
@router.get("", response_model=list[ChemistRead])
|
||||||
async def list_chemists(
|
async def list_chemists(
|
||||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
) -> list[Chemist]:
|
) -> list[ChemistRead]:
|
||||||
return await ChemistService(db).list_for(current_user)
|
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)
|
@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)),
|
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Chemist:
|
) -> 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))
|
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))
|
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)
|
@router.post("/{chemist_id}/assign", status_code=status.HTTP_201_CREATED)
|
||||||
async def assign_chemist(
|
async def assign_chemist(
|
||||||
chemist_id: uuid.UUID,
|
chemist_id: uuid.UUID,
|
||||||
payload: AssignToMR,
|
payload: AssignToMR,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
):
|
):
|
||||||
assignment = await ChemistService(db).assign_to_mr(
|
assignment = await ChemistService(db).assign_to_mr(
|
||||||
@@ -67,8 +89,8 @@ async def assign_chemist(
|
|||||||
async def list_chemist_requests(
|
async def list_chemist_requests(
|
||||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
) -> list[Chemist]:
|
) -> list[Chemist]:
|
||||||
"""Chemists an MR added that wait for the Area Manager: an MR sees their own (with any
|
"""Chemists an MR added that wait for the Area Business Manager: an MR sees their own (with any
|
||||||
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
|
rejected and why), an Area Business Manager what waits for them, the administrator and AGM all."""
|
||||||
return await ChemistService(db).requests_for(current_user)
|
return await ChemistService(db).requests_for(current_user)
|
||||||
|
|
||||||
|
|
||||||
@@ -76,10 +98,10 @@ async def list_chemist_requests(
|
|||||||
async def approve_chemist(
|
async def approve_chemist(
|
||||||
chemist_id: uuid.UUID,
|
chemist_id: uuid.UUID,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Chemist:
|
) -> 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))
|
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,
|
chemist_id: uuid.UUID,
|
||||||
payload: RejectMaster,
|
payload: RejectMaster,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Chemist:
|
) -> Chemist:
|
||||||
return await ChemistService(db).review(chemist_id, False, payload.reason, current_user, client_ip(request))
|
return await ChemistService(db).review(chemist_id, False, payload.reason, current_user, client_ip(request))
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ class ChemistCreate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ChemistUpdate(BaseModel):
|
class ChemistUpdate(BaseModel):
|
||||||
|
headquarters_id: uuid.UUID | None = None
|
||||||
name: str | None = Field(default=None, min_length=2, max_length=200)
|
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)
|
shop_address: str | None = Field(default=None, min_length=2, max_length=500)
|
||||||
contact_number: str | None = Field(default=None, max_length=20)
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
@@ -32,4 +33,7 @@ class ChemistRead(BaseModel):
|
|||||||
rejection_reason: str | None
|
rejection_reason: str | None
|
||||||
requested_by_name: str | None
|
requested_by_name: str | None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
#: Filled by the list endpoint only.
|
||||||
|
assigned_mr_name: str | None = None
|
||||||
|
assigned_mr_id: uuid.UUID | None = None
|
||||||
|
|
||||||
|
|||||||
+38
-5
@@ -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.models import Chemist, ChemistAssignment
|
||||||
from app.chemists.schemas import ChemistCreate, ChemistUpdate
|
from app.chemists.schemas import ChemistCreate, ChemistUpdate
|
||||||
from app.common import master_approval
|
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.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
from app.common.utils import snapshot
|
from app.common.utils import snapshot
|
||||||
from app.users.models import User
|
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:
|
class ChemistService:
|
||||||
@@ -27,7 +28,7 @@ class ChemistService:
|
|||||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||||
|
|
||||||
values = data.model_dump()
|
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
|
twin = None
|
||||||
if actor.role in FIELD_ROLES:
|
if actor.role in FIELD_ROLES:
|
||||||
twin = await master_approval.rejected_twin(
|
twin = await master_approval.rejected_twin(
|
||||||
@@ -97,7 +98,11 @@ class ChemistService:
|
|||||||
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
||||||
|
|
||||||
before = snapshot(chemist, _AUDIT_FIELDS)
|
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)
|
setattr(chemist, field, value)
|
||||||
|
|
||||||
await self.audit.log(
|
await self.audit.log(
|
||||||
@@ -109,7 +114,7 @@ class ChemistService:
|
|||||||
after=snapshot(chemist, _AUDIT_FIELDS),
|
after=snapshot(chemist, _AUDIT_FIELDS),
|
||||||
ip_address=ip,
|
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
|
return chemist
|
||||||
|
|
||||||
async def list_for(self, actor: User) -> list[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]))
|
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
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(
|
async def assign_to_mr(
|
||||||
self,
|
self,
|
||||||
chemist_id: uuid.UUID,
|
chemist_id: uuid.UUID,
|
||||||
@@ -146,7 +179,7 @@ class ChemistService:
|
|||||||
raise NotFoundError("Chemist not found")
|
raise NotFoundError("Chemist not found")
|
||||||
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
||||||
if chemist.approval_status != MasterApproval.APPROVED:
|
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)
|
mr = await self.db.get(User, mr_user_id)
|
||||||
if mr is None:
|
if mr is None:
|
||||||
|
|||||||
+13
-12
@@ -9,18 +9,18 @@ from enum import StrEnum
|
|||||||
|
|
||||||
|
|
||||||
class Role(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
|
ADMIN sits OUTSIDE the business hierarchy. It provisions users and masters and
|
||||||
can never approve a report or read report content (report §8, SEC-2).
|
may monitor reports, but can never approve one (report §8, SEC-2).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
ADMIN = "ADMIN"
|
ADMIN = "ADMIN"
|
||||||
GM = "GM"
|
AGM = "AGM"
|
||||||
AM = "AM"
|
ABM = "ABM"
|
||||||
MR = "MR"
|
MR = "MR"
|
||||||
#: Senior Field Executive: does an MR's work (daily reports, forms, doctors, chemists) and
|
#: 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"
|
SFE = "SFE"
|
||||||
|
|
||||||
|
|
||||||
@@ -29,25 +29,25 @@ FIELD_ROLES: frozenset[Role] = frozenset({Role.MR, Role.SFE})
|
|||||||
|
|
||||||
|
|
||||||
class DCRStatus(StrEnum):
|
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
|
`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"
|
DRAFT = "DRAFT"
|
||||||
PENDING_AM = "PENDING_AM"
|
PENDING_ABM = "PENDING_ABM"
|
||||||
RETURNED = "RETURNED"
|
RETURNED = "RETURNED"
|
||||||
APPROVED = "APPROVED"
|
APPROVED = "APPROVED"
|
||||||
|
|
||||||
|
|
||||||
class ReportType(StrEnum):
|
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.
|
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
|
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.
|
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.
|
plan and no approval: submitting it makes it final.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ class ConversionStatus(StrEnum):
|
|||||||
|
|
||||||
|
|
||||||
class MasterApproval(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"
|
PENDING = "PENDING"
|
||||||
APPROVED = "APPROVED"
|
APPROVED = "APPROVED"
|
||||||
@@ -109,6 +109,7 @@ class EntityType(StrEnum):
|
|||||||
HEADQUARTERS = "headquarters"
|
HEADQUARTERS = "headquarters"
|
||||||
DOCTOR = "doctor"
|
DOCTOR = "doctor"
|
||||||
CHEMIST = "chemist"
|
CHEMIST = "chemist"
|
||||||
|
STOCKIST = "stockist"
|
||||||
DCR = "dcr"
|
DCR = "dcr"
|
||||||
PRODUCT = "product"
|
PRODUCT = "product"
|
||||||
#: A row of a company form (the table is named in the entry's data).
|
#: A row of a company form (the table is named in the entry's data).
|
||||||
|
|||||||
@@ -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)
|
MR adds one --> PENDING --approve(ABM)--> APPROVED (listed, and visitable by that MR)
|
||||||
--reject(AM)---> REJECTED (the MR sees why; adding it again re-sends it)
|
--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
|
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
|
APPROVED at once. The reviewer is the Area Business Manager of the master's headquarters (or the
|
||||||
administrator); the General Manager may look but not act.
|
administrator); the Assistant General Manager may look but not act.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
@@ -34,14 +34,22 @@ async def rejected_twin(db: AsyncSession, model: Any, match: dict[str, Any]) ->
|
|||||||
|
|
||||||
|
|
||||||
async def resubmit(
|
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:
|
) -> 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():
|
for field, value in values.items():
|
||||||
setattr(record, field, value)
|
setattr(record, field, value)
|
||||||
record.approval_status = MasterApproval.PENDING
|
record.approval_status = MasterApproval.PENDING
|
||||||
record.requested_by_user_id = actor.id
|
record.requested_by_user_id = actor.id
|
||||||
record.rejection_reason = None
|
record.rejection_reason = None
|
||||||
|
if assignment_model is None or fk is None:
|
||||||
|
return
|
||||||
today = date.today()
|
today = date.today()
|
||||||
current = (
|
current = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
@@ -59,7 +67,7 @@ async def resubmit(
|
|||||||
|
|
||||||
async def requests_for(db: AsyncSession, model: Any, actor: User) -> list[Any]:
|
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 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())
|
stmt = select(model).order_by(model.created_at.desc())
|
||||||
if actor.role in FIELD_ROLES:
|
if actor.role in FIELD_ROLES:
|
||||||
return list(
|
return list(
|
||||||
@@ -92,8 +100,8 @@ async def review(
|
|||||||
record = await db.get(model, record_id)
|
record = await db.get(model, record_id)
|
||||||
if record is None:
|
if record is None:
|
||||||
raise NotFoundError(f"{entity_type.value.capitalize()} not found")
|
raise NotFoundError(f"{entity_type.value.capitalize()} not found")
|
||||||
if actor.role not in (Role.AM, Role.ADMIN):
|
if actor.role not in (Role.ABM, Role.ADMIN):
|
||||||
raise ForbiddenError("Only the Area Manager approves a new doctor or chemist")
|
raise ForbiddenError("Only the Area Business Manager approves a new doctor, chemist or stockist")
|
||||||
await assert_can_view_hq(db, actor, record.headquarters_id)
|
await assert_can_view_hq(db, actor, record.headquarters_id)
|
||||||
target = MasterApproval.APPROVED if approve else MasterApproval.REJECTED
|
target = MasterApproval.APPROVED if approve else MasterApproval.REJECTED
|
||||||
if record.approval_status == target:
|
if record.approval_status == target:
|
||||||
|
|||||||
@@ -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
|
||||||
+10
-10
@@ -1,6 +1,6 @@
|
|||||||
"""Approval workflow for the company forms that carry an Area Manager signature.
|
"""Approval workflow for the company forms that carry an Area Business Manager signature.
|
||||||
|
|
||||||
draft --request(MR)--> pending --approve(AM)--> approved
|
draft --request(MR)--> pending --approve(ABM)--> approved
|
||||||
pending / approved --any change to the rows--> draft (a signature never covers edited data)
|
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
|
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]:
|
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)
|
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:
|
if user.role in FIELD_ROLES:
|
||||||
stmt = stmt.where(User.id == user.id)
|
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)))
|
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 []
|
||||||
return list((await db.execute(stmt)).scalars())
|
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):
|
for owner in await owners_in_scope(db, user):
|
||||||
if owner.id == owner_id:
|
if owner.id == owner_id:
|
||||||
return owner
|
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 NotFoundError("Medical representative not found", {"id": str(owner_id)})
|
||||||
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
|
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]]:
|
async def list_approvals(db: AsyncSession, user: User) -> list[tuple[FormApproval, User, str | None]]:
|
||||||
"""(approval, MR, headquarters name) for what `user` can see.
|
"""(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.
|
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)}
|
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:
|
async def request_approval(db: AsyncSession, table_name: str, actor: User) -> FormApproval:
|
||||||
if await assigned_area_manager(db, actor) is None:
|
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)
|
row = await _get_or_create(db, table_name, actor.id)
|
||||||
if row.status == "pending":
|
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":
|
if row.status == "approved":
|
||||||
raise ConflictError("This form is already approved. Change a row to send it again.")
|
raise ConflictError("This form is already approved. Change a row to send it again.")
|
||||||
if await _row_count(db, table_name, actor.id) == 0:
|
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:
|
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)
|
row = await _get_or_create(db, table_name, owner_id)
|
||||||
if row.status == "approved":
|
if row.status == "approved":
|
||||||
return row # a double click
|
return row # a double click
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Approval state of the company forms that carry an Area Manager signature."""
|
"""Approval state of the company forms that carry an Area Business Manager signature."""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -9,7 +9,7 @@ from sqlalchemy.orm import Mapped, mapped_column
|
|||||||
|
|
||||||
from app.database.base import Base
|
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")
|
FORM_APPROVAL_STATUSES = ("draft", "pending", "approved")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+58
-23
@@ -24,7 +24,7 @@ SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
|
|||||||
IDENTITY_COLUMNS = {"name", "employee_name", "headquarter"}
|
IDENTITY_COLUMNS = {"name", "employee_name", "headquarter"}
|
||||||
APPROVAL_TABLES = approvals.APPROVAL_TABLES
|
APPROVAL_TABLES = approvals.APPROVAL_TABLES
|
||||||
HIDDEN_TABLES = {"daily_call_report_csv"}
|
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
|
OWNED_TABLES = APPROVAL_TABLES
|
||||||
|
|
||||||
|
|
||||||
@@ -60,6 +60,10 @@ async def _reject_repeat(
|
|||||||
raise ConflictError("An identical row already exists in this form")
|
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
|
#: 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
|
#: forever — a shared master list (e.g. Sales Projection's product list) refilled every
|
||||||
#: month, not one MR's own running form.
|
#: month, not one MR's own running form.
|
||||||
@@ -173,6 +177,35 @@ async def _apply_sales_projection_product(
|
|||||||
return values
|
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 Statement: the TOTAL column is always fare + daily allowance + postage + other expenses.
|
||||||
EXPENSE_AMOUNTS = ("fare", "da_hq", "da_ex", "da_out", "postage", "other_expense")
|
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
|
table_name: str, current_user: User, db: AsyncSession, owner_id: uuid.UUID | None
|
||||||
) -> tuple[list[str], dict[str, object]]:
|
) -> 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,
|
"""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:
|
if table_name not in OWNED_TABLES:
|
||||||
return [], {}
|
return [], {}
|
||||||
if current_user.role in FIELD_ROLES:
|
if current_user.role in FIELD_ROLES:
|
||||||
@@ -211,7 +244,7 @@ async def _owner_condition(
|
|||||||
if owner_id is not None:
|
if owner_id is not None:
|
||||||
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||||
return ["owner_user_id = :owner"], {"owner": 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 ["owner_user_id = ANY(:owners)"], {"owners": [o.id for o in await approvals.owners_in_scope(db, current_user)]}
|
||||||
return [], {}
|
return [], {}
|
||||||
|
|
||||||
@@ -231,7 +264,7 @@ async def _row_owner(table_name: str, row_id: uuid.UUID, current_user: User, db:
|
|||||||
return owner_id
|
return owner_id
|
||||||
if current_user.role in FIELD_ROLES and owner_id != current_user.id:
|
if current_user.role in FIELD_ROLES and owner_id != current_user.id:
|
||||||
raise ForbiddenError("This row belongs to another medical representative")
|
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:
|
if owner_id is None:
|
||||||
raise ForbiddenError("This row is outside your headquarters")
|
raise ForbiddenError("This row is outside your headquarters")
|
||||||
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
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:
|
if who in people:
|
||||||
item["name"], item["headquarter"] = people[who][0], people[who][1] or ""
|
item["name"], item["headquarter"] = people[who][0], people[who][1] or ""
|
||||||
out.append(item)
|
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]]:
|
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]:
|
def _available_csv_tables(current_user: User) -> list[str]:
|
||||||
visible = [name for name in FORM_ORDER if name not in HIDDEN_TABLES]
|
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 [name for name in visible if name in APPROVAL_TABLES]
|
||||||
return visible
|
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:
|
def _ensure_table_access(table_name: str, current_user: User) -> None:
|
||||||
if table_name in HIDDEN_TABLES:
|
if table_name in HIDDEN_TABLES:
|
||||||
raise ForbiddenError("This CSV form is not available for export.", {"table": table_name})
|
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:
|
if current_user.role == Role.ABM and table_name not in APPROVAL_TABLES:
|
||||||
raise ForbiddenError("Area Manager can only access approval forms.", {"table": table_name})
|
raise ForbiddenError("Area Business Manager can only access approval forms.", {"table": table_name})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/tables")
|
@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)]
|
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")
|
@router.get("/approvals")
|
||||||
async def list_form_approvals(
|
async def list_form_approvals(
|
||||||
db: AsyncSession = Depends(get_db),
|
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]]:
|
) -> 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)]
|
return [_approval_out(r, owner, hq) for r, owner, hq in await approvals.list_approvals(db, current_user)]
|
||||||
|
|
||||||
|
|
||||||
@router.get("/owners")
|
@router.get("/owners")
|
||||||
async def list_form_owners(
|
async def list_form_owners(
|
||||||
db: AsyncSession = Depends(get_db),
|
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]]:
|
) -> list[dict[str, object]]:
|
||||||
"""The medical representatives whose forms this user may open."""
|
"""The medical representatives whose forms this user may open."""
|
||||||
hq = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR)),
|
||||||
) -> dict[str, object]:
|
) -> 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)
|
row = await approvals.request_approval(db, _approval_table(table_name), current_user)
|
||||||
return _approval_out(row, current_user, await _hq_name(db, 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,
|
table_name: str,
|
||||||
owner_id: uuid.UUID = Query(description="The MR whose form is being approved"),
|
owner_id: uuid.UUID = Query(description="The MR whose form is being approved"),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.AM)),
|
current_user: User = Depends(require_role(Role.ABM)),
|
||||||
) -> dict[str, object]:
|
) -> 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)
|
row = await approvals.approve(db, _approval_table(table_name), owner_id, current_user)
|
||||||
owner = await db.get(User, owner_id)
|
owner = await db.get(User, owner_id)
|
||||||
return _approval_out(row, owner, await _hq_name(db, owner))
|
return _approval_out(row, owner, await _hq_name(db, owner))
|
||||||
@@ -475,7 +508,7 @@ async def list_csv_rows(
|
|||||||
table_name: str,
|
table_name: str,
|
||||||
owner_id: uuid.UUID | None = None,
|
owner_id: uuid.UUID | None = None,
|
||||||
db: AsyncSession = Depends(get_db),
|
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]]:
|
) -> list[dict[str, object]]:
|
||||||
_ensure_table_access(table_name, current_user)
|
_ensure_table_access(table_name, current_user)
|
||||||
return await _load_rows(table_name, db, current_user, owner_id)
|
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)
|
values = _apply_expense_total(values)
|
||||||
if not _has_user_data(table_name, values):
|
if not _has_user_data(table_name, values):
|
||||||
raise ValidationError("Add at least one value before creating a row")
|
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()
|
next_row = (await db.execute(text(f'SELECT COALESCE(MAX(source_row_number), 0) + 1 FROM "{table_name}"'))).scalar_one()
|
||||||
for column in columns:
|
for column in columns:
|
||||||
if column in SERIAL_COLUMNS:
|
if column in SERIAL_COLUMNS:
|
||||||
@@ -524,7 +559,7 @@ async def create_csv_row(
|
|||||||
await _renumber_rows(table_name, db)
|
await _renumber_rows(table_name, db)
|
||||||
await approvals.invalidate(db, table_name, owner.id if owner else None)
|
await approvals.invalidate(db, table_name, owner.id if owner else None)
|
||||||
await db.commit()
|
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:
|
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 _renumber_rows(table_name, db)
|
||||||
await db.commit()
|
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}")
|
@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)})
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
await approvals.invalidate(db, table_name, row_owner)
|
await approvals.invalidate(db, table_name, row_owner)
|
||||||
await db.commit()
|
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)
|
@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,
|
table_name: str,
|
||||||
row_id: uuid.UUID,
|
row_id: uuid.UUID,
|
||||||
db: AsyncSession = Depends(get_db),
|
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:
|
) -> Response:
|
||||||
_ensure_table_access(table_name, current_user)
|
_ensure_table_access(table_name, current_user)
|
||||||
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
row = await _get_row(table_name, row_id, 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)
|
approval_status, am_name, approved_at = await _signature(table_name, row_owner, db)
|
||||||
return Response(
|
return Response(
|
||||||
_pdf_bytes(table_name, CSV_LABELS[table_name], row, approval_status, am_name, approved_at),
|
_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,
|
owner_id: uuid.UUID | None = None,
|
||||||
month: str | None = None,
|
month: str | None = None,
|
||||||
db: AsyncSession = Depends(get_db),
|
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:
|
) -> Response:
|
||||||
"""The whole form, or only one month of it (for the forms that have a month)."""
|
"""The whole form, or only one month of it (for the forms that have a month)."""
|
||||||
_ensure_table_access(table_name, current_user)
|
_ensure_table_access(table_name, current_user)
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ from app.database.base import Base
|
|||||||
from app.doctors.models import Doctor, DoctorAssignment
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
from app.organization.models import AMHeadquarters, Company, Headquarters
|
from app.organization.models import AMHeadquarters, Company, Headquarters
|
||||||
from app.products.models import Product
|
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
|
from app.users.models import User, UserExtraHeadquarters # noqa: F401
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
@@ -32,6 +33,8 @@ __all__ = [
|
|||||||
"DailyCallReport",
|
"DailyCallReport",
|
||||||
"DoctorCall",
|
"DoctorCall",
|
||||||
"MissedVisit",
|
"MissedVisit",
|
||||||
|
"StockistCall",
|
||||||
"User",
|
"User",
|
||||||
"Product",
|
"Product",
|
||||||
|
"Stockist",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ class Doctor(Base, UUIDMixin, TimestampMixin):
|
|||||||
#: Core doctors are the high-value targets tracked for conversion.
|
#: Core doctors are the high-value targets tracked for conversion.
|
||||||
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, 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(
|
approval_status: Mapped[str] = mapped_column(
|
||||||
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
||||||
)
|
)
|
||||||
|
|||||||
+27
-10
@@ -17,9 +17,15 @@ router = APIRouter(prefix="/doctors", tags=["doctors"])
|
|||||||
@router.get("", response_model=list[DoctorRead])
|
@router.get("", response_model=list[DoctorRead])
|
||||||
async def list_doctors(
|
async def list_doctors(
|
||||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
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."""
|
"""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)
|
@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)),
|
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Doctor:
|
) -> 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))
|
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))
|
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)
|
@router.post("/{doctor_id}/assign", status_code=status.HTTP_201_CREATED)
|
||||||
async def assign_doctor(
|
async def assign_doctor(
|
||||||
doctor_id: uuid.UUID,
|
doctor_id: uuid.UUID,
|
||||||
payload: AssignToMR,
|
payload: AssignToMR,
|
||||||
request: Request,
|
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),
|
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(
|
assignment = await DoctorService(db).assign_to_mr(
|
||||||
doctor_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
|
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(
|
async def list_doctor_requests(
|
||||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
) -> list[Doctor]:
|
) -> list[Doctor]:
|
||||||
"""Doctors an MR added that wait for the Area Manager: an MR sees their own (with any
|
"""Doctors an MR added that wait for the Area Business Manager: an MR sees their own (with any
|
||||||
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
|
rejected and why), an Area Business Manager what waits for them, the administrator and AGM all."""
|
||||||
return await DoctorService(db).requests_for(current_user)
|
return await DoctorService(db).requests_for(current_user)
|
||||||
|
|
||||||
|
|
||||||
@@ -77,10 +94,10 @@ async def list_doctor_requests(
|
|||||||
async def approve_doctor(
|
async def approve_doctor(
|
||||||
doctor_id: uuid.UUID,
|
doctor_id: uuid.UUID,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Doctor:
|
) -> 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))
|
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,
|
doctor_id: uuid.UUID,
|
||||||
payload: RejectMaster,
|
payload: RejectMaster,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Doctor:
|
) -> Doctor:
|
||||||
return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request))
|
return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request))
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ class DoctorCreate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class DoctorUpdate(BaseModel):
|
class DoctorUpdate(BaseModel):
|
||||||
|
headquarters_id: uuid.UUID | None = None
|
||||||
name: str | None = Field(default=None, min_length=2, max_length=200)
|
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)
|
clinic_address: str | None = Field(default=None, min_length=2, max_length=500)
|
||||||
speciality: str | None = Field(default=None, max_length=100)
|
speciality: str | None = Field(default=None, max_length=100)
|
||||||
@@ -49,6 +50,8 @@ class DoctorRead(BaseModel):
|
|||||||
date_of_birth: date | None
|
date_of_birth: date | None
|
||||||
is_core_doctor: bool
|
is_core_doctor: bool
|
||||||
is_active: 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.
|
#: PENDING / APPROVED / REJECTED — see app/common/master_approval.py.
|
||||||
approval_status: str
|
approval_status: str
|
||||||
rejection_reason: str | None
|
rejection_reason: str | None
|
||||||
@@ -62,6 +65,6 @@ class AssignToMR(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class RejectMaster(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)
|
reason: str = Field(min_length=3, max_length=500)
|
||||||
|
|||||||
+50
-22
@@ -1,13 +1,14 @@
|
|||||||
import uuid
|
import uuid
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import and_, select
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.audit.service import AuditService
|
from app.audit.service import AuditService
|
||||||
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||||
from app.common import master_approval
|
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.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
from app.common.utils import snapshot
|
from app.common.utils import snapshot
|
||||||
@@ -16,6 +17,7 @@ from app.doctors.schemas import DoctorCreate, DoctorUpdate
|
|||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
_AUDIT_FIELDS = [
|
_AUDIT_FIELDS = [
|
||||||
|
"headquarters_id",
|
||||||
"name",
|
"name",
|
||||||
"clinic_address",
|
"clinic_address",
|
||||||
"speciality",
|
"speciality",
|
||||||
@@ -35,7 +37,7 @@ class DoctorService:
|
|||||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||||
|
|
||||||
values = data.model_dump()
|
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
|
twin = None
|
||||||
if actor.role in FIELD_ROLES:
|
if actor.role in FIELD_ROLES:
|
||||||
twin = await master_approval.rejected_twin(
|
twin = await master_approval.rejected_twin(
|
||||||
@@ -105,7 +107,11 @@ class DoctorService:
|
|||||||
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||||
|
|
||||||
before = snapshot(doctor, _AUDIT_FIELDS)
|
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)
|
setattr(doctor, field, value)
|
||||||
|
|
||||||
await self.audit.log(
|
await self.audit.log(
|
||||||
@@ -117,30 +123,52 @@ class DoctorService:
|
|||||||
after=snapshot(doctor, _AUDIT_FIELDS),
|
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||||
ip_address=ip,
|
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
|
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)."""
|
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
||||||
if actor.role in FIELD_ROLES:
|
stmt = (
|
||||||
stmt = (
|
select(Doctor, User.full_name, User.id)
|
||||||
select(Doctor)
|
.outerjoin(
|
||||||
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
DoctorAssignment,
|
||||||
.where(
|
and_(
|
||||||
DoctorAssignment.mr_user_id == actor.id,
|
DoctorAssignment.doctor_id == Doctor.id,
|
||||||
DoctorAssignment.effective_to.is_(None),
|
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)
|
async def unassign(self, doctor_id: uuid.UUID, actor: User, ip: str | None = None) -> None:
|
||||||
stmt = select(Doctor).where(Doctor.approval_status == MasterApproval.APPROVED).order_by(Doctor.name)
|
"""Take the doctor away from its MR, leaving it unassigned."""
|
||||||
if allowed is not None:
|
doctor = await self.db.get(Doctor, doctor_id)
|
||||||
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
if doctor is None:
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
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(
|
async def assign_to_mr(
|
||||||
self,
|
self,
|
||||||
@@ -155,7 +183,7 @@ class DoctorService:
|
|||||||
raise NotFoundError("Doctor not found")
|
raise NotFoundError("Doctor not found")
|
||||||
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||||
if doctor.approval_status != MasterApproval.APPROVED:
|
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)
|
mr = await self.db.get(User, mr_user_id)
|
||||||
if mr is None:
|
if mr is None:
|
||||||
|
|||||||
+1
-1
@@ -50,7 +50,7 @@ def create_app() -> FastAPI:
|
|||||||
version="0.1.0",
|
version="0.1.0",
|
||||||
description=(
|
description=(
|
||||||
"Pharmaceutical field-force reporting — MVP. "
|
"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."
|
"locked PDFs and audit trails."
|
||||||
),
|
),
|
||||||
docs_url="/docs",
|
docs_url="/docs",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
Design notes (report §13.2):
|
Design notes (report §13.2):
|
||||||
- `area_territory` was merged into `headquarters` — the brief states HQ *is* the
|
- `area_territory` was merged into `headquarters` — the brief states HQ *is* the
|
||||||
territory, and two tables for one concept invites drift.
|
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.
|
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):
|
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
|
`effective_to IS NULL` means "current". A headquarters may have several Area Business Managers
|
||||||
and an Area Manager several headquarters; the partial unique index only stops the same
|
and an Area Business Manager several headquarters; the partial unique index only stops the same
|
||||||
pair being active twice.
|
pair being active twice.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
@@ -24,16 +24,16 @@ router = APIRouter(prefix="/headquarters", tags=["organization"])
|
|||||||
async def list_headquarters(
|
async def list_headquarters(
|
||||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
) -> list[Headquarters]:
|
) -> 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)
|
return await OrganizationService(db).list_headquarters(current_user)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/area-managers", response_model=list[AMHeadquartersRead])
|
@router.get("/area-managers", response_model=list[AMHeadquartersRead])
|
||||||
async def list_area_manager_mappings(
|
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),
|
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)
|
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)),
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
db: AsyncSession = Depends(get_db),
|
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(
|
return await OrganizationService(db).set_area_manager_headquarters(
|
||||||
area_manager_user_id,
|
area_manager_user_id,
|
||||||
payload.headquarters_ids,
|
payload.headquarters_ids,
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ class AssignAreaManager(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class SetAreaManagerHeadquarters(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)
|
headquarters_ids: list[uuid.UUID] = Field(default_factory=list, max_length=500)
|
||||||
effective_from: date | None = None
|
effective_from: date | None = None
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ class OrganizationService:
|
|||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
async def list_area_manager_mappings(self, actor: User) -> list[AMHeadquarters]:
|
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 = (
|
stmt = (
|
||||||
select(AMHeadquarters)
|
select(AMHeadquarters)
|
||||||
.join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id)
|
.join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id)
|
||||||
@@ -79,7 +79,7 @@ class OrganizationService:
|
|||||||
actor: User,
|
actor: User,
|
||||||
ip: str | None = None,
|
ip: str | None = None,
|
||||||
) -> list[AMHeadquarters]:
|
) -> 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
|
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.
|
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)
|
manager = await self.db.get(User, am_user_id)
|
||||||
if manager is None or manager.company_id != actor.company_id:
|
if manager is None or manager.company_id != actor.company_id:
|
||||||
raise NotFoundError("User not found")
|
raise NotFoundError("User not found")
|
||||||
if manager.role != Role.AM:
|
if manager.role != Role.ABM:
|
||||||
raise ValidationError(
|
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},
|
{"user_role": manager.role.value},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -165,7 +165,7 @@ class OrganizationService:
|
|||||||
actor: User,
|
actor: User,
|
||||||
ip: str | None = None,
|
ip: str | None = None,
|
||||||
) -> AMHeadquarters:
|
) -> 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`).
|
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)
|
manager = await self.db.get(User, am_user_id)
|
||||||
if manager is None:
|
if manager is None:
|
||||||
raise NotFoundError("User not found")
|
raise NotFoundError("User not found")
|
||||||
if manager.role != Role.AM:
|
if manager.role != Role.ABM:
|
||||||
raise ValidationError(
|
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},
|
{"user_role": manager.role.value},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+35
-6
@@ -80,7 +80,7 @@ FORMS: dict[str, FormSpec] = {
|
|||||||
Col("From", "from_location", 25.0),
|
Col("From", "from_location", 25.0),
|
||||||
Col("To", "to_location", 23.2),
|
Col("To", "to_location", 23.2),
|
||||||
Col("POB", "pob", 15.3, "center"),
|
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_field="serial_no",
|
||||||
serial_dot=True,
|
serial_dot=True,
|
||||||
@@ -231,6 +231,17 @@ _PLAN_CHEMIST_COLS = (
|
|||||||
Col("NAME OF THE CHEMIST", "chemist_name", 52.8),
|
Col("NAME OF THE CHEMIST", "chemist_name", 52.8),
|
||||||
Col("PLANNED TIME", "planned_time", 37.0, "center"),
|
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.
|
# End-of-day report: the planned visits that were not made, and why.
|
||||||
_MISSED_COLS = (
|
_MISSED_COLS = (
|
||||||
_serial("SR. NO.", 8.6),
|
_serial("SR. NO.", 8.6),
|
||||||
@@ -576,13 +587,14 @@ def build_dcr_context(
|
|||||||
chemist_calls,
|
chemist_calls,
|
||||||
approval: dict[str, str] | None = None,
|
approval: dict[str, str] | None = None,
|
||||||
missed: list[Row] | None = None,
|
missed: list[Row] | None = None,
|
||||||
|
stockist_calls=(),
|
||||||
) -> dict[str, object]:
|
) -> dict[str, object]:
|
||||||
"""The approved Daily Call Report, laid out exactly like the printed company form.
|
"""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
|
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
|
``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
|
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.
|
approval signature with its date and time.
|
||||||
|
|
||||||
A morning day plan uses the same form with a PLANNED TIME column in place of the
|
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(dcr, "report_type", None)
|
||||||
report_type = getattr(report_type, "value", report_type)
|
report_type = getattr(report_type, "value", report_type)
|
||||||
if report_type == "PLAN":
|
if report_type == "PLAN":
|
||||||
return _build_plan_context(dcr, doctor_calls, chemist_calls, approval)
|
return _build_plan_context(dcr, doctor_calls, chemist_calls, approval, stockist_calls)
|
||||||
is_self = report_type == "SELF" # an Area Manager's own report: no approval signature
|
is_self = report_type == "SELF" # an Area Business Manager's own report: no approval signature
|
||||||
doctors = [
|
doctors = [
|
||||||
{
|
{
|
||||||
"doctor_name": c.doctor.name,
|
"doctor_name": c.doctor.name,
|
||||||
@@ -605,6 +617,7 @@ def build_dcr_context(
|
|||||||
for c in doctor_calls
|
for c in doctor_calls
|
||||||
]
|
]
|
||||||
chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_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 = [
|
meta = [
|
||||||
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
|
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
|
||||||
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))],
|
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))],
|
||||||
@@ -619,12 +632,17 @@ def build_dcr_context(
|
|||||||
"grids": {
|
"grids": {
|
||||||
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
|
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
|
||||||
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
|
"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 {}),
|
**({"missed": _grid(_MISSED_COLS, missed, min_rows=0)} if missed else {}),
|
||||||
},
|
},
|
||||||
"is_plan": False,
|
"is_plan": False,
|
||||||
"stockist_visit": dcr.stockist_visit or "",
|
"stockist_visit": dcr.stockist_visit or "",
|
||||||
"order_value": dcr.order_value 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})",
|
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
|
||||||
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
|
"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 [])
|
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 = [
|
doctors = [
|
||||||
{
|
{
|
||||||
"doctor_name": c.doctor.name,
|
"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")}
|
{"chemist_name": c.chemist.name, "planned_time": c.visit_time.strftime("%H:%M")}
|
||||||
for c in chemist_calls
|
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 = [
|
meta = [
|
||||||
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
|
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
|
||||||
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %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": {
|
"grids": {
|
||||||
"doctors": _grid(_PLAN_DOCTOR_COLS, doctors, min_rows=10),
|
"doctors": _grid(_PLAN_DOCTOR_COLS, doctors, min_rows=10),
|
||||||
"chemists": _grid(_PLAN_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
|
"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,
|
"is_plan": True,
|
||||||
"stockist_visit": "",
|
"stockist_visit": "",
|
||||||
|
|||||||
@@ -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"'},
|
||||||
|
)
|
||||||
+3
-2
@@ -142,7 +142,7 @@ def _approval_signature_line(
|
|||||||
table_name: str,
|
table_name: str,
|
||||||
approval_status: str | None = None,
|
approval_status: str | None = None,
|
||||||
am_name: str | None = None,
|
am_name: str | None = None,
|
||||||
am_role: str = "Area Manager",
|
am_role: str = "Area Business Manager",
|
||||||
) -> str:
|
) -> str:
|
||||||
return approval_signature_line(table_name, approval_status, am_name)
|
return approval_signature_line(table_name, approval_status, am_name)
|
||||||
|
|
||||||
@@ -154,7 +154,7 @@ def csv_table_pdf_bytes(
|
|||||||
rows: list[dict[str, object]],
|
rows: list[dict[str, object]],
|
||||||
approval_status: str | None = None,
|
approval_status: str | None = None,
|
||||||
am_name: str | None = None,
|
am_name: str | None = None,
|
||||||
am_role: str = "Area Manager",
|
am_role: str = "Area Business Manager",
|
||||||
approved_at: str | None = None,
|
approved_at: str | None = None,
|
||||||
renumber: bool = False,
|
renumber: bool = False,
|
||||||
) -> bytes:
|
) -> bytes:
|
||||||
@@ -210,6 +210,7 @@ class PDFService:
|
|||||||
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
|
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
|
||||||
await self._approval(dcr),
|
await self._approval(dcr),
|
||||||
missed,
|
missed,
|
||||||
|
sorted(dcr.stockist_calls, key=lambda c: c.visit_time),
|
||||||
)
|
)
|
||||||
|
|
||||||
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
|
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
|
||||||
|
|||||||
@@ -21,6 +21,10 @@
|
|||||||
{{ grid(grids.doctors, left=True) }}
|
{{ grid(grids.doctors, left=True) }}
|
||||||
<h2 class="section">{{ "CHEMISTS TO VISIT" if is_plan else "CHEMIST VISIT" }}</h2>
|
<h2 class="section">{{ "CHEMISTS TO VISIT" if is_plan else "CHEMIST VISIT" }}</h2>
|
||||||
{{ grid(grids.chemists, left=True) }}
|
{{ grid(grids.chemists, left=True) }}
|
||||||
|
{% if grids.stockists %}
|
||||||
|
<h2 class="section">{{ "STOCKISTS TO VISIT" if is_plan else "STOCKIST VISIT" }}</h2>
|
||||||
|
{{ grid(grids.stockists, left=True) }}
|
||||||
|
{% endif %}
|
||||||
{% if is_plan %}
|
{% if is_plan %}
|
||||||
{% if mr_remarks %}<div class="visit"><div><b>REMARKS :</b> {{ mr_remarks }}</div></div>{% endif %}
|
{% if mr_remarks %}<div class="visit"><div><b>REMARKS :</b> {{ mr_remarks }}</div></div>{% endif %}
|
||||||
{% else %}
|
{% else %}
|
||||||
@@ -46,7 +50,7 @@
|
|||||||
{% if approval %}
|
{% if approval %}
|
||||||
<div class="sign-label">APPROVAL SIGNATURE:</div>
|
<div class="sign-label">APPROVAL SIGNATURE:</div>
|
||||||
<div class="signed">{{ approval.name }}</div>
|
<div class="signed">{{ approval.name }}</div>
|
||||||
<div class="signed-when">Area Manager · {{ approval.at }}</div>
|
<div class="signed-when">Area Business Manager · {{ approval.at }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -11,7 +11,11 @@ Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_p
|
|||||||
{{ grids.chemists.headers | join(' | ') }}
|
{{ grids.chemists.headers | join(' | ') }}
|
||||||
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
|
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
|
||||||
{% endfor %}
|
{% 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(' | ') }}
|
{{ grids.missed.headers | join(' | ') }}
|
||||||
{% for r in grids.missed.rows %}{{ r.cells | join(' | ') }}
|
{% for r in grids.missed.rows %}{{ r.cells | join(' | ') }}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
|
|||||||
@@ -45,7 +45,7 @@
|
|||||||
<div class="sign-right">{{ text }}</div>
|
<div class="sign-right">{{ text }}</div>
|
||||||
{% endmacro %}
|
{% 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) %}
|
{% macro sign_approval(approval) %}
|
||||||
<table class="sign-approval">
|
<table class="sign-approval">
|
||||||
<tr>
|
<tr>
|
||||||
|
|||||||
+37
-7
@@ -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
|
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``.
|
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``
|
An Area Business 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."""
|
is then the Area Business Manager (the report's owner), and submitting it makes it final."""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import date, datetime, time
|
from datetime import date, datetime, time
|
||||||
@@ -73,7 +73,7 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
|
|||||||
nullable=False,
|
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).
|
#: history (report §5.5).
|
||||||
current_am_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
current_am_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT")
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT")
|
||||||
@@ -104,6 +104,9 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
|
|||||||
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
|
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
|
||||||
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
|
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(
|
missed_visits: Mapped[list["MissedVisit"]] = relationship(
|
||||||
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
|
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
|
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
|
||||||
|
|
||||||
|
|
||||||
class MissedVisit(Base, UUIDMixin, TimestampMixin):
|
class StockistCall(Base, UUIDMixin, TimestampMixin):
|
||||||
"""Why a doctor or chemist on the approved plan was not visited that day.
|
__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"
|
__tablename__ = "missed_visit"
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"),
|
UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"),
|
||||||
UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"),
|
UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"),
|
||||||
|
UniqueConstraint("dcr_id", "stockist_id", name="uq_missed_dcr_stockist"),
|
||||||
CheckConstraint(
|
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(
|
chemist_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT")
|
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)
|
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
|
||||||
dcr: Mapped["DailyCallReport"] = relationship(back_populates="missed_visits")
|
dcr: Mapped["DailyCallReport"] = relationship(back_populates="missed_visits")
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from sqlalchemy.orm import selectinload
|
|||||||
|
|
||||||
from app.common.enums import DCRStatus, ReportType
|
from app.common.enums import DCRStatus, ReportType
|
||||||
from app.common.repository import BaseRepository
|
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]):
|
class DCRRepository(BaseRepository[DailyCallReport]):
|
||||||
@@ -19,6 +19,7 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
.options(
|
.options(
|
||||||
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
|
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
|
||||||
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
|
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
|
||||||
|
selectinload(DailyCallReport.stockist_calls).selectinload(StockistCall.stockist),
|
||||||
selectinload(DailyCallReport.missed_visits),
|
selectinload(DailyCallReport.missed_visits),
|
||||||
selectinload(DailyCallReport.mr),
|
selectinload(DailyCallReport.mr),
|
||||||
selectinload(DailyCallReport.headquarters),
|
selectinload(DailyCallReport.headquarters),
|
||||||
@@ -29,6 +30,9 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
selectinload(DailyCallReport.plan)
|
selectinload(DailyCallReport.plan)
|
||||||
.selectinload(DailyCallReport.chemist_calls)
|
.selectinload(DailyCallReport.chemist_calls)
|
||||||
.selectinload(ChemistCall.chemist),
|
.selectinload(ChemistCall.chemist),
|
||||||
|
selectinload(DailyCallReport.plan)
|
||||||
|
.selectinload(DailyCallReport.stockist_calls)
|
||||||
|
.selectinload(StockistCall.stockist),
|
||||||
selectinload(DailyCallReport.actual),
|
selectinload(DailyCallReport.actual),
|
||||||
)
|
)
|
||||||
# The session keeps objects after commit (expire_on_commit=False), so without this the
|
# The session keeps objects after commit (expire_on_commit=False), so without this the
|
||||||
|
|||||||
+23
-9
@@ -12,6 +12,7 @@ from app.pdf.service import PDFService
|
|||||||
from app.reports.schemas import (
|
from app.reports.schemas import (
|
||||||
ApproveRequest,
|
ApproveRequest,
|
||||||
ChemistCallCreate,
|
ChemistCallCreate,
|
||||||
|
StockistCallCreate,
|
||||||
DCRCreate,
|
DCRCreate,
|
||||||
DCRListItem,
|
DCRListItem,
|
||||||
DCRRead,
|
DCRRead,
|
||||||
@@ -111,7 +112,7 @@ async def download_pdf(
|
|||||||
async def create_report(
|
async def create_report(
|
||||||
payload: DCRCreate,
|
payload: DCRCreate,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(await DCRService(db).create(payload, current_user, client_ip(request)))
|
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,
|
dcr_id: uuid.UUID,
|
||||||
payload: DCRUpdate,
|
payload: DCRUpdate,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -137,7 +138,7 @@ async def add_doctor_call(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
payload: DoctorCallCreate,
|
payload: DoctorCallCreate,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -150,7 +151,7 @@ async def add_chemist_call(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
payload: ChemistCallCreate,
|
payload: ChemistCallCreate,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
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)
|
@router.delete("/{dcr_id}/calls/{call_id}", response_model=DCRRead)
|
||||||
async def delete_call(
|
async def delete_call(
|
||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
call_id: uuid.UUID,
|
call_id: uuid.UUID,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -207,7 +221,7 @@ async def clear_missed_reason(
|
|||||||
async def submit(
|
async def submit(
|
||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
request: Request,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request)))
|
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,
|
dcr_id: uuid.UUID,
|
||||||
payload: ReturnRequest,
|
payload: ReturnRequest,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.AM)),
|
current_user: User = Depends(require_role(Role.ABM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -233,10 +247,10 @@ async def approve(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
payload: ApproveRequest,
|
payload: ApproveRequest,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.AM)),
|
current_user: User = Depends(require_role(Role.ABM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> 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(
|
return to_read(
|
||||||
await DCRService(db).approve(dcr_id, payload.comment, current_user, client_ip(request))
|
await DCRService(db).approve(dcr_id, payload.comment, current_user, client_ip(request))
|
||||||
)
|
)
|
||||||
|
|||||||
+24
-4
@@ -52,6 +52,13 @@ class ChemistCallCreate(BaseModel):
|
|||||||
remarks: str | None = Field(default=None, max_length=2000)
|
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):
|
class DoctorCallRead(BaseModel):
|
||||||
model_config = ConfigDict(from_attributes=True)
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
@@ -80,10 +87,21 @@ class ChemistCallRead(BaseModel):
|
|||||||
remarks: str | None
|
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):
|
class DCRCreate(BaseModel):
|
||||||
report_date: date
|
report_date: date
|
||||||
report_type: ReportType = ReportType.ACTUAL
|
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
|
headquarters_id: uuid.UUID | None = None
|
||||||
mr_remarks: str | None = Field(default=None, max_length=2000)
|
mr_remarks: str | None = Field(default=None, max_length=2000)
|
||||||
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
|
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
|
||||||
@@ -97,10 +115,11 @@ class DCRUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class MissedVisitSet(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
|
doctor_id: uuid.UUID | None = None
|
||||||
chemist_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)
|
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).
|
PENDING — neither yet (the report cannot be submitted while any remain).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
kind: Literal["DOCTOR", "CHEMIST"]
|
kind: Literal["DOCTOR", "CHEMIST", "STOCKIST"]
|
||||||
target_id: uuid.UUID
|
target_id: uuid.UUID
|
||||||
name: str
|
name: str
|
||||||
is_core_doctor: bool
|
is_core_doctor: bool
|
||||||
@@ -176,6 +195,7 @@ class DCRRead(BaseModel):
|
|||||||
approved_at: datetime | None
|
approved_at: datetime | None
|
||||||
doctor_calls: list[DoctorCallRead]
|
doctor_calls: list[DoctorCallRead]
|
||||||
chemist_calls: list[ChemistCallRead]
|
chemist_calls: list[ChemistCallRead]
|
||||||
|
stockist_calls: list[StockistCallRead]
|
||||||
#: End-of-day report only: the approved plan, line by line, with what became of it.
|
#: End-of-day report only: the approved plan, line by line, with what became of it.
|
||||||
planned_visits: list[PlannedVisitRead]
|
planned_visits: list[PlannedVisitRead]
|
||||||
|
|
||||||
@@ -184,6 +204,6 @@ class StatusCounts(BaseModel):
|
|||||||
"""Header counts on the list screens — the cheap replacement for dashboards."""
|
"""Header counts on the list screens — the cheap replacement for dashboards."""
|
||||||
|
|
||||||
DRAFT: int = 0
|
DRAFT: int = 0
|
||||||
PENDING_AM: int = 0
|
PENDING_ABM: int = 0
|
||||||
RETURNED: int = 0
|
RETURNED: int = 0
|
||||||
APPROVED: int = 0
|
APPROVED: int = 0
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from app.reports.schemas import (
|
|||||||
DCRRead,
|
DCRRead,
|
||||||
DoctorCallRead,
|
DoctorCallRead,
|
||||||
PlannedVisitRead,
|
PlannedVisitRead,
|
||||||
|
StockistCallRead,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -15,8 +16,12 @@ def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]:
|
|||||||
plan = dcr.plan
|
plan = dcr.plan
|
||||||
if plan is None:
|
if plan is None:
|
||||||
return []
|
return []
|
||||||
visited = {c.doctor_id for c in dcr.doctor_calls} | {c.chemist_id for c in dcr.chemist_calls}
|
visited = (
|
||||||
missed = {m.doctor_id or m.chemist_id: m for m in dcr.missed_visits}
|
{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:
|
def line(kind, target_id, name, is_core, planned_time) -> PlannedVisitRead:
|
||||||
note = missed.get(target_id)
|
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)
|
line("CHEMIST", c.chemist_id, c.chemist.name, False, c.visit_time)
|
||||||
for c in plan.chemist_calls
|
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)
|
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)
|
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),
|
planned_visits=planned_visits(dcr),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+125
-34
@@ -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
|
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".
|
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
|
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.
|
APPROVED by the Area Business Manager; it is linked to that plan.
|
||||||
P3 Every planned doctor/chemist must, before submit, either have a visit recorded on
|
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.
|
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.
|
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.
|
P5 Visits not on the plan may still be added to the end-of-day report.
|
||||||
|
|
||||||
Area Manager's own report (S1-S3):
|
Area Business Manager's own report (S1-S3):
|
||||||
S1 An Area Manager files one SELF report per date, for one headquarters they manage;
|
S1 An Area Business Manager files one SELF report per date, for one headquarters they manage;
|
||||||
it needs no plan.
|
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).
|
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.common.utils import local_now, local_today, snapshot, utcnow
|
||||||
from app.config.settings import settings
|
from app.config.settings import settings
|
||||||
from app.doctors.models import Doctor, DoctorAssignment
|
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.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.reports.serializers import planned_visits
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
@@ -73,7 +83,7 @@ _AUDIT_FIELDS = [
|
|||||||
|
|
||||||
|
|
||||||
#: Who files (and alone may edit or submit) each type of report.
|
#: 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 = {
|
_LABEL = {
|
||||||
ReportType.PLAN: "Daily Call Report (Plan)",
|
ReportType.PLAN: "Daily Call Report (Plan)",
|
||||||
ReportType.ACTUAL: "Daily Call Report (Done)",
|
ReportType.ACTUAL: "Daily Call Report (Done)",
|
||||||
@@ -146,8 +156,23 @@ class DCRService:
|
|||||||
)
|
)
|
||||||
return set((await self.db.execute(stmt)).scalars().all())
|
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]:
|
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 = (
|
stmt = (
|
||||||
select(DoctorAssignment.doctor_id)
|
select(DoctorAssignment.doctor_id)
|
||||||
.join(Doctor, Doctor.id == DoctorAssignment.doctor_id)
|
.join(Doctor, Doctor.id == DoctorAssignment.doctor_id)
|
||||||
@@ -230,6 +255,25 @@ class DCRService:
|
|||||||
remarks=payload.remarks,
|
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
|
# Commands
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
@@ -238,8 +282,8 @@ class DCRService:
|
|||||||
self, data: DCRCreate, actor: User, ip: str | None = None
|
self, data: DCRCreate, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> DailyCallReport:
|
||||||
if data.report_type == ReportType.SELF:
|
if data.report_type == ReportType.SELF:
|
||||||
if actor.role != Role.AM:
|
if actor.role != Role.ABM:
|
||||||
raise ForbiddenError("Only an Area Manager files a Daily Call Report (Self)")
|
raise ForbiddenError("Only an Area Business Manager files a Daily Call Report (Self)")
|
||||||
headquarters_id = await self._self_report_hq(actor, data.headquarters_id)
|
headquarters_id = await self._self_report_hq(actor, data.headquarters_id)
|
||||||
elif actor.role not in FIELD_ROLES:
|
elif actor.role not in FIELD_ROLES:
|
||||||
raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)")
|
raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)")
|
||||||
@@ -403,6 +447,36 @@ class DCRService:
|
|||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
return await self.repo.get_full(dcr.id)
|
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:
|
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)."""
|
"""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():
|
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
|
self, dcr_id: uuid.UUID, call_id: uuid.UUID, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> DailyCallReport:
|
||||||
dcr = await self._get_owned_editable(dcr_id, actor)
|
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:
|
if call is None or call.dcr_id != dcr.id:
|
||||||
raise NotFoundError("Call not found on this report", {"call_id": str(call_id)})
|
raise NotFoundError("Call not found on this report", {"call_id": str(call_id)})
|
||||||
await self.db.delete(call)
|
await self.db.delete(call)
|
||||||
@@ -435,30 +513,36 @@ class DCRService:
|
|||||||
async def set_missed_reason(
|
async def set_missed_reason(
|
||||||
self, dcr_id: uuid.UUID, payload: MissedVisitSet, actor: User, ip: str | None = None
|
self, dcr_id: uuid.UUID, payload: MissedVisitSet, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> 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)
|
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||||
if dcr.report_type != ReportType.ACTUAL or dcr.plan is None:
|
if dcr.report_type != ReportType.ACTUAL or dcr.plan is None:
|
||||||
raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)")
|
raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)")
|
||||||
if (payload.doctor_id is None) == (payload.chemist_id is None):
|
targets = [t for t in (payload.doctor_id, payload.chemist_id, payload.stockist_id) if t]
|
||||||
raise ValidationError("Give exactly one of doctor_id or chemist_id")
|
if len(targets) != 1:
|
||||||
|
raise ValidationError("Give exactly one of doctor_id, chemist_id or stockist_id")
|
||||||
reason = _clean(payload.reason)
|
reason = _clean(payload.reason)
|
||||||
if reason is None:
|
if reason is None:
|
||||||
raise ValidationError("Say briefly why the visit was missed")
|
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)
|
line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None)
|
||||||
if line is None:
|
if line is None:
|
||||||
raise ValidationError(
|
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":
|
if line.status == "VISITED":
|
||||||
raise ConflictError(
|
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)},
|
{"target_id": str(target_id)},
|
||||||
)
|
)
|
||||||
|
|
||||||
note = next(
|
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
|
before = {"reason": note.reason} if note else None
|
||||||
if note is None:
|
if note is None:
|
||||||
@@ -467,6 +551,7 @@ class DCRService:
|
|||||||
dcr_id=dcr.id,
|
dcr_id=dcr.id,
|
||||||
doctor_id=payload.doctor_id,
|
doctor_id=payload.doctor_id,
|
||||||
chemist_id=payload.chemist_id,
|
chemist_id=payload.chemist_id,
|
||||||
|
stockist_id=payload.stockist_id,
|
||||||
reason=reason,
|
reason=reason,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -499,7 +584,10 @@ class DCRService:
|
|||||||
entity_type=EntityType.DCR,
|
entity_type=EntityType.DCR,
|
||||||
entity_id=dcr.id,
|
entity_id=dcr.id,
|
||||||
action=AuditAction.DELETE,
|
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,
|
ip_address=ip,
|
||||||
)
|
)
|
||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
@@ -522,7 +610,7 @@ class DCRService:
|
|||||||
if dcr.report_type == ReportType.SELF:
|
if dcr.report_type == ReportType.SELF:
|
||||||
return await self._finalise_self_report(dcr, actor, ip)
|
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
|
return dcr # already submitted (a double click): nothing more to do
|
||||||
|
|
||||||
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
|
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
|
||||||
@@ -552,7 +640,7 @@ class DCRService:
|
|||||||
async def _finalise_self_report(
|
async def _finalise_self_report(
|
||||||
self, dcr: DailyCallReport, actor: User, ip: str | None
|
self, dcr: DailyCallReport, actor: User, ip: str | None
|
||||||
) -> DailyCallReport:
|
) -> 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:
|
if dcr.status == DCRStatus.APPROVED:
|
||||||
return dcr # already submitted (a double click)
|
return dcr # already submitted (a double click)
|
||||||
assert_editable(dcr.status)
|
assert_editable(dcr.status)
|
||||||
@@ -606,9 +694,9 @@ class DCRService:
|
|||||||
async def approve(
|
async def approve(
|
||||||
self, dcr_id: uuid.UUID, comment: str | None, actor: User, ip: str | None = None
|
self, dcr_id: uuid.UUID, comment: str | None, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> 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)
|
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
|
return dcr # already approved (a double click): the report stays as it is
|
||||||
transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role)
|
transition = assert_transition(dcr.status, WorkflowAction.APPROVE, actor.role)
|
||||||
|
|
||||||
@@ -661,9 +749,9 @@ class DCRService:
|
|||||||
async def list_for(
|
async def list_for(
|
||||||
self, actor: User, headquarters_id: uuid.UUID | None = None, **filters
|
self, actor: User, headquarters_id: uuid.UUID | None = None, **filters
|
||||||
) -> list[DailyCallReport]:
|
) -> 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 (
|
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)
|
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
|
||||||
hq_ids = await self._hq_scope(actor, headquarters_id)
|
hq_ids = await self._hq_scope(actor, headquarters_id)
|
||||||
@@ -692,7 +780,7 @@ class DCRService:
|
|||||||
return dcr
|
return dcr
|
||||||
|
|
||||||
async def _self_report_hq(self, actor: User, headquarters_id: uuid.UUID | None) -> uuid.UUID:
|
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)
|
managed = await active_hq_ids_for_am(self.db, actor.id)
|
||||||
if headquarters_id is None and len(managed) == 1:
|
if headquarters_id is None and len(managed) == 1:
|
||||||
return next(iter(managed))
|
return next(iter(managed))
|
||||||
@@ -711,14 +799,14 @@ class DCRService:
|
|||||||
|
|
||||||
def _check_submit_contents(self, dcr: DailyCallReport) -> None:
|
def _check_submit_contents(self, dcr: DailyCallReport) -> None:
|
||||||
if dcr.report_type == ReportType.PLAN:
|
if dcr.report_type == ReportType.PLAN:
|
||||||
if not dcr.doctor_calls and not dcr.chemist_calls:
|
if not dcr.doctor_calls and not dcr.chemist_calls and not dcr.stockist_calls:
|
||||||
raise ValidationError("Plan at least one doctor or chemist visit to submit")
|
raise ValidationError("Plan at least one doctor, chemist or stockist visit to submit")
|
||||||
return
|
return
|
||||||
# P3 — every planned visit is either recorded or explained.
|
# P3 — every planned visit is either recorded or explained.
|
||||||
pending = [p for p in planned_visits(dcr) if p.status == "PENDING"]
|
pending = [p for p in planned_visits(dcr) if p.status == "PENDING"]
|
||||||
if pending:
|
if pending:
|
||||||
raise ValidationError(
|
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]},
|
{"pending": [p.name for p in pending]},
|
||||||
)
|
)
|
||||||
# V4 — at least one doctor call, unless the planned visits were all explained.
|
# V4 — at least one doctor call, unless the planned visits were all explained.
|
||||||
@@ -737,7 +825,7 @@ class DCRService:
|
|||||||
if plan.status != DCRStatus.APPROVED:
|
if plan.status != DCRStatus.APPROVED:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Your Daily Call Report (Plan) for this date must be approved "
|
"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},
|
{"report_date": report_date.isoformat(), "plan_status": plan.status.value},
|
||||||
)
|
)
|
||||||
return plan
|
return plan
|
||||||
@@ -747,18 +835,21 @@ class DCRService:
|
|||||||
dcr: DailyCallReport,
|
dcr: DailyCallReport,
|
||||||
doctor_id: uuid.UUID | None = None,
|
doctor_id: uuid.UUID | None = None,
|
||||||
chemist_id: uuid.UUID | None = None,
|
chemist_id: uuid.UUID | None = None,
|
||||||
|
stockist_id: uuid.UUID | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""P4 — a recorded visit replaces any note saying it was missed."""
|
"""P4 — a recorded visit replaces any note saying it was missed."""
|
||||||
for note in dcr.missed_visits:
|
for note in dcr.missed_visits:
|
||||||
if (doctor_id and note.doctor_id == doctor_id) or (
|
if (
|
||||||
chemist_id and note.chemist_id == chemist_id
|
(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)
|
await self.db.delete(note)
|
||||||
|
|
||||||
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
|
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
|
||||||
from app.organization.models import AMHeadquarters
|
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 = (
|
stmt = (
|
||||||
select(AMHeadquarters.area_manager_user_id)
|
select(AMHeadquarters.area_manager_user_id)
|
||||||
.where(
|
.where(
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -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))
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -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."""
|
work, who they report to, their doctors and chemists, their reports and their company forms."""
|
||||||
|
|
||||||
import uuid
|
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["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in recent]
|
||||||
data["forms"] = await _forms(db, user)
|
data["forms"] = await _forms(db, user)
|
||||||
|
|
||||||
elif user.role == Role.AM:
|
elif user.role == Role.ABM:
|
||||||
managed = (
|
managed = (
|
||||||
await db.execute(
|
await db.execute(
|
||||||
select(Headquarters)
|
select(Headquarters)
|
||||||
|
|||||||
+3
-3
@@ -24,17 +24,17 @@ async def my_profile(
|
|||||||
@router.get("/{user_id}/overview")
|
@router.get("/{user_id}/overview")
|
||||||
async def user_overview(
|
async def user_overview(
|
||||||
user_id: uuid.UUID,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> dict:
|
) -> 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)
|
return await overview.user_overview(db, current_user, user_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=list[UserRead])
|
@router.get("", response_model=list[UserRead])
|
||||||
async def list_users(
|
async def list_users(
|
||||||
role: Role | None = None,
|
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),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> list[User]:
|
) -> list[User]:
|
||||||
return await UserService(db).list_users(current_user, role)
|
return await UserService(db).list_users(current_user, role)
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ class UserUpdate(BaseModel):
|
|||||||
#: A new password. Signs the user out everywhere and clears a lockout.
|
#: A new password. Signs the user out everywhere and clears a lockout.
|
||||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||||
phone: str | None = Field(default=None, max_length=20)
|
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.
|
#: assignments, and the user is signed out so they sign in again with the new role.
|
||||||
role: Role | None = None
|
role: Role | None = None
|
||||||
headquarters_id: uuid.UUID | None = None
|
headquarters_id: uuid.UUID | None = None
|
||||||
@@ -61,7 +61,7 @@ class UserRead(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class MyProfile(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
|
id: uuid.UUID
|
||||||
full_name: str
|
full_name: str
|
||||||
|
|||||||
@@ -175,14 +175,14 @@ class UserService:
|
|||||||
return user
|
return user
|
||||||
|
|
||||||
async def _end_role_assignments(self, user_id: uuid.UUID, old_role: Role) -> dict[str, int]:
|
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()
|
today = date.today()
|
||||||
if old_role in FIELD_ROLES:
|
if old_role in FIELD_ROLES:
|
||||||
targets = [
|
targets = [
|
||||||
("doctors", DoctorAssignment, DoctorAssignment.mr_user_id),
|
("doctors", DoctorAssignment, DoctorAssignment.mr_user_id),
|
||||||
("chemists", ChemistAssignment, ChemistAssignment.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)]
|
targets = [("headquarters", AMHeadquarters, AMHeadquarters.area_manager_user_id)]
|
||||||
else:
|
else:
|
||||||
return {}
|
return {}
|
||||||
@@ -204,7 +204,7 @@ class UserService:
|
|||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
async def my_profile(self, user: User) -> MyProfile:
|
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
|
hq_code = hq_name = None
|
||||||
manager_id = manager_name = None
|
manager_id = manager_name = None
|
||||||
|
|
||||||
@@ -221,7 +221,7 @@ class UserService:
|
|||||||
AMHeadquarters.effective_to.is_(None),
|
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())
|
managers = list((await self.db.execute(stmt.order_by(User.full_name))).scalars())
|
||||||
if managers:
|
if managers:
|
||||||
manager_id = managers[0].id
|
manager_id = managers[0].id
|
||||||
|
|||||||
+17
-5
@@ -26,7 +26,13 @@ services:
|
|||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 10
|
retries: 10
|
||||||
restart: unless-stopped
|
# `always`, not `unless-stopped`: after a Docker daemon restart, unless-stopped
|
||||||
|
# containers on this host stayed down until started by hand (2026-10-28, 65 min).
|
||||||
|
restart: always
|
||||||
|
# The VPS is shared and has no swap; the limit keeps one service from starving
|
||||||
|
# the box, and the negative score makes the kernel kill other workloads first.
|
||||||
|
mem_limit: 512m
|
||||||
|
oom_score_adj: -500
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
|
|
||||||
# Daily pg_dump of the whole database into ./backups on the host, the last 14 days kept.
|
# Daily pg_dump of the whole database into ./backups on the host, the last 14 days kept.
|
||||||
@@ -46,7 +52,8 @@ services:
|
|||||||
- ./backups:/backups
|
- ./backups:/backups
|
||||||
- ./scripts/backup.sh:/backup.sh:ro
|
- ./scripts/backup.sh:/backup.sh:ro
|
||||||
entrypoint: ["/bin/sh", "/backup.sh"]
|
entrypoint: ["/bin/sh", "/backup.sh"]
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
|
mem_limit: 256m
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
|
|
||||||
api:
|
api:
|
||||||
@@ -75,14 +82,18 @@ services:
|
|||||||
- no-new-privileges:true
|
- no-new-privileges:true
|
||||||
cap_drop:
|
cap_drop:
|
||||||
- ALL
|
- ALL
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
|
# Headroom for WeasyPrint PDF rendering on top of two uvicorn workers.
|
||||||
|
mem_limit: 768m
|
||||||
|
oom_score_adj: -500
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
|
|
||||||
# Responsive React web application. It is static after its production build;
|
# Responsive React web application. It is static after its production build;
|
||||||
# Caddy below provides the public TLS endpoint.
|
# Caddy below provides the public TLS endpoint.
|
||||||
web:
|
web:
|
||||||
build: ./web
|
build: ./web
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
|
mem_limit: 128m
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
|
|
||||||
# Automatic HTTPS via Let's Encrypt — two lines of config, auto-renewal,
|
# Automatic HTTPS via Let's Encrypt — two lines of config, auto-renewal,
|
||||||
@@ -103,7 +114,8 @@ services:
|
|||||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||||
- caddydata:/data
|
- caddydata:/data
|
||||||
- caddyconfig:/config
|
- caddyconfig:/config
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
|
mem_limit: 128m
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+26
-15
@@ -2,7 +2,7 @@
|
|||||||
"openapi": "3.1.0",
|
"openapi": "3.1.0",
|
||||||
"info": {
|
"info": {
|
||||||
"title": "Pharma Field Force Reporting",
|
"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"
|
"version": "0.1.0"
|
||||||
},
|
},
|
||||||
"paths": {
|
"paths": {
|
||||||
@@ -325,7 +325,7 @@
|
|||||||
"organization"
|
"organization"
|
||||||
],
|
],
|
||||||
"summary": "List Headquarters",
|
"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",
|
"operationId": "list_headquarters_api_v1_headquarters_get",
|
||||||
"responses": {
|
"responses": {
|
||||||
"200": {
|
"200": {
|
||||||
@@ -399,7 +399,7 @@
|
|||||||
"tags": [
|
"tags": [
|
||||||
"organization"
|
"organization"
|
||||||
],
|
],
|
||||||
"summary": "Assign Area Manager",
|
"summary": "Assign Area Business Manager",
|
||||||
"operationId": "assign_area_manager_api_v1_headquarters__headquarters_id__area_manager_post",
|
"operationId": "assign_area_manager_api_v1_headquarters__headquarters_id__area_manager_post",
|
||||||
"security": [
|
"security": [
|
||||||
{
|
{
|
||||||
@@ -592,7 +592,7 @@
|
|||||||
"doctors"
|
"doctors"
|
||||||
],
|
],
|
||||||
"summary": "Assign Doctor",
|
"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",
|
"operationId": "assign_doctor_api_v1_doctors__doctor_id__assign_post",
|
||||||
"security": [
|
"security": [
|
||||||
{
|
{
|
||||||
@@ -1397,7 +1397,7 @@
|
|||||||
"reports"
|
"reports"
|
||||||
],
|
],
|
||||||
"summary": "Forward",
|
"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",
|
"operationId": "forward_api_v1_dcr__dcr_id__forward_post",
|
||||||
"security": [
|
"security": [
|
||||||
{
|
{
|
||||||
@@ -1514,7 +1514,7 @@
|
|||||||
"reports"
|
"reports"
|
||||||
],
|
],
|
||||||
"summary": "Approve",
|
"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",
|
"operationId": "approve_api_v1_dcr__dcr_id__approve_post",
|
||||||
"security": [
|
"security": [
|
||||||
{
|
{
|
||||||
@@ -1719,7 +1719,7 @@
|
|||||||
"area_manager_user_id": {
|
"area_manager_user_id": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "uuid",
|
"format": "uuid",
|
||||||
"title": "Area Manager User Id"
|
"title": "Area Business Manager User Id"
|
||||||
},
|
},
|
||||||
"headquarters_id": {
|
"headquarters_id": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -1818,7 +1818,7 @@
|
|||||||
"area_manager_user_id": {
|
"area_manager_user_id": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "uuid",
|
"format": "uuid",
|
||||||
"title": "Area Manager User Id"
|
"title": "Area Business Manager User Id"
|
||||||
},
|
},
|
||||||
"effective_from": {
|
"effective_from": {
|
||||||
"anyOf": [
|
"anyOf": [
|
||||||
@@ -2530,13 +2530,13 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": [
|
"enum": [
|
||||||
"DRAFT",
|
"DRAFT",
|
||||||
"PENDING_AM",
|
"PENDING_ABM",
|
||||||
"PENDING_GM",
|
"PENDING_GM",
|
||||||
"RETURNED",
|
"RETURNED",
|
||||||
"APPROVED"
|
"APPROVED"
|
||||||
],
|
],
|
||||||
"title": "DCRStatus",
|
"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": {
|
"DCRUpdate": {
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -2806,6 +2806,17 @@
|
|||||||
"is_active": {
|
"is_active": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "Is Active"
|
"title": "Is Active"
|
||||||
|
},
|
||||||
|
"assigned_mr_name": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Assigned Mr Name"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -3185,7 +3196,7 @@
|
|||||||
"reporting_manager_name"
|
"reporting_manager_name"
|
||||||
],
|
],
|
||||||
"title": "MyProfile",
|
"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": {
|
"RefreshRequest": {
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -3220,12 +3231,12 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": [
|
"enum": [
|
||||||
"ADMIN",
|
"ADMIN",
|
||||||
"GM",
|
"AGM",
|
||||||
"AM",
|
"ABM",
|
||||||
"MR"
|
"MR"
|
||||||
],
|
],
|
||||||
"title": "Role",
|
"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": {
|
"StatusCounts": {
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -3234,7 +3245,7 @@
|
|||||||
"title": "Draft",
|
"title": "Draft",
|
||||||
"default": 0
|
"default": 0
|
||||||
},
|
},
|
||||||
"PENDING_AM": {
|
"PENDING_ABM": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
"title": "Pending Am",
|
"title": "Pending Am",
|
||||||
"default": 0
|
"default": 0
|
||||||
|
|||||||
+5
-5
@@ -1,6 +1,6 @@
|
|||||||
"""Seed the minimum MVP system described in report §10.2.
|
"""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.
|
15 doctors (3 flagged as core) and 5 chemists, all assigned to the MR.
|
||||||
|
|
||||||
python -m scripts.seed
|
python -m scripts.seed
|
||||||
@@ -64,8 +64,8 @@ async def seed() -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
admin = make(Role.ADMIN, "System Administrator", "ADM001")
|
admin = make(Role.ADMIN, "System Administrator", "ADM001")
|
||||||
gm = make(Role.GM, "Anita Mohanty", "GM001")
|
gm = make(Role.AGM, "Anita Mohanty", "GM001")
|
||||||
am = make(Role.AM, "Suresh Behera", "AM001")
|
am = make(Role.ABM, "Suresh Behera", "AM001")
|
||||||
mr = make(Role.MR, "Ravi Das", "MR001", hq.id)
|
mr = make(Role.MR, "Ravi Das", "MR001", hq.id)
|
||||||
db.add_all([admin, gm, am, mr])
|
db.add_all([admin, gm, am, mr])
|
||||||
await db.flush()
|
await db.flush()
|
||||||
@@ -113,8 +113,8 @@ async def seed() -> None:
|
|||||||
print("Seeded the minimum MVP system.\n")
|
print("Seeded the minimum MVP system.\n")
|
||||||
print(f" Password for every account: {DEMO_PASSWORD}\n")
|
print(f" Password for every account: {DEMO_PASSWORD}\n")
|
||||||
print(" System Admin adm001@acmepharma.in")
|
print(" System Admin adm001@acmepharma.in")
|
||||||
print(" General Mgr gm001@acmepharma.in")
|
print(" Assistant General Manager (AGM) gm001@acmepharma.in")
|
||||||
print(" Area Manager am001@acmepharma.in")
|
print(" Area Business Manager (ABM) am001@acmepharma.in")
|
||||||
print(" MR mr001@acmepharma.in")
|
print(" MR mr001@acmepharma.in")
|
||||||
print("\n 1 headquarters (BBSR), 15 doctors (3 core), 5 chemists — all assigned to MR001.")
|
print("\n 1 headquarters (BBSR), 15 doctors (3 core), 5 chemists — all assigned to MR001.")
|
||||||
print("\n CHANGE THESE PASSWORDS before any real use.")
|
print("\n CHANGE THESE PASSWORDS before any real use.")
|
||||||
|
|||||||
+5
-5
@@ -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.
|
# Organisation fixture: the minimum MVP system — 1 company, 2 HQs, AGM, 2 AMs, 2 MRs.
|
||||||
# The second HQ/AM/MR exist purely so the negative-scope tests (X1, X2) have someone
|
# The second HQ/ABM/MR exist purely so the negative-scope tests (X1, X2) have someone
|
||||||
# to be denied.
|
# to be denied.
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@@ -142,9 +142,9 @@ async def org(db: AsyncSession) -> dict:
|
|||||||
)
|
)
|
||||||
|
|
||||||
admin = make(Role.ADMIN, "System Admin", "ADM001")
|
admin = make(Role.ADMIN, "System Admin", "ADM001")
|
||||||
gm = make(Role.GM, "Anita Mohanty", "GM001")
|
gm = make(Role.AGM, "Anita Mohanty", "GM001")
|
||||||
am1 = make(Role.AM, "Suresh Behera", "AM001")
|
am1 = make(Role.ABM, "Suresh Behera", "AM001")
|
||||||
am2 = make(Role.AM, "Rakesh Sahu", "AM002")
|
am2 = make(Role.ABM, "Rakesh Sahu", "AM002")
|
||||||
mr1 = make(Role.MR, "Ravi Das", "MR001", hq1.id)
|
mr1 = make(Role.MR, "Ravi Das", "MR001", hq1.id)
|
||||||
mr2 = make(Role.MR, "Priya Nayak", "MR002", hq2.id)
|
mr2 = make(Role.MR, "Priya Nayak", "MR002", hq2.id)
|
||||||
db.add_all([admin, gm, am1, am2, mr1, mr2])
|
db.add_all([admin, gm, am1, am2, mr1, mr2])
|
||||||
|
|||||||
@@ -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
|
import uuid
|
||||||
|
|
||||||
@@ -104,7 +104,7 @@ class TestAreaManagerHeadquarters:
|
|||||||
for who in ("gm", "am1", "mr1"):
|
for who in ("gm", "am1", "mr1"):
|
||||||
put = await client.put(f"{API}/area-managers/{org['am1'].id}", headers=auth[who], json=body)
|
put = await client.put(f"{API}/area-managers/{org['am1'].id}", headers=auth[who], json=body)
|
||||||
assert put.status_code == 403, (who, put.text)
|
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
|
assert (await client.get(f"{API}/area-managers", headers=auth["gm"])).status_code == 200
|
||||||
for who in ("am1", "mr1"):
|
for who in ("am1", "mr1"):
|
||||||
assert (await client.get(f"{API}/area-managers", headers=auth[who])).status_code == 403
|
assert (await client.get(f"{API}/area-managers", headers=auth[who])).status_code == 403
|
||||||
|
|||||||
@@ -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
|
from datetime import date
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ class TestEndOfDayNeedsAnApprovedPlan:
|
|||||||
await _plan(client, auth, doctors, [], approve=False)
|
await _plan(client, auth, doctors, [], approve=False)
|
||||||
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
|
||||||
assert resp.status_code == 422
|
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):
|
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)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ class TestReports:
|
|||||||
first = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
first = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||||
second = 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 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 second.json()["submitted_at"] == first.json()["submitted_at"]
|
||||||
assert await _audit_count(db, dcr, "SUBMIT") == 1
|
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 == 201
|
||||||
assert (await client.post(f"{API}/products", headers=auth["admin"], json=product)).status_code == 409
|
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 == 201
|
||||||
assert (await client.post(f"{API}/users", headers=auth["admin"], json=user)).status_code == 409
|
assert (await client.post(f"{API}/users", headers=auth["admin"], json=user)).status_code == 409
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ def _by_table(resp):
|
|||||||
|
|
||||||
class TestFormApproval:
|
class TestFormApproval:
|
||||||
async def test_every_approval_form_starts_as_draft_for_everyone(self, client, auth):
|
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"]))
|
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 set(forms) == {"tour_plan", "standard_tour_plan", "fare_chart", "expense_statement"}
|
||||||
assert {f["status"] for f in forms.values()} == {"draft"}
|
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"])
|
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.status_code == 200, done.text
|
||||||
assert done.json()["status"] == "approved" and done.json()["approved_by_name"] == "Suresh Behera"
|
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"]
|
seen = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]
|
||||||
assert (seen["status"], seen["approved_by_name"]) == ("approved", "Suresh Behera")
|
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"])
|
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 early.status_code == 409, early.text
|
||||||
assert _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]["status"] == "draft"
|
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):
|
async def test_double_clicks_are_harmless(self, client, auth, org, fare_chart):
|
||||||
await _add_row(client, auth)
|
await _add_row(client, auth)
|
||||||
@@ -93,11 +93,11 @@ class TestFormApproval:
|
|||||||
assert (await change()).status_code in (200, 201)
|
assert (await change()).status_code in (200, 201)
|
||||||
state = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]
|
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
|
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.
|
# 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"])
|
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.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):
|
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.
|
# Not approved: a browser claiming otherwise changes nothing.
|
||||||
|
|||||||
@@ -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
|
from tests.e2e.test_form_ownership import forms # noqa: F401 - creates the form tables
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
import pytest
|
||||||
from sqlalchemy import text
|
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.execute(text("UPDATE am_headquarters SET effective_to = current_date WHERE headquarters_id = :h"), {"h": org["hq1"].id})
|
||||||
await db.commit()
|
await db.commit()
|
||||||
resp = await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
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):
|
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
|
from app.csv_data.router import _signature
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ async def _create_masters(client, auth, org, n_doctors=15, n_chemists=5):
|
|||||||
class TestStep1And2Setup:
|
class TestStep1And2Setup:
|
||||||
async def test_admin_creates_user_and_org_mapping(self, client, auth, org):
|
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
|
"""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"])
|
resp = await client.get(f"{API}/users/me/profile", headers=auth["mr1"])
|
||||||
assert resp.status_code == 200, resp.text
|
assert resp.status_code == 200, resp.text
|
||||||
profile = resp.json()
|
profile = resp.json()
|
||||||
@@ -120,6 +120,15 @@ class TestStep1And2Setup:
|
|||||||
|
|
||||||
|
|
||||||
class TestStep3And5Masters:
|
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):
|
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."""
|
"""Step 3 + Step 5 (S5): 15 doctors created and assigned → MR sees 15."""
|
||||||
await _create_masters(client, auth, org)
|
await _create_masters(client, auth, org)
|
||||||
@@ -288,11 +297,11 @@ class TestFullApprovalFlow:
|
|||||||
# --- Step 8: MR submits ---------------------------------------
|
# --- Step 8: MR submits ---------------------------------------
|
||||||
resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
||||||
assert resp.status_code == 200, resp.text
|
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
|
assert resp.json()["submitted_at"] is not None
|
||||||
|
|
||||||
# --- Step 9a: AM returns it -----------------------------------
|
# --- Step 9a: ABM returns it -----------------------------------
|
||||||
queue = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am1"])
|
queue = await client.get(f"{API}/dcr?status=PENDING_ABM", headers=auth["am1"])
|
||||||
assert [r["id"] for r in queue.json()] == [dcr_id]
|
assert [r["id"] for r in queue.json()] == [dcr_id]
|
||||||
|
|
||||||
# A reason is mandatory (V8).
|
# A reason is mandatory (V8).
|
||||||
@@ -309,7 +318,7 @@ class TestFullApprovalFlow:
|
|||||||
assert resp.status_code == 200, resp.text
|
assert resp.status_code == 200, resp.text
|
||||||
returned = resp.json()
|
returned = resp.json()
|
||||||
assert returned["status"] == DCRStatus.RETURNED.value
|
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"]
|
assert "chemist visits" in returned["return_reason"]
|
||||||
|
|
||||||
# The MR can edit again once returned.
|
# The MR can edit again once returned.
|
||||||
@@ -322,12 +331,12 @@ class TestFullApprovalFlow:
|
|||||||
|
|
||||||
# --- Step 9b: MR resubmits ------------------------------------
|
# --- Step 9b: MR resubmits ------------------------------------
|
||||||
resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
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.
|
# Resubmission clears the previous return.
|
||||||
assert resp.json()["return_reason"] is None
|
assert resp.json()["return_reason"] is None
|
||||||
|
|
||||||
# --- Step 10: the Area Manager gives the final approval -------
|
# --- Step 10: the Area Business Manager gives the final approval -------
|
||||||
# There is no General Manager stage, and the GM cannot approve.
|
# 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={})
|
gm_try = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["gm"], json={})
|
||||||
assert gm_try.status_code == 403, gm_try.text
|
assert gm_try.status_code == 403, gm_try.text
|
||||||
gone = await client.post(f"{API}/dcr/{dcr_id}/forward", headers=auth["am1"], json={})
|
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"):
|
for role in ("gm", "admin"):
|
||||||
again = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth[role], json={})
|
again = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth[role], json={})
|
||||||
assert again.status_code in (403, 409)
|
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={})
|
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"]
|
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.
|
# ...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"})
|
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
|
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"):
|
for role in ("mr1", "am1", "gm"):
|
||||||
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth[role])
|
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth[role])
|
||||||
assert pdf.status_code == 200, f"{role}: {pdf.text}"
|
assert pdf.status_code == 200, f"{role}: {pdf.text}"
|
||||||
@@ -399,11 +408,11 @@ class TestFullApprovalFlow:
|
|||||||
|
|
||||||
entries = history.json()
|
entries = history.json()
|
||||||
assert entries[2]["actor_name"] == "Suresh Behera"
|
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"]
|
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_name"] == "Suresh Behera"
|
||||||
assert entries[-1]["actor_role"] == "AM"
|
assert entries[-1]["actor_role"] == "ABM"
|
||||||
assert entries[-1]["comment"] == "Approved for the month."
|
assert entries[-1]["comment"] == "Approved for the month."
|
||||||
assert all(e["at"] for e in entries)
|
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)
|
await client.post(f"{API}/dcr/{dcr_id}/{action}", headers=auth["am2"], json=body)
|
||||||
).status_code == 403
|
).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() == []
|
assert listing.json() == []
|
||||||
|
|
||||||
async def test_x3_admin_cannot_approve(self, client, auth, org, approved_plan):
|
async def test_x3_admin_cannot_approve(self, client, auth, org, approved_plan):
|
||||||
@@ -470,6 +479,9 @@ class TestNegativeScope:
|
|||||||
assert (
|
assert (
|
||||||
await client.get(f"{API}/dcr/{dcr_id}", headers=auth["admin"])
|
await client.get(f"{API}/dcr/{dcr_id}", headers=auth["admin"])
|
||||||
).status_code == 200
|
).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):
|
async def test_admin_cannot_create_a_report(self, client, auth):
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
|
|||||||
@@ -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
|
from datetime import date
|
||||||
|
|
||||||
@@ -80,6 +80,37 @@ class TestAnMrsChemistWaitsToo:
|
|||||||
assert "New Pharmacy" in await _names(client, auth["mr1"], "/chemists")
|
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:
|
class TestGift:
|
||||||
async def test_a_doctor_visit_records_the_gift_and_the_pdf_notes_it(self, client, auth, org, approved_plan):
|
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")
|
doctor = await _add_doctor(client, auth, org, who="admin", name="Dr Gifted")
|
||||||
|
|||||||
@@ -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
|
from datetime import date
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ class TestSelfReport:
|
|||||||
assert report["headquarters_id"] == str(org["hq1"].id) # the one HQ am1 manages
|
assert report["headquarters_id"] == str(org["hq1"].id) # the one HQ am1 manages
|
||||||
dcr_id = report["id"]
|
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(
|
visit = await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor",
|
f"{API}/dcr/{dcr_id}/calls/doctor",
|
||||||
headers=auth["am1"],
|
headers=auth["am1"],
|
||||||
|
|||||||
@@ -23,9 +23,9 @@ class TestAdminChangesRole:
|
|||||||
)
|
)
|
||||||
assert doctor.status_code == 201
|
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.status_code == 200, resp.text
|
||||||
assert resp.json()["role"] == "AM"
|
assert resp.json()["role"] == "ABM"
|
||||||
assert resp.json()["headquarters_id"] is None
|
assert resp.json()["headquarters_id"] is None
|
||||||
|
|
||||||
# The doctor stays in the headquarters but is no longer assigned to anyone.
|
# 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()}
|
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):
|
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.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):
|
async def test_role_change_signs_the_user_out(self, client, auth, org):
|
||||||
login = await client.post(
|
login = await client.post(
|
||||||
f"{API}/auth/login",
|
f"{API}/auth/login",
|
||||||
json={"email": org["gm"].email, "password": DEFAULT_PASSWORD},
|
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(
|
again = await client.post(
|
||||||
f"{API}/auth/refresh", json={"refresh_token": login.json()["refresh_token"]}
|
f"{API}/auth/refresh", json={"refresh_token": login.json()["refresh_token"]}
|
||||||
)
|
)
|
||||||
@@ -68,9 +68,9 @@ class TestAdminChangesRole:
|
|||||||
assert resp.status_code == 422
|
assert resp.status_code == 422
|
||||||
|
|
||||||
async def test_admin_cannot_change_own_role(self, client, auth, org):
|
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
|
assert resp.status_code == 422
|
||||||
|
|
||||||
async def test_only_admin_can_change_a_role(self, client, auth, org):
|
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
|
assert resp.status_code == 403
|
||||||
|
|||||||
@@ -169,9 +169,9 @@ class TestMRRequiresHeadquarters:
|
|||||||
company_id=org["company"].id,
|
company_id=org["company"].id,
|
||||||
email="gm2@acmepharma.in",
|
email="gm2@acmepharma.in",
|
||||||
password_hash=hash_password("x" * 12),
|
password_hash=hash_password("x" * 12),
|
||||||
full_name="Wrong GM",
|
full_name="Wrong AGM",
|
||||||
employee_code="GM999",
|
employee_code="GM999",
|
||||||
role=Role.GM,
|
role=Role.AGM,
|
||||||
headquarters_id=org["hq1"].id,
|
headquarters_id=org["hq1"].id,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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.
|
# Headings exactly as printed on the company forms, in printed order.
|
||||||
PRINTED_HEADERS = {
|
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"],
|
"standard_tour_plan": ["Sl.No.", "PLACE"],
|
||||||
"fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)\n(One Way)"],
|
"fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)\n(One Way)"],
|
||||||
"area_covered": ["AREA TO COVER", "SALE OBJECTIVE", "STATUS"],
|
"area_covered": ["AREA TO COVER", "SALE OBJECTIVE", "STATUS"],
|
||||||
|
|||||||
@@ -98,3 +98,18 @@ class TestSignatures:
|
|||||||
def test_user_text_is_escaped(self):
|
def test_user_text_is_escaped(self):
|
||||||
html = _render(_context([_doctor("<script>alert(1)</script>")]))
|
html = _render(_context([_doctor("<script>alert(1)</script>")]))
|
||||||
assert "<script>" not in html
|
assert "<script>" not in html
|
||||||
|
|
||||||
|
|
||||||
|
class TestStockistVisits:
|
||||||
|
def test_stockist_table_printed_only_when_stockists_were_visited(self):
|
||||||
|
assert "NAME OF THE STOCKIST" not in _render(_context([_doctor("Dr Sen")]))
|
||||||
|
dcr = NS(
|
||||||
|
mr=NS(full_name="Sumit Patel", employee_code="MR001"), headquarters=NS(name="Bhubaneswar"),
|
||||||
|
report_date=date(2026, 9, 21), stockist_visit="", order_value="", mr_remarks="",
|
||||||
|
)
|
||||||
|
stockist = NS(stockist=NS(name="Ganesh Distributors"), pob="12000", visit_time=datetime(2026, 9, 21, 11, 0).time())
|
||||||
|
done = _render(build_dcr_context(dcr, [_doctor("Dr Sen")], [], None, None, [stockist]))
|
||||||
|
assert "NAME OF THE STOCKIST" in done and "Ganesh Distributors" in done and "12000" in done
|
||||||
|
dcr.report_type = "PLAN"
|
||||||
|
plan = _render(build_dcr_context(dcr, [], [], None, None, [stockist]))
|
||||||
|
assert "STOCKISTS TO VISIT" in plan and "11:00" in plan
|
||||||
|
|||||||
@@ -14,40 +14,40 @@ from app.common.exceptions import (
|
|||||||
class TestHappyPath:
|
class TestHappyPath:
|
||||||
def test_mr_submits_draft(self):
|
def test_mr_submits_draft(self):
|
||||||
t = assert_transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, Role.MR)
|
t = assert_transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, Role.MR)
|
||||||
assert t.to_status == DCRStatus.PENDING_AM
|
assert t.to_status == DCRStatus.PENDING_ABM
|
||||||
|
|
||||||
def test_mr_resubmits_returned(self):
|
def test_mr_resubmits_returned(self):
|
||||||
t = assert_transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, Role.MR)
|
t = assert_transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, Role.MR)
|
||||||
assert t.to_status == DCRStatus.PENDING_AM
|
assert t.to_status == DCRStatus.PENDING_ABM
|
||||||
|
|
||||||
def test_am_approves(self):
|
def test_am_approves(self):
|
||||||
t = assert_transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, Role.AM)
|
t = assert_transition(DCRStatus.PENDING_ABM, WorkflowAction.APPROVE, Role.ABM)
|
||||||
assert t.to_status == DCRStatus.APPROVED
|
assert t.to_status == DCRStatus.APPROVED
|
||||||
|
|
||||||
def test_am_returns_requires_reason(self):
|
def test_am_returns_requires_reason(self):
|
||||||
t = assert_transition(DCRStatus.PENDING_AM, WorkflowAction.RETURN, Role.AM)
|
t = assert_transition(DCRStatus.PENDING_ABM, WorkflowAction.RETURN, Role.ABM)
|
||||||
assert t.to_status == DCRStatus.RETURNED
|
assert t.to_status == DCRStatus.RETURNED
|
||||||
assert t.requires_reason is True
|
assert t.requires_reason is True
|
||||||
|
|
||||||
def test_gm_cannot_approve_or_return(self):
|
def test_gm_cannot_approve_or_return(self):
|
||||||
for action in (WorkflowAction.APPROVE, WorkflowAction.RETURN):
|
for action in (WorkflowAction.APPROVE, WorkflowAction.RETURN):
|
||||||
with pytest.raises(ForbiddenError):
|
with pytest.raises(ForbiddenError):
|
||||||
assert_transition(DCRStatus.PENDING_AM, action, Role.GM)
|
assert_transition(DCRStatus.PENDING_ABM, action, Role.AGM)
|
||||||
|
|
||||||
|
|
||||||
class TestAreaManagerIsTheFinalApprover:
|
class TestAreaManagerIsTheFinalApprover:
|
||||||
"""There is no General Manager stage: the AM approves or returns."""
|
"""There is no AGM stage: the ABM approves or returns."""
|
||||||
|
|
||||||
def test_no_general_manager_status_or_action_exists(self):
|
def test_no_general_manager_status_or_action_exists(self):
|
||||||
assert "PENDING_GM" not in {s.value for s in DCRStatus}
|
assert "PENDING_GM" not in {s.value for s in DCRStatus}
|
||||||
assert "FORWARD" not in {a.value for a in WorkflowAction}
|
assert "FORWARD" not in {a.value for a in WorkflowAction}
|
||||||
assert not [t for t in TRANSITIONS if t.allowed_role == Role.GM]
|
assert not [t for t in TRANSITIONS if t.allowed_role == Role.AGM]
|
||||||
|
|
||||||
def test_only_the_area_manager_can_decide_a_pending_report(self):
|
def test_only_the_area_manager_can_decide_a_pending_report(self):
|
||||||
for role in (Role.MR, Role.GM, Role.ADMIN):
|
for role in (Role.MR, Role.AGM, Role.ADMIN):
|
||||||
for action in (WorkflowAction.APPROVE, WorkflowAction.RETURN):
|
for action in (WorkflowAction.APPROVE, WorkflowAction.RETURN):
|
||||||
with pytest.raises(ForbiddenError):
|
with pytest.raises(ForbiddenError):
|
||||||
assert_transition(DCRStatus.PENDING_AM, action, role)
|
assert_transition(DCRStatus.PENDING_ABM, action, role)
|
||||||
|
|
||||||
|
|
||||||
class TestAdminCanNeverApprove:
|
class TestAdminCanNeverApprove:
|
||||||
@@ -80,7 +80,7 @@ class TestEditability:
|
|||||||
def test_editable(self, status):
|
def test_editable(self, status):
|
||||||
assert_editable(status) # must not raise
|
assert_editable(status) # must not raise
|
||||||
|
|
||||||
@pytest.mark.parametrize("status", [DCRStatus.PENDING_AM, DCRStatus.APPROVED])
|
@pytest.mark.parametrize("status", [DCRStatus.PENDING_ABM, DCRStatus.APPROVED])
|
||||||
def test_not_editable(self, status):
|
def test_not_editable(self, status):
|
||||||
with pytest.raises(ReportLockedError):
|
with pytest.raises(ReportLockedError):
|
||||||
assert_editable(status)
|
assert_editable(status)
|
||||||
@@ -89,11 +89,11 @@ class TestEditability:
|
|||||||
class TestWrongRoleAtRightStage:
|
class TestWrongRoleAtRightStage:
|
||||||
def test_mr_cannot_approve(self):
|
def test_mr_cannot_approve(self):
|
||||||
with pytest.raises(ForbiddenError):
|
with pytest.raises(ForbiddenError):
|
||||||
assert_transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, Role.MR)
|
assert_transition(DCRStatus.PENDING_ABM, WorkflowAction.APPROVE, Role.MR)
|
||||||
|
|
||||||
def test_gm_cannot_submit(self):
|
def test_gm_cannot_submit(self):
|
||||||
with pytest.raises(ForbiddenError):
|
with pytest.raises(ForbiddenError):
|
||||||
assert_transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, Role.GM)
|
assert_transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, Role.AGM)
|
||||||
|
|
||||||
def test_mr_cannot_return_its_own_report(self):
|
def test_mr_cannot_return_its_own_report(self):
|
||||||
with pytest.raises(InvalidStateTransitionError):
|
with pytest.raises(InvalidStateTransitionError):
|
||||||
@@ -101,6 +101,6 @@ class TestWrongRoleAtRightStage:
|
|||||||
|
|
||||||
|
|
||||||
def test_exactly_four_transitions():
|
def test_exactly_four_transitions():
|
||||||
"""submit (x2), then the Area Manager approves or returns."""
|
"""submit (x2), then the Area Business Manager approves or returns."""
|
||||||
assert len(TRANSITIONS) == 4
|
assert len(TRANSITIONS) == 4
|
||||||
assert len(DCRStatus) == 4
|
assert len(DCRStatus) == 4
|
||||||
|
|||||||
+13
-13
@@ -22,27 +22,27 @@ import type { Role } from "./types";
|
|||||||
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
|
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
|
||||||
{ pattern: "/", render: () => <DashboardPage /> },
|
{ pattern: "/", render: () => <DashboardPage /> },
|
||||||
// Daily Call Report (Plan) and (Done) each have their own list, new-report form and report pages.
|
// Daily Call Report (Plan) and (Done) each have their own list, new-report form and report pages.
|
||||||
{ pattern: "/reports", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
|
{ pattern: "/reports", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
|
||||||
{ pattern: "/reports/plan", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
|
{ pattern: "/reports/plan", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
|
||||||
{ pattern: "/reports/done", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="ACTUAL" key="ACTUAL" /> },
|
{ pattern: "/reports/done", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="ACTUAL" key="ACTUAL" /> },
|
||||||
{ pattern: "/reports/plan/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
|
{ pattern: "/reports/plan/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
|
||||||
{ pattern: "/reports/done/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="ACTUAL" key="ACTUAL" /> },
|
{ pattern: "/reports/done/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="ACTUAL" key="ACTUAL" /> },
|
||||||
{ pattern: "/reports/plan/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
{ pattern: "/reports/plan/:id", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
{ pattern: "/reports/done/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
{ pattern: "/reports/done/:id", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
{ pattern: "/reports/self", roles: ["AM", "GM"], render: () => <ReportsPage type="SELF" key="SELF" /> },
|
{ pattern: "/reports/self", roles: ["ABM", "AGM", "ADMIN"], render: () => <ReportsPage type="SELF" key="SELF" /> },
|
||||||
{ pattern: "/reports/self/new", roles: ["AM"], render: () => <NewReportPage type="SELF" key="SELF" /> },
|
{ pattern: "/reports/self/new", roles: ["ABM"], render: () => <NewReportPage type="SELF" key="SELF" /> },
|
||||||
{ pattern: "/reports/self/:id", roles: ["AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
{ pattern: "/reports/self/:id", roles: ["ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
// Links from before the split.
|
// Links from before the split.
|
||||||
{ pattern: "/reports/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
|
{ pattern: "/reports/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
|
||||||
{ pattern: "/reports/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
{ pattern: "/reports/:id", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
{ pattern: "/directory", render: () => <DirectoryPage /> },
|
{ pattern: "/directory", render: () => <DirectoryPage /> },
|
||||||
{ pattern: "/products", render: () => <ProductsPage /> },
|
{ pattern: "/products", render: () => <ProductsPage /> },
|
||||||
{ pattern: "/forms", roles: ["MR", "SFE", "AM", "GM", "ADMIN"], render: () => <FormsPage /> },
|
{ pattern: "/forms", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: () => <FormsPage /> },
|
||||||
{ pattern: "/forms/:table", roles: ["MR", "SFE", "AM", "GM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
|
{ pattern: "/forms/:table", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
|
||||||
{ pattern: "/profile", render: () => <ProfilePage /> },
|
{ pattern: "/profile", render: () => <ProfilePage /> },
|
||||||
{ pattern: "/admin", roles: ["ADMIN", "MR", "SFE"], render: () => <AdminPage /> },
|
{ pattern: "/admin", roles: ["ADMIN", "MR", "SFE"], render: () => <AdminPage /> },
|
||||||
{ pattern: "/users", roles: ["ADMIN", "GM"], render: () => <UsersPage /> },
|
{ pattern: "/users", roles: ["ADMIN", "AGM"], render: () => <UsersPage /> },
|
||||||
{ pattern: "/users/:id", roles: ["ADMIN", "GM"], render: (p) => <UserDetailPage id={p.id!} key={p.id} /> },
|
{ pattern: "/users/:id", roles: ["ADMIN", "AGM"], render: (p) => <UserDetailPage id={p.id!} key={p.id} /> },
|
||||||
];
|
];
|
||||||
|
|
||||||
function Routes({ role }: { role: Role }) {
|
function Routes({ role }: { role: Role }) {
|
||||||
|
|||||||
@@ -121,3 +121,33 @@ export async function download(url: string, filename: string): Promise<void> {
|
|||||||
link.click();
|
link.click();
|
||||||
URL.revokeObjectURL(href);
|
URL.revokeObjectURL(href);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fetch a protected PDF and show it in a new browser tab (no download). */
|
||||||
|
export async function view(url: string, init: RequestInit = {}): Promise<void> {
|
||||||
|
// Opened before the fetch so the browser treats it as part of the click, not a pop-up.
|
||||||
|
const tab = window.open("", "_blank");
|
||||||
|
try {
|
||||||
|
const headers = { ...(init.headers as Record<string, string> | undefined), Authorization: `Bearer ${accessToken}` };
|
||||||
|
const response = await fetch(url, { ...init, headers });
|
||||||
|
if (!response.ok) throw new ApiError("The PDF could not be opened", response.status);
|
||||||
|
const href = URL.createObjectURL(new Blob([await response.blob()], { type: "application/pdf" }));
|
||||||
|
if (tab) tab.location.href = href;
|
||||||
|
else window.open(href, "_blank");
|
||||||
|
setTimeout(() => URL.revokeObjectURL(href), 60_000);
|
||||||
|
} catch (err) {
|
||||||
|
tab?.close();
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST a JSON body and download the PDF the server returns. */
|
||||||
|
export async function downloadPost(url: string, body: unknown, filename: string): Promise<void> {
|
||||||
|
const response = await fetch(url, { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` } });
|
||||||
|
if (!response.ok) throw new ApiError("The PDF could not be downloaded", response.status);
|
||||||
|
const href = URL.createObjectURL(await response.blob());
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = href;
|
||||||
|
link.download = filename;
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(href);
|
||||||
|
}
|
||||||
|
|||||||
+27
-7
@@ -1,8 +1,8 @@
|
|||||||
import type {
|
import type {
|
||||||
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
|
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
|
||||||
FormApproval, Product, Profile, UserOverview, ReportType, StatusCounts, StockInventory, User,
|
FormApproval, Product, Profile, Stockist, UserOverview, ReportType, StatusCounts, StockInventory, User,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import { API_BASE, auth, download, json, request } from "./client";
|
import { API_BASE, auth, download, downloadPost, json, request, view } from "./client";
|
||||||
|
|
||||||
export { ApiError, auth } from "./client";
|
export { ApiError, auth } from "./client";
|
||||||
|
|
||||||
@@ -33,8 +33,9 @@ export const api = {
|
|||||||
updateReport: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}`, json("PATCH", payload)),
|
updateReport: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}`, json("PATCH", payload)),
|
||||||
addDoctorCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/doctor`, json("POST", payload)),
|
addDoctorCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/doctor`, json("POST", payload)),
|
||||||
addChemistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/chemist`, json("POST", payload)),
|
addChemistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/chemist`, json("POST", payload)),
|
||||||
|
addStockistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/stockist`, json("POST", payload)),
|
||||||
deleteCall: (id: string, callId: string) => request<Dcr>(`/dcr/${id}/calls/${callId}`, json("DELETE")),
|
deleteCall: (id: string, callId: string) => request<Dcr>(`/dcr/${id}/calls/${callId}`, json("DELETE")),
|
||||||
/** End-of-day report: why a planned doctor/chemist (`target` holds doctor_id or chemist_id) was not visited. */
|
/** End-of-day report: why a planned doctor/chemist/stockist (`target` holds doctor_id, chemist_id or stockist_id) was not visited. */
|
||||||
setMissedReason: (id: string, target: Payload, reason: string) => request<Dcr>(`/dcr/${id}/missed`, json("PUT", { ...target, reason })),
|
setMissedReason: (id: string, target: Payload, reason: string) => request<Dcr>(`/dcr/${id}/missed`, json("PUT", { ...target, reason })),
|
||||||
clearMissedReason: (id: string, missedId: string) => request<Dcr>(`/dcr/${id}/missed/${missedId}`, json("DELETE")),
|
clearMissedReason: (id: string, missedId: string) => request<Dcr>(`/dcr/${id}/missed/${missedId}`, json("DELETE")),
|
||||||
submit: (id: string) => request<Dcr>(`/dcr/${id}/submit`, json("POST")),
|
submit: (id: string) => request<Dcr>(`/dcr/${id}/submit`, json("POST")),
|
||||||
@@ -42,15 +43,18 @@ export const api = {
|
|||||||
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
|
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
|
||||||
approvalHistory: (id: string) => request<Approval[]>(`/audit/dcr/${id}/approval-history`),
|
approvalHistory: (id: string) => request<Approval[]>(`/audit/dcr/${id}/approval-history`),
|
||||||
downloadReportPdf: (id: string) => download(`${API_BASE}/dcr/${id}/pdf`, `DCR-${id}.pdf`),
|
downloadReportPdf: (id: string) => download(`${API_BASE}/dcr/${id}/pdf`, `DCR-${id}.pdf`),
|
||||||
|
viewReportPdf: (id: string) => view(`${API_BASE}/dcr/${id}/pdf`),
|
||||||
|
|
||||||
// masters and organisation
|
// masters and organisation
|
||||||
doctors: () => request<Doctor[]>("/doctors"),
|
doctors: () => request<Doctor[]>("/doctors"),
|
||||||
chemists: () => request<Chemist[]>("/chemists"),
|
chemists: () => request<Chemist[]>("/chemists"),
|
||||||
/** Doctors / chemists added by an MR that wait for (or were refused by) the Area Manager. */
|
stockists: () => request<Stockist[]>("/stockists"),
|
||||||
|
/** Doctors / chemists / stockists added by an MR that wait for (or were refused by) the Area Business Manager. */
|
||||||
doctorRequests: () => request<Doctor[]>("/doctors/requests"),
|
doctorRequests: () => request<Doctor[]>("/doctors/requests"),
|
||||||
chemistRequests: () => request<Chemist[]>("/chemists/requests"),
|
chemistRequests: () => request<Chemist[]>("/chemists/requests"),
|
||||||
reviewMaster: (kind: "doctor" | "chemist", id: string, approve: boolean, reason?: string) =>
|
stockistRequests: () => request<Stockist[]>("/stockists/requests"),
|
||||||
request<Doctor | Chemist>(`/${kind}s/${id}/${approve ? "approve" : "reject"}`, json("POST", approve ? undefined : { reason })),
|
reviewMaster: (kind: "doctor" | "chemist" | "stockist", id: string, approve: boolean, reason?: string) =>
|
||||||
|
request<Doctor | Chemist | Stockist>(`/${kind}s/${id}/${approve ? "approve" : "reject"}`, json("POST", approve ? undefined : { reason })),
|
||||||
headquarters: () => request<Headquarters[]>("/headquarters"),
|
headquarters: () => request<Headquarters[]>("/headquarters"),
|
||||||
users: () => request<User[]>("/users"),
|
users: () => request<User[]>("/users"),
|
||||||
userOverview: (id: string) => request<UserOverview>(`/users/${id}/overview`),
|
userOverview: (id: string) => request<UserOverview>(`/users/${id}/overview`),
|
||||||
@@ -64,6 +68,7 @@ export const api = {
|
|||||||
deleteStockItem: (id: number) => request<void>(`/products/stock-inventory/${id}`, json("DELETE")),
|
deleteStockItem: (id: number) => request<void>(`/products/stock-inventory/${id}`, json("DELETE")),
|
||||||
updateDoctor: (id: string, payload: Payload) => request<Doctor>(`/doctors/${id}`, json("PATCH", payload)),
|
updateDoctor: (id: string, payload: Payload) => request<Doctor>(`/doctors/${id}`, json("PATCH", payload)),
|
||||||
updateChemist: (id: string, payload: Payload) => request<Chemist>(`/chemists/${id}`, json("PATCH", payload)),
|
updateChemist: (id: string, payload: Payload) => request<Chemist>(`/chemists/${id}`, json("PATCH", payload)),
|
||||||
|
updateStockist: (id: string, payload: Payload) => request<Stockist>(`/stockists/${id}`, json("PATCH", payload)),
|
||||||
createHeadquarters: (payload: Payload) => request<Headquarters>("/headquarters", json("POST", payload)),
|
createHeadquarters: (payload: Payload) => request<Headquarters>("/headquarters", json("POST", payload)),
|
||||||
createUser: (payload: Payload) => request<User>("/users", json("POST", payload)),
|
createUser: (payload: Payload) => request<User>("/users", json("POST", payload)),
|
||||||
updateUser: (id: string, payload: Payload) => request<User>(`/users/${id}`, json("PATCH", payload)),
|
updateUser: (id: string, payload: Payload) => request<User>(`/users/${id}`, json("PATCH", payload)),
|
||||||
@@ -71,15 +76,18 @@ export const api = {
|
|||||||
request<unknown>(`/headquarters/${headquartersId}/area-manager`, json("POST", { area_manager_user_id })),
|
request<unknown>(`/headquarters/${headquartersId}/area-manager`, json("POST", { area_manager_user_id })),
|
||||||
createDoctor: (payload: Payload) => request<Doctor>("/doctors", json("POST", payload)),
|
createDoctor: (payload: Payload) => request<Doctor>("/doctors", json("POST", payload)),
|
||||||
createChemist: (payload: Payload) => request<Chemist>("/chemists", json("POST", payload)),
|
createChemist: (payload: Payload) => request<Chemist>("/chemists", json("POST", payload)),
|
||||||
|
createStockist: (payload: Payload) => request<Stockist>("/stockists", json("POST", payload)),
|
||||||
createProduct: (payload: Payload) => request<Product>("/products", json("POST", payload)),
|
createProduct: (payload: Payload) => request<Product>("/products", json("POST", payload)),
|
||||||
assignDoctor: (doctorId: string, mr_user_id: string) =>
|
assignDoctor: (doctorId: string, mr_user_id: string) =>
|
||||||
request<unknown>(`/doctors/${doctorId}/assign`, json("POST", { mr_user_id })),
|
request<unknown>(`/doctors/${doctorId}/assign`, json("POST", { mr_user_id })),
|
||||||
assignChemist: (chemistId: string, mr_user_id: string) =>
|
assignChemist: (chemistId: string, mr_user_id: string) =>
|
||||||
request<unknown>(`/chemists/${chemistId}/assign`, json("POST", { mr_user_id })),
|
request<unknown>(`/chemists/${chemistId}/assign`, json("POST", { mr_user_id })),
|
||||||
|
/** Administrator only: leave a doctor / chemist with no MR. */
|
||||||
|
unassignMaster: (kind: "doctor" | "chemist", id: string) => request<void>(`/${kind}s/${id}/assign`, json("DELETE")),
|
||||||
|
|
||||||
// company forms (CSV tables)
|
// company forms (CSV tables)
|
||||||
csvTables: () => request<CsvTable[]>("/csv-data/tables"),
|
csvTables: () => request<CsvTable[]>("/csv-data/tables"),
|
||||||
/** `ownerId` picks one MR's copy of a form (Area Manager and admin); an MR always gets their own. */
|
/** `ownerId` picks one MR's copy of a form (Area Business Manager and admin); an MR always gets their own. */
|
||||||
csvRows: (table: string, ownerId?: string) => request<CsvRow[]>(`/csv-data/${table}/rows${query({ owner_id: ownerId })}`),
|
csvRows: (table: string, ownerId?: string) => request<CsvRow[]>(`/csv-data/${table}/rows${query({ owner_id: ownerId })}`),
|
||||||
createCsvRow: (table: string, payload: Record<string, string>, ownerId?: string) =>
|
createCsvRow: (table: string, payload: Record<string, string>, ownerId?: string) =>
|
||||||
request<CsvRow>(`/csv-data/${table}/rows${query({ owner_id: ownerId })}`, json("POST", payload)),
|
request<CsvRow>(`/csv-data/${table}/rows${query({ owner_id: ownerId })}`, json("POST", payload)),
|
||||||
@@ -98,4 +106,16 @@ export const api = {
|
|||||||
const suffix = month ? `-${month.toLowerCase()}` : "";
|
const suffix = month ? `-${month.toLowerCase()}` : "";
|
||||||
return download(`${API_BASE}/csv-data/${table}/pdf${query({ owner_id: ownerId, month })}`, `${table}${suffix}.pdf`);
|
return download(`${API_BASE}/csv-data/${table}/pdf${query({ owner_id: ownerId, month })}`, `${table}${suffix}.pdf`);
|
||||||
},
|
},
|
||||||
|
/** Same PDF as downloadCsvPdf, shown in a new tab instead of saved. */
|
||||||
|
viewCsvPdf(table: string, opts: { rowId?: string; ownerId?: string; month?: string } = {}) {
|
||||||
|
const { rowId, ownerId, month } = opts;
|
||||||
|
if (rowId) return view(`${API_BASE}/csv-data/${table}/rows/${rowId}/pdf`);
|
||||||
|
return view(`${API_BASE}/csv-data/${table}/pdf${query({ owner_id: ownerId, month })}`);
|
||||||
|
},
|
||||||
|
/** A printable list of the doctors / chemists / stockists exactly as shown on screen. */
|
||||||
|
directoryPdf(payload: { title: string; columns: string[]; rows: Record<string, string>[] }, mode: "view" | "download") {
|
||||||
|
const url = `${API_BASE}/directory/pdf`;
|
||||||
|
if (mode === "view") return view(url, { method: "POST", body: JSON.stringify(payload), headers: { "Content-Type": "application/json" } });
|
||||||
|
return downloadPost(url, payload, `${payload.title.toLowerCase().replace(/\s+/g, "-")}.pdf`);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export function HeadquartersChecklist({ headquarters, selected, onChange, owners
|
|||||||
<input type="checkbox" checked={selected.has(h.id)} disabled={disabled} onChange={() => toggle(h.id)} />
|
<input type="checkbox" checked={selected.has(h.id)} disabled={disabled} onChange={() => toggle(h.id)} />
|
||||||
<span className="hq-check-text">
|
<span className="hq-check-text">
|
||||||
<strong>{h.code}</strong> · {h.name}
|
<strong>{h.code}</strong> · {h.name}
|
||||||
{owners[h.id] && <small>Area Manager: {owners[h.id]}</small>}
|
{owners[h.id] && <small>Area Business Manager: {owners[h.id]}</small>}
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -11,25 +11,31 @@ import { LIVE, useAsync } from "../../hooks/useAsync";
|
|||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { errorMessage, formatDate } from "../../lib/format";
|
import { errorMessage, formatDate } from "../../lib/format";
|
||||||
import { useUser } from "../../lib/session";
|
import { useUser } from "../../lib/session";
|
||||||
import type { Chemist, Doctor } from "../../types";
|
import type { Chemist, Doctor, Stockist } from "../../types";
|
||||||
|
|
||||||
type Request = { kind: "doctor" | "chemist"; item: Doctor | Chemist };
|
type Request = { kind: "doctor" | "chemist" | "stockist"; item: Doctor | Chemist | Stockist };
|
||||||
|
|
||||||
const address = (r: Request) => (r.kind === "doctor" ? (r.item as Doctor).clinic_address : (r.item as Chemist).shop_address);
|
const address = (r: Request) =>
|
||||||
|
r.kind === "doctor" ? (r.item as Doctor).clinic_address : r.kind === "chemist" ? (r.item as Chemist).shop_address : (r.item as Stockist).address;
|
||||||
|
const KIND_LABEL = { doctor: "Doctor", chemist: "Chemist", stockist: "Stockist" } as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Doctors and chemists an MR added that wait for the Area Manager.
|
* Doctors, chemists and stockists an MR added that wait for the Area Business Manager.
|
||||||
* `mine`: the MR's own requests, with any rejection and its reason.
|
* `mine`: the MR's own requests, with any rejection and its reason.
|
||||||
* `review`: what waits for this Area Manager (or the admin) to approve or reject; the GM only looks.
|
* `review`: what waits for this Area Business Manager (or the admin) to approve or reject; the AGM only looks.
|
||||||
* Shows nothing when there is nothing to show.
|
* Shows nothing when there is nothing to show.
|
||||||
*/
|
*/
|
||||||
export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review"; onReviewed?: () => void }) {
|
export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review"; onReviewed?: () => void }) {
|
||||||
const user = useUser();
|
const user = useUser();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const canAct = mode === "review" && (user.role === "AM" || user.role === "ADMIN");
|
const canAct = mode === "review" && (user.role === "ABM" || user.role === "ADMIN");
|
||||||
const data = useAsync(async () => {
|
const data = useAsync(async () => {
|
||||||
const [doctors, chemists] = await Promise.all([api.doctorRequests(), api.chemistRequests()]);
|
const [doctors, chemists, stockists] = await Promise.all([api.doctorRequests(), api.chemistRequests(), api.stockistRequests()]);
|
||||||
return [...doctors.map((item) => ({ kind: "doctor" as const, item })), ...chemists.map((item) => ({ kind: "chemist" as const, item }))]
|
return [
|
||||||
|
...doctors.map((item) => ({ kind: "doctor" as const, item })),
|
||||||
|
...chemists.map((item) => ({ kind: "chemist" as const, item })),
|
||||||
|
...stockists.map((item) => ({ kind: "stockist" as const, item })),
|
||||||
|
]
|
||||||
.sort((a, b) => b.item.created_at.localeCompare(a.item.created_at));
|
.sort((a, b) => b.item.created_at.localeCompare(a.item.created_at));
|
||||||
}, [], { poll: LIVE });
|
}, [], { poll: LIVE });
|
||||||
const [acting, setActing] = useState<string | null>(null);
|
const [acting, setActing] = useState<string | null>(null);
|
||||||
@@ -57,7 +63,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
|
|||||||
if (rows.length === 0) return null;
|
if (rows.length === 0) return null;
|
||||||
|
|
||||||
const columns: Column<Request>[] = [
|
const columns: Column<Request>[] = [
|
||||||
{ key: "kind", header: "Type", render: (r) => <Badge tone="brand">{r.kind === "doctor" ? "Doctor" : "Chemist"}</Badge>, nowrap: true },
|
{ key: "kind", header: "Type", render: (r) => <Badge tone="brand">{KIND_LABEL[r.kind]}</Badge>, nowrap: true },
|
||||||
{ key: "name", header: "Name", render: (r) => <strong>{r.item.name}</strong> },
|
{ key: "name", header: "Name", render: (r) => <strong>{r.item.name}</strong> },
|
||||||
{ key: "address", header: "Address", render: address },
|
{ key: "address", header: "Address", render: address },
|
||||||
...(mode === "review" ? [{ key: "by", header: "Added by", render: (r: Request) => r.item.requested_by_name ?? "—", nowrap: true }] : []),
|
...(mode === "review" ? [{ key: "by", header: "Added by", render: (r: Request) => r.item.requested_by_name ?? "—", nowrap: true }] : []),
|
||||||
@@ -67,7 +73,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
|
|||||||
key: "status", header: "Status",
|
key: "status", header: "Status",
|
||||||
render: (r) => r.item.approval_status === "REJECTED"
|
render: (r) => r.item.approval_status === "REJECTED"
|
||||||
? <span><Badge tone="danger" dot>Rejected</Badge>{r.item.rejection_reason && <span className="muted"> — {r.item.rejection_reason}</span>}</span>
|
? <span><Badge tone="danger" dot>Rejected</Badge>{r.item.rejection_reason && <span className="muted"> — {r.item.rejection_reason}</span>}</span>
|
||||||
: <Badge tone="warning" dot>Waiting for Area Manager</Badge>,
|
: <Badge tone="warning" dot>Waiting for Area Business Manager</Badge>,
|
||||||
}
|
}
|
||||||
: {
|
: {
|
||||||
key: "_actions", header: "", align: "right", nowrap: true,
|
key: "_actions", header: "", align: "right", nowrap: true,
|
||||||
@@ -76,7 +82,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
|
|||||||
<Button size="sm" variant="primary" icon="check" loading={acting === r.item.id} onClick={() => void decide(r, true)}>Approve</Button>
|
<Button size="sm" variant="primary" icon="check" loading={acting === r.item.id} onClick={() => void decide(r, true)}>Approve</Button>
|
||||||
<Button size="sm" variant="ghost" disabled={acting === r.item.id} onClick={() => { setRejecting(r); setReason(""); setReasonError(null); }}>Reject</Button>
|
<Button size="sm" variant="ghost" disabled={acting === r.item.id} onClick={() => { setRejecting(r); setReason(""); setReasonError(null); }}>Reject</Button>
|
||||||
</span>
|
</span>
|
||||||
) : <Badge tone="warning" dot>Waiting for Area Manager</Badge>,
|
) : <Badge tone="warning" dot>Waiting for Area Business Manager</Badge>,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -87,8 +93,8 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title={mode === "mine" ? "Your requests" : "Waiting for approval"}
|
title={mode === "mine" ? "Your requests" : "Waiting for approval"}
|
||||||
description={mode === "mine"
|
description={mode === "mine"
|
||||||
? "Doctors and chemists you added. Each joins your list once your Area Manager approves it. To re-send a rejected one, add it again with the corrected details."
|
? "Doctors, chemists and stockists you added. Each joins your list once your Area Business Manager approves it. To re-send a rejected one, add it again with the corrected details."
|
||||||
: `${pending} new doctor${pending === 1 ? "" : "s"} or chemist${pending === 1 ? "" : "s"} added by MRs. Once approved, each joins the list and is assigned to the MR who added it.`}
|
: `${pending} new doctor${pending === 1 ? "" : "s"}, chemist${pending === 1 ? "" : "s"} or stockist${pending === 1 ? "" : "s"} added by MRs. Once approved, each joins the list (doctors and chemists are assigned to the MR who added them).`}
|
||||||
/>
|
/>
|
||||||
<CardBody flush>
|
<CardBody flush>
|
||||||
<DataTable columns={columns} rows={rows} rowKey={(r) => `${r.kind}-${r.item.id}`} loading={data.loading} minWidth={720} />
|
<DataTable columns={columns} rows={rows} rowKey={(r) => `${r.kind}-${r.item.id}`} loading={data.loading} minWidth={720} />
|
||||||
@@ -106,7 +112,7 @@ export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review";
|
|||||||
}}>Reject</Button></>}
|
}}>Reject</Button></>}
|
||||||
>
|
>
|
||||||
<Field label="Reason" required error={reasonError ?? undefined} hint={`${reason.length}/500`}>
|
<Field label="Reason" required error={reasonError ?? undefined} hint={`${reason.length}/500`}>
|
||||||
<Textarea value={reason} maxLength={500} rows={3} onChange={(e) => { setReason(e.target.value); setReasonError(null); }} placeholder="e.g. Wrong clinic address, or this doctor is already in the list" />
|
<Textarea value={reason} maxLength={500} rows={3} onChange={(e) => { setReason(e.target.value); setReasonError(null); }} placeholder="e.g. Wrong address, or this one is already in the list" />
|
||||||
</Field>
|
</Field>
|
||||||
</Modal>
|
</Modal>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ export function Sidebar({ role, path, collapsed, mobileOpen, onToggleCollapsed,
|
|||||||
role: Role; path: string; collapsed: boolean; mobileOpen: boolean;
|
role: Role; path: string; collapsed: boolean; mobileOpen: boolean;
|
||||||
onToggleCollapsed: () => void; onNavigate: () => void;
|
onToggleCollapsed: () => void; onNavigate: () => void;
|
||||||
}) {
|
}) {
|
||||||
// An Area Manager is told how many new doctors / chemists wait for their approval.
|
// An Area Business Manager is told how many new doctors / chemists wait for their approval.
|
||||||
const waiting = useAsync(
|
const waiting = useAsync(
|
||||||
async () => (role === "AM" ? (await Promise.all([api.doctorRequests(), api.chemistRequests()])).reduce((n, list) => n + list.length, 0) : 0),
|
async () => (role === "ABM" ? (await Promise.all([api.doctorRequests(), api.chemistRequests()])).reduce((n, list) => n + list.length, 0) : 0),
|
||||||
[role], { poll: LIVE },
|
[role], { poll: LIVE },
|
||||||
);
|
);
|
||||||
const flags: Record<string, number> = { "/directory": waiting.data ?? 0 };
|
const flags: Record<string, number> = { "/directory": waiting.data ?? 0 };
|
||||||
|
|||||||
@@ -8,18 +8,22 @@ import { api } from "../../api";
|
|||||||
import { useAsync } from "../../hooks/useAsync";
|
import { useAsync } from "../../hooks/useAsync";
|
||||||
import { errorMessage, nowHHMM, todayISO } from "../../lib/format";
|
import { errorMessage, nowHHMM, todayISO } from "../../lib/format";
|
||||||
import { amount, maxLength, required, useValidation } from "../../lib/validation";
|
import { amount, maxLength, required, useValidation } from "../../lib/validation";
|
||||||
import type { Chemist, Dcr, Doctor } from "../../types";
|
import type { Chemist, Dcr, Doctor, Stockist } from "../../types";
|
||||||
|
|
||||||
/** Pre-selects a doctor/chemist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
|
export type VisitKind = "doctor" | "chemist" | "stockist";
|
||||||
export interface VisitPreset { kind: "doctor" | "chemist"; targetId: string; key: number }
|
|
||||||
|
|
||||||
export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
/** Pre-selects a doctor/chemist/stockist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
|
||||||
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
|
export interface VisitPreset { kind: VisitKind; targetId: string; key: number }
|
||||||
|
|
||||||
|
const KIND_LABEL: Record<VisitKind, string> = { doctor: "Doctor", chemist: "Chemist", stockist: "Stockist" };
|
||||||
|
|
||||||
|
export function AddVisitForm({ dcr, doctors, chemists, stockists, onChange, preset }: {
|
||||||
|
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; stockists: Stockist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
|
||||||
}) {
|
}) {
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const products = useAsync(api.stockInventory, []);
|
const products = useAsync(api.stockInventory, []);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [kind, setKind] = useState<"doctor" | "chemist">("doctor");
|
const [kind, setKind] = useState<VisitKind>("doctor");
|
||||||
const [targetId, setTargetId] = useState("");
|
const [targetId, setTargetId] = useState("");
|
||||||
const [time, setTime] = useState(nowHHMM);
|
const [time, setTime] = useState(nowHHMM);
|
||||||
const [outcome, setOutcome] = useState("MET");
|
const [outcome, setOutcome] = useState("MET");
|
||||||
@@ -33,7 +37,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
|||||||
const formRef = useRef<HTMLFormElement>(null);
|
const formRef = useRef<HTMLFormElement>(null);
|
||||||
// A day plan records who and when only; outcomes, products and POB come at the end of the day.
|
// A day plan records who and when only; outcomes, products and POB come at the end of the day.
|
||||||
const isPlan = dcr.report_type === "PLAN";
|
const isPlan = dcr.report_type === "PLAN";
|
||||||
// An Area Manager's own report lists the headquarters' doctors and chemists, not assigned ones.
|
// An Area Business Manager's own report lists the headquarters' doctors and chemists, not assigned ones.
|
||||||
const isSelf = dcr.report_type === "SELF";
|
const isSelf = dcr.report_type === "SELF";
|
||||||
const productNames = (products.data ?? []).map((p) => p.product_name);
|
const productNames = (products.data ?? []).map((p) => p.product_name);
|
||||||
|
|
||||||
@@ -47,11 +51,11 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
|||||||
}, [preset?.key]);
|
}, [preset?.key]);
|
||||||
|
|
||||||
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
|
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
|
||||||
const options = kind === "doctor" ? doctors : chemists;
|
const options = kind === "doctor" ? doctors : kind === "chemist" ? chemists : stockists;
|
||||||
// Visit times are local; today's report cannot hold a visit later than now.
|
// Visit times are local; today's report cannot hold a visit later than now.
|
||||||
const isToday = !isPlan && dcr.report_date === todayISO();
|
const isToday = !isPlan && dcr.report_date === todayISO();
|
||||||
const timeLabel = isPlan ? "Planned time" : "Visit time";
|
const timeLabel = isPlan ? "Planned time" : "Visit time";
|
||||||
const label = kind === "doctor" ? "Doctor" : "Chemist";
|
const label = KIND_LABEL[kind];
|
||||||
|
|
||||||
const v = useValidation({
|
const v = useValidation({
|
||||||
target: [required(label)],
|
target: [required(label)],
|
||||||
@@ -70,7 +74,9 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
|||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const updated = isPlan
|
const updated = kind === "stockist"
|
||||||
|
? await api.addStockistCall(dcr.id, { stockist_id: targetId, visit_time: time, pob: isPlan ? null : pob.trim() || null, remarks: remarks.trim() || null })
|
||||||
|
: isPlan
|
||||||
? kind === "doctor"
|
? kind === "doctor"
|
||||||
? await api.addDoctorCall(dcr.id, { doctor_id: targetId, visit_time: time, remarks: remarks.trim() || null })
|
? await api.addDoctorCall(dcr.id, { doctor_id: targetId, visit_time: time, remarks: remarks.trim() || null })
|
||||||
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, remarks: remarks.trim() || null })
|
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, remarks: remarks.trim() || null })
|
||||||
@@ -96,14 +102,15 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
|||||||
<form ref={formRef} className="form-grid" onSubmit={submit} noValidate>
|
<form ref={formRef} className="form-grid" onSubmit={submit} noValidate>
|
||||||
<Alert>{error}</Alert>
|
<Alert>{error}</Alert>
|
||||||
<Field label="Visit type">
|
<Field label="Visit type">
|
||||||
<Select value={kind} onChange={(e) => { setKind(e.target.value as "doctor" | "chemist"); setTargetId(""); v.clear(); }}>
|
<Select value={kind} onChange={(e) => { setKind(e.target.value as VisitKind); setTargetId(""); v.clear(); }}>
|
||||||
<option value="doctor">Doctor</option>
|
<option value="doctor">Doctor</option>
|
||||||
<option value="chemist">Chemist</option>
|
<option value="chemist">Chemist</option>
|
||||||
|
<option value="stockist">Stockist</option>
|
||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : `No ${kind}s are assigned to you yet — ask your administrator to assign some.`) : undefined}>
|
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : kind === "stockist" ? "Your headquarters has no stockists yet — ask your administrator to add some." : `No ${kind}s are assigned to you yet — ask your administrator to assign some.`) : undefined}>
|
||||||
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
|
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
|
||||||
<option value="">{isSelf ? `Choose a ${kind}` : `Choose an assigned ${kind}`}</option>
|
<option value="">{isSelf || kind === "stockist" ? `Choose a ${kind}` : `Choose an assigned ${kind}`}</option>
|
||||||
{options.map((o) => (
|
{options.map((o) => (
|
||||||
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
|
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { EmptyState } from "../ui/States";
|
import { EmptyState } from "../ui/States";
|
||||||
import { formatDateTime } from "../../lib/format";
|
import { formatDateTime, roleLabel } from "../../lib/format";
|
||||||
import type { Approval } from "../../types";
|
import type { Approval } from "../../types";
|
||||||
|
|
||||||
export function ApprovalTimeline({ items }: { items: Approval[] }) {
|
export function ApprovalTimeline({ items }: { items: Approval[] }) {
|
||||||
@@ -11,7 +11,7 @@ export function ApprovalTimeline({ items }: { items: Approval[] }) {
|
|||||||
<span className="timeline-dot" />
|
<span className="timeline-dot" />
|
||||||
<div>
|
<div>
|
||||||
<p className="timeline-action">{item.action.replaceAll("_", " ")}</p>
|
<p className="timeline-action">{item.action.replaceAll("_", " ")}</p>
|
||||||
<p className="timeline-meta">{item.actor_name} · {item.actor_role}</p>
|
<p className="timeline-meta">{item.actor_name} · {roleLabel(item.actor_role)}</p>
|
||||||
<time className="timeline-meta">{formatDateTime(item.at)}</time>
|
<time className="timeline-meta">{formatDateTime(item.at)}</time>
|
||||||
{item.comment && <p className="timeline-note">{item.comment}</p>}
|
{item.comment && <p className="timeline-note">{item.comment}</p>}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { Field, Textarea } from "../ui/Field";
|
|||||||
import { EmptyState } from "../ui/States";
|
import { EmptyState } from "../ui/States";
|
||||||
import type { Dcr, PlannedVisit } from "../../types";
|
import type { Dcr, PlannedVisit } from "../../types";
|
||||||
|
|
||||||
|
const KIND_LABEL: Record<PlannedVisit["kind"], string> = { DOCTOR: "Doctor", CHEMIST: "Chemist", STOCKIST: "Stockist" };
|
||||||
|
|
||||||
const STATUS: Record<PlannedVisit["status"], { label: string; tone: "success" | "warning" | "danger" }> = {
|
const STATUS: Record<PlannedVisit["status"], { label: string; tone: "success" | "warning" | "danger" }> = {
|
||||||
VISITED: { label: "Visited", tone: "success" },
|
VISITED: { label: "Visited", tone: "success" },
|
||||||
MISSED: { label: "Missed", tone: "warning" },
|
MISSED: { label: "Missed", tone: "warning" },
|
||||||
@@ -50,7 +52,7 @@ export function PlannedVisitList({ dcr, editable, onRecord, onSaveReason, onClea
|
|||||||
<span className="visit-time">{line.planned_time.slice(0, 5)}</span>
|
<span className="visit-time">{line.planned_time.slice(0, 5)}</span>
|
||||||
<div className="visit-main">
|
<div className="visit-main">
|
||||||
<p>
|
<p>
|
||||||
<strong>{line.name}</strong> <Badge tone={line.kind === "DOCTOR" ? "brand" : "neutral"}>{line.kind === "DOCTOR" ? "Doctor" : "Chemist"}</Badge>
|
<strong>{line.name}</strong> <Badge tone={line.kind === "DOCTOR" ? "brand" : "neutral"}>{KIND_LABEL[line.kind]}</Badge>
|
||||||
{line.is_core_doctor && <> <Badge tone="warning">Core</Badge></>} <Badge tone={status.tone} dot>{status.label}</Badge>
|
{line.is_core_doctor && <> <Badge tone="warning">Core</Badge></>} <Badge tone={status.tone} dot>{status.label}</Badge>
|
||||||
</p>
|
</p>
|
||||||
{line.status === "MISSED" && !isEditing && <p className="visit-detail">Why missed: {line.missed_reason}</p>}
|
{line.status === "MISSED" && !isEditing && <p className="visit-detail">Why missed: {line.missed_reason}</p>}
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ export function ReviewPanel({ dcr, role, busy, onDecide }: {
|
|||||||
}) {
|
}) {
|
||||||
const [comment, setComment] = useState("");
|
const [comment, setComment] = useState("");
|
||||||
const [problem, setProblem] = useState<string | null>(null);
|
const [problem, setProblem] = useState<string | null>(null);
|
||||||
// The Area Manager is the final approver: approve and lock, or return for correction.
|
// The Area Business Manager is the final approver: approve and lock, or return for correction.
|
||||||
const canDecide = role === "AM" && dcr.status === "PENDING_AM";
|
const canDecide = role === "ABM" && dcr.status === "PENDING_ABM";
|
||||||
if (!canDecide) return null;
|
if (!canDecide) return null;
|
||||||
|
|
||||||
const check = (action: ReviewAction, text: string): string | null =>
|
const check = (action: ReviewAction, text: string): string | null =>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type { DcrStatus, ReportType } from "../../types";
|
|||||||
|
|
||||||
const TONE: Record<DcrStatus, Tone> = {
|
const TONE: Record<DcrStatus, Tone> = {
|
||||||
DRAFT: "neutral",
|
DRAFT: "neutral",
|
||||||
PENDING_AM: "warning",
|
PENDING_ABM: "warning",
|
||||||
RETURNED: "danger",
|
RETURNED: "danger",
|
||||||
APPROVED: "success",
|
APPROVED: "success",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { EmptyState } from "../ui/States";
|
|||||||
import { humanize } from "../../lib/format";
|
import { humanize } from "../../lib/format";
|
||||||
import type { Dcr } from "../../types";
|
import type { Dcr } from "../../types";
|
||||||
|
|
||||||
interface Visit { id: string; kind: "Doctor" | "Chemist"; name: string; time: string; detail: string; core: boolean }
|
interface Visit { id: string; kind: "Doctor" | "Chemist" | "Stockist"; name: string; time: string; detail: string; core: boolean }
|
||||||
|
|
||||||
export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boolean; onRemove: (callId: string) => void }) {
|
export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boolean; onRemove: (callId: string) => void }) {
|
||||||
const visits: Visit[] = [
|
const visits: Visit[] = [
|
||||||
@@ -15,6 +15,9 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
|
|||||||
...dcr.chemist_calls.map((c) => ({
|
...dcr.chemist_calls.map((c) => ({
|
||||||
id: c.id, kind: "Chemist" as const, name: c.chemist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
|
id: c.id, kind: "Chemist" as const, name: c.chemist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
|
||||||
})),
|
})),
|
||||||
|
...(dcr.stockist_calls ?? []).map((c) => ({
|
||||||
|
id: c.id, kind: "Stockist" as const, name: c.stockist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
|
||||||
|
})),
|
||||||
].sort((a, b) => a.time.localeCompare(b.time));
|
].sort((a, b) => a.time.localeCompare(b.time));
|
||||||
|
|
||||||
if (visits.length === 0) {
|
if (visits.length === 0) {
|
||||||
@@ -23,7 +26,7 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
|
|||||||
<EmptyState
|
<EmptyState
|
||||||
icon="stethoscope"
|
icon="stethoscope"
|
||||||
title={plan ? "No visits planned" : "No visits recorded"}
|
title={plan ? "No visits planned" : "No visits recorded"}
|
||||||
description={editable ? (plan ? "Add the doctors and chemists you plan to visit above." : "Add doctor and chemist visits above.") : undefined}
|
description={editable ? (plan ? "Add the doctors, chemists and stockists you plan to visit above." : "Add doctor, chemist and stockist visits above.") : undefined}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import { Icon } from "../ui/Icon";
|
import { Icon } from "../ui/Icon";
|
||||||
import type { DcrStatus, ReportType } from "../../types";
|
import type { DcrStatus, ReportType } from "../../types";
|
||||||
|
|
||||||
const STEPS = ["Draft", "Area Manager", "Approved"];
|
const STEPS = ["Draft", "Area Business Manager (ABM)", "Approved"];
|
||||||
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_AM: 1, APPROVED: 2 };
|
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_ABM: 1, APPROVED: 2 };
|
||||||
/** An Area Manager's own report goes straight from draft to final. */
|
/** An Area Business Manager's own report goes straight from draft to final. */
|
||||||
const SELF_STEPS = ["Draft", "Submitted"];
|
const SELF_STEPS = ["Draft", "Submitted"];
|
||||||
|
|
||||||
/** Where a report is in DRAFT → AM → APPROVED. A returned report sits back at step one. */
|
/** Where a report is in DRAFT → ABM → APPROVED. A returned report sits back at step one. */
|
||||||
export function WorkflowTracker({ status, type }: { status: DcrStatus; type?: ReportType }) {
|
export function WorkflowTracker({ status, type }: { status: DcrStatus; type?: ReportType }) {
|
||||||
const steps = type === "SELF" ? SELF_STEPS : STEPS;
|
const steps = type === "SELF" ? SELF_STEPS : STEPS;
|
||||||
const current = Math.min(INDEX[status], steps.length - 1);
|
const current = Math.min(INDEX[status], steps.length - 1);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { SVGProps } from "react";
|
|||||||
|
|
||||||
const PATHS = {
|
const PATHS = {
|
||||||
dashboard: "M3 3h7v9H3z M14 3h7v5h-7z M14 12h7v9h-7z M3 16h7v5H3z",
|
dashboard: "M3 3h7v9H3z M14 3h7v5h-7z M14 12h7v9h-7z M3 16h7v5H3z",
|
||||||
|
eye: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6",
|
||||||
file: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z M14 3v5h5 M9 13h6 M9 17h6",
|
file: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z M14 3v5h5 M9 13h6 M9 17h6",
|
||||||
stethoscope: "M6 3v6a4 4 0 0 0 8 0V3 M4 3h4 M12 3h4 M10 13v2a5 5 0 0 0 10 0v-2 M20 8a2 2 0 1 0 0 4 2 2 0 0 0 0-4z",
|
stethoscope: "M6 3v6a4 4 0 0 0 8 0V3 M4 3h4 M12 3h4 M10 13v2a5 5 0 0 0 10 0v-2 M20 8a2 2 0 1 0 0 4 2 2 0 0 0 0-4z",
|
||||||
box: "M21 8l-9-5-9 5v8l9 5 9-5z M3 8l9 5 9-5 M12 13v9",
|
box: "M21 8l-9-5-9 5v8l9 5 9-5z M3 8l9 5 9-5 M12 13v9",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { DcrStatus, ReportType, Role } from "../types";
|
|||||||
|
|
||||||
export const STATUS_LABEL: Record<DcrStatus, string> = {
|
export const STATUS_LABEL: Record<DcrStatus, string> = {
|
||||||
DRAFT: "Draft",
|
DRAFT: "Draft",
|
||||||
PENDING_AM: "With Area Manager",
|
PENDING_ABM: "With Area Business Manager (ABM)",
|
||||||
RETURNED: "Returned",
|
RETURNED: "Returned",
|
||||||
APPROVED: "Approved",
|
APPROVED: "Approved",
|
||||||
};
|
};
|
||||||
@@ -10,7 +10,7 @@ export const STATUS_LABEL: Record<DcrStatus, string> = {
|
|||||||
export const REPORT_TYPE_LABEL: Record<ReportType, string> = { PLAN: "Daily Call Report (Plan)", ACTUAL: "Daily Call Report (Done)", SELF: "Daily Call Report (Self)" };
|
export const REPORT_TYPE_LABEL: Record<ReportType, string> = { PLAN: "Daily Call Report (Plan)", ACTUAL: "Daily Call Report (Done)", SELF: "Daily Call Report (Self)" };
|
||||||
/** Short form for badges and tight spaces. */
|
/** Short form for badges and tight spaces. */
|
||||||
export const REPORT_TYPE_SHORT: Record<ReportType, string> = { PLAN: "Plan", ACTUAL: "Done", SELF: "Self" };
|
export const REPORT_TYPE_SHORT: Record<ReportType, string> = { PLAN: "Plan", ACTUAL: "Done", SELF: "Self" };
|
||||||
/** An Area Manager's own report has no approval: once submitted it is final. */
|
/** An Area Business Manager's own report has no approval: once submitted it is final. */
|
||||||
export const statusLabel = (status: DcrStatus, type?: ReportType) => (type === "SELF" && status === "APPROVED" ? "Submitted" : STATUS_LABEL[status]);
|
export const statusLabel = (status: DcrStatus, type?: ReportType) => (type === "SELF" && status === "APPROVED" ? "Submitted" : STATUS_LABEL[status]);
|
||||||
|
|
||||||
/** The roles that do field work and file reports: an SFE does an MR's work. */
|
/** The roles that do field work and file reports: an SFE does an MR's work. */
|
||||||
@@ -19,11 +19,14 @@ export const isField = (role: string): boolean => role === "MR" || role === "SFE
|
|||||||
export const ROLE_LABEL: Record<Role, string> = {
|
export const ROLE_LABEL: Record<Role, string> = {
|
||||||
MR: "Medical Representative",
|
MR: "Medical Representative",
|
||||||
SFE: "Senior Field Executive",
|
SFE: "Senior Field Executive",
|
||||||
AM: "Area Manager",
|
ABM: "Area Business Manager (ABM)",
|
||||||
GM: "General Manager",
|
AGM: "Assistant General Manager (AGM)",
|
||||||
ADMIN: "Administrator",
|
ADMIN: "Administrator",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const ROLE_LABELS: ReadonlyMap<string, string> = new Map(Object.entries(ROLE_LABEL));
|
||||||
|
export const roleLabel = (role: string) => ROLE_LABELS.get(role) ?? role;
|
||||||
|
|
||||||
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
|
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
|
||||||
/** Today's local date as YYYY-MM-DD, or `days` from today. */
|
/** Today's local date as YYYY-MM-DD, or `days` from today. */
|
||||||
export const todayISO = (days = 0) => {
|
export const todayISO = (days = 0) => {
|
||||||
@@ -74,6 +77,7 @@ const COLUMN_LABEL_OVERRIDES: Record<string, string> = {
|
|||||||
postage: "Postage (Rs)",
|
postage: "Postage (Rs)",
|
||||||
other_expense: "Other expense (Rs)",
|
other_expense: "Other expense (Rs)",
|
||||||
total: "Total (Rs)",
|
total: "Total (Rs)",
|
||||||
|
stockiest_visit: "Stockist Visit",
|
||||||
};
|
};
|
||||||
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
|
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { isField } from "./format";
|
import { isField } from "./format";
|
||||||
import type { AreaManagerMapping, Headquarters, User } from "../types";
|
import type { AreaManagerMapping, Headquarters, User } from "../types";
|
||||||
|
|
||||||
/** Headquarters a person works in: an MR has one, an AM has any number, GM and Admin cover all. */
|
/** Headquarters a person works in: an MR has one, an ABM has any number, AGM and Admin cover all. */
|
||||||
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
|
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
|
||||||
if (user.role === "GM" || user.role === "ADMIN") return { all: true, items: [] };
|
if (user.role === "AGM" || user.role === "ADMIN") return { all: true, items: [] };
|
||||||
const ids = isField(user.role)
|
const ids = isField(user.role)
|
||||||
? [...(user.headquarters_id ? [user.headquarters_id] : []), ...(user.extra_headquarter_ids ?? [])]
|
? [...(user.headquarters_id ? [user.headquarters_id] : []), ...(user.extra_headquarter_ids ?? [])]
|
||||||
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
|
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
|
||||||
@@ -12,15 +12,15 @@ export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaMa
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Area Managers of each headquarters, by name ("Asha Rao, Ravi Das"). A headquarters may
|
* The Area Business Managers of each headquarters, by name ("Asha Rao, Ravi Das"). A headquarters may
|
||||||
* have several. `except` leaves one Area Manager out, e.g. the one whose headquarters are being edited.
|
* have several. `except` leaves one Area Business Manager out, e.g. the one whose headquarters are being edited.
|
||||||
*/
|
*/
|
||||||
export function areaManagersOf(mappings: AreaManagerMapping[], users: User[], except?: string): Record<string, string> {
|
export function areaManagersOf(mappings: AreaManagerMapping[], users: User[], except?: string): Record<string, string> {
|
||||||
const name = new Map(users.map((u) => [u.id, u.full_name]));
|
const name = new Map(users.map((u) => [u.id, u.full_name]));
|
||||||
const byHq = new Map<string, string[]>();
|
const byHq = new Map<string, string[]>();
|
||||||
for (const m of mappings) {
|
for (const m of mappings) {
|
||||||
if (m.area_manager_user_id === except) continue;
|
if (m.area_manager_user_id === except) continue;
|
||||||
byHq.set(m.headquarters_id, [...(byHq.get(m.headquarters_id) ?? []), name.get(m.area_manager_user_id) ?? "an Area Manager"]);
|
byHq.set(m.headquarters_id, [...(byHq.get(m.headquarters_id) ?? []), name.get(m.area_manager_user_id) ?? "an Area Business Manager"]);
|
||||||
}
|
}
|
||||||
return Object.fromEntries([...byHq].map(([hq, names]) => [hq, names.sort().join(", ")]));
|
return Object.fromEntries([...byHq].map(([hq, names]) => [hq, names.sort().join(", ")]));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,9 +24,9 @@ export const NAVIGATION: NavSection[] = [
|
|||||||
title: "Workspace",
|
title: "Workspace",
|
||||||
items: [
|
items: [
|
||||||
{ to: "/", label: "Dashboard", icon: "dashboard" },
|
{ to: "/", label: "Dashboard", icon: "dashboard" },
|
||||||
{ to: "/reports/plan", label: "Daily Call Report (Plan)", icon: "file", roles: ["MR", "SFE", "AM", "GM"] },
|
{ to: "/reports/plan", label: "Daily Call Report (Plan)", icon: "file", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"] },
|
||||||
{ to: "/reports/done", label: "Daily Call Report (Done)", icon: "checkCircle", roles: ["MR", "SFE", "AM", "GM"] },
|
{ to: "/reports/done", label: "Daily Call Report (Done)", icon: "checkCircle", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"] },
|
||||||
{ to: "/reports/self", label: "Daily Call Report (Self)", icon: "file", roles: ["AM", "GM"] },
|
{ to: "/reports/self", label: "Daily Call Report (Self)", icon: "file", roles: ["ABM", "AGM", "ADMIN"] },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -34,14 +34,14 @@ export const NAVIGATION: NavSection[] = [
|
|||||||
items: [
|
items: [
|
||||||
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
|
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
|
||||||
{ to: "/products", label: "Products", icon: "box" },
|
{ to: "/products", label: "Products", icon: "box" },
|
||||||
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "SFE", "AM", "GM", "ADMIN"] },
|
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "SFE", "ABM", "AGM", "ADMIN"] },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Administration",
|
title: "Administration",
|
||||||
items: [
|
items: [
|
||||||
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN", "MR", "SFE"] },
|
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN", "MR", "SFE"] },
|
||||||
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
|
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "AGM"] },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ import { ROLE_LABEL, isField } from "../lib/format";
|
|||||||
import { headquartersOf } from "../lib/headquarters";
|
import { headquartersOf } from "../lib/headquarters";
|
||||||
import type { DcrListItem, Headquarters, Role, User } from "../types";
|
import type { DcrListItem, Headquarters, Role, User } from "../types";
|
||||||
|
|
||||||
const WAITING: Record<"MR" | "AM", { statuses: DcrListItem["status"][]; title: string; empty: string }> = {
|
const WAITING: Record<"MR" | "ABM", { statuses: DcrListItem["status"][]; title: string; empty: string }> = {
|
||||||
MR: { statuses: ["RETURNED", "DRAFT"], title: "Waiting on you", empty: "No drafts or reports sent back for correction." },
|
MR: { statuses: ["RETURNED", "DRAFT"], title: "Waiting on you", empty: "No drafts or reports sent back for correction." },
|
||||||
AM: { statuses: ["PENDING_AM"], title: "Waiting on you", empty: "No reports are waiting for your review." },
|
ABM: { statuses: ["PENDING_ABM"], title: "Waiting on you", empty: "No reports are waiting for your review." },
|
||||||
};
|
};
|
||||||
|
|
||||||
export function DashboardPage() {
|
export function DashboardPage() {
|
||||||
@@ -42,40 +42,40 @@ function HeadquartersFilter({ value, onChange }: { value: string; onChange: (id:
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
|
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
|
||||||
// The General Manager looks across every headquarters, so they can narrow it to one.
|
// The Assistant General Manager looks across every headquarters, so they can narrow it to one.
|
||||||
const [hq, setHq] = useState("");
|
const [hq, setHq] = useState("");
|
||||||
const hqId = role === "GM" ? hq || undefined : undefined;
|
const hqId = role === "AGM" ? hq || undefined : undefined;
|
||||||
const counts = useAsync(() => api.counts(hqId), [hqId], { poll: LIVE });
|
const counts = useAsync(() => api.counts(hqId), [hqId], { poll: LIVE });
|
||||||
const reports = useAsync(() => api.reports(undefined, hqId), [hqId], { poll: LIVE });
|
const reports = useAsync(() => api.reports(undefined, hqId), [hqId], { poll: LIVE });
|
||||||
const isMR = isField(role);
|
const isMR = isField(role);
|
||||||
// A General Manager has no approval step — they get a read-only overview.
|
// An Assistant General Manager has no approval step — they get a read-only overview.
|
||||||
const config = role === "GM" ? null : WAITING[isField(role) ? "MR" : (role as "AM")];
|
const config = role === "AGM" ? null : WAITING[isField(role) ? "MR" : (role as "ABM")];
|
||||||
const all = reports.data ?? [];
|
const all = reports.data ?? [];
|
||||||
const waiting = config ? all.filter((r) => config.statuses.includes(r.status)) : [];
|
const waiting = config ? all.filter((r) => config.statuses.includes(r.status)) : [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={isMR ? `Good to see you, ${name}` : role === "GM" ? "Reports overview" : "Your review queue"}
|
title={isMR ? `Good to see you, ${name}` : role === "AGM" ? "Reports overview" : "Your review queue"}
|
||||||
description={isMR ? "Track drafts, submissions and anything sent back for correction." : role === "GM" ? "A read-only view of every report across all headquarters." : "Reports from your scope awaiting your decision."}
|
description={isMR ? "Track drafts, submissions and anything sent back for correction." : role === "AGM" ? "A read-only view of every report across all headquarters." : "Reports from your scope awaiting your decision."}
|
||||||
actions={isMR
|
actions={isMR
|
||||||
? <>
|
? <>
|
||||||
<Button icon="plus" onClick={() => navigate("/reports/done/new")}>New report (Done)</Button>
|
<Button icon="plus" onClick={() => navigate("/reports/done/new")}>New report (Done)</Button>
|
||||||
<Button variant="primary" icon="plus" onClick={() => navigate("/reports/plan/new")}>Plan my day</Button>
|
<Button variant="primary" icon="plus" onClick={() => navigate("/reports/plan/new")}>Plan my day</Button>
|
||||||
</>
|
</>
|
||||||
: <>
|
: <>
|
||||||
{role === "GM" && <HeadquartersFilter value={hq} onChange={setHq} />}
|
{role === "AGM" && <HeadquartersFilter value={hq} onChange={setHq} />}
|
||||||
<Button icon="file" onClick={() => navigate("/reports/plan")}>View all reports</Button>
|
<Button icon="file" onClick={() => navigate("/reports/plan")}>View all reports</Button>
|
||||||
</>}
|
</>}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{role === "SFE" && <MyHeadquarters />}
|
{role === "SFE" && <MyHeadquarters />}
|
||||||
|
|
||||||
{role === "GM" && <OrganisationOverview canManage={false} hqId={hqId} />}
|
{role === "AGM" && <OrganisationOverview canManage={false} hqId={hqId} />}
|
||||||
|
|
||||||
<div className="stats">
|
<div className="stats">
|
||||||
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
|
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
|
||||||
<Stat label="With Area Manager" value={counts.data?.PENDING_AM ?? "–"} tone="warning" />
|
<Stat label="With Area Business Manager" value={counts.data?.PENDING_ABM ?? "–"} tone="warning" />
|
||||||
<Stat label="Returned" value={counts.data?.RETURNED ?? "–"} tone="danger" />
|
<Stat label="Returned" value={counts.data?.RETURNED ?? "–"} tone="danger" />
|
||||||
<Stat label="Approved" value={counts.data?.APPROVED ?? "–"} tone="success" />
|
<Stat label="Approved" value={counts.data?.APPROVED ?? "–"} tone="success" />
|
||||||
</div>
|
</div>
|
||||||
@@ -94,13 +94,13 @@ function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: s
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title={role === "GM" ? "Recent MR reports" : "Recent reports"} description="The latest activity within your permitted scope." actions={<Link to="/reports" className="text-link">See all →</Link>} />
|
<CardHeader title={role === "AGM" ? "Recent MR reports" : "Recent reports"} description="The latest activity within your permitted scope." actions={<Link to="/reports" className="text-link">See all →</Link>} />
|
||||||
<CardBody flush>
|
<CardBody flush>
|
||||||
{reports.error ? null : <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
|
{reports.error ? null : <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{role === "GM" && <AreaManagerReports hqId={hqId} />}
|
{role === "AGM" && <AreaManagerReports hqId={hqId} />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ function MyHeadquarters() {
|
|||||||
.sort((a, b) => Number(b.id === user.headquarters_id) - Number(a.id === user.headquarters_id));
|
.sort((a, b) => Number(b.id === user.headquarters_id) - Number(a.id === user.headquarters_id));
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="Your headquarters" description={hqs.data ? `You cover ${mine.length} headquarters. Reports go to the Area Manager of ${mine.find((h) => h.id === user.headquarters_id)?.name ?? "your main headquarters"}.` : "Loading…"} />
|
<CardHeader title="Your headquarters" description={hqs.data ? `You cover ${mine.length} headquarters. Reports go to the Area Business Manager of ${mine.find((h) => h.id === user.headquarters_id)?.name ?? "your main headquarters"}.` : "Loading…"} />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<div className="chip-row">
|
<div className="chip-row">
|
||||||
{mine.map((h) => <Badge key={h.id} tone={h.id === user.headquarters_id ? "brand" : "neutral"}>{h.code} · {h.name}{h.id === user.headquarters_id ? " (main)" : ""}</Badge>)}
|
{mine.map((h) => <Badge key={h.id} tone={h.id === user.headquarters_id ? "brand" : "neutral"}>{h.code} · {h.name}{h.id === user.headquarters_id ? " (main)" : ""}</Badge>)}
|
||||||
@@ -123,7 +123,7 @@ function MyHeadquarters() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** For a General Manager: what the Area Managers did themselves (their Daily Call Report (Self)). */
|
/** For an Assistant General Manager: what the Area Business Managers did themselves (their Daily Call Report (Self)). */
|
||||||
function AreaManagerReports({ hqId }: { hqId?: string }) {
|
function AreaManagerReports({ hqId }: { hqId?: string }) {
|
||||||
const reports = useAsync(() => api.reports("SELF", hqId), [hqId], { poll: LIVE });
|
const reports = useAsync(() => api.reports("SELF", hqId), [hqId], { poll: LIVE });
|
||||||
const all = reports.data ?? [];
|
const all = reports.data ?? [];
|
||||||
@@ -131,7 +131,7 @@ function AreaManagerReports({ hqId }: { hqId?: string }) {
|
|||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader
|
<CardHeader
|
||||||
title="Area Managers' own reports"
|
title="Area Business Managers' own reports"
|
||||||
description={reports.data ? `${submitted} submitted · ${all.length - submitted} in draft. Their Daily Call Report (Self), across every headquarters.` : "Their Daily Call Report (Self), across every headquarters."}
|
description={reports.data ? `${submitted} submitted · ${all.length - submitted} in draft. Their Daily Call Report (Self), across every headquarters.` : "Their Daily Call Report (Self), across every headquarters."}
|
||||||
actions={<Link to="/reports/self" className="text-link">See all →</Link>}
|
actions={<Link to="/reports/self" className="text-link">See all →</Link>}
|
||||||
/>
|
/>
|
||||||
@@ -139,14 +139,14 @@ function AreaManagerReports({ hqId }: { hqId?: string }) {
|
|||||||
{reports.error
|
{reports.error
|
||||||
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
|
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
|
||||||
: !reports.loading && all.length === 0
|
: !reports.loading && all.length === 0
|
||||||
? <EmptyState icon="file" title="No Area Manager reports yet" />
|
? <EmptyState icon="file" title="No Area Business Manager reports yet" />
|
||||||
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} ownerHeader="Area Manager" />}
|
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} ownerHeader="Area Business Manager" />}
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type AdminView = "hq" | "mr" | "am" | "gm" | "users";
|
type AdminView = "hq" | "mr" | "abm" | "agm" | "users";
|
||||||
|
|
||||||
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
|
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
|
||||||
|
|
||||||
@@ -156,14 +156,48 @@ function AdminDashboard() {
|
|||||||
<>
|
<>
|
||||||
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<><HeadquartersFilter value={hq} onChange={setHq} /><Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button></>} />
|
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<><HeadquartersFilter value={hq} onChange={setHq} /><Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button></>} />
|
||||||
<OrganisationOverview canManage hqId={hq || undefined} />
|
<OrganisationOverview canManage hqId={hq || undefined} />
|
||||||
|
<AdminReportMonitor />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AdminReportMonitor() {
|
||||||
|
const [hq, setHq] = useState("");
|
||||||
|
const hqId = hq || undefined;
|
||||||
|
const reports = useAsync(() => api.reports(undefined, hqId), [hqId], { poll: LIVE });
|
||||||
|
const counts = useAsync(() => api.counts(hqId), [hqId], { poll: LIVE });
|
||||||
|
const all = reports.data ?? [];
|
||||||
|
const error = reports.error ?? counts.error;
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader
|
||||||
|
title="Daily Call Report monitoring"
|
||||||
|
description="Read-only view of reports across the company."
|
||||||
|
actions={<><HeadquartersFilter value={hq} onChange={setHq} /><Link to="/reports/plan" className="text-link">View all →</Link></>}
|
||||||
|
/>
|
||||||
|
<CardBody>
|
||||||
|
{error
|
||||||
|
? <ErrorState message={error} onRetry={() => { void reports.reload(); void counts.reload(); }} />
|
||||||
|
: <div className="stats">
|
||||||
|
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
|
||||||
|
<Stat label="With Area Business Manager" value={counts.data?.PENDING_ABM ?? "–"} tone="warning" />
|
||||||
|
<Stat label="Returned" value={counts.data?.RETURNED ?? "–"} tone="danger" />
|
||||||
|
<Stat label="Approved" value={counts.data?.APPROVED ?? "–"} tone="success" />
|
||||||
|
</div>}
|
||||||
|
</CardBody>
|
||||||
|
<CardBody flush>
|
||||||
|
{error
|
||||||
|
? null
|
||||||
|
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Headquarters and people across the whole company, with a details table per tile.
|
* Headquarters and people across the whole company, with a details table per tile.
|
||||||
* The admin manages them; a General Manager (`canManage` false) only looks — every
|
* The admin manages them; an Assistant General Manager (`canManage` false) only looks — every
|
||||||
* headquarters, every MR, AM and GM — and is sent to the People page, never to Setup.
|
* headquarters, every MR, ABM and AGM — and is sent to the People page, never to Setup.
|
||||||
*/
|
*/
|
||||||
function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?: string }) {
|
function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?: string }) {
|
||||||
const users = useAsync(api.users, [], { poll: LIVE });
|
const users = useAsync(api.users, [], { poll: LIVE });
|
||||||
@@ -172,8 +206,8 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
|
|||||||
const [view, setView] = useState<AdminView | null>(null);
|
const [view, setView] = useState<AdminView | null>(null);
|
||||||
const panel = useRef<HTMLDivElement>(null);
|
const panel = useRef<HTMLDivElement>(null);
|
||||||
const list = users.data ?? [];
|
const list = users.data ?? [];
|
||||||
// With one headquarters chosen: that headquarters, its MRs, the Area Managers who manage it,
|
// With one headquarters chosen: that headquarters, its MRs, the Area Business Managers who manage it,
|
||||||
// and the General Managers and admins (who cover every headquarters).
|
// and the Assistant General Managers and admins (who cover every headquarters).
|
||||||
const shownHqs = useMemo(() => (hqs.data ?? []).filter((h) => !hqId || h.id === hqId), [hqs.data, hqId]);
|
const shownHqs = useMemo(() => (hqs.data ?? []).filter((h) => !hqId || h.id === hqId), [hqs.data, hqId]);
|
||||||
const worksIn = (u: User) => {
|
const worksIn = (u: User) => {
|
||||||
if (!hqId) return true;
|
if (!hqId) return true;
|
||||||
@@ -209,7 +243,7 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
|
|||||||
{ key: "status", header: "Status", render: (u) => statusBadge(u.is_active), nowrap: true },
|
{ key: "status", header: "Status", render: (u) => statusBadge(u.is_active), nowrap: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Setup is the admin's; a GM may open the People page but not Setup.
|
// Setup is the admin's; a AGM may open the People page but not Setup.
|
||||||
const manageLink = (to: string) => (canManage || to !== "/admin" ? to : null);
|
const manageLink = (to: string) => (canManage || to !== "/admin" ? to : null);
|
||||||
const setupHint = (text: string) => (canManage ? text : undefined);
|
const setupHint = (text: string) => (canManage ? text : undefined);
|
||||||
|
|
||||||
@@ -224,15 +258,15 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
|
|||||||
error: users.error, loading: users.loading,
|
error: users.error, loading: users.loading,
|
||||||
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description={setupHint("Add one under Setup → People.")} />} />,
|
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description={setupHint("Add one under Setup → People.")} />} />,
|
||||||
},
|
},
|
||||||
am: {
|
abm: {
|
||||||
title: "Area Managers", description: "Active Area Managers and every headquarters each one manages.", manage: "/users",
|
title: "Area Business Managers (ABMs)", description: "Active Area Business Managers (ABMs) and every headquarters each one manages.", manage: "/users",
|
||||||
error: users.error, loading: users.loading,
|
error: users.error, loading: users.loading,
|
||||||
table: <DataTable columns={userColumns(false, true)} rows={byRole("AM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Managers" description={setupHint("Add one under Setup → People.")} />} />,
|
table: <DataTable columns={userColumns(false, true)} rows={byRole("ABM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Business Managers" description={setupHint("Add one under Setup → People.")} />} />,
|
||||||
},
|
},
|
||||||
gm: {
|
agm: {
|
||||||
title: "General Managers", description: "Active General Managers. They have a read-only view across every headquarters.", manage: "/users",
|
title: "Assistant General Managers (AGMs)", description: "Active Assistant General Managers (AGMs). They have a read-only view across every headquarters.", manage: "/users",
|
||||||
error: users.error, loading: users.loading,
|
error: users.error, loading: users.loading,
|
||||||
table: <DataTable columns={userColumns(false, true)} rows={byRole("GM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active General Managers" description={setupHint("Add one under Setup → People.")} />} />,
|
table: <DataTable columns={userColumns(false, true)} rows={byRole("AGM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Assistant General Managers" description={setupHint("Add one under Setup → People.")} />} />,
|
||||||
},
|
},
|
||||||
users: {
|
users: {
|
||||||
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
|
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
|
||||||
@@ -248,8 +282,8 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
|
|||||||
<div className="stats stats-5">
|
<div className="stats stats-5">
|
||||||
<Stat label="Headquarters" value={hqs.data ? shownHqs.length : "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
|
<Stat label="Headquarters" value={hqs.data ? shownHqs.length : "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
|
||||||
<Stat label="Medical Representatives" value={users.data ? byRole("MR").length : "–"} hint="View details" onClick={() => pick("mr")} selected={view === "mr"} />
|
<Stat label="Medical Representatives" value={users.data ? byRole("MR").length : "–"} hint="View details" onClick={() => pick("mr")} selected={view === "mr"} />
|
||||||
<Stat label="Area Managers" value={users.data ? byRole("AM").length : "–"} hint="View details" onClick={() => pick("am")} selected={view === "am"} />
|
<Stat label="Area Business Managers (ABMs)" value={users.data ? byRole("ABM").length : "–"} hint="View details" onClick={() => pick("abm")} selected={view === "abm"} />
|
||||||
<Stat label="General Managers" value={users.data ? byRole("GM").length : "–"} hint="View details" onClick={() => pick("gm")} selected={view === "gm"} />
|
<Stat label="Assistant General Managers (AGMs)" value={users.data ? byRole("AGM").length : "–"} hint="View details" onClick={() => pick("agm")} selected={view === "agm"} />
|
||||||
<Stat label="Active users" value={users.data ? activeUsers.length : "–"} tone="success" hint="View details" onClick={() => pick("users")} selected={view === "users"} />
|
<Stat label="Active users" value={users.data ? activeUsers.length : "–"} tone="success" hint="View details" onClick={() => pick("users")} selected={view === "users"} />
|
||||||
</div>
|
</div>
|
||||||
{current && (
|
{current && (
|
||||||
@@ -266,14 +300,14 @@ function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?:
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{/* Setup steps are the admin's to follow; the GM's dashboard leaves them out. */}
|
{/* Setup steps are the admin's to follow; the AGM's dashboard leaves them out. */}
|
||||||
{canManage && <Card>
|
{canManage && <Card>
|
||||||
<CardHeader title="Recommended order" description="Create organisation data in this order." />
|
<CardHeader title="Recommended order" description="Create organisation data in this order." />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<ol className="checklist">
|
<ol className="checklist">
|
||||||
<li>Create headquarters</li>
|
<li>Create headquarters</li>
|
||||||
<li>Create users (MR, AM, GM)</li>
|
<li>Create users (MR, ABM, AGM)</li>
|
||||||
<li>Assign an Area Manager to each headquarters</li>
|
<li>Assign an Area Business Manager to each headquarters</li>
|
||||||
<li>Create doctors, chemists and products</li>
|
<li>Create doctors, chemists and products</li>
|
||||||
<li>Assign doctors and chemists to Medical Representatives</li>
|
<li>Assign doctors and chemists to Medical Representatives</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|||||||
+171
-27
@@ -17,7 +17,7 @@ import { api } from "../api";
|
|||||||
import { errorMessage, isField } from "../lib/format";
|
import { errorMessage, isField } from "../lib/format";
|
||||||
import { useUser } from "../lib/session";
|
import { useUser } from "../lib/session";
|
||||||
import { maxLength, minLength, required, useValidation } from "../lib/validation";
|
import { maxLength, minLength, required, useValidation } from "../lib/validation";
|
||||||
import type { Chemist, Doctor } from "../types";
|
import type { Chemist, Doctor, Stockist } from "../types";
|
||||||
|
|
||||||
const DOCTOR_COLUMNS: Column<Doctor>[] = [
|
const DOCTOR_COLUMNS: Column<Doctor>[] = [
|
||||||
{ key: "name", header: "Doctor", render: (d) => <strong>{d.name}</strong> },
|
{ key: "name", header: "Doctor", render: (d) => <strong>{d.name}</strong> },
|
||||||
@@ -31,38 +31,94 @@ const CHEMIST_COLUMNS: Column<Chemist>[] = [
|
|||||||
{ key: "address", header: "Shop address", render: (c) => c.shop_address },
|
{ key: "address", header: "Shop address", render: (c) => c.shop_address },
|
||||||
{ key: "status", header: "Status", render: (c) => <Badge tone={c.is_active ? "success" : "neutral"} dot>{c.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
|
{ key: "status", header: "Status", render: (c) => <Badge tone={c.is_active ? "success" : "neutral"} dot>{c.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
|
||||||
];
|
];
|
||||||
|
const STOCKIST_COLUMNS: Column<Stockist>[] = [
|
||||||
|
{ key: "name", header: "Stockist", render: (s) => <strong>{s.name}</strong> },
|
||||||
|
{ key: "address", header: "Stockist address", render: (s) => s.address },
|
||||||
|
{ key: "status", header: "Status", render: (s) => <Badge tone={s.is_active ? "success" : "neutral"} dot>{s.is_active ? "Active" : "Inactive"}</Badge>, nowrap: true },
|
||||||
|
];
|
||||||
|
|
||||||
type Editing = { kind: "doctor"; item: Doctor } | { kind: "chemist"; item: Chemist };
|
const UNASSIGNED = "__unassigned__";
|
||||||
|
|
||||||
|
type Editing = { kind: "doctor"; item: Doctor } | { kind: "chemist"; item: Chemist } | { kind: "stockist"; item: Stockist };
|
||||||
|
|
||||||
export function DirectoryPage() {
|
export function DirectoryPage() {
|
||||||
const user = useUser();
|
const user = useUser();
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const isAdmin = user.role === "ADMIN";
|
const isAdmin = user.role === "ADMIN";
|
||||||
|
const canSeeAssignedMr = user.role === "ADMIN" || user.role === "AGM";
|
||||||
|
/** Chemists and stockists show the Assigned MR column to the admin, AGM and Area Business Manager. */
|
||||||
|
const canSeeMasterMr = canSeeAssignedMr || user.role === "ABM";
|
||||||
const [editing, setEditing] = useState<Editing | null>(null);
|
const [editing, setEditing] = useState<Editing | null>(null);
|
||||||
const [toggling, setToggling] = useState<string | null>(null);
|
const [toggling, setToggling] = useState<string | null>(null);
|
||||||
const doctors = useAsync(api.doctors, [], { poll: LIVE });
|
const doctors = useAsync(api.doctors, [], { poll: LIVE });
|
||||||
const chemists = useAsync(api.chemists, [], { poll: LIVE });
|
const chemists = useAsync(api.chemists, [], { poll: LIVE });
|
||||||
|
const stockists = useAsync(api.stockists, [], { poll: LIVE });
|
||||||
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
||||||
const hqLabel = useMemo(() => new Map((hqs.data ?? []).map((h) => [h.id, `${h.code} · ${h.name}`])), [hqs.data]);
|
const hqLabel = useMemo(() => new Map((hqs.data ?? []).map((h) => [h.id, `${h.code} · ${h.name}`])), [hqs.data]);
|
||||||
const [tab, setTab] = useState<"doctors" | "chemists">("doctors");
|
const [tab, setTab] = useState<"doctors" | "chemists" | "stockists">("doctors");
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const q = query.trim().toLowerCase();
|
const q = query.trim().toLowerCase();
|
||||||
// Headquarters filter: the list holds only the headquarters this user may see (every one for
|
// Headquarters filter: the list holds only the headquarters this user may see (every one for
|
||||||
// the admin and GM, an Area Manager's own), so it offers exactly those. "" = all of them.
|
// the admin and AGM, an Area Business Manager's own), so it offers exactly those. "" = all of them.
|
||||||
const [hqFilter, setHqFilter] = useState("");
|
const [hqFilter, setHqFilter] = useState("");
|
||||||
const inHq = (id: string) => !hqFilter || id === hqFilter;
|
const inHq = (id: string) => !hqFilter || id === hqFilter;
|
||||||
|
// MR filter (admin, AGM, Area Business Manager): "" = every MR, UNASSIGNED = no MR.
|
||||||
|
// A stockist belongs to every MR working its headquarters, so it matches any of them.
|
||||||
|
const canFilterMr = canSeeAssignedMr || user.role === "ABM";
|
||||||
|
const [mrFilter, setMrFilter] = useState("");
|
||||||
|
const mrNames = (names: string | null | undefined) => (names ?? "").split(",").map((n) => n.trim()).filter(Boolean);
|
||||||
|
const ofMr = (names: string | null | undefined) => {
|
||||||
|
if (!mrFilter) return true;
|
||||||
|
const list = mrNames(names);
|
||||||
|
return mrFilter === UNASSIGNED ? list.length === 0 : list.includes(mrFilter);
|
||||||
|
};
|
||||||
|
|
||||||
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => inHq(d.headquarters_id) && (!q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [doctors.data, hqLabel, q, hqFilter]);
|
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => inHq(d.headquarters_id) && ofMr(d.assigned_mr_name) && (!q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [doctors.data, hqLabel, q, hqFilter, mrFilter]);
|
||||||
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => inHq(c.headquarters_id) && (!q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [chemists.data, hqLabel, q, hqFilter]);
|
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => inHq(c.headquarters_id) && ofMr(c.assigned_mr_name) && (!q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [chemists.data, hqLabel, q, hqFilter, mrFilter]);
|
||||||
const active = tab === "doctors" ? doctors : chemists;
|
const stockistRows = useMemo(() => (stockists.data ?? []).filter((s) => inHq(s.headquarters_id) && ofMr(s.assigned_mr_name) && (!q || `${s.name} ${s.address} ${hqLabel.get(s.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [stockists.data, hqLabel, q, hqFilter, mrFilter]);
|
||||||
|
const active = tab === "doctors" ? doctors : tab === "chemists" ? chemists : stockists;
|
||||||
|
/** The MRs in this tab's list (within the chosen headquarters), for the MR filter. */
|
||||||
|
const mrOptions = useMemo(() => {
|
||||||
|
const items: { headquarters_id: string; assigned_mr_name?: string | null }[] = active.data ?? [];
|
||||||
|
const names = new Set(items.filter((i) => inHq(i.headquarters_id)).flatMap((i) => mrNames(i.assigned_mr_name)));
|
||||||
|
if (mrFilter && mrFilter !== UNASSIGNED) names.add(mrFilter);
|
||||||
|
return [...names].sort((a, b) => a.localeCompare(b));
|
||||||
|
}, [active.data, hqFilter, mrFilter]);
|
||||||
|
const [printing, setPrinting] = useState<"view" | "download" | null>(null);
|
||||||
|
const shownCount = tab === "doctors" ? doctorRows.length : tab === "chemists" ? chemistRows.length : stockistRows.length;
|
||||||
|
/** The list on screen (current tab, headquarters filter and search) as a PDF. */
|
||||||
|
async function printList(mode: "view" | "download") {
|
||||||
|
const hq = (id: string) => hqLabel.get(id) ?? "";
|
||||||
|
const yesNo = (v: boolean) => (v ? "Active" : "Inactive");
|
||||||
|
const payload =
|
||||||
|
tab === "doctors"
|
||||||
|
? {
|
||||||
|
title: "Doctors",
|
||||||
|
columns: ["doctor", "headquarters", "speciality", "clinic_address", "type", ...(canSeeAssignedMr ? ["assigned_mr"] : []), "status"],
|
||||||
|
rows: doctorRows.map((d) => ({ doctor: d.name, headquarters: hq(d.headquarters_id), speciality: d.speciality || "", clinic_address: d.clinic_address, type: d.is_core_doctor ? "Core doctor" : "Regular", assigned_mr: d.assigned_mr_name || "Unassigned", status: yesNo(d.is_active) })),
|
||||||
|
}
|
||||||
|
: tab === "chemists"
|
||||||
|
? { title: "Chemists", columns: ["chemist", "headquarters", "shop_address", ...(canSeeMasterMr ? ["assigned_mr"] : []), "status"], rows: chemistRows.map((c) => ({ chemist: c.name, headquarters: hq(c.headquarters_id), shop_address: c.shop_address, assigned_mr: c.assigned_mr_name || "Unassigned", status: yesNo(c.is_active) })) }
|
||||||
|
: { title: "Stockists", columns: ["stockist", "headquarters", "stockist_address", ...(canSeeMasterMr ? ["assigned_mr"] : []), "status"], rows: stockistRows.map((s) => ({ stockist: s.name, headquarters: hq(s.headquarters_id), stockist_address: s.address, assigned_mr: s.assigned_mr_name || "Unassigned", status: yesNo(s.is_active) })) };
|
||||||
|
setPrinting(mode);
|
||||||
|
try {
|
||||||
|
await api.directoryPdf(payload, mode);
|
||||||
|
} catch (err) {
|
||||||
|
toast.error(errorMessage(err, mode === "view" ? "Could not open the PDF" : "Download failed"));
|
||||||
|
} finally {
|
||||||
|
setPrinting(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
async function toggleActive(target: Editing) {
|
async function toggleActive(target: Editing) {
|
||||||
const next = !target.item.is_active;
|
const next = !target.item.is_active;
|
||||||
setToggling(target.item.id);
|
setToggling(target.item.id);
|
||||||
try {
|
try {
|
||||||
if (target.kind === "doctor") await api.updateDoctor(target.item.id, { is_active: next });
|
if (target.kind === "doctor") await api.updateDoctor(target.item.id, { is_active: next });
|
||||||
else await api.updateChemist(target.item.id, { is_active: next });
|
else if (target.kind === "chemist") await api.updateChemist(target.item.id, { is_active: next });
|
||||||
toast.success(`${target.kind === "doctor" ? "Doctor" : "Chemist"} ${next ? "activated" : "deactivated"}`);
|
else await api.updateStockist(target.item.id, { is_active: next });
|
||||||
await (target.kind === "doctor" ? doctors : chemists).reload();
|
const label = target.kind === "doctor" ? "Doctor" : target.kind === "chemist" ? "Chemist" : "Stockist";
|
||||||
|
toast.success(`${label} ${next ? "activated" : "deactivated"}`);
|
||||||
|
await (target.kind === "doctor" ? doctors : target.kind === "chemist" ? chemists : stockists).reload();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.error(errorMessage(err, "Could not change the status"));
|
toast.error(errorMessage(err, "Could not change the status"));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -80,40 +136,67 @@ export function DirectoryPage() {
|
|||||||
const doctorColumns: Column<Doctor>[] = [
|
const doctorColumns: Column<Doctor>[] = [
|
||||||
...DOCTOR_COLUMNS.slice(0, 1),
|
...DOCTOR_COLUMNS.slice(0, 1),
|
||||||
{ key: "hq", header: "Headquarters", render: (d) => hqCell(d.headquarters_id), nowrap: true },
|
{ key: "hq", header: "Headquarters", render: (d) => hqCell(d.headquarters_id), nowrap: true },
|
||||||
...DOCTOR_COLUMNS.slice(1),
|
...DOCTOR_COLUMNS.slice(1, 4),
|
||||||
|
...(canSeeAssignedMr ? [{ key: "assigned-mr", header: "Assigned MR", render: (d: Doctor) => d.assigned_mr_name || "Unassigned" }] : []),
|
||||||
|
...DOCTOR_COLUMNS.slice(4),
|
||||||
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (d: Doctor) => editButton({ kind: "doctor", item: d }) }] : []),
|
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (d: Doctor) => editButton({ kind: "doctor", item: d }) }] : []),
|
||||||
];
|
];
|
||||||
const chemistColumns: Column<Chemist>[] = [
|
const chemistColumns: Column<Chemist>[] = [
|
||||||
...CHEMIST_COLUMNS.slice(0, 1),
|
...CHEMIST_COLUMNS.slice(0, 1),
|
||||||
{ key: "hq", header: "Headquarters", render: (c) => hqCell(c.headquarters_id), nowrap: true },
|
{ key: "hq", header: "Headquarters", render: (c) => hqCell(c.headquarters_id), nowrap: true },
|
||||||
...CHEMIST_COLUMNS.slice(1),
|
...CHEMIST_COLUMNS.slice(1, 2),
|
||||||
|
...(canSeeMasterMr ? [{ key: "assigned-mr", header: "Assigned MR", render: (c: Chemist) => c.assigned_mr_name || "Unassigned" }] : []),
|
||||||
|
...CHEMIST_COLUMNS.slice(2),
|
||||||
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (c: Chemist) => editButton({ kind: "chemist", item: c }) }] : []),
|
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (c: Chemist) => editButton({ kind: "chemist", item: c }) }] : []),
|
||||||
];
|
];
|
||||||
|
const stockistColumns: Column<Stockist>[] = [
|
||||||
|
...STOCKIST_COLUMNS.slice(0, 1),
|
||||||
|
{ key: "hq", header: "Headquarters", render: (s) => hqCell(s.headquarters_id), nowrap: true },
|
||||||
|
...STOCKIST_COLUMNS.slice(1, 2),
|
||||||
|
...(canSeeMasterMr ? [{ key: "assigned-mr", header: "Assigned MR", render: (s: Stockist) => s.assigned_mr_name || "Unassigned" }] : []),
|
||||||
|
...STOCKIST_COLUMNS.slice(2),
|
||||||
|
...(isAdmin ? [{ key: "edit", header: "", align: "right" as const, nowrap: true, render: (s: Stockist) => editButton({ kind: "stockist", item: s }) }] : []),
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
|
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
|
||||||
{!isField(user.role) && <MasterRequests mode="review" onReviewed={() => { void doctors.reload(); void chemists.reload(); }} />}
|
{!isField(user.role) && <MasterRequests mode="review" onReviewed={() => { void doctors.reload(); void chemists.reload(); void stockists.reload(); }} />}
|
||||||
<Card>
|
<Card>
|
||||||
<div className="toolbar">
|
<div className="toolbar">
|
||||||
<Tabs
|
<Tabs
|
||||||
label="Directory"
|
label="Directory"
|
||||||
value={tab}
|
value={tab}
|
||||||
onChange={setTab}
|
onChange={setTab}
|
||||||
items={[{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined }, { key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined }]}
|
items={[
|
||||||
|
{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined },
|
||||||
|
{ key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined },
|
||||||
|
{ key: "stockists", label: "Stockists", count: stockists.data ? stockistRows.length : undefined },
|
||||||
|
]}
|
||||||
/>
|
/>
|
||||||
<div className="toolbar-group">
|
<div className="toolbar-group">
|
||||||
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
|
<Select className="hq-filter" value={hqFilter} onChange={(e) => { setHqFilter(e.target.value); setMrFilter(""); }} aria-label="Filter by headquarters" disabled={!hqs.data}>
|
||||||
<option value="">All headquarters</option>
|
<option value="">All headquarters</option>
|
||||||
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
</Select>
|
</Select>
|
||||||
|
{canFilterMr && (
|
||||||
|
<Select className="hq-filter" value={mrFilter} onChange={(e) => setMrFilter(e.target.value)} aria-label="Filter by MR" disabled={!active.data}>
|
||||||
|
<option value="">All MRs</option>
|
||||||
|
{mrOptions.map((name) => <option key={name} value={name}>{name}</option>)}
|
||||||
|
<option value={UNASSIGNED}>Unassigned</option>
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
|
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
|
||||||
|
<Button icon="eye" disabled={shownCount === 0} loading={printing === "view"} onClick={() => void printList("view")}>View</Button>
|
||||||
|
<Button icon="download" disabled={shownCount === 0} loading={printing === "download"} onClick={() => void printList("download")}>Download PDF</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{active.error ? <ErrorState message={active.error} onRetry={() => void active.reload()} /> : tab === "doctors" ? (
|
{active.error ? <ErrorState message={active.error} onRetry={() => void active.reload()} /> : tab === "doctors" ? (
|
||||||
<DataTable columns={doctorColumns} rows={doctorRows} rowKey={(d) => d.id} loading={doctors.loading} minWidth={820} empty={<EmptyState icon="stethoscope" title="No doctors found" />} />
|
<DataTable columns={doctorColumns} rows={doctorRows} rowKey={(d) => d.id} loading={doctors.loading} minWidth={820} empty={<EmptyState icon="stethoscope" title="No doctors found" />} />
|
||||||
) : (
|
) : tab === "chemists" ? (
|
||||||
<DataTable columns={chemistColumns} rows={chemistRows} rowKey={(c) => c.id} loading={chemists.loading} minWidth={640} empty={<EmptyState icon="stethoscope" title="No chemists found" />} />
|
<DataTable columns={chemistColumns} rows={chemistRows} rowKey={(c) => c.id} loading={chemists.loading} minWidth={640} empty={<EmptyState icon="stethoscope" title="No chemists found" />} />
|
||||||
|
) : (
|
||||||
|
<DataTable columns={stockistColumns} rows={stockistRows} rowKey={(s) => s.id} loading={stockists.loading} minWidth={640} empty={<EmptyState icon="box" title="No stockists found" />} />
|
||||||
)}
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
{editing && (
|
{editing && (
|
||||||
@@ -121,9 +204,10 @@ export function DirectoryPage() {
|
|||||||
editing={editing}
|
editing={editing}
|
||||||
onClose={() => setEditing(null)}
|
onClose={() => setEditing(null)}
|
||||||
onSaved={() => {
|
onSaved={() => {
|
||||||
|
const label = editing.kind === "doctor" ? "Doctor" : editing.kind === "chemist" ? "Chemist" : "Stockist";
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
toast.success(`${editing.kind === "doctor" ? "Doctor" : "Chemist"} updated`);
|
toast.success(`${label} updated`);
|
||||||
void (editing.kind === "doctor" ? doctors : chemists).reload();
|
void (editing.kind === "doctor" ? doctors : editing.kind === "chemist" ? chemists : stockists).reload();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -133,29 +217,68 @@ export function DirectoryPage() {
|
|||||||
|
|
||||||
function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onClose: () => void; onSaved: () => void }) {
|
function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onClose: () => void; onSaved: () => void }) {
|
||||||
const isDoctor = editing.kind === "doctor";
|
const isDoctor = editing.kind === "doctor";
|
||||||
|
const isChemist = editing.kind === "chemist";
|
||||||
|
const hasMr = editing.kind !== "stockist";
|
||||||
|
const doctor = isDoctor ? (editing.item as Doctor) : null;
|
||||||
|
const chemist = isChemist ? (editing.item as Chemist) : null;
|
||||||
|
const originalMr = (doctor?.assigned_mr_id ?? chemist?.assigned_mr_id) || "";
|
||||||
const [name, setName] = useState(editing.item.name);
|
const [name, setName] = useState(editing.item.name);
|
||||||
const [address, setAddress] = useState(isDoctor ? (editing.item as Doctor).clinic_address : (editing.item as Chemist).shop_address);
|
const [hqId, setHqId] = useState(editing.item.headquarters_id);
|
||||||
const [speciality, setSpeciality] = useState(isDoctor ? (editing.item as Doctor).speciality ?? "" : "");
|
const [address, setAddress] = useState(doctor ? doctor.clinic_address : chemist ? chemist.shop_address : (editing.item as Stockist).address);
|
||||||
const [core, setCore] = useState(isDoctor ? (editing.item as Doctor).is_core_doctor : false);
|
const [contact, setContact] = useState((doctor?.contact_number ?? chemist?.contact_number ?? (editing.item as Stockist).contact_number) || "");
|
||||||
|
const [speciality, setSpeciality] = useState(doctor?.speciality ?? "");
|
||||||
|
const [qualification, setQualification] = useState(doctor?.qualification ?? "");
|
||||||
|
const [dob, setDob] = useState(doctor?.date_of_birth ?? "");
|
||||||
|
const [core, setCore] = useState(doctor?.is_core_doctor ?? false);
|
||||||
|
const [mrId, setMrId] = useState(originalMr);
|
||||||
const [active, setActive] = useState(editing.item.is_active);
|
const [active, setActive] = useState(editing.item.is_active);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const hqs = useAsync(api.headquarters, []);
|
||||||
|
const users = useAsync(api.users, []);
|
||||||
|
/** Active MRs / SFEs who work a headquarters (their own one or an extra one). */
|
||||||
|
const mrsOf = (hq: string) => (users.data ?? [])
|
||||||
|
.filter((u) => u.is_active && (u.role === "MR" || u.role === "SFE") && (u.headquarters_id === hq || (u.extra_headquarter_ids ?? []).includes(hq)))
|
||||||
|
.sort((a, b) => a.full_name.localeCompare(b.full_name));
|
||||||
|
const mrOptions = mrsOf(hqId);
|
||||||
|
const stockistMrs = !hasMr ? mrOptions.map((u) => u.full_name).join(", ") : "";
|
||||||
|
const addressLabel = isDoctor ? "Clinic address" : isChemist ? "Shop address" : "Stockist address";
|
||||||
const v = useValidation({
|
const v = useValidation({
|
||||||
name: [required("Name"), minLength(2, "Name"), maxLength(200, "Name")],
|
name: [required("Name"), minLength(2, "Name"), maxLength(200, "Name")],
|
||||||
address: [required(isDoctor ? "Clinic address" : "Shop address"), minLength(2, "Address"), maxLength(500, "Address")],
|
address: [required(addressLabel), minLength(2, "Address"), maxLength(500, "Address")],
|
||||||
speciality: [maxLength(100, "Speciality")],
|
speciality: [maxLength(100, "Speciality")],
|
||||||
|
qualification: [maxLength(100, "Qualification")],
|
||||||
|
contact: [maxLength(20, "Contact number")],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function changeHq(next: string) {
|
||||||
|
setHqId(next);
|
||||||
|
// An MR can only hold masters of a headquarters they work, as the server also enforces.
|
||||||
|
if (mrId && !mrsOf(next).some((u) => u.id === mrId)) setMrId("");
|
||||||
|
}
|
||||||
|
|
||||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!v.check({ name, address, speciality }, e.currentTarget)) return;
|
if (!v.check({ name, address, speciality, qualification, contact }, e.currentTarget)) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
const common = {
|
||||||
|
name: name.trim(),
|
||||||
|
contact_number: contact.trim() || null,
|
||||||
|
is_active: active,
|
||||||
|
...(hqId !== editing.item.headquarters_id ? { headquarters_id: hqId } : {}),
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
if (isDoctor) {
|
if (isDoctor) {
|
||||||
await api.updateDoctor(editing.item.id, { name: name.trim(), clinic_address: address.trim(), speciality: speciality.trim() || null, is_core_doctor: core, is_active: active });
|
await api.updateDoctor(editing.item.id, { ...common, clinic_address: address.trim(), speciality: speciality.trim() || null, qualification: qualification.trim() || null, date_of_birth: dob || null, is_core_doctor: core });
|
||||||
|
} else if (isChemist) {
|
||||||
|
await api.updateChemist(editing.item.id, { ...common, shop_address: address.trim() });
|
||||||
} else {
|
} else {
|
||||||
await api.updateChemist(editing.item.id, { name: name.trim(), shop_address: address.trim(), is_active: active });
|
await api.updateStockist(editing.item.id, { ...common, address: address.trim() });
|
||||||
|
}
|
||||||
|
if (hasMr && mrId !== originalMr) {
|
||||||
|
if (mrId) await (isDoctor ? api.assignDoctor(editing.item.id, mrId) : api.assignChemist(editing.item.id, mrId));
|
||||||
|
else await api.unassignMaster(isDoctor ? "doctor" : "chemist", editing.item.id);
|
||||||
}
|
}
|
||||||
onSaved();
|
onSaved();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -168,15 +291,36 @@ function DirectoryEditor({ editing, onClose, onSaved }: { editing: Editing; onCl
|
|||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
open
|
open
|
||||||
title={isDoctor ? "Edit doctor" : "Edit chemist"}
|
title={isDoctor ? "Edit doctor" : isChemist ? "Edit chemist" : "Edit stockist"}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("directory-editor-form") as HTMLFormElement | null)?.requestSubmit()}>Save changes</Button></>}
|
footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => (document.getElementById("directory-editor-form") as HTMLFormElement | null)?.requestSubmit()}>Save changes</Button></>}
|
||||||
>
|
>
|
||||||
<form id="directory-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
|
<form id="directory-editor-form" className="form-grid form-single" onSubmit={submit} noValidate>
|
||||||
<Alert>{error}</Alert>
|
<Alert>{error}</Alert>
|
||||||
<Field label="Name" required error={v.errors.name}><Input value={name} onChange={(e) => { setName(e.target.value); v.retouch("name", e.target.value); }} onBlur={(e) => v.touch("name", e.target.value)} /></Field>
|
<Field label="Name" required error={v.errors.name}><Input value={name} onChange={(e) => { setName(e.target.value); v.retouch("name", e.target.value); }} onBlur={(e) => v.touch("name", e.target.value)} /></Field>
|
||||||
<Field label={isDoctor ? "Clinic address" : "Shop address"} required error={v.errors.address}><Input value={address} onChange={(e) => { setAddress(e.target.value); v.retouch("address", e.target.value); }} onBlur={(e) => v.touch("address", e.target.value)} /></Field>
|
<Field label="Headquarters" required>
|
||||||
|
<Select value={hqId} onChange={(e) => changeHq(e.target.value)} disabled={!hqs.data}>
|
||||||
|
{!hqs.data && <option value={hqId}>Loading…</option>}
|
||||||
|
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
{hasMr ? (
|
||||||
|
<Field label="Assigned MR" hint={mrOptions.length === 0 && users.data ? "No active MR works this headquarters yet." : undefined}>
|
||||||
|
<Select value={mrId} onChange={(e) => setMrId(e.target.value)} disabled={!users.data}>
|
||||||
|
<option value="">Unassigned</option>
|
||||||
|
{mrOptions.map((u) => <option key={u.id} value={u.id}>{u.full_name} ({u.employee_code})</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
) : (
|
||||||
|
<Field label="Assigned MR" hint="A stockist serves every MR of its headquarters; change the headquarters to change them.">
|
||||||
|
<Input value={users.data ? stockistMrs || "No active MR in this headquarters" : "Loading…"} readOnly disabled />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
<Field label={addressLabel} required error={v.errors.address}><Input value={address} onChange={(e) => { setAddress(e.target.value); v.retouch("address", e.target.value); }} onBlur={(e) => v.touch("address", e.target.value)} /></Field>
|
||||||
{isDoctor && <Field label="Speciality" error={v.errors.speciality}><Input value={speciality} onChange={(e) => { setSpeciality(e.target.value); v.retouch("speciality", e.target.value); }} onBlur={(e) => v.touch("speciality", e.target.value)} /></Field>}
|
{isDoctor && <Field label="Speciality" error={v.errors.speciality}><Input value={speciality} onChange={(e) => { setSpeciality(e.target.value); v.retouch("speciality", e.target.value); }} onBlur={(e) => v.touch("speciality", e.target.value)} /></Field>}
|
||||||
|
{isDoctor && <Field label="Qualification" error={v.errors.qualification}><Input value={qualification} onChange={(e) => { setQualification(e.target.value); v.retouch("qualification", e.target.value); }} onBlur={(e) => v.touch("qualification", e.target.value)} /></Field>}
|
||||||
|
<Field label="Contact number" error={v.errors.contact}><Input type="tel" value={contact} onChange={(e) => { setContact(e.target.value); v.retouch("contact", e.target.value); }} onBlur={(e) => v.touch("contact", e.target.value)} /></Field>
|
||||||
|
{isDoctor && <Field label="Date of birth"><Input type="date" value={dob} max={new Date().toISOString().slice(0, 10)} onChange={(e) => setDob(e.target.value)} /></Field>}
|
||||||
{isDoctor && <Checkbox label="Core doctor" checked={core} onChange={(e) => setCore(e.target.checked)} />}
|
{isDoctor && <Checkbox label="Core doctor" checked={core} onChange={(e) => setCore(e.target.checked)} />}
|
||||||
<Checkbox label="Active" checked={active} onChange={(e) => setActive(e.target.checked)} />
|
<Checkbox label="Active" checked={active} onChange={(e) => setActive(e.target.checked)} />
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export function ProfilePage() {
|
|||||||
{ label: "Employee code", value: p.employee_code },
|
{ label: "Employee code", value: p.employee_code },
|
||||||
{ label: "Phone", value: p.phone },
|
{ label: "Phone", value: p.phone },
|
||||||
{ label: "Headquarters", value: p.headquarters_name ? `${p.headquarters_name}${p.headquarters_code ? ` (${p.headquarters_code})` : ""}` : "Not assigned" },
|
{ label: "Headquarters", value: p.headquarters_name ? `${p.headquarters_name}${p.headquarters_code ? ` (${p.headquarters_code})` : ""}` : "Not assigned" },
|
||||||
{ label: "Reporting Area Manager", value: p.reporting_manager_name || "Not assigned" },
|
{ label: "Reporting Area Business Manager", value: p.reporting_manager_name || "Not assigned" },
|
||||||
]} />
|
]} />
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ const optional = (f: FormData, key: string) => text(f, key) || null;
|
|||||||
|
|
||||||
type Section = "organisation" | "people" | "masters" | "assignments";
|
type Section = "organisation" | "people" | "masters" | "assignments";
|
||||||
|
|
||||||
/** Setup for the signed-in role: an MR gets only the doctor and chemist forms. */
|
/** Setup for the signed-in role: an MR gets only the doctor, chemist and stockist forms. */
|
||||||
export function AdminPage() {
|
export function AdminPage() {
|
||||||
return isField(useUser().role) ? <MasterDataSetup /> : <FullSetup />;
|
return isField(useUser().role) ? <MasterDataSetup /> : <FullSetup />;
|
||||||
}
|
}
|
||||||
@@ -118,8 +118,8 @@ function HeadquartersSelect({ hqs }: { hqs: Headquarters[] }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What an MR sees after adding a doctor or chemist: it is not in their list yet. */
|
/** What an MR sees after adding a doctor, chemist or stockist: it is not in their list yet. */
|
||||||
const sentForApproval = (role: string, what: string) => isField(role) ? `${what} sent to your Area Manager for approval` : undefined;
|
const sentForApproval = (role: string, what: string) => isField(role) ? `${what} sent to your Area Business Manager for approval` : undefined;
|
||||||
|
|
||||||
function DoctorForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
|
function DoctorForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
|
||||||
const role = useUser().role;
|
const role = useUser().role;
|
||||||
@@ -152,7 +152,21 @@ function ChemistForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An MR adds doctors and chemists to their own headquarters; each is assigned to them. */
|
function StockistForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
|
||||||
|
const role = useUser().role;
|
||||||
|
return (
|
||||||
|
<AdminForm title="Create stockist" submitLabel={isField(role) ? "Send for approval" : "Create stockist"} successMessage={sentForApproval(role, "Stockist")}
|
||||||
|
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Stockist address"), phone: [phoneRule] }}
|
||||||
|
onSubmit={(f) => refresh(api.createStockist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), address: text(f, "address"), contact_number: optional(f, "phone") }))}>
|
||||||
|
<HeadquartersSelect hqs={hqs} />
|
||||||
|
<Field label="Name" name="name" required><Input name="name" /></Field>
|
||||||
|
<Field label="Stockist address" name="address" required span><Input name="address" /></Field>
|
||||||
|
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An MR adds doctors, chemists and stockists to their own headquarters; each waits for approval. */
|
||||||
function MasterDataSetup() {
|
function MasterDataSetup() {
|
||||||
const hqs = useAsync(() => api.headquarters(), []);
|
const hqs = useAsync(() => api.headquarters(), []);
|
||||||
// A new request shows in "Your requests" straight away, not only on the next poll.
|
// A new request shows in "Your requests" straight away, not only on the next poll.
|
||||||
@@ -160,11 +174,12 @@ function MasterDataSetup() {
|
|||||||
const refresh: Refresh = async (task) => { const result = await task; setSent((n) => n + 1); return result; };
|
const refresh: Refresh = async (task) => { const result = await task; setSent((n) => n + 1); return result; };
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Setup" description="Add a doctor or chemist in your headquarters. Your Area Manager approves it, and then it joins your Doctors & Chemists list." />
|
<PageHeader title="Setup" description="Add a doctor, chemist or stockist in your headquarters. Your Area Business Manager approves it, and then it joins your Doctors & Chemists list." />
|
||||||
<Alert tone="danger">{hqs.error}</Alert>
|
<Alert tone="danger">{hqs.error}</Alert>
|
||||||
<div className="grid-2">
|
<div className="grid-2">
|
||||||
<DoctorForm hqs={hqs.data ?? []} refresh={refresh} />
|
<DoctorForm hqs={hqs.data ?? []} refresh={refresh} />
|
||||||
<ChemistForm hqs={hqs.data ?? []} refresh={refresh} />
|
<ChemistForm hqs={hqs.data ?? []} refresh={refresh} />
|
||||||
|
<StockistForm hqs={hqs.data ?? []} refresh={refresh} />
|
||||||
</div>
|
</div>
|
||||||
<MasterRequests key={sent} mode="mine" />
|
<MasterRequests key={sent} mode="mine" />
|
||||||
</>
|
</>
|
||||||
@@ -179,12 +194,12 @@ function FullSetup() {
|
|||||||
}, [], { poll: LIVE });
|
}, [], { poll: LIVE });
|
||||||
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
|
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
|
||||||
const mrs = users.filter((u) => isField(u.role));
|
const mrs = users.filter((u) => isField(u.role));
|
||||||
const ams = users.filter((u) => u.role === "AM");
|
const ams = users.filter((u) => u.role === "ABM");
|
||||||
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
|
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Setup" description="Create organisation data in this order: headquarters, users, Area Manager mapping, master data, then assignments." />
|
<PageHeader title="Setup" description="Create organisation data in this order: headquarters, users, Area Business Manager mapping, master data, then assignments." />
|
||||||
<Alert tone="danger">{data.error}</Alert>
|
<Alert tone="danger">{data.error}</Alert>
|
||||||
<Tabs
|
<Tabs
|
||||||
label="Setup sections"
|
label="Setup sections"
|
||||||
@@ -219,6 +234,7 @@ function FullSetup() {
|
|||||||
<div className="grid-2">
|
<div className="grid-2">
|
||||||
<DoctorForm hqs={hqs} refresh={refresh} />
|
<DoctorForm hqs={hqs} refresh={refresh} />
|
||||||
<ChemistForm hqs={hqs} refresh={refresh} />
|
<ChemistForm hqs={hqs} refresh={refresh} />
|
||||||
|
<StockistForm hqs={hqs} refresh={refresh} />
|
||||||
<AdminForm title="Create product" submitLabel="Create product"
|
<AdminForm title="Create product" submitLabel="Create product"
|
||||||
rules={{ name: nameRule("Product name"), pack: [maxLength(100, "Pack")], unit: [maxLength(50, "Unit")] }}
|
rules={{ name: nameRule("Product name"), pack: [maxLength(100, "Pack")], unit: [maxLength(50, "Unit")] }}
|
||||||
onSubmit={(f) => refresh(api.createProduct({ name: text(f, "name"), pack: optional(f, "pack"), unit: optional(f, "unit") }))}>
|
onSubmit={(f) => refresh(api.createProduct({ name: text(f, "name"), pack: optional(f, "pack"), unit: optional(f, "unit") }))}>
|
||||||
@@ -249,11 +265,11 @@ function FullSetup() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Choose an Area Manager, then tick every headquarters they should manage. */
|
/** Choose an Area Business Manager, then tick every headquarters they should manage. */
|
||||||
function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[]; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onSaved: () => Promise<unknown> }) {
|
function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[]; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onSaved: () => Promise<unknown> }) {
|
||||||
const [amId, setAmId] = useState("");
|
const [amId, setAmId] = useState("");
|
||||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||||
// The other Area Managers of each headquarters: ticking one adds this AM beside them.
|
// The other Area Business Managers of each headquarters: ticking one adds this ABM beside them.
|
||||||
const owners = areaManagersOf(mappings, users, amId || undefined);
|
const owners = areaManagersOf(mappings, users, amId || undefined);
|
||||||
|
|
||||||
function choose(id: string) {
|
function choose(id: string) {
|
||||||
@@ -262,23 +278,23 @@ function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[];
|
|||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<AdminForm
|
<AdminForm
|
||||||
title="Assign headquarters to an Area Manager"
|
title="Assign headquarters to an Area Business Manager"
|
||||||
description="An Area Manager can manage any number of headquarters, and a headquarters can have several Area Managers. Ticking one already managed by someone else adds this Area Manager beside them."
|
description="An Area Business Manager can manage any number of headquarters, and a headquarters can have several Area Business Managers. Ticking one already managed by someone else adds this Area Business Manager beside them."
|
||||||
submitLabel="Save assignments"
|
submitLabel="Save assignments"
|
||||||
rules={{ area_manager_user_id: [required("Area Manager")] }}
|
rules={{ area_manager_user_id: [required("Area Business Manager")] }}
|
||||||
onSubmit={async () => {
|
onSubmit={async () => {
|
||||||
await api.setAreaManagerHeadquarters(amId, [...picked]);
|
await api.setAreaManagerHeadquarters(amId, [...picked]);
|
||||||
setAmId(""); setPicked(new Set());
|
setAmId(""); setPicked(new Set());
|
||||||
await onSaved();
|
await onSaved();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Field label="Area Manager" name="area_manager_user_id" required span>
|
<Field label="Area Business Manager" name="area_manager_user_id" required span>
|
||||||
<Select name="area_manager_user_id" value={amId} onChange={(e) => choose(e.target.value)}>
|
<Select name="area_manager_user_id" value={amId} onChange={(e) => choose(e.target.value)}>
|
||||||
<option value="">Choose Area Manager</option>
|
<option value="">Choose Area Business Manager</option>
|
||||||
{ams.map((u) => <option key={u.id} value={u.id}>{u.full_name}</option>)}
|
{ams.map((u) => <option key={u.id} value={u.id}>{u.full_name}</option>)}
|
||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Headquarters they manage" span group hint={amId ? `${picked.size} selected` : "Choose an Area Manager first."}>
|
<Field label="Headquarters they manage" span group hint={amId ? `${picked.size} selected` : "Choose an Area Business Manager first."}>
|
||||||
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} disabled={!amId} />
|
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} disabled={!amId} />
|
||||||
</Field>
|
</Field>
|
||||||
</AdminForm>
|
</AdminForm>
|
||||||
@@ -293,12 +309,12 @@ function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquar
|
|||||||
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
|
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
|
||||||
{ key: "name", header: "Headquarters", render: (h) => h.name },
|
{ key: "name", header: "Headquarters", render: (h) => h.name },
|
||||||
{ key: "place", header: "District / State", render: (h) => [h.district, h.state].filter(Boolean).join(", ") || "—" },
|
{ key: "place", header: "District / State", render: (h) => [h.district, h.state].filter(Boolean).join(", ") || "—" },
|
||||||
{ key: "am", header: "Area Managers", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
|
{ key: "am", header: "Area Business Managers", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
|
||||||
{ key: "mrs", header: "MRs", render: (h) => mrCount(h.id), align: "right", nowrap: true },
|
{ key: "mrs", header: "MRs", render: (h) => mrCount(h.id), align: "right", nowrap: true },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="Headquarters overview" description="Every headquarters, its Area Manager and how many active MRs work there." />
|
<CardHeader title="Headquarters overview" description="Every headquarters, its Area Business Manager and how many active MRs work there." />
|
||||||
<CardBody flush>
|
<CardBody flush>
|
||||||
<DataTable columns={columns} rows={hqs} rowKey={(h) => h.id} loading={loading} minWidth={560} />
|
<DataTable columns={columns} rows={hqs} rowKey={(h) => h.id} loading={loading} minWidth={560} />
|
||||||
</CardBody>
|
</CardBody>
|
||||||
@@ -307,11 +323,11 @@ function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquar
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ROLES = [
|
const ROLES = [
|
||||||
{ value: "MR", label: "Medical Representative" }, { value: "SFE", label: "Senior Field Executive" }, { value: "AM", label: "Area Manager" },
|
{ value: "MR", label: "Medical Representative" }, { value: "SFE", label: "Senior Field Executive" }, { value: "ABM", label: "Area Business Manager (ABM)" },
|
||||||
{ value: "GM", label: "General Manager" }, { value: "ADMIN", label: "Administrator" },
|
{ value: "AGM", label: "Assistant General Manager (AGM)" }, { value: "ADMIN", label: "Administrator" },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/** Create-user form. Headquarters depends on the role: one for an MR, several for an AM, none for GM/Admin. */
|
/** Create-user form. Headquarters depends on the role: one for an MR, several for an ABM, none for AGM/Admin. */
|
||||||
function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task: Promise<T>) => Promise<T> }) {
|
function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task: Promise<T>) => Promise<T> }) {
|
||||||
const [role, setRole] = useState<string>("MR");
|
const [role, setRole] = useState<string>("MR");
|
||||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||||
@@ -334,7 +350,7 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
|
|||||||
headquarters_id: isField(role) ? text(f, "headquarters_id") : null,
|
headquarters_id: isField(role) ? text(f, "headquarters_id") : null,
|
||||||
...(role === "SFE" ? { extra_headquarter_ids: [...extras].filter((id) => id !== text(f, "headquarters_id")) } : {}),
|
...(role === "SFE" ? { extra_headquarter_ids: [...extras].filter((id) => id !== text(f, "headquarters_id")) } : {}),
|
||||||
});
|
});
|
||||||
if (role === "AM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
|
if (role === "ABM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
|
||||||
setRole("MR"); setPicked(new Set()); setExtras(new Set());
|
setRole("MR"); setPicked(new Set()); setExtras(new Set());
|
||||||
await refresh(Promise.resolve(created));
|
await refresh(Promise.resolve(created));
|
||||||
}}
|
}}
|
||||||
@@ -346,22 +362,22 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
|
|||||||
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); setExtras(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
|
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); setExtras(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
|
||||||
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
||||||
{isField(role) && (
|
{isField(role) && (
|
||||||
<Field label="Headquarters" name="headquarters_id" required hint={role === "SFE" ? "Their main headquarters: reports go to its Area Manager." : "The headquarters this Medical Representative works in."}>
|
<Field label="Headquarters" name="headquarters_id" required hint={role === "SFE" ? "Their main headquarters: reports go to its Area Business Manager." : "The headquarters this Medical Representative works in."}>
|
||||||
<Select name="headquarters_id"><option value="">Choose headquarters</option>{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}</Select>
|
<Select name="headquarters_id"><option value="">Choose headquarters</option>{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}</Select>
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{role === "SFE" && (
|
{role === "SFE" && (
|
||||||
<Field label="Other districts they cover" span group hint={`Optional. ${extras.size} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Manager.`}>
|
<Field label="Other districts they cover" span group hint={`Optional. ${extras.size} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Business Manager.`}>
|
||||||
<HeadquartersChecklist headquarters={hqs} selected={extras} onChange={setExtras} />
|
<HeadquartersChecklist headquarters={hqs} selected={extras} onChange={setExtras} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{role === "AM" && (
|
{role === "ABM" && (
|
||||||
<Field label="Headquarters they manage" span group hint={`Optional now — you can also set these later. ${picked.size} selected.`}>
|
<Field label="Headquarters they manage" span group hint={`Optional now — you can also set these later. ${picked.size} selected.`}>
|
||||||
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} />
|
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{(role === "GM" || role === "ADMIN") && (
|
{(role === "AGM" || role === "ADMIN") && (
|
||||||
<p className="field-hint field-span">General Managers and Administrators see every headquarters, so none is assigned.</p>
|
<p className="field-hint field-span">Assistant General Managers and Administrators see every headquarters, so none is assigned.</p>
|
||||||
)}
|
)}
|
||||||
</AdminForm>
|
</AdminForm>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,11 +13,11 @@ import { Link } from "../../lib/router";
|
|||||||
import { useUser } from "../../lib/session";
|
import { useUser } from "../../lib/session";
|
||||||
import type { DcrListItem, DcrStatus, ReportType, UserOverview } from "../../types";
|
import type { DcrListItem, DcrStatus, ReportType, UserOverview } from "../../types";
|
||||||
|
|
||||||
const STATUSES: DcrStatus[] = ["DRAFT", "PENDING_AM", "RETURNED", "APPROVED"];
|
const STATUSES: DcrStatus[] = ["DRAFT", "PENDING_ABM", "RETURNED", "APPROVED"];
|
||||||
const APPROVAL_TONE = { draft: "neutral", pending: "warning", approved: "success" } as const;
|
const APPROVAL_TONE = { draft: "neutral", pending: "warning", approved: "success" } as const;
|
||||||
const APPROVAL_LABEL = { draft: "Draft", pending: "With Area Manager", approved: "Approved" } as const;
|
const APPROVAL_LABEL = { draft: "Draft", pending: "With Area Business Manager", approved: "Approved" } as const;
|
||||||
|
|
||||||
/** One person's whole picture, for the General Manager and Admin: where they work, who they report to, their people, reports and forms. */
|
/** One person's whole picture, for the Assistant General Manager and Admin: where they work, who they report to, their people, reports and forms. */
|
||||||
export function UserDetailPage({ id }: { id: string }) {
|
export function UserDetailPage({ id }: { id: string }) {
|
||||||
const viewer = useUser();
|
const viewer = useUser();
|
||||||
const data = useAsync(() => api.userOverview(id), [id], { poll: LIVE });
|
const data = useAsync(() => api.userOverview(id), [id], { poll: LIVE });
|
||||||
@@ -38,10 +38,10 @@ export function UserDetailPage({ id }: { id: string }) {
|
|||||||
|
|
||||||
<div className="detail-grid">
|
<div className="detail-grid">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title={user.role === "AM" ? "Headquarters they manage" : field ? "Headquarters" : "Headquarters"} description={user.role === "AM" ? `${o.headquarters.length} headquarters` : field ? "The main headquarters is where their reports are sent." : undefined} />
|
<CardHeader title={user.role === "ABM" ? "Headquarters they manage" : field ? "Headquarters" : "Headquarters"} description={user.role === "ABM" ? `${o.headquarters.length} headquarters` : field ? "The main headquarters is where their reports are sent." : undefined} />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
{o.headquarters.length === 0
|
{o.headquarters.length === 0
|
||||||
? <span className="muted">{field || user.role === "AM" ? "None assigned" : "This role sees every headquarters."}</span>
|
? <span className="muted">{field || user.role === "ABM" ? "None assigned" : "This role sees every headquarters."}</span>
|
||||||
: <div className="chip-row">{o.headquarters.map((h) => (
|
: <div className="chip-row">{o.headquarters.map((h) => (
|
||||||
<Badge key={h.id} tone={h.main ? "brand" : "neutral"}>{h.code} · {h.name}{h.main && field && o.headquarters.length > 1 ? " (main)" : ""}{h.field_staff !== undefined ? ` · ${h.field_staff} field staff` : ""}</Badge>
|
<Badge key={h.id} tone={h.main ? "brand" : "neutral"}>{h.code} · {h.name}{h.main && field && o.headquarters.length > 1 ? " (main)" : ""}{h.field_staff !== undefined ? ` · ${h.field_staff} field staff` : ""}</Badge>
|
||||||
))}</div>}
|
))}</div>}
|
||||||
@@ -49,9 +49,9 @@ export function UserDetailPage({ id }: { id: string }) {
|
|||||||
</Card>
|
</Card>
|
||||||
{field && (
|
{field && (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="Reports to" description="Area Manager(s) of the main headquarters" />
|
<CardHeader title="Reports to" description="Area Business Manager(s) of the main headquarters" />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
{o.reporting_managers.length === 0 ? <span className="muted">No Area Manager assigned</span>
|
{o.reporting_managers.length === 0 ? <span className="muted">No Area Business Manager assigned</span>
|
||||||
: <div className="chip-row">{o.reporting_managers.map((m) => <Link key={m.id} to={`/users/${m.id}`}><Badge tone="brand">{m.full_name}</Badge></Link>)}</div>}
|
: <div className="chip-row">{o.reporting_managers.map((m) => <Link key={m.id} to={`/users/${m.id}`}><Badge tone="brand">{m.full_name}</Badge></Link>)}</div>}
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -59,13 +59,13 @@ export function UserDetailPage({ id }: { id: string }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{field && <PeopleCards o={o} />}
|
{field && <PeopleCards o={o} />}
|
||||||
{user.role === "AM" && <Team o={o} />}
|
{user.role === "ABM" && <Team o={o} />}
|
||||||
{(field || user.role === "AM") && <ReportsSection o={o} viewerRole={viewer.role} title={user.role === "AM" ? "Reports in their headquarters" : "Daily call reports"} />}
|
{(field || user.role === "ABM") && <ReportsSection o={o} viewerRole={viewer.role} title={user.role === "ABM" ? "Reports in their headquarters" : "Daily call reports"} />}
|
||||||
{user.role === "AM" && o.own_reports && o.own_reports.length > 0 && (
|
{user.role === "ABM" && o.own_reports && o.own_reports.length > 0 && (
|
||||||
<ReportList title="Their own reports (Daily Call Report (Self))" rows={o.own_reports} link={viewer.role === "GM"} />
|
<ReportList title="Their own reports (Daily Call Report (Self))" rows={o.own_reports} link={viewer.role === "AGM"} />
|
||||||
)}
|
)}
|
||||||
{field && <Forms o={o} />}
|
{field && <Forms o={o} />}
|
||||||
{!field && user.role !== "AM" && <Card><CardBody><EmptyState icon="users" title="Nothing field-related to show" description="This role sets things up or looks across the company; it has no doctors, reports or forms of its own." /></CardBody></Card>}
|
{!field && user.role !== "ABM" && <Card><CardBody><EmptyState icon="users" title="Nothing field-related to show" description="This role sets things up or looks across the company; it has no doctors, reports or forms of its own." /></CardBody></Card>}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -105,7 +105,7 @@ function Team({ o }: { o: UserOverview }) {
|
|||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="Field team" description="MRs and SFEs who report to this Area Manager" />
|
<CardHeader title="Field team" description="MRs and SFEs who report to this Area Business Manager" />
|
||||||
<CardBody flush><DataTable columns={cols} rows={o.team} rowKey={(p) => p.id} minWidth={520} empty={<EmptyState icon="users" title="Nobody reports to them yet" />} /></CardBody>
|
<CardBody flush><DataTable columns={cols} rows={o.team} rowKey={(p) => p.id} minWidth={520} empty={<EmptyState icon="users" title="Nobody reports to them yet" />} /></CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
@@ -123,14 +123,14 @@ function ReportsSection({ o, viewerRole, title }: { o: UserOverview; viewerRole:
|
|||||||
<div key={t} className="summary-block">
|
<div key={t} className="summary-block">
|
||||||
<strong>{REPORT_TYPE_LABEL[t]}</strong>
|
<strong>{REPORT_TYPE_LABEL[t]}</strong>
|
||||||
<div className="chip-row">
|
<div className="chip-row">
|
||||||
{STATUSES.map((s) => <Badge key={s} tone={s === "APPROVED" ? "success" : s === "RETURNED" ? "danger" : s === "PENDING_AM" ? "warning" : "neutral"}>{STATUS_LABEL[s]}: {o.reports.counts[t]?.[s] ?? 0}</Badge>)}
|
{STATUSES.map((s) => <Badge key={s} tone={s === "APPROVED" ? "success" : s === "RETURNED" ? "danger" : s === "PENDING_ABM" ? "warning" : "neutral"}>{STATUS_LABEL[s]}: {o.reports.counts[t]?.[s] ?? 0}</Badge>)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
<ReportList title="Latest reports" rows={o.reports.recent} link={viewerRole === "GM"} />
|
<ReportList title="Latest reports" rows={o.reports.recent} link={viewerRole === "AGM"} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ export function UsersPage() {
|
|||||||
const q = query.trim().toLowerCase();
|
const q = query.trim().toLowerCase();
|
||||||
return (users.data ?? []).filter((u) => {
|
return (users.data ?? []).filter((u) => {
|
||||||
const place = headquartersOf(u, hqs, mappings);
|
const place = headquartersOf(u, hqs, mappings);
|
||||||
// One headquarters chosen: only the people who work in it (GM and Admin cover all, so they drop out).
|
// One headquarters chosen: only the people who work in it (AGM and Admin cover all, so they drop out).
|
||||||
if (hqFilter && !place.items.some((h) => h.id === hqFilter)) return false;
|
if (hqFilter && !place.items.some((h) => h.id === hqFilter)) return false;
|
||||||
if (!q) return true;
|
if (!q) return true;
|
||||||
const where = place.all ? "all headquarters" : place.items.map((h) => `${h.code} ${h.name}`).join(" ");
|
const where = place.all ? "all headquarters" : place.items.map((h) => `${h.code} ${h.name}`).join(" ");
|
||||||
@@ -94,11 +94,11 @@ export function UsersPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Headquarters of one person: chips for an MR or AM, "All headquarters" for GM and Admin. */
|
/** Headquarters of one person: chips for an MR or ABM, "All headquarters" for AGM and Admin. */
|
||||||
function HqChips({ user, hqs, mappings }: { user: User; hqs: Headquarters[]; mappings: AreaManagerMapping[] }) {
|
function HqChips({ user, hqs, mappings }: { user: User; hqs: Headquarters[]; mappings: AreaManagerMapping[] }) {
|
||||||
const place = headquartersOf(user, hqs, mappings);
|
const place = headquartersOf(user, hqs, mappings);
|
||||||
if (place.all) return <Badge tone="neutral">All headquarters</Badge>;
|
if (place.all) return <Badge tone="neutral">All headquarters</Badge>;
|
||||||
if (place.items.length === 0) return <span className="muted">{user.role === "AM" ? "None assigned" : "—"}</span>;
|
if (place.items.length === 0) return <span className="muted">{user.role === "ABM" ? "None assigned" : "—"}</span>;
|
||||||
return <span className="chips">{place.items.map((h) => <Badge key={h.id} tone="brand">{h.code}</Badge>)}</span>;
|
return <span className="chips">{place.items.map((h) => <Badge key={h.id} tone="brand">{h.code}</Badge>)}</span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +113,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
const [role, setRole] = useState<Role>(user.role);
|
const [role, setRole] = useState<Role>(user.role);
|
||||||
const [hqId, setHqId] = useState(user.headquarters_id ?? "");
|
const [hqId, setHqId] = useState(user.headquarters_id ?? "");
|
||||||
const roleChanged = role !== user.role;
|
const roleChanged = role !== user.role;
|
||||||
const isAm = role === "AM";
|
const isAm = role === "ABM";
|
||||||
const hqChanged = !roleChanged && isField(user.role) && isField(role) && hqId !== (user.headquarters_id ?? "");
|
const hqChanged = !roleChanged && isField(user.role) && isField(role) && hqId !== (user.headquarters_id ?? "");
|
||||||
const editingSelf = user.id === me.id;
|
const editingSelf = user.id === me.id;
|
||||||
const credentialsChanged = email.trim().toLowerCase() !== user.email || password !== "";
|
const credentialsChanged = email.trim().toLowerCase() !== user.email || password !== "";
|
||||||
@@ -199,7 +199,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
<Alert tone="warning">
|
<Alert tone="warning">
|
||||||
{user.full_name} will be signed out and must sign in again as {ROLE_LABEL[role]}.
|
{user.full_name} will be signed out and must sign in again as {ROLE_LABEL[role]}.
|
||||||
{isField(user.role) && " Their doctor and chemist assignments end, so reassign them in Setup → Assignments."}
|
{isField(user.role) && " Their doctor and chemist assignments end, so reassign them in Setup → Assignments."}
|
||||||
{user.role === "AM" && " The headquarters they manage are released; any that have no other Area Manager need a new one."}
|
{user.role === "ABM" && " The headquarters they manage are released; any that have no other Area Business Manager need a new one."}
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
{hqChanged && (
|
{hqChanged && (
|
||||||
@@ -209,16 +209,16 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
<Alert tone="warning">{editingSelf ? "You are changing your own sign-in details — you will need to sign in again. " : ""}{user.full_name} will be signed out everywhere{password ? " and must use the new password" : ""}. Share the new details securely.</Alert>
|
<Alert tone="warning">{editingSelf ? "You are changing your own sign-in details — you will need to sign in again. " : ""}{user.full_name} will be signed out everywhere{password ? " and must use the new password" : ""}. Share the new details securely.</Alert>
|
||||||
)}
|
)}
|
||||||
{role === "SFE" && (
|
{role === "SFE" && (
|
||||||
<Field label="Other districts they cover" group hint={`${[...extras].filter((id) => id !== hqId).length} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Manager.`}>
|
<Field label="Other districts they cover" group hint={`${[...extras].filter((id) => id !== hqId).length} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Business Manager.`}>
|
||||||
<HeadquartersChecklist headquarters={hqs.filter((h) => h.id !== hqId)} selected={extras} onChange={setExtras} />
|
<HeadquartersChecklist headquarters={hqs.filter((h) => h.id !== hqId)} selected={extras} onChange={setExtras} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{isAm && (
|
{isAm && (
|
||||||
<Field label="Headquarters they manage" group hint={`${picked.size} selected. A headquarters can have several Area Managers; the others keep theirs.`}>
|
<Field label="Headquarters they manage" group hint={`${picked.size} selected. A headquarters can have several Area Business Managers; the others keep theirs.`}>
|
||||||
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
|
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{(role === "GM" || role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
|
{(role === "AGM" || role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
|
||||||
</form>
|
</form>
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -60,10 +60,10 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
|
|
||||||
const approvals = useAsync(api.formApprovals, [], { poll: APPROVAL_POLL_MS });
|
const approvals = useAsync(api.formApprovals, [], { poll: APPROVAL_POLL_MS });
|
||||||
const needsApproval = !!table && APPROVAL_FORMS.has(table.name);
|
const needsApproval = !!table && APPROVAL_FORMS.has(table.name);
|
||||||
const isManager = user.role === "AM" || user.role === "ADMIN" || user.role === "GM";
|
const isManager = user.role === "ABM" || user.role === "ADMIN" || user.role === "AGM";
|
||||||
// Admin and the General Manager look across every medical representative; the GM only reads.
|
// Admin and the Assistant General Manager look across every medical representative; the AGM only reads.
|
||||||
const seesAll = user.role === "ADMIN" || user.role === "GM";
|
const seesAll = user.role === "ADMIN" || user.role === "AGM";
|
||||||
// Each MR has their own copy of these forms. An Area Manager (or admin) opens one MR's copy at a time.
|
// Each MR has their own copy of these forms. An Area Business Manager (or admin) opens one MR's copy at a time.
|
||||||
// Sales Projection isn't an approval form but managers still pick a headquarters / MR to look at.
|
// Sales Projection isn't an approval form but managers still pick a headquarters / MR to look at.
|
||||||
const hasPeopleFilter = isManager && (needsApproval || seesAll);
|
const hasPeopleFilter = isManager && (needsApproval || seesAll);
|
||||||
const owners = useAsync(() => (hasPeopleFilter ? api.formOwners() : Promise.resolve([])), [hasPeopleFilter], { poll: LIVE });
|
const owners = useAsync(() => (hasPeopleFilter ? api.formOwners() : Promise.resolve([])), [hasPeopleFilter], { poll: LIVE });
|
||||||
@@ -77,8 +77,8 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
if (!isManager || !needsApproval || !table) return undefined;
|
if (!isManager || !needsApproval || !table) return undefined;
|
||||||
const chosen = ownerList.find((o) => o.id === (seesAll ? mrChoice : ownerChoice));
|
const chosen = ownerList.find((o) => o.id === (seesAll ? mrChoice : ownerChoice));
|
||||||
if (chosen) return chosen;
|
if (chosen) return chosen;
|
||||||
// An Area Manager lands on the MR who is waiting for them; an admin starts with everyone.
|
// An Area Business Manager lands on the MR who is waiting for them; an admin starts with everyone.
|
||||||
return user.role === "AM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
|
return user.role === "ABM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, mrChoice, seesAll, user.role, approvals.data]);
|
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, mrChoice, seesAll, user.role, approvals.data]);
|
||||||
const waitingForOwners = isManager && needsApproval && !owners.data;
|
const waitingForOwners = isManager && needsApproval && !owners.data;
|
||||||
@@ -138,7 +138,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
|
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
|
||||||
// Only the controls that make sense right now: nothing to approve means nothing to show.
|
// Only the controls that make sense right now: nothing to approve means nothing to show.
|
||||||
const canSend = needsApproval && isField(user.role) && status === "draft" && hasRows;
|
const canSend = needsApproval && isField(user.role) && status === "draft" && hasRows;
|
||||||
const canApprove = needsApproval && user.role === "AM" && status === "pending" && !!viewOwner;
|
const canApprove = needsApproval && user.role === "ABM" && status === "pending" && !!viewOwner;
|
||||||
const showStatus = needsApproval && (status === "pending" || status === "approved");
|
const showStatus = needsApproval && (status === "pending" || status === "approved");
|
||||||
|
|
||||||
// Forms with a month can be downloaded one month at a time. Every month is always offered —
|
// Forms with a month can be downloaded one month at a time. Every month is always offered —
|
||||||
@@ -158,7 +158,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
// Starts on the current month when the form already has rows for it, otherwise on everything.
|
// Starts on the current month when the form already has rows for it, otherwise on everything.
|
||||||
// Any of the twelve real months is a valid choice, whether or not it has rows yet.
|
// Any of the twelve real months is a valid choice, whether or not it has rows yet.
|
||||||
const month = chosenMonth !== undefined ? (chosenMonth === "" || MONTHS.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : monthsWithRows.find((m) => sameMonth(m, thisMonth)) ?? "";
|
const month = chosenMonth !== undefined ? (chosenMonth === "" || MONTHS.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : monthsWithRows.find((m) => sameMonth(m, thisMonth)) ?? "";
|
||||||
// The General Manager and Admin can narrow every form by headquarters and medical representative.
|
// The Assistant General Manager and Admin can narrow every form by headquarters and medical representative.
|
||||||
const peopleFilter = seesAll;
|
const peopleFilter = seesAll;
|
||||||
// Forms kept per MR on the server are narrowed there; the rest by the name and headquarters written on each row.
|
// Forms kept per MR on the server are narrowed there; the rest by the name and headquarters written on each row.
|
||||||
const narrowedByServer = !!mrChoice && !!table && (needsApproval || PRODUCT_LIST_TABLES.has(table.name));
|
const narrowedByServer = !!mrChoice && !!table && (needsApproval || PRODUCT_LIST_TABLES.has(table.name));
|
||||||
@@ -170,7 +170,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
const base = (rows.data ?? []).filter((r) => !peopleFilter || narrowedByServer || (isProductList && !String(r.name ?? "").trim() && !String(r.headquarter ?? "").trim()) || ((!hqChoice || sameMonth(r.headquarter, hqChoice)) && (!mrName || sameMonth(r.name ?? r.employee_name, mrName))));
|
const base = (rows.data ?? []).filter((r) => !peopleFilter || narrowedByServer || (isProductList && !String(r.name ?? "").trim() && !String(r.headquarter ?? "").trim()) || ((!hqChoice || sameMonth(r.headquarter, hqChoice)) && (!mrName || sameMonth(r.name ?? r.employee_name, mrName))));
|
||||||
// "All MRs": the rows MRs have entered; for a month, every product of the list is there too, blank where nobody has entered it.
|
// "All MRs": the rows MRs have entered; for a month, every product of the list is there too, blank where nobody has entered it.
|
||||||
const listAcrossMrs = isProductList && peopleFilter && !mrChoice;
|
const listAcrossMrs = isProductList && peopleFilter && !mrChoice;
|
||||||
if (listAcrossMrs && user.role === "GM" && !month) return base.filter((r) => String(r.month ?? "").trim());
|
if (listAcrossMrs && user.role === "AGM" && !month) return base.filter((r) => String(r.month ?? "").trim());
|
||||||
if (!month) return base;
|
if (!month) return base;
|
||||||
if (listAcrossMrs) {
|
if (listAcrossMrs) {
|
||||||
const key = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
|
const key = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
|
||||||
@@ -213,7 +213,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
|
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
|
||||||
const numberOf = (r: CsvRow) => String(positional ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
|
const numberOf = (r: CsvRow) => String(positional ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
|
||||||
|
|
||||||
/** Send (MR) or approve (AM). The screen changes at once; the server's answer confirms it, or undoes it. */
|
/** Send (MR) or approve (ABM). The screen changes at once; the server's answer confirms it, or undoes it. */
|
||||||
async function act(kind: "request" | "approve") {
|
async function act(kind: "request" | "approve") {
|
||||||
if (!table || acting) return;
|
if (!table || acting) return;
|
||||||
const name = table.name;
|
const name = table.name;
|
||||||
@@ -231,7 +231,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
try {
|
try {
|
||||||
const saved = await (kind === "request" ? api.requestFormApproval(name) : api.approveForm(name, ownerId));
|
const saved = await (kind === "request" ? api.requestFormApproval(name) : api.approveForm(name, ownerId));
|
||||||
approvals.setData(merge(before, saved));
|
approvals.setData(merge(before, saved));
|
||||||
toast.success(kind === "request" ? "Sent to the Area Manager for approval" : "Form approved");
|
toast.success(kind === "request" ? "Sent to the Area Business Manager for approval" : "Form approved");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
approvals.setData(before);
|
approvals.setData(before);
|
||||||
toast.error(errorMessage(e, kind === "request" ? "Could not send the form for approval" : "Could not approve the form"));
|
toast.error(errorMessage(e, kind === "request" ? "Could not send the form for approval" : "Could not approve the form"));
|
||||||
@@ -298,6 +298,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
render: (r) => (
|
render: (r) => (
|
||||||
<span className="row-actions">
|
<span className="row-actions">
|
||||||
{showEdit && !isNewRow(r) && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
|
{showEdit && !isNewRow(r) && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
|
||||||
|
<Button size="sm" variant="ghost" icon="eye" disabled={isNewRow(r)} onClick={() => void run(api.viewCsvPdf(table.name, { rowId: r.id }))}>View</Button>
|
||||||
<Button size="sm" variant="ghost" icon="download" disabled={isNewRow(r)} onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
|
<Button size="sm" variant="ghost" icon="download" disabled={isNewRow(r)} onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
|
||||||
{canDelete && (
|
{canDelete && (
|
||||||
<Button size="sm" variant="ghost" icon="trash" disabled={isNewRow(r) || (clearsInstead(r) && !hasFigures(r))} title={clearsInstead(r) ? (hasFigures(r) ? "This is the product's only row, so only its figures are cleared" : "Nothing entered in this row yet") : undefined} onClick={() => setDeleting(r)}>
|
<Button size="sm" variant="ghost" icon="trash" disabled={isNewRow(r) || (clearsInstead(r) && !hasFigures(r))} title={clearsInstead(r) ? (hasFigures(r) ? "This is the product's only row, so only its figures are cleared" : "Nothing entered in this row yet") : undefined} onClick={() => setDeleting(r)}>
|
||||||
@@ -313,13 +314,13 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Company forms" description={user.role === "GM" ? "Every medical representative’s company forms, read-only. Download any of them as a PDF." : "Fill in the company’s standard forms and print them as ready-to-sign PDFs."} />
|
<PageHeader title="Company forms" description={user.role === "AGM" ? "Every medical representative’s company forms, read-only. Download any of them as a PDF." : "Fill in the company’s standard forms and print them as ready-to-sign PDFs."} />
|
||||||
<div className="forms-layout">
|
<div className="forms-layout">
|
||||||
<nav className="form-nav" aria-label="Forms">
|
<nav className="form-nav" aria-label="Forms">
|
||||||
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
|
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
|
||||||
<Link key={t.name} to={`/forms/${t.name}`} className={`form-nav-item${t.name === table?.name ? " active" : ""}`} aria-current={t.name === table?.name ? "page" : undefined}>
|
<Link key={t.name} to={`/forms/${t.name}`} className={`form-nav-item${t.name === table?.name ? " active" : ""}`} aria-current={t.name === table?.name ? "page" : undefined}>
|
||||||
{t.label}
|
{t.label}
|
||||||
{user.role === "AM" && APPROVAL_FORMS.has(t.name) && approvals.data?.some((a) => a.table_name === t.name && a.status === "pending") && <span className="nav-flag" title="Waiting for your approval">Needs approval</span>}
|
{user.role === "ABM" && APPROVAL_FORMS.has(t.name) && approvals.data?.some((a) => a.table_name === t.name && a.status === "pending") && <span className="nav-flag" title="Waiting for your approval">Needs approval</span>}
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
@@ -328,12 +329,13 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
{!table ? <CardBody><EmptyState icon="table" title="No forms available" /></CardBody> : (
|
{!table ? <CardBody><EmptyState icon="table" title="No forms available" /></CardBody> : (
|
||||||
<>
|
<>
|
||||||
<CardHeader
|
<CardHeader
|
||||||
title={<span className="title-row">{table.label}{showStatus && <Badge tone={status === "approved" ? "success" : "warning"} dot>{status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Manager"}` : "Pending AM approval"}</Badge>}</span>}
|
title={<span className="title-row">{table.label}{showStatus && <Badge tone={status === "approved" ? "success" : "warning"} dot>{status === "approved" ? `Approved by ${approval?.approved_by_name ?? "Area Business Manager"}` : "Pending ABM approval"}</Badge>}</span>}
|
||||||
description={`${shownRows.length} row${shownRows.length === 1 ? "" : "s"}${month ? ` in ${month}` : ""}${canSend ? " · ready to send for approval" : ""}`}
|
description={`${shownRows.length} row${shownRows.length === 1 ? "" : "s"}${month ? ` in ${month}` : ""}${canSend ? " · ready to send for approval" : ""}`}
|
||||||
actions={
|
actions={
|
||||||
<>
|
<>
|
||||||
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
|
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
|
||||||
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
|
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as ABM</Button>}
|
||||||
|
<Button icon="eye" disabled={shownRows.length === 0} onClick={() => void run(api.viewCsvPdf(table.name, { ownerId: viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined), month: hasMonthColumn ? month || undefined : undefined }))}>View</Button>
|
||||||
<Button icon="download" disabled={shownRows.length === 0} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined), month: hasMonthColumn ? month || undefined : undefined }))}>{month && hasMonthColumn ? `Download ${month} PDF` : "Download PDF"}</Button>
|
<Button icon="download" disabled={shownRows.length === 0} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined), month: hasMonthColumn ? month || undefined : undefined }))}>{month && hasMonthColumn ? `Download ${month} PDF` : "Download PDF"}</Button>
|
||||||
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
|
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
|
||||||
</>
|
</>
|
||||||
@@ -341,7 +343,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
/>
|
/>
|
||||||
{showToolbar && (
|
{showToolbar && (
|
||||||
<div className="toolbar">
|
<div className="toolbar">
|
||||||
{user.role === "AM" && needsApproval && (
|
{user.role === "ABM" && needsApproval && (
|
||||||
<label className="filter">
|
<label className="filter">
|
||||||
<span>Medical representative</span>
|
<span>Medical representative</span>
|
||||||
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
|
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
|
||||||
@@ -390,7 +392,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
empty={month
|
empty={month
|
||||||
? <EmptyState icon="table" title={`No rows for ${month}`} description="Choose another month, or All months." />
|
? <EmptyState icon="table" title={`No rows for ${month}`} description="Choose another month, or All months." />
|
||||||
: isManager && needsApproval && ownerList.length === 0
|
: isManager && needsApproval && ownerList.length === 0
|
||||||
? <EmptyState icon="users" title="No medical representatives" description={user.role === "AM" ? "No medical representative is assigned to your headquarters yet." : "Add medical representatives under Setup → People."} />
|
? <EmptyState icon="users" title="No medical representatives" description={user.role === "ABM" ? "No medical representative is assigned to your headquarters yet." : "Add medical representatives under Setup → People."} />
|
||||||
: <EmptyState icon="table" title="No rows yet" description={canAdd ? "Add a row to start filling in this form." : isManager && needsApproval ? "This medical representative has not filled in this form." : undefined} action={canAdd ? <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button> : undefined} />}
|
: <EmptyState icon="table" title="No rows yet" description={canAdd ? "Add a row to start filling in this form." : isManager && needsApproval ? "This medical representative has not filled in this form." : undefined} action={canAdd ? <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button> : undefined} />}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -39,8 +39,9 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
|
|||||||
const columns = useMemo(() => screenColumns(table, user.role).filter((c) => !SERIAL.has(c)), [table, user.role]);
|
const columns = useMemo(() => screenColumns(table, user.role).filter((c) => !SERIAL.has(c)), [table, user.role]);
|
||||||
const isAdmin = user.role === "ADMIN";
|
const isAdmin = user.role === "ADMIN";
|
||||||
// Admin maintains the product list, so PTS is editable for them; for MRs it follows the product.
|
// Admin maintains the product list, so PTS is editable for them; for MRs it follows the product.
|
||||||
|
// Sales and Stock Statement's VALUE IN PTS always follows the product's Sales Projection PTS.
|
||||||
const isExpense = table.name === "expense_statement";
|
const isExpense = table.name === "expense_statement";
|
||||||
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin) || (isExpense && c === "total");
|
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin) || (table.name === "sales_and_stock_statement" && c === "value_in_pts") || (isExpense && c === "total");
|
||||||
// NAME / HEADQUARTER are the MR's: the signed-in MR, or the one an admin is filling the form in for.
|
// NAME / HEADQUARTER are the MR's: the signed-in MR, or the one an admin is filling the form in for.
|
||||||
const account = (c: string) => {
|
const account = (c: string) => {
|
||||||
if (isAdmin && owner) return c === "headquarter" ? owner.headquarters_name ?? "" : owner.name;
|
if (isAdmin && owner) return c === "headquarter" ? owner.headquarters_name ?? "" : owner.name;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
/** Forms that carry an Area Manager approval signature on their PDF. */
|
/** Forms that carry an Area Business Manager approval signature on their PDF. */
|
||||||
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"]);
|
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"]);
|
||||||
|
|
||||||
/** How often the approval state is re-checked, so an approval shows up for the other person within seconds. */
|
/** How often the approval state is re-checked, so an approval shows up for the other person within seconds. */
|
||||||
|
|||||||
@@ -31,6 +31,6 @@ export function screenColumns(table: CsvTable, role: Role): string[] {
|
|||||||
|
|
||||||
/** Columns typed straight into the table, in a small box per cell, instead of through the Edit drawer. */
|
/** Columns typed straight into the table, in a small box per cell, instead of through the Edit drawer. */
|
||||||
export const INLINE_COLUMNS: Record<string, Set<string>> = {
|
export const INLINE_COLUMNS: Record<string, Set<string>> = {
|
||||||
sales_and_stock_statement: new Set(["month", "value_in_pts", "opening", "receipt", "sale", "closing"]),
|
sales_and_stock_statement: new Set(["month", "opening", "receipt", "sale", "closing"]),
|
||||||
sales_projection: new Set(["month", "closing_qty", "closing_value", "projection_qty", "projection_value"]),
|
sales_projection: new Set(["month", "closing_qty", "closing_value", "projection_qty", "projection_value"]),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ const COPY: Record<ReportType, { title: string; description: string; remarks: st
|
|||||||
},
|
},
|
||||||
PLAN: {
|
PLAN: {
|
||||||
title: "New Daily Call Report (Plan)",
|
title: "New Daily Call Report (Plan)",
|
||||||
description: "List the doctors and chemists you intend to visit today and when, then send the plan to your Area Manager.",
|
description: "List the doctors and chemists you intend to visit today and when, then send the plan to your Area Business Manager.",
|
||||||
remarks: "Optional note for your Area Manager, e.g. the area you will cover",
|
remarks: "Optional note for your Area Business Manager, e.g. the area you will cover",
|
||||||
create: "Start plan",
|
create: "Start plan",
|
||||||
},
|
},
|
||||||
ACTUAL: {
|
ACTUAL: {
|
||||||
@@ -41,7 +41,7 @@ export function NewReportPage({ type }: { type: ReportType }) {
|
|||||||
const copy = COPY[type];
|
const copy = COPY[type];
|
||||||
const latest = todayISO(type === "PLAN" ? PLAN_AHEAD_DAYS : 0);
|
const latest = todayISO(type === "PLAN" ? PLAN_AHEAD_DAYS : 0);
|
||||||
const isSelf = type === "SELF";
|
const isSelf = type === "SELF";
|
||||||
// An Area Manager's own report is for one of the headquarters they manage.
|
// An Area Business Manager's own report is for one of the headquarters they manage.
|
||||||
const hqs = useAsync(() => (isSelf ? api.headquarters() : Promise.resolve([])), [isSelf]);
|
const hqs = useAsync(() => (isSelf ? api.headquarters() : Promise.resolve([])), [isSelf]);
|
||||||
const [hqChoice, setHqChoice] = useState("");
|
const [hqChoice, setHqChoice] = useState("");
|
||||||
const hqId = hqChoice || (hqs.data?.length === 1 ? hqs.data[0].id : "");
|
const hqId = hqChoice || (hqs.data?.length === 1 ? hqs.data[0].id : "");
|
||||||
@@ -77,7 +77,7 @@ export function NewReportPage({ type }: { type: ReportType }) {
|
|||||||
<CardBody>
|
<CardBody>
|
||||||
<form className="form-grid" onSubmit={submit} noValidate>
|
<form className="form-grid" onSubmit={submit} noValidate>
|
||||||
<Alert>{error}</Alert>
|
<Alert>{error}</Alert>
|
||||||
<Field label="Report date" required error={v.errors.date} hint={type === "PLAN" ? `One plan per day. You can plan today or up to ${PLAN_AHEAD_DAYS} days ahead.` : isSelf ? "One report per day." : "Your Daily Call Report (Plan) for this date must already be approved by your Area Manager."}>
|
<Field label="Report date" required error={v.errors.date} hint={type === "PLAN" ? `One plan per day. You can plan today or up to ${PLAN_AHEAD_DAYS} days ahead.` : isSelf ? "One report per day." : "Your Daily Call Report (Plan) for this date must already be approved by your Area Business Manager."}>
|
||||||
<Input type="date" value={date} max={latest} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
|
<Input type="date" value={date} max={latest} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
|
||||||
</Field>
|
</Field>
|
||||||
{isSelf && (
|
{isSelf && (
|
||||||
|
|||||||
@@ -16,12 +16,12 @@ import { VisitList } from "../../components/reports/VisitList";
|
|||||||
import { WorkflowTracker } from "../../components/reports/WorkflowTracker";
|
import { WorkflowTracker } from "../../components/reports/WorkflowTracker";
|
||||||
import { LIVE, useAsync } from "../../hooks/useAsync";
|
import { LIVE, useAsync } from "../../hooks/useAsync";
|
||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { errorMessage, formatDate, formatDateTime, REPORT_TYPE_LABEL, isField } from "../../lib/format";
|
import { errorMessage, formatDate, formatDateTime, REPORT_TYPE_LABEL, isField, roleLabel } from "../../lib/format";
|
||||||
import { reportPath, reportsPath } from "../../lib/navigation";
|
import { reportPath, reportsPath } from "../../lib/navigation";
|
||||||
import { navigate } from "../../lib/router";
|
import { navigate } from "../../lib/router";
|
||||||
import { useUser } from "../../lib/session";
|
import { useUser } from "../../lib/session";
|
||||||
import { maxLength, useValidation } from "../../lib/validation";
|
import { maxLength, useValidation } from "../../lib/validation";
|
||||||
import type { Approval, Chemist, Dcr, Doctor, PlannedVisit } from "../../types";
|
import type { Approval, Chemist, Dcr, Doctor, PlannedVisit, Stockist } from "../../types";
|
||||||
|
|
||||||
export function ReportDetailPage({ id }: { id: string }) {
|
export function ReportDetailPage({ id }: { id: string }) {
|
||||||
const user = useUser();
|
const user = useUser();
|
||||||
@@ -59,11 +59,13 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
}
|
}
|
||||||
}, [report.data]);
|
}, [report.data]);
|
||||||
|
|
||||||
// Only the report's owner edits it: the MR for a plan or done report, the AM for their own.
|
// Only the report's owner edits it: the MR for a plan or done report, the ABM for their own.
|
||||||
const editable = !!dcr && dcr.mr_user_id === user.id && !dcr.is_locked && ["DRAFT", "RETURNED"].includes(dcr.status);
|
const editable = !!dcr && dcr.mr_user_id === user.id && !dcr.is_locked && ["DRAFT", "RETURNED"].includes(dcr.status);
|
||||||
editableRef.current = editable;
|
editableRef.current = editable;
|
||||||
const masters = useAsync(
|
const masters = useAsync(
|
||||||
() => (editable ? Promise.all([api.doctors(), api.chemists()]).then(([doctors, chemists]) => ({ doctors, chemists })) : Promise.resolve({ doctors: [] as Doctor[], chemists: [] as Chemist[] })),
|
() => (editable
|
||||||
|
? Promise.all([api.doctors(), api.chemists(), api.stockists()]).then(([doctors, chemists, stockists]) => ({ doctors, chemists, stockists }))
|
||||||
|
: Promise.resolve({ doctors: [] as Doctor[], chemists: [] as Chemist[], stockists: [] as Stockist[] })),
|
||||||
[editable], { poll: LIVE },
|
[editable], { poll: LIVE },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -112,7 +114,7 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
// Removing a visit vanishes from the list immediately; if the server refuses, it comes back.
|
// Removing a visit vanishes from the list immediately; if the server refuses, it comes back.
|
||||||
const removeVisit = async (callId: string) => {
|
const removeVisit = async (callId: string) => {
|
||||||
const before = dcr;
|
const before = dcr;
|
||||||
apply({ ...dcr, doctor_calls: dcr.doctor_calls.filter((c) => c.id !== callId), chemist_calls: dcr.chemist_calls.filter((c) => c.id !== callId) });
|
apply({ ...dcr, doctor_calls: dcr.doctor_calls.filter((c) => c.id !== callId), chemist_calls: dcr.chemist_calls.filter((c) => c.id !== callId), stockist_calls: dcr.stockist_calls.filter((c) => c.id !== callId) });
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
apply(await api.deleteCall(dcr.id, callId));
|
apply(await api.deleteCall(dcr.id, callId));
|
||||||
@@ -126,14 +128,14 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
// --- day plan / end-of-day ---------------------------------------------------------------
|
// --- day plan / end-of-day ---------------------------------------------------------------
|
||||||
const isPlan = dcr.report_type === "PLAN";
|
const isPlan = dcr.report_type === "PLAN";
|
||||||
const isSelf = dcr.report_type === "SELF";
|
const isSelf = dcr.report_type === "SELF";
|
||||||
// An Area Manager sees every headquarters they manage; their own report covers just one.
|
// An Area Business Manager sees every headquarters they manage; their own report covers just one.
|
||||||
const inReportHq = <T extends { headquarters_id: string; is_active: boolean }>(items: T[]) =>
|
const inReportHq = <T extends { headquarters_id: string; is_active: boolean }>(items: T[]) =>
|
||||||
isSelf ? items.filter((i) => i.is_active && i.headquarters_id === dcr.headquarters_id) : items;
|
isSelf ? items.filter((i) => i.is_active && i.headquarters_id === dcr.headquarters_id) : items;
|
||||||
const planned = dcr.planned_visits;
|
const planned = dcr.planned_visits;
|
||||||
const pending = planned.filter((p) => p.status === "PENDING").length;
|
const pending = planned.filter((p) => p.status === "PENDING").length;
|
||||||
const visitedPlanned = planned.filter((p) => p.status === "VISITED").length;
|
const visitedPlanned = planned.filter((p) => p.status === "VISITED").length;
|
||||||
const target = (line: PlannedVisit) => (line.kind === "DOCTOR" ? { doctor_id: line.target_id } : { chemist_id: line.target_id });
|
const target = (line: PlannedVisit) => (line.kind === "DOCTOR" ? { doctor_id: line.target_id } : line.kind === "STOCKIST" ? { stockist_id: line.target_id } : { chemist_id: line.target_id });
|
||||||
const recordPlanned = (line: PlannedVisit) => setPreset({ kind: line.kind === "DOCTOR" ? "doctor" : "chemist", targetId: line.target_id, key: Date.now() });
|
const recordPlanned = (line: PlannedVisit) => setPreset({ kind: line.kind === "DOCTOR" ? "doctor" : line.kind === "STOCKIST" ? "stockist" : "chemist", targetId: line.target_id, key: Date.now() });
|
||||||
const saveReason = async (line: PlannedVisit, reason: string): Promise<boolean> => {
|
const saveReason = async (line: PlannedVisit, reason: string): Promise<boolean> => {
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
@@ -176,6 +178,9 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
actions={<>
|
actions={<>
|
||||||
{dcr.plan_id && <Button icon="file" onClick={() => navigate(reportPath({ id: dcr.plan_id!, report_type: "PLAN" }))}>View plan</Button>}
|
{dcr.plan_id && <Button icon="file" onClick={() => navigate(reportPath({ id: dcr.plan_id!, report_type: "PLAN" }))}>View plan</Button>}
|
||||||
{dcr.actual_report_id && <Button icon="file" onClick={() => navigate(reportPath({ id: dcr.actual_report_id!, report_type: "ACTUAL" }))}>View done report</Button>}
|
{dcr.actual_report_id && <Button icon="file" onClick={() => navigate(reportPath({ id: dcr.actual_report_id!, report_type: "ACTUAL" }))}>View done report</Button>}
|
||||||
|
{dcr.status === "APPROVED" && (
|
||||||
|
<Button icon="eye" onClick={() => api.viewReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>View</Button>
|
||||||
|
)}
|
||||||
{dcr.status === "APPROVED" && (
|
{dcr.status === "APPROVED" && (
|
||||||
<Button variant="primary" icon="download" onClick={() => api.downloadReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>Download PDF</Button>
|
<Button variant="primary" icon="download" onClick={() => api.downloadReportPdf(dcr.id).catch((e) => setError(errorMessage(e)))}>Download PDF</Button>
|
||||||
)}
|
)}
|
||||||
@@ -183,7 +188,7 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
/>
|
/>
|
||||||
<Alert>{error}</Alert>
|
<Alert>{error}</Alert>
|
||||||
{dcr.return_reason && (
|
{dcr.return_reason && (
|
||||||
<Alert tone="warning" title={`Returned by ${dcr.returned_by_role ?? "reviewer"}`}>{dcr.return_reason}</Alert>
|
<Alert tone="warning" title={`Returned by ${dcr.returned_by_role ? roleLabel(dcr.returned_by_role) : "reviewer"}`}>{dcr.return_reason}</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Card><CardBody><WorkflowTracker status={dcr.status} type={dcr.report_type} /></CardBody></Card>
|
<Card><CardBody><WorkflowTracker status={dcr.status} type={dcr.report_type} /></CardBody></Card>
|
||||||
@@ -194,10 +199,11 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
<CardHeader title="Summary" />
|
<CardHeader title="Summary" />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<KeyValue items={[
|
<KeyValue items={[
|
||||||
{ label: isSelf ? "Area Manager" : "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
|
{ label: isSelf ? "Area Business Manager" : "Medical Representative", value: `${dcr.mr_name} (${dcr.employee_code})` },
|
||||||
{ label: "Headquarters", value: dcr.headquarters_name },
|
{ label: "Headquarters", value: dcr.headquarters_name },
|
||||||
{ label: isPlan ? "Doctors planned" : "Doctor visits", value: dcr.doctor_calls.length },
|
{ label: isPlan ? "Doctors planned" : "Doctor visits", value: dcr.doctor_calls.length },
|
||||||
{ label: isPlan ? "Chemists planned" : "Chemist visits", value: dcr.chemist_calls.length },
|
{ label: isPlan ? "Chemists planned" : "Chemist visits", value: dcr.chemist_calls.length },
|
||||||
|
...(dcr.stockist_calls.length ? [{ label: isPlan ? "Stockists planned" : "Stockist visits", value: dcr.stockist_calls.length }] : []),
|
||||||
...(dcr.plan_id ? [{ label: "Planned visits made", value: `${visitedPlanned} of ${planned.length}` }] : []),
|
...(dcr.plan_id ? [{ label: "Planned visits made", value: `${visitedPlanned} of ${planned.length}` }] : []),
|
||||||
{ label: "Submitted", value: formatDateTime(dcr.submitted_at) },
|
{ label: "Submitted", value: formatDateTime(dcr.submitted_at) },
|
||||||
...(isSelf ? [] : [{ label: "Approved", value: formatDateTime(dcr.approved_at) }]),
|
...(isSelf ? [] : [{ label: "Approved", value: formatDateTime(dcr.approved_at) }]),
|
||||||
@@ -214,7 +220,7 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
</Field>
|
</Field>
|
||||||
</>}
|
</>}
|
||||||
<Field label={isPlan ? "Plan note" : "Daily remarks"} span error={details.errors.remarks} hint={`${remarks.length}/2000 — saved when you leave the box`}>
|
<Field label={isPlan ? "Plan note" : "Daily remarks"} span error={details.errors.remarks} hint={`${remarks.length}/2000 — saved when you leave the box`}>
|
||||||
<Textarea value={remarks} onChange={typed(setRemarks, "remarks")} onBlur={() => void saveDetails()} rows={3} placeholder={isPlan ? "Optional note for your Area Manager" : "Optional summary of the day"} />
|
<Textarea value={remarks} onChange={typed(setRemarks, "remarks")} onBlur={() => void saveDetails()} rows={3} placeholder={isPlan ? "Optional note for your Area Business Manager" : "Optional summary of the day"} />
|
||||||
</Field>
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -230,8 +236,8 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{isPlan && isField(user.role) && dcr.status === "PENDING_AM" && (
|
{isPlan && isField(user.role) && dcr.status === "PENDING_ABM" && (
|
||||||
<Alert tone="info">Once your Area Manager approves this plan, you can fill the Daily Call Report (Done) for {formatDate(dcr.report_date)}.</Alert>
|
<Alert tone="info">Once your Area Business Manager approves this plan, you can fill the Daily Call Report (Done) for {formatDate(dcr.report_date)}.</Alert>
|
||||||
)}
|
)}
|
||||||
{isPlan && dcr.status === "APPROVED" && isField((user.role) || dcr.actual_report_id) && (
|
{isPlan && dcr.status === "APPROVED" && isField((user.role) || dcr.actual_report_id) && (
|
||||||
<Card>
|
<Card>
|
||||||
@@ -263,13 +269,13 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title={isPlan ? "Add to your plan" : "Add a visit"}
|
title={isPlan ? "Add to your plan" : "Add a visit"}
|
||||||
description={isPlan
|
description={isPlan
|
||||||
? "Who you intend to visit today, and when. Only doctors and chemists assigned to you are listed."
|
? "Who you intend to visit today, and when. Only doctors and chemists assigned to you, and stockists of your headquarters, are listed."
|
||||||
: isSelf
|
: isSelf
|
||||||
? `Doctors and chemists of ${dcr.headquarters_name} are listed.`
|
? `Doctors, chemists and stockists of ${dcr.headquarters_name} are listed.`
|
||||||
: "Only doctors and chemists assigned to you are listed. Unplanned visits can be added too."}
|
: "Only doctors and chemists assigned to you, and stockists of your headquarters, are listed. Unplanned visits can be added too."}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<AddVisitForm dcr={dcr} doctors={inReportHq(masters.data?.doctors ?? [])} chemists={inReportHq(masters.data?.chemists ?? [])} preset={preset} onChange={(next) => { apply(next); reconcile(); }} />
|
<AddVisitForm dcr={dcr} doctors={inReportHq(masters.data?.doctors ?? [])} chemists={inReportHq(masters.data?.chemists ?? [])} stockists={inReportHq(masters.data?.stockists ?? []).filter((s) => s.is_active)} preset={preset} onChange={(next) => { apply(next); reconcile(); }} />
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
@@ -278,8 +284,8 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title={isPlan ? "Planned visits" : "Visits"}
|
title={isPlan ? "Planned visits" : "Visits"}
|
||||||
description={isPlan
|
description={isPlan
|
||||||
? `${dcr.doctor_calls.length + dcr.chemist_calls.length} planned, in time order.`
|
? `${dcr.doctor_calls.length + dcr.chemist_calls.length + dcr.stockist_calls.length} planned, in time order.`
|
||||||
: `${dcr.doctor_calls.length + dcr.chemist_calls.length} recorded, in visit order.`}
|
: `${dcr.doctor_calls.length + dcr.chemist_calls.length + dcr.stockist_calls.length} recorded, in visit order.`}
|
||||||
/>
|
/>
|
||||||
<CardBody flush>
|
<CardBody flush>
|
||||||
<VisitList dcr={dcr} editable={editable} onRemove={(callId) => void removeVisit(callId)} />
|
<VisitList dcr={dcr} editable={editable} onRemove={(callId) => void removeVisit(callId)} />
|
||||||
@@ -297,8 +303,8 @@ export function ReportDetailPage({ id }: { id: string }) {
|
|||||||
: "Submitted reports cannot be edited unless they are returned for correction."}
|
: "Submitted reports cannot be edited unless they are returned for correction."}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<Button variant="primary" icon="send" loading={busy} disabled={pending > 0} onClick={() => void run(() => api.submit(dcr.id), isPlan ? "Plan sent to the Area Manager" : isSelf ? "Report submitted" : "Submitted to the Area Manager")}>
|
<Button variant="primary" icon="send" loading={busy} disabled={pending > 0} onClick={() => void run(() => api.submit(dcr.id), isPlan ? "Plan sent to the Area Business Manager" : isSelf ? "Report submitted" : "Submitted to the Area Business Manager")}>
|
||||||
{isPlan ? "Send plan to Area Manager" : isSelf ? "Submit report" : "Submit to Area Manager"}
|
{isPlan ? "Send plan to Area Business Manager" : isSelf ? "Submit report" : "Submit to Area Business Manager"}
|
||||||
</Button>
|
</Button>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ type Filter = "ALL" | "DRAFT" | "PENDING" | "RETURNED" | "APPROVED";
|
|||||||
const MATCH: Record<Filter, (r: DcrListItem) => boolean> = {
|
const MATCH: Record<Filter, (r: DcrListItem) => boolean> = {
|
||||||
ALL: () => true,
|
ALL: () => true,
|
||||||
DRAFT: (r) => r.status === "DRAFT",
|
DRAFT: (r) => r.status === "DRAFT",
|
||||||
PENDING: (r) => r.status === "PENDING_AM",
|
PENDING: (r) => r.status === "PENDING_ABM",
|
||||||
RETURNED: (r) => r.status === "RETURNED",
|
RETURNED: (r) => r.status === "RETURNED",
|
||||||
APPROVED: (r) => r.status === "APPROVED",
|
APPROVED: (r) => r.status === "APPROVED",
|
||||||
};
|
};
|
||||||
@@ -27,10 +27,10 @@ const DESCRIPTION: Record<ReportType, { mr: string; manager: string; gm?: string
|
|||||||
SELF: {
|
SELF: {
|
||||||
mr: "",
|
mr: "",
|
||||||
manager: "Your own visits to doctors and chemists, one report a day. No approval is needed: submitting a report makes it final.",
|
manager: "Your own visits to doctors and chemists, one report a day. No approval is needed: submitting a report makes it final.",
|
||||||
gm: "Area Managers' own visits to doctors and chemists, across every headquarters. A submitted report is final.",
|
gm: "Area Business Managers' own visits to doctors and chemists, across every headquarters. A submitted report is final.",
|
||||||
},
|
},
|
||||||
PLAN: {
|
PLAN: {
|
||||||
mr: "Plan the doctors and chemists you will visit each day, and send the plan to your Area Manager.",
|
mr: "Plan the doctors and chemists you will visit each day, and send the plan to your Area Business Manager.",
|
||||||
manager: "Day plans from your scope. Approving a plan lets the MR file its Daily Call Report (Done).",
|
manager: "Day plans from your scope. Approving a plan lets the MR file its Daily Call Report (Done).",
|
||||||
},
|
},
|
||||||
ACTUAL: {
|
ACTUAL: {
|
||||||
@@ -39,12 +39,12 @@ const DESCRIPTION: Record<ReportType, { mr: string; manager: string; gm?: string
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The list behind one sidebar entry: Daily Call Report (Plan), (Done) or an Area Manager's (Self). */
|
/** The list behind one sidebar entry: Daily Call Report (Plan), (Done) or an Area Business Manager's (Self). */
|
||||||
export function ReportsPage({ type }: { type: ReportType }) {
|
export function ReportsPage({ type }: { type: ReportType }) {
|
||||||
const user = useUser();
|
const user = useUser();
|
||||||
const isSelf = type === "SELF";
|
const isSelf = type === "SELF";
|
||||||
// The role that files this type of report, and so gets the "new report" button.
|
// The role that files this type of report, and so gets the "new report" button.
|
||||||
const author = isSelf ? "AM" : "MR";
|
const author = isSelf ? "ABM" : "MR";
|
||||||
const reports = useAsync(() => api.reports(type), [type], { poll: LIVE });
|
const reports = useAsync(() => api.reports(type), [type], { poll: LIVE });
|
||||||
const [filter, setFilter] = useState<Filter>("ALL");
|
const [filter, setFilter] = useState<Filter>("ALL");
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
@@ -66,7 +66,7 @@ export function ReportsPage({ type }: { type: ReportType }) {
|
|||||||
<>
|
<>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={REPORT_TYPE_LABEL[type]}
|
title={REPORT_TYPE_LABEL[type]}
|
||||||
description={isField(user.role) ? DESCRIPTION[type].mr : (user.role === "GM" && DESCRIPTION[type].gm) || DESCRIPTION[type].manager}
|
description={isField(user.role) ? DESCRIPTION[type].mr : (user.role === "AGM" && DESCRIPTION[type].gm) || DESCRIPTION[type].manager}
|
||||||
actions={user.role === author && (
|
actions={user.role === author && (
|
||||||
<Button variant="primary" icon="plus" onClick={() => navigate(`${reportsPath(type)}/new`)}>
|
<Button variant="primary" icon="plus" onClick={() => navigate(`${reportsPath(type)}/new`)}>
|
||||||
{type === "PLAN" ? "Plan my day" : `New report (${isSelf ? "Self" : "Done"})`}
|
{type === "PLAN" ? "Plan my day" : `New report (${isSelf ? "Self" : "Done"})`}
|
||||||
@@ -80,7 +80,7 @@ export function ReportsPage({ type }: { type: ReportType }) {
|
|||||||
</div>
|
</div>
|
||||||
{reports.error
|
{reports.error
|
||||||
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
|
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
|
||||||
: <ReportTable rows={rows} loading={reports.loading} ownerHeader={isSelf ? "Area Manager" : undefined} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
|
: <ReportTable rows={rows} loading={reports.loading} ownerHeader={isSelf ? "Area Business Manager (ABM)" : undefined} emptyText={query || filter !== "ALL" ? "No reports match your filters" : "No reports yet"} />}
|
||||||
</Card>
|
</Card>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
+11
-9
@@ -1,30 +1,32 @@
|
|||||||
export type Role = "ADMIN" | "GM" | "AM" | "MR" | "SFE";
|
export type Role = "ADMIN" | "AGM" | "ABM" | "MR" | "SFE";
|
||||||
export type DcrStatus = "DRAFT" | "PENDING_AM" | "RETURNED" | "APPROVED";
|
export type DcrStatus = "DRAFT" | "PENDING_ABM" | "RETURNED" | "APPROVED";
|
||||||
/** PLAN = the morning day plan; ACTUAL = the end-of-day report filed against it. */
|
/** PLAN = the morning day plan; ACTUAL = the end-of-day report filed against it. */
|
||||||
export type ReportType = "PLAN" | "ACTUAL" | "SELF";
|
export type ReportType = "PLAN" | "ACTUAL" | "SELF";
|
||||||
export interface User { id: string; full_name: string; email: string; employee_code: string; phone?: string | null; role: Role; headquarters_id: string | null; is_active: boolean; is_superadmin?: boolean; extra_headquarter_ids?: string[] }
|
export interface User { id: string; full_name: string; email: string; employee_code: string; phone?: string | null; role: Role; headquarters_id: string | null; is_active: boolean; is_superadmin?: boolean; extra_headquarter_ids?: string[] }
|
||||||
export interface Headquarters { id: string; code: string; name: string; district: string | null; state: string | null; is_active: boolean }
|
export interface Headquarters { id: string; code: string; name: string; district: string | null; state: string | null; is_active: boolean }
|
||||||
export interface AreaManagerMapping { id: string; area_manager_user_id: string; headquarters_id: string; effective_from: string; effective_to: string | null }
|
export interface AreaManagerMapping { id: string; area_manager_user_id: string; headquarters_id: string; effective_from: string; effective_to: string | null }
|
||||||
/** A doctor or chemist an MR adds is PENDING until their Area Manager approves it; only APPROVED ones are listed. */
|
/** A doctor or chemist an MR adds is PENDING until their Area Business Manager approves it; only APPROVED ones are listed. */
|
||||||
export type MasterApproval = "PENDING" | "APPROVED" | "REJECTED";
|
export type MasterApproval = "PENDING" | "APPROVED" | "REJECTED";
|
||||||
interface MasterApprovalFields { approval_status: MasterApproval; rejection_reason: string | null; requested_by_name: string | null; created_at: string }
|
interface MasterApprovalFields { approval_status: MasterApproval; rejection_reason: string | null; requested_by_name: string | null; created_at: string }
|
||||||
export interface Doctor extends MasterApprovalFields { id: string; headquarters_id: string; name: string; speciality: string | null; clinic_address: string; date_of_birth: string | null; is_core_doctor: boolean; is_active: boolean }
|
export interface Doctor extends MasterApprovalFields { id: string; headquarters_id: string; name: string; speciality: string | null; qualification?: string | null; contact_number?: string | null; clinic_address: string; date_of_birth: string | null; is_core_doctor: boolean; is_active: boolean; assigned_mr_name: string | null; assigned_mr_id?: string | null }
|
||||||
export interface Chemist extends MasterApprovalFields { id: string; headquarters_id: string; name: string; shop_address: string; is_active: boolean }
|
export interface Chemist extends MasterApprovalFields { id: string; headquarters_id: string; name: string; shop_address: string; contact_number?: string | null; is_active: boolean; assigned_mr_name?: string | null; assigned_mr_id?: string | null }
|
||||||
|
export interface Stockist extends MasterApprovalFields { id: string; headquarters_id: string; name: string; address: string; contact_number?: string | null; is_active: boolean; assigned_mr_name?: string | null }
|
||||||
export interface Product { id: string; company_id: string; name: string; pack: string | null; unit: string | null; is_active: boolean }
|
export interface Product { id: string; company_id: string; name: string; pack: string | null; unit: string | null; is_active: boolean }
|
||||||
export interface StockInventory { id: number; serial_no: number; product_name: string; pack: string | null; quantity: string | null; unit: string | null }
|
export interface StockInventory { id: number; serial_no: number; product_name: string; pack: string | null; quantity: string | null; unit: string | null }
|
||||||
export interface DoctorCall { id: string; doctor_id: string; doctor_name: string; doctor_speciality: string | null; is_core_doctor: boolean; visit_time: string; call_outcome: string | null; conversion_status: string | null; product_promote: string[]; product_sample: string[]; gift: string | null; remarks: string | null }
|
export interface DoctorCall { id: string; doctor_id: string; doctor_name: string; doctor_speciality: string | null; is_core_doctor: boolean; visit_time: string; call_outcome: string | null; conversion_status: string | null; product_promote: string[]; product_sample: string[]; gift: string | null; remarks: string | null }
|
||||||
export interface ChemistCall { id: string; chemist_id: string; chemist_name: string; visit_time: string; pob: string | null; remarks: string | null }
|
export interface ChemistCall { id: string; chemist_id: string; chemist_name: string; visit_time: string; pob: string | null; remarks: string | null }
|
||||||
|
export interface StockistCall { id: string; stockist_id: string; stockist_name: string; visit_time: string; pob: string | null; remarks: string | null }
|
||||||
export interface DcrListItem { id: string; report_date: string; report_type: ReportType; status: DcrStatus; mr_name: string; headquarters_name: string; doctor_call_count: number; chemist_call_count: number; submitted_at: string | null; approved_at: string | null; returned_by_role: Role | null }
|
export interface DcrListItem { id: string; report_date: string; report_type: ReportType; status: DcrStatus; mr_name: string; headquarters_name: string; doctor_call_count: number; chemist_call_count: number; submitted_at: string | null; approved_at: string | null; returned_by_role: Role | null }
|
||||||
export interface Dcr extends DcrListItem { mr_user_id: string; employee_code: string; headquarters_id: string; is_locked: boolean; mr_remarks: string | null; stockist_visit: string | null; order_value: string | null; return_reason: string | null; doctor_calls: DoctorCall[]; chemist_calls: ChemistCall[]; plan_id: string | null; actual_report_id: string | null; planned_visits: PlannedVisit[] }
|
export interface Dcr extends DcrListItem { mr_user_id: string; employee_code: string; headquarters_id: string; is_locked: boolean; mr_remarks: string | null; stockist_visit: string | null; order_value: string | null; return_reason: string | null; doctor_calls: DoctorCall[]; chemist_calls: ChemistCall[]; stockist_calls: StockistCall[]; plan_id: string | null; actual_report_id: string | null; planned_visits: PlannedVisit[] }
|
||||||
/** One line of the approved plan, checked against the end-of-day report. */
|
/** One line of the approved plan, checked against the end-of-day report. */
|
||||||
export interface PlannedVisit { kind: "DOCTOR" | "CHEMIST"; target_id: string; name: string; is_core_doctor: boolean; planned_time: string; status: "VISITED" | "MISSED" | "PENDING"; missed_visit_id: string | null; missed_reason: string | null }
|
export interface PlannedVisit { kind: "DOCTOR" | "CHEMIST" | "STOCKIST"; target_id: string; name: string; is_core_doctor: boolean; planned_time: string; status: "VISITED" | "MISSED" | "PENDING"; missed_visit_id: string | null; missed_reason: string | null }
|
||||||
export interface Profile extends User { phone: string | null; headquarters_code: string | null; headquarters_name: string | null; reporting_manager_name: string | null }
|
export interface Profile extends User { phone: string | null; headquarters_code: string | null; headquarters_name: string | null; reporting_manager_name: string | null }
|
||||||
export interface Approval { action: string; actor_name: string; actor_role: string; comment: string | null; at: string }
|
export interface Approval { action: string; actor_name: string; actor_role: string; comment: string | null; at: string }
|
||||||
export interface CsvTable { name: string; label: string; columns: string[] }
|
export interface CsvTable { name: string; label: string; columns: string[] }
|
||||||
export interface CsvRow { id: string; source_row_number: number;[key: string]: string | number }
|
export interface CsvRow { id: string; source_row_number: number;[key: string]: string | number }
|
||||||
|
|
||||||
export interface StatusCounts { DRAFT: number; PENDING_AM: number; RETURNED: number; APPROVED: number }
|
export interface StatusCounts { DRAFT: number; PENDING_ABM: number; RETURNED: number; APPROVED: number }
|
||||||
/** Server-side approval state of a company form. draft = not sent, pending = with the Area Manager. */
|
/** Server-side approval state of a company form. draft = not sent, pending = with the Area Business Manager. */
|
||||||
export type FormApproval = {
|
export type FormApproval = {
|
||||||
table_name: string; owner_user_id: string; owner_name: string; headquarters_name: string | null;
|
table_name: string; owner_user_id: string; owner_name: string; headquarters_name: string | null;
|
||||||
status: "draft" | "pending" | "approved"; approved_by_name: string | null; updated_at: string | null;
|
status: "draft" | "pending" | "approved"; approved_by_name: string | null; updated_at: string | null;
|
||||||
|
|||||||
Reference in New Issue
Block a user