"""THE acceptance test — the 13-step flow from the report, plus 3 negative-scope tests. This is the definition of done for Phase 1. It walks the complete value chain: setup → entry → approval → PDF → audit. If this passes, the product is real. The three negative tests (X1-X3) matter as much as the thirteen positive ones: a permission system that has never been tested against a wrong-scope request is a permission system that does not work. """ from datetime import date import pytest from app.common.enums import DCRStatus pytestmark = pytest.mark.anyio API = "/api/v1" # --------------------------------------------------------------------------- # Steps 1-3: Admin sets up users, org mapping and masters # --------------------------------------------------------------------------- async def _create_masters(client, auth, org, n_doctors=15, n_chemists=5): """Steps 3: Admin creates doctors and chemists and assigns them to the MR.""" doctors, chemists = [], [] for i in range(n_doctors): resp = await client.post( f"{API}/doctors", headers=auth["admin"], json={ "headquarters_id": str(org["hq1"].id), "name": f"Dr Doctor {i:02d}", "clinic_address": f"Clinic {i:02d}, Bhubaneswar", "speciality": "General Medicine", # The first three are core doctors, so conversion status is exercised. "is_core_doctor": i < 3, }, ) assert resp.status_code == 201, resp.text doctor = resp.json() assign = await client.post( f"{API}/doctors/{doctor['id']}/assign", headers=auth["admin"], json={"mr_user_id": str(org["mr1"].id)}, ) assert assign.status_code == 201, assign.text doctors.append(doctor) for i in range(n_chemists): resp = await client.post( f"{API}/chemists", headers=auth["admin"], json={ "headquarters_id": str(org["hq1"].id), "name": f"Chemist {i:02d}", "shop_address": f"Shop {i:02d}, Bhubaneswar", }, ) assert resp.status_code == 201, resp.text chemist = resp.json() assign = await client.post( f"{API}/chemists/{chemist['id']}/assign", headers=auth["admin"], json={"mr_user_id": str(org["mr1"].id)}, ) assert assign.status_code == 201, assign.text chemists.append(chemist) return doctors, chemists class TestStep1And2Setup: async def test_admin_creates_user_and_org_mapping(self, client, auth, org): """Step 1-2: users exist with correct roles, and the MR's profile resolves both its headquarters and its DERIVED reporting Area Manager.""" resp = await client.get(f"{API}/users/me/profile", headers=auth["mr1"]) assert resp.status_code == 200, resp.text profile = resp.json() assert profile["role"] == "MR" assert profile["headquarters_code"] == "BBSR" assert profile["headquarters_name"] == "Bhubaneswar" # Derived through am_headquarters, not stored on the MR. assert profile["reporting_manager_name"] == "Suresh Behera" async def test_admin_can_create_a_new_mr(self, client, auth, org): resp = await client.post( f"{API}/users", headers=auth["admin"], json={ "email": "newmr@acmepharma.in", "password": "An0therStr0ngPwd!", "full_name": "New Rep", "employee_code": "MR010", "role": "MR", "headquarters_id": str(org["hq1"].id), }, ) assert resp.status_code == 201, resp.text assert resp.json()["role"] == "MR" async def test_creating_an_mr_without_hq_is_rejected(self, client, auth): resp = await client.post( f"{API}/users", headers=auth["admin"], json={ "email": "bad@acmepharma.in", "password": "An0therStr0ngPwd!", "full_name": "Bad Rep", "employee_code": "MR011", "role": "MR", }, ) assert resp.status_code == 422 class TestStep3And5Masters: async def test_mr_sees_exactly_the_assigned_doctors(self, client, auth, org): """Step 3 + Step 5 (S5): 15 doctors created and assigned → MR sees 15.""" await _create_masters(client, auth, org) resp = await client.get(f"{API}/doctors", headers=auth["mr1"]) assert resp.status_code == 200 assert len(resp.json()) == 15 resp = await client.get(f"{API}/chemists", headers=auth["mr1"]) assert len(resp.json()) == 5 async def test_other_mr_sees_none_of_them(self, client, auth, org): """An MR can view only their own data (R5).""" await _create_masters(client, auth, org) resp = await client.get(f"{API}/doctors", headers=auth["mr2"]) assert resp.json() == [] async def test_mr_creates_doctor_and_chemist_in_own_hq(self, client, auth, org): """The MR's new doctor and chemist are assigned to them, so they show up at once.""" hq1 = str(org["hq1"].id) doctor = await client.post( f"{API}/doctors", headers=auth["mr1"], json={"headquarters_id": hq1, "name": "Dr Selfmade", "clinic_address": "Nowhere"}, ) assert doctor.status_code == 201 chemist = await client.post( f"{API}/chemists", headers=auth["mr1"], json={"headquarters_id": hq1, "name": "Selfmade Pharmacy", "shop_address": "Nowhere"}, ) assert chemist.status_code == 201 doctors = (await client.get(f"{API}/doctors", headers=auth["mr1"])).json() assert doctor.json()["id"] in {d["id"] for d in doctors} chemists = (await client.get(f"{API}/chemists", headers=auth["mr1"])).json() assert chemist.json()["id"] in {c["id"] for c in chemists} async def test_mr_cannot_create_outside_own_hq_or_a_product(self, client, auth, org): resp = await client.post( f"{API}/doctors", headers=auth["mr1"], json={ "headquarters_id": str(org["hq2"].id), "name": "Dr Elsewhere", "clinic_address": "Nowhere", }, ) assert resp.status_code == 403 resp = await client.post(f"{API}/products", headers=auth["mr1"], json={"name": "Pill"}) assert resp.status_code == 403 class TestStep4Login: async def test_login_returns_token_pair(self, client, org): resp = await client.post( f"{API}/auth/login", json={"email": org["mr1"].email, "password": "Str0ngPassw0rd!"}, ) assert resp.status_code == 200 body = resp.json() assert body["access_token"] and body["refresh_token"] assert body["token_type"] == "bearer" async def test_wrong_password_rejected(self, client, org): resp = await client.post( f"{API}/auth/login", json={"email": org["mr1"].email, "password": "wrong-password"}, ) assert resp.status_code == 401 async def test_refresh_rotates_the_token(self, client, org): first = await client.post( f"{API}/auth/login", json={"email": org["mr1"].email, "password": "Str0ngPassw0rd!"}, ) refresh_token = first.json()["refresh_token"] second = await client.post(f"{API}/auth/refresh", json={"refresh_token": refresh_token}) assert second.status_code == 200 # The presented token is burned on rotation. replay = await client.post(f"{API}/auth/refresh", json={"refresh_token": refresh_token}) assert replay.status_code == 401 async def test_unauthenticated_request_rejected(self, client): assert (await client.get(f"{API}/dcr")).status_code == 401 # --------------------------------------------------------------------------- # Steps 5-13: the full report lifecycle # --------------------------------------------------------------------------- class TestFullApprovalFlow: async def test_thirteen_step_flow(self, client, auth, org, approved_plan): doctors, chemists = await _create_masters(client, auth, org) today = date.today().isoformat() await approved_plan() # --- Step 5: MR creates a DCR --------------------------------- resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": today, "mr_remarks": "Covered MG Road belt."}, ) assert resp.status_code == 201, resp.text dcr = resp.json() assert dcr["status"] == DCRStatus.DRAFT.value assert dcr["is_locked"] is False dcr_id = dcr["id"] # --- Step 6: 5 doctor calls + 2 chemist calls ----------------- for i in range(5): payload = { "doctor_id": doctors[i]["id"], "visit_time": f"{9 + i:02d}:30:00", "call_outcome": "MET", "remarks": f"Discussed product line {i}", } if doctors[i]["is_core_doctor"]: payload["conversion_status"] = "IN_PROGRESS" r = await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json=payload ) assert r.status_code == 201, r.text for i in range(2): r = await client.post( f"{API}/dcr/{dcr_id}/calls/chemist", headers=auth["mr1"], json={ "chemist_id": chemists[i]["id"], "visit_time": f"{15 + i:02d}:00:00", "remarks": "Stock check", }, ) assert r.status_code == 201, r.text # A duplicate doctor on the same report is refused (V5). dup = await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json={ "doctor_id": doctors[0]["id"], "visit_time": "17:00:00", "call_outcome": "MET", }, ) assert dup.status_code == 409 assert dup.json()["error"]["code"] == "CONFLICT" # --- Step 7: the draft persists ------------------------------- resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr1"]) dcr = resp.json() assert len(dcr["doctor_calls"]) == 5 assert len(dcr["chemist_calls"]) == 2 assert dcr["status"] == DCRStatus.DRAFT.value # A second report for the same date is refused (V1/A9). again = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": today} ) assert again.status_code == 409 # --- Step 8: MR submits --------------------------------------- resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) assert resp.status_code == 200, resp.text assert resp.json()["status"] == DCRStatus.PENDING_AM.value assert resp.json()["submitted_at"] is not None # --- Step 9a: AM returns it ----------------------------------- queue = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am1"]) assert [r["id"] for r in queue.json()] == [dcr_id] # A reason is mandatory (V8). no_reason = await client.post( f"{API}/dcr/{dcr_id}/return", headers=auth["am1"], json={"reason": "bad"} ) assert no_reason.status_code == 422 resp = await client.post( f"{API}/dcr/{dcr_id}/return", headers=auth["am1"], json={"reason": "Please add remarks for the two chemist visits."}, ) assert resp.status_code == 200, resp.text returned = resp.json() assert returned["status"] == DCRStatus.RETURNED.value assert returned["returned_by_role"] == "AM" assert "chemist visits" in returned["return_reason"] # The MR can edit again once returned. edit = await client.patch( f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"mr_remarks": "Covered MG Road belt. Chemist remarks added."}, ) assert edit.status_code == 200 # --- Step 9b: MR resubmits ------------------------------------ resp = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) assert resp.json()["status"] == DCRStatus.PENDING_AM.value # Resubmission clears the previous return. assert resp.json()["return_reason"] is None # --- Step 10: the Area Manager gives the final approval ------- # There is no General Manager stage, and the GM cannot approve. gm_try = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["gm"], json={}) assert gm_try.status_code == 403, gm_try.text gone = await client.post(f"{API}/dcr/{dcr_id}/forward", headers=auth["am1"], json={}) assert gone.status_code in (404, 405), gone.text am_approve = await client.post( f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={"comment": "Approved for the month."}, ) assert am_approve.status_code == 200, am_approve.text assert am_approve.json()["status"] == DCRStatus.APPROVED.value approved_view = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["gm"]) assert approved_view.status_code == 200, approved_view.text approved = approved_view.json() assert approved["status"] == DCRStatus.APPROVED.value assert approved["approved_at"] is not None # --- Step 11: the report is locked ---------------------------- # APPROVED is the lock. There is no separate LOCKED status. assert approved["is_locked"] is True locked_edit = await client.patch( f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"mr_remarks": "sneaky edit"} ) assert locked_edit.status_code == 409 assert locked_edit.json()["error"]["code"] == "REPORT_LOCKED" locked_add = await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json={ "doctor_id": doctors[9]["id"], "visit_time": "18:00:00", "call_outcome": "MET", }, ) assert locked_add.status_code == 409 # No role can move an approved report anywhere (A6/Q6 — no reopen). for role in ("gm", "admin"): again = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth[role], json={}) assert again.status_code in (403, 409) # The approving AM repeating the click changes nothing (idempotent), and is not an error. repeat = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={}) assert repeat.status_code == 200 and repeat.json()["approved_at"] == approved["approved_at"] # ...but an approved report can still not be returned or reopened by anybody. for role in ("gm", "am1", "admin", "mr1"): back = await client.post(f"{API}/dcr/{dcr_id}/return", headers=auth[role], json={"reason": "reopen it please"}) assert back.status_code in (403, 409), role # --- Step 12: MR, AM and GM each download the PDF ------------- for role in ("mr1", "am1", "gm"): pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth[role]) assert pdf.status_code == 200, f"{role}: {pdf.text}" assert pdf.headers["content-type"] == "application/pdf" assert pdf.content.startswith(b"%PDF-") assert len(pdf.content) > 500 # --- Step 13: the audit history is complete ------------------- history = await client.get( f"{API}/audit/dcr/{dcr_id}/approval-history", headers=auth["gm"] ) assert history.status_code == 200, history.text actions = [h["action"] for h in history.json()] # create → submit → return → submit → approve assert actions == ["CREATE", "SUBMIT", "RETURN", "SUBMIT", "APPROVE"], actions entries = history.json() assert entries[2]["actor_name"] == "Suresh Behera" assert entries[2]["actor_role"] == "AM" assert "chemist visits" in entries[2]["comment"] # The final entry is the Area Manager's approval. assert entries[-1]["actor_name"] == "Suresh Behera" assert entries[-1]["actor_role"] == "AM" assert entries[-1]["comment"] == "Approved for the month." assert all(e["at"] for e in entries) # --------------------------------------------------------------------------- # Negative-scope tests — X1, X2, X3 # --------------------------------------------------------------------------- class TestNegativeScope: async def _submitted_report(self, client, auth, org, approved_plan): doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1) await approved_plan() resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) dcr_id = resp.json()["id"] await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json={ "doctor_id": doctors[0]["id"], "visit_time": "10:00:00", "call_outcome": "MET", }, ) await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) return dcr_id async def test_x1_second_mr_cannot_see_the_first_mrs_report(self, client, auth, org, approved_plan): dcr_id = await self._submitted_report(client, auth, org, approved_plan) resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr2"]) assert resp.status_code == 403, resp.text assert resp.json()["error"]["code"] == "FORBIDDEN" # It must not appear in their list either. listing = await client.get(f"{API}/dcr", headers=auth["mr2"]) assert listing.json() == [] async def test_x2_area_manager_of_another_hq_cannot_see_it(self, client, auth, org, approved_plan): dcr_id = await self._submitted_report(client, auth, org, approved_plan) resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["am2"]) assert resp.status_code == 403, resp.text # And cannot act on it. for action, body in (("approve", {}), ("return", {"reason": "Not my headquarters at all"})): assert ( await client.post(f"{API}/dcr/{dcr_id}/{action}", headers=auth["am2"], json=body) ).status_code == 403 listing = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am2"]) assert listing.json() == [] async def test_x3_admin_cannot_approve(self, client, auth, org, approved_plan): """SEC-2 — the single most important governance rule in the design.""" dcr_id = await self._submitted_report(client, auth, org, approved_plan) resp = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["admin"], json={}) assert resp.status_code == 403, resp.text # Admin may inspect report content but cannot approve it. assert ( await client.get(f"{API}/dcr/{dcr_id}", headers=auth["admin"]) ).status_code == 200 async def test_admin_cannot_create_a_report(self, client, auth): resp = await client.post( f"{API}/dcr", headers=auth["admin"], json={"report_date": date.today().isoformat()} ) assert resp.status_code == 403 async def test_deactivated_user_loses_access_immediately(self, client, auth, org): """SEC-5 — is_active is checked on every request, not only at login.""" assert (await client.get(f"{API}/dcr", headers=auth["mr1"])).status_code == 200 deact = await client.patch( f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"is_active": False} ) assert deact.status_code == 200 assert (await client.get(f"{API}/dcr", headers=auth["mr1"])).status_code == 401 # --------------------------------------------------------------------------- # Validation rules # --------------------------------------------------------------------------- class TestValidationRules: async def test_v2_future_date_rejected(self, client, auth, org): from datetime import timedelta future = (date.today() + timedelta(days=1)).isoformat() resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": future}) assert resp.status_code == 422 assert resp.json()["error"]["code"] == "VALIDATION_ERROR" async def test_v3_beyond_backdating_window_rejected(self, client, auth, org): from datetime import timedelta from app.config.settings import settings old = (date.today() - timedelta(days=settings.BACKDATING_WINDOW_DAYS + 1)).isoformat() resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": old}) assert resp.status_code == 422 assert "back-dating" in resp.json()["error"]["message"] async def test_v4_cannot_submit_without_a_doctor_call(self, client, auth, org, approved_plan): await approved_plan() resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) dcr_id = resp.json()["id"] submit = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) assert submit.status_code == 422 assert "at least one doctor call" in submit.json()["error"]["message"] async def test_v6_unassigned_doctor_rejected(self, client, auth, org, approved_plan): """A doctor from another HQ, not assigned to this MR.""" await approved_plan() other = await client.post( f"{API}/doctors", headers=auth["admin"], json={ "headquarters_id": str(org["hq2"].id), "name": "Dr Outsider", "clinic_address": "Sambalpur", }, ) resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) dcr_id = resp.json()["id"] call = await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json={ "doctor_id": other.json()["id"], "visit_time": "10:00:00", "call_outcome": "MET", }, ) assert call.status_code == 422 assert "not assigned" in call.json()["error"]["message"] async def test_v7_conversion_status_only_for_core_doctors(self, client, auth, org, approved_plan): doctors, _ = await _create_masters(client, auth, org, n_doctors=5, n_chemists=1) await approved_plan() non_core = next(d for d in doctors if not d["is_core_doctor"]) resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) dcr_id = resp.json()["id"] call = await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json={ "doctor_id": non_core["id"], "visit_time": "10:00:00", "call_outcome": "MET", "conversion_status": "CONVERTED", }, ) assert call.status_code == 422 assert "core doctor" in call.json()["error"]["message"] async def test_cannot_edit_while_pending_with_the_manager(self, client, auth, org, approved_plan): doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1) await approved_plan() resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) dcr_id = resp.json()["id"] await client.post( f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"], json={ "doctor_id": doctors[0]["id"], "visit_time": "10:00:00", "call_outcome": "MET", }, ) await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"]) edit = await client.patch( f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"mr_remarks": "late change"} ) assert edit.status_code == 409 assert edit.json()["error"]["code"] == "REPORT_LOCKED" async def test_pdf_unavailable_before_approval(self, client, auth, org, approved_plan): doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1) await approved_plan() resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) dcr_id = resp.json()["id"] pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["mr1"]) assert pdf.status_code == 422 assert "finally approved" in pdf.json()["error"]["message"] class TestStatusCounts: async def test_counts_replace_the_dashboard(self, client, auth, org, approved_plan): doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1) await approved_plan() resp = await client.post( f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()} ) assert resp.status_code == 201 counts = await client.get(f"{API}/dcr/counts", headers=auth["mr1"]) assert counts.status_code == 200 assert counts.json()["DRAFT"] == 1 assert counts.json()["APPROVED"] == 1 # the day plan the report follows