Production
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
"""An Area Manager can manage any number of headquarters; only an Admin can change that."""
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.organization.models import Headquarters
|
||||
|
||||
API = "/api/v1/headquarters"
|
||||
|
||||
|
||||
async def _third_hq(db, org) -> Headquarters:
|
||||
hq = Headquarters(
|
||||
id=uuid.uuid4(), company_id=org["company"].id, code="CTC", name="Cuttack",
|
||||
district="Cuttack", state="Odisha",
|
||||
)
|
||||
db.add(hq)
|
||||
await db.commit()
|
||||
return hq
|
||||
|
||||
|
||||
def _hq_ids(resp) -> set[str]:
|
||||
return {row["headquarters_id"] for row in resp.json()}
|
||||
|
||||
|
||||
class TestAreaManagerHeadquarters:
|
||||
async def test_one_am_can_hold_several_headquarters(self, client, auth, org, db):
|
||||
hq3 = await _third_hq(db, org)
|
||||
wanted = [str(org["hq1"].id), str(org["hq2"].id), str(hq3.id)]
|
||||
resp = await client.put(
|
||||
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||
json={"headquarters_ids": wanted},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert _hq_ids(resp) == set(wanted)
|
||||
|
||||
listing = await client.get(f"{API}/area-managers", headers=auth["admin"])
|
||||
mine = {r["headquarters_id"] for r in listing.json() if r["area_manager_user_id"] == str(org["am1"].id)}
|
||||
assert mine == set(wanted)
|
||||
|
||||
async def test_taking_a_headquarters_moves_it_from_the_other_am(self, client, auth, org):
|
||||
# am2 currently manages hq2; give hq2 to am1 as well.
|
||||
await client.put(
|
||||
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||
json={"headquarters_ids": [str(org["hq1"].id), str(org["hq2"].id)]},
|
||||
)
|
||||
listing = (await client.get(f"{API}/area-managers", headers=auth["admin"])).json()
|
||||
owners = {r["headquarters_id"]: r["area_manager_user_id"] for r in listing}
|
||||
assert owners[str(org["hq2"].id)] == str(org["am1"].id) # one AM per HQ still holds
|
||||
assert len(listing) == len(owners)
|
||||
|
||||
async def test_omitted_headquarters_are_released(self, client, auth, org):
|
||||
resp = await client.put(
|
||||
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||
json={"headquarters_ids": []},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == []
|
||||
# am1 loses scope over hq1 straight away.
|
||||
hqs = await client.get(API, headers=auth["am1"])
|
||||
assert hqs.json() == []
|
||||
|
||||
async def test_am_sees_all_of_their_headquarters(self, client, auth, org):
|
||||
await client.put(
|
||||
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||
json={"headquarters_ids": [str(org["hq1"].id), str(org["hq2"].id)]},
|
||||
)
|
||||
hqs = await client.get(API, headers=auth["am1"])
|
||||
assert {h["code"] for h in hqs.json()} == {"BBSR", "SBP"}
|
||||
|
||||
async def test_setting_the_same_set_twice_is_a_no_op(self, client, auth, org):
|
||||
body = {"headquarters_ids": [str(org["hq1"].id)]}
|
||||
first = await client.put(f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"], json=body)
|
||||
second = await client.put(f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"], json=body)
|
||||
assert first.status_code == second.status_code == 200
|
||||
assert len(second.json()) == 1
|
||||
|
||||
async def test_only_an_am_can_be_assigned(self, client, auth, org):
|
||||
resp = await client.put(
|
||||
f"{API}/area-managers/{org['mr1'].id}", headers=auth["admin"],
|
||||
json={"headquarters_ids": [str(org["hq1"].id)]},
|
||||
)
|
||||
assert resp.status_code in (400, 422), resp.text
|
||||
|
||||
async def test_unknown_headquarters_is_rejected(self, client, auth, org):
|
||||
resp = await client.put(
|
||||
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||
json={"headquarters_ids": [str(uuid.uuid4())]},
|
||||
)
|
||||
assert resp.status_code == 404, resp.text
|
||||
|
||||
async def test_permissions(self, client, auth, org):
|
||||
body = {"headquarters_ids": [str(org["hq1"].id)]}
|
||||
for who in ("gm", "am1", "mr1"):
|
||||
put = await client.put(f"{API}/area-managers/{org['am1'].id}", headers=auth[who], json=body)
|
||||
assert put.status_code == 403, (who, put.text)
|
||||
# GM may read the mappings (to see who manages what), AM and MR may not.
|
||||
assert (await client.get(f"{API}/area-managers", headers=auth["gm"])).status_code == 200
|
||||
for who in ("am1", "mr1"):
|
||||
assert (await client.get(f"{API}/area-managers", headers=auth[who])).status_code == 403
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Product promoted/sample, POB, stockist visit and order: stored, returned, validated, printed."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from tests.e2e.test_full_approval_flow import _create_masters
|
||||
|
||||
API = "/api/v1"
|
||||
|
||||
|
||||
async def _draft(client, auth, org):
|
||||
doctors, chemists = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})
|
||||
assert resp.status_code == 201, resp.text
|
||||
return resp.json()["id"], doctors, chemists
|
||||
|
||||
|
||||
class TestFormFields:
|
||||
async def test_fields_round_trip_through_the_api(self, client, auth, org):
|
||||
dcr_id, doctors, chemists = await _draft(client, auth, org)
|
||||
d = await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET",
|
||||
"product_promote": " Calcium ", "product_sample": "Vit D", "remarks": "ok"},
|
||||
)
|
||||
assert d.status_code == 201, d.text
|
||||
c = await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/chemist", headers=auth["mr1"],
|
||||
json={"chemist_id": chemists[0]["id"], "visit_time": "10:00:00", "pob": "12,500"},
|
||||
)
|
||||
assert c.status_code == 201, c.text
|
||||
patched = await client.patch(
|
||||
f"{API}/dcr/{dcr_id}", headers=auth["mr1"],
|
||||
json={"stockist_visit": "Ganesh Distributors", "order_value": "45,000"},
|
||||
)
|
||||
assert patched.status_code == 200, patched.text
|
||||
|
||||
report = (await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr1"])).json()
|
||||
assert report["doctor_calls"][0]["product_promote"] == "Calcium" # trimmed
|
||||
assert report["doctor_calls"][0]["product_sample"] == "Vit D"
|
||||
assert report["chemist_calls"][0]["pob"] == "12,500"
|
||||
assert report["stockist_visit"] == "Ganesh Distributors"
|
||||
assert report["order_value"] == "45,000"
|
||||
|
||||
async def test_blank_values_are_stored_as_null_and_can_be_cleared(self, client, auth, org):
|
||||
dcr_id, _, _ = await _draft(client, auth, org)
|
||||
await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "X"})
|
||||
cleared = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": " "})
|
||||
assert cleared.json()["stockist_visit"] is None
|
||||
|
||||
async def test_patching_one_field_leaves_the_others_alone(self, client, auth, org):
|
||||
dcr_id, _, _ = await _draft(client, auth, org)
|
||||
await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"mr_remarks": "Good day", "order_value": "10"})
|
||||
again = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "S"})
|
||||
body = again.json()
|
||||
assert (body["mr_remarks"], body["order_value"], body["stockist_visit"]) == ("Good day", "10", "S")
|
||||
|
||||
async def test_too_long_values_are_rejected(self, client, auth, org):
|
||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
||||
too_long = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "x" * 201})
|
||||
assert too_long.status_code == 422
|
||||
bad_call = await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET", "product_promote": "x" * 201},
|
||||
)
|
||||
assert bad_call.status_code == 422
|
||||
|
||||
async def test_only_the_owner_can_edit_them_and_only_while_editable(self, client, auth, org):
|
||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
||||
assert (await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr2"], json={"order_value": "1"})).status_code in (403, 404)
|
||||
assert (await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["am1"], json={"order_value": "1"})).status_code == 403
|
||||
await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||
)
|
||||
assert (await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])).status_code == 200
|
||||
locked = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"order_value": "1"})
|
||||
assert locked.status_code == 409 # submitted reports are locked
|
||||
|
||||
async def test_approved_pdf_is_generated_with_the_new_layout(self, client, auth, org):
|
||||
dcr_id, doctors, chemists = await _draft(client, auth, org)
|
||||
await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET", "product_promote": "Calcium"},
|
||||
)
|
||||
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
||||
assert (await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={})).status_code == 200
|
||||
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["mr1"])
|
||||
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
|
||||
|
||||
|
||||
class TestResponsesReflectTheChange:
|
||||
"""Regression: the response to an add/remove used to list the visits as they were BEFORE it."""
|
||||
|
||||
async def test_adding_a_visit_returns_it_in_the_same_response(self, client, auth, org):
|
||||
dcr_id, doctors, chemists = await _draft(client, auth, org)
|
||||
added = await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||
)
|
||||
assert [c["doctor_id"] for c in added.json()["doctor_calls"]] == [doctors[0]["id"]]
|
||||
second = await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/chemist", headers=auth["mr1"],
|
||||
json={"chemist_id": chemists[0]["id"], "visit_time": "10:00:00"},
|
||||
)
|
||||
body = second.json()
|
||||
assert len(body["doctor_calls"]) == 1 and len(body["chemist_calls"]) == 1
|
||||
|
||||
async def test_removing_a_visit_returns_the_report_without_it(self, client, auth, org):
|
||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
||||
for i, doctor in enumerate(doctors):
|
||||
r = await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctor["id"], "visit_time": f"09:{30 + i}:00", "call_outcome": "MET"},
|
||||
)
|
||||
call_id = r.json()["doctor_calls"][0]["id"]
|
||||
removed = await client.delete(f"{API}/dcr/{dcr_id}/calls/{call_id}", headers=auth["mr1"])
|
||||
assert removed.status_code == 200, removed.text
|
||||
assert call_id not in [c["id"] for c in removed.json()["doctor_calls"]]
|
||||
assert len(removed.json()["doctor_calls"]) == len(doctors) - 1
|
||||
# ...and a fresh read agrees.
|
||||
again = (await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr1"])).json()
|
||||
assert len(again["doctor_calls"]) == len(doctors) - 1
|
||||
|
||||
|
||||
class TestDownloadUsesTheCurrentLayout:
|
||||
async def test_a_report_approved_under_an_older_layout_still_downloads_in_the_new_one(self, client, auth, org, db):
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.reports.models import DailyCallReport
|
||||
|
||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
||||
await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||
)
|
||||
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
||||
assert (await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={})).status_code == 200
|
||||
|
||||
# Simulate the file stored back when an older design was in use.
|
||||
stored = (await db.execute(select(DailyCallReport.pdf_path).where(DailyCallReport.id == dcr_id))).scalar_one()
|
||||
Path(stored).write_bytes(b"%PDF-1.4 OLD DESIGN")
|
||||
|
||||
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["mr1"])
|
||||
assert pdf.status_code == 200
|
||||
assert b"OLD DESIGN" not in pdf.content and pdf.content.startswith(b"%PDF-") and len(pdf.content) > 5000
|
||||
# ...and still only for approved reports.
|
||||
draft_id, _, _ = await _draft_second(client, auth, org)
|
||||
assert (await client.get(f"{API}/dcr/{draft_id}/pdf", headers=auth["mr1"])).status_code == 422
|
||||
|
||||
|
||||
async def _draft_second(client, auth, org):
|
||||
"""A second, unapproved report (yesterday's) for the same MR."""
|
||||
from datetime import timedelta
|
||||
|
||||
resp = await client.post(
|
||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": (date.today() - timedelta(days=1)).isoformat()}
|
||||
)
|
||||
assert resp.status_code == 201, resp.text
|
||||
return resp.json()["id"], None, None
|
||||
|
||||
|
||||
class TestApprovedPdfIsSigned:
|
||||
async def test_the_pdf_names_the_approving_area_manager_from_the_audit_trail(self, client, auth, org, db):
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.pdf.service import PDFService
|
||||
from app.reports.models import DailyCallReport
|
||||
from app.reports.repository import DCRRepository
|
||||
|
||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
||||
await client.post(
|
||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||
)
|
||||
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
||||
assert (await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={})).status_code == 200
|
||||
|
||||
report = await DCRRepository(db).get_full(
|
||||
(await db.execute(select(DailyCallReport.id).where(DailyCallReport.id == dcr_id))).scalar_one()
|
||||
)
|
||||
context = await PDFService(db)._context(report)
|
||||
assert context["approval"]["name"] == "Suresh Behera"
|
||||
assert len(context["approval"]["at"]) == 16 and context["mr_signed"] == "Ravi Das (MR001)"
|
||||
|
||||
async def test_a_report_that_is_not_approved_has_no_approval_signature(self, client, auth, org, db):
|
||||
from app.pdf.service import PDFService
|
||||
from app.reports.repository import DCRRepository
|
||||
|
||||
dcr_id, _, _ = await _draft(client, auth, org)
|
||||
report = await DCRRepository(db).get_full(dcr_id if not isinstance(dcr_id, str) else __import__("uuid").UUID(dcr_id))
|
||||
assert (await PDFService(db)._context(report))["approval"] is None
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Sending the same request twice (a double click, a slow network) never creates or changes anything twice."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from tests.e2e.test_full_approval_flow import _create_masters
|
||||
|
||||
API = "/api/v1"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def tables(db):
|
||||
await db.execute(text('DROP TABLE IF EXISTS "fare_chart"'))
|
||||
await db.execute(text(
|
||||
'CREATE TABLE "fare_chart" (id UUID PRIMARY KEY, source_row_number INTEGER, name TEXT, headquarter TEXT, '
|
||||
"serial_no TEXT, report_date TEXT, from_location TEXT, to_location TEXT, kilometers_km TEXT, owner_user_id UUID)"
|
||||
))
|
||||
await db.execute(text("DROP TABLE IF EXISTS stock_inventory"))
|
||||
await db.execute(text(
|
||||
"CREATE TABLE stock_inventory (id SERIAL PRIMARY KEY, serial_no INTEGER UNIQUE, product_name TEXT NOT NULL, "
|
||||
"pack TEXT, quantity TEXT, unit TEXT)"
|
||||
))
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def _audit_count(db, entity_id, action) -> int:
|
||||
row = await db.execute(
|
||||
text("SELECT count(*) FROM audit_log WHERE entity_id = :e AND action = :a"), {"e": entity_id, "a": action}
|
||||
)
|
||||
return row.scalar_one()
|
||||
|
||||
|
||||
class TestReports:
|
||||
async def _submitted(self, client, auth, org):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||
dcr = (await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})).json()["id"]
|
||||
await client.post(
|
||||
f"{API}/dcr/{dcr}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||
)
|
||||
return dcr, doctors
|
||||
|
||||
async def test_submitting_twice_is_one_submission(self, client, auth, org, db):
|
||||
dcr, _ = await self._submitted(client, auth, org)
|
||||
first = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||
second = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||
assert first.status_code == second.status_code == 200
|
||||
assert second.json()["status"] == "PENDING_AM"
|
||||
assert second.json()["submitted_at"] == first.json()["submitted_at"]
|
||||
assert await _audit_count(db, dcr, "SUBMIT") == 1
|
||||
|
||||
async def test_approving_twice_is_one_approval(self, client, auth, org, db):
|
||||
dcr, _ = await self._submitted(client, auth, org)
|
||||
await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||
first = await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
||||
second = await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
||||
assert first.status_code == second.status_code == 200
|
||||
assert second.json()["approved_at"] == first.json()["approved_at"]
|
||||
assert await _audit_count(db, dcr, "APPROVE") == 1
|
||||
|
||||
async def test_an_area_manager_of_another_hq_still_cannot_approve(self, client, auth, org):
|
||||
dcr, _ = await self._submitted(client, auth, org)
|
||||
await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||
await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
||||
assert (await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am2"], json={})).status_code == 403
|
||||
|
||||
async def test_adding_the_same_visit_or_creating_the_same_report_twice_is_refused(self, client, auth, org):
|
||||
dcr, doctors = await self._submitted(client, auth, org)
|
||||
again = await client.post(
|
||||
f"{API}/dcr/{dcr}/calls/doctor", headers=auth["mr1"],
|
||||
json={"doctor_id": doctors[0]["id"], "visit_time": "10:30:00", "call_outcome": "MET"},
|
||||
)
|
||||
assert again.status_code == 409
|
||||
assert (await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})).status_code == 409
|
||||
report = (await client.get(f"{API}/dcr/{dcr}", headers=auth["mr1"])).json()
|
||||
assert len(report["doctor_calls"]) == 1
|
||||
|
||||
|
||||
class TestSetup:
|
||||
async def test_the_same_doctor_headquarters_product_and_user_cannot_be_created_twice(self, client, auth, org):
|
||||
doctor = {"headquarters_id": str(org["hq1"].id), "name": "Dr Twice", "clinic_address": "1 Main Road"}
|
||||
assert (await client.post(f"{API}/doctors", headers=auth["admin"], json=doctor)).status_code == 201
|
||||
assert (await client.post(f"{API}/doctors", headers=auth["admin"], json=doctor)).status_code == 409
|
||||
|
||||
hq = {"code": "NEW1", "name": "New Place"}
|
||||
assert (await client.post(f"{API}/headquarters", headers=auth["admin"], json=hq)).status_code == 201
|
||||
assert (await client.post(f"{API}/headquarters", headers=auth["admin"], json=hq)).status_code == 409
|
||||
|
||||
product = {"name": "Twice Tonic"}
|
||||
assert (await client.post(f"{API}/products", headers=auth["admin"], json=product)).status_code == 201
|
||||
assert (await client.post(f"{API}/products", headers=auth["admin"], json=product)).status_code == 409
|
||||
|
||||
user = {"email": "dup@acmepharma.in", "password": "Str0ngPass9", "full_name": "Dup User", "employee_code": "D1", "role": "GM"}
|
||||
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
|
||||
|
||||
async def test_assigning_twice_leaves_one_assignment(self, client, auth, org):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=0)
|
||||
again = await client.post(f"{API}/doctors/{doctors[0]['id']}/assign", headers=auth["admin"], json={"mr_user_id": str(org["mr1"].id)})
|
||||
assert again.status_code == 201
|
||||
visible = await client.get(f"{API}/doctors", headers=auth["mr1"])
|
||||
assert len(visible.json()) == 1
|
||||
|
||||
async def test_area_manager_assignment_is_repeatable(self, client, auth, org):
|
||||
body = {"headquarters_ids": [str(org["hq1"].id)]}
|
||||
for _ in range(2):
|
||||
resp = await client.put(f"{API}/headquarters/area-managers/{org['am1'].id}", headers=auth["admin"], json=body)
|
||||
assert resp.status_code == 200 and len(resp.json()) == 1
|
||||
|
||||
async def test_the_stock_list_keeps_each_product_once(self, client, auth, tables):
|
||||
item = {"product_name": "ZINCOVIT-X", "pack": "10X10 TAB"}
|
||||
assert (await client.post(f"{API}/products/stock-inventory", headers=auth["admin"], json=item)).status_code == 201
|
||||
for spelling in ("ZINCOVIT-X", " zincovit-x "):
|
||||
dup = await client.post(f"{API}/products/stock-inventory", headers=auth["admin"], json={"product_name": spelling})
|
||||
assert dup.status_code == 409, spelling
|
||||
other = (await client.post(f"{API}/products/stock-inventory", headers=auth["admin"], json={"product_name": "OTHER-Y"})).json()
|
||||
clash = await client.patch(f"{API}/products/stock-inventory/{other['id']}", headers=auth["admin"], json={"product_name": "zincovit-x"})
|
||||
assert clash.status_code == 409
|
||||
keep = await client.patch(f"{API}/products/stock-inventory/{other['id']}", headers=auth["admin"], json={"product_name": "OTHER-Y", "pack": "new"})
|
||||
assert keep.status_code == 200 # saving a product under its own name is fine
|
||||
|
||||
|
||||
class TestCompanyForms:
|
||||
async def test_an_identical_row_is_a_repeat_but_a_different_one_is_not(self, client, auth, tables):
|
||||
row = {"report_date": "2026-09-21", "from_location": "Bhubaneswar", "to_location": "Puri", "kilometers_km": "69"}
|
||||
assert (await client.post(f"{API}/csv-data/fare_chart/rows", headers=auth["mr1"], json=row)).status_code == 201
|
||||
repeat = await client.post(f"{API}/csv-data/fare_chart/rows", headers=auth["mr1"], json=row)
|
||||
assert repeat.status_code == 409, repeat.text
|
||||
other = {**row, "to_location": "Cuttack", "kilometers_km": "39"}
|
||||
assert (await client.post(f"{API}/csv-data/fare_chart/rows", headers=auth["mr1"], json=other)).status_code == 201
|
||||
rows = (await client.get(f"{API}/csv-data/fare_chart/rows", headers=auth["mr1"])).json()
|
||||
assert len(rows) == 2
|
||||
|
||||
async def test_repeated_send_and_approve_are_absorbed(self, client, auth, org, tables):
|
||||
await client.post(f"{API}/csv-data/fare_chart/rows", headers=auth["mr1"], json={"from_location": "A", "to_location": "B"})
|
||||
statuses = [
|
||||
(await client.post(f"{API}/csv-data/fare_chart/approval/request", headers=auth["mr1"])).json()["status"] for _ in range(3)
|
||||
]
|
||||
assert statuses == ["pending"] * 3
|
||||
approved = [
|
||||
(await client.post(f"{API}/csv-data/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])).json()["status"] for _ in range(3)
|
||||
]
|
||||
assert approved == ["approved"] * 3
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Company-form approvals live on the server, so everyone sees the same state at once."""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.csv_data.router import _signature
|
||||
|
||||
API = "/api/v1/csv-data"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def fare_chart(db):
|
||||
await db.execute(text('DROP TABLE IF EXISTS "fare_chart"'))
|
||||
await db.execute(text(
|
||||
'CREATE TABLE "fare_chart" (id UUID PRIMARY KEY, source_row_number INTEGER, name TEXT, headquarter TEXT, '
|
||||
"serial_no TEXT, report_date TEXT, from_location TEXT, to_location TEXT, kilometers_km TEXT, owner_user_id UUID)"
|
||||
))
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def _add_row(client, auth) -> str:
|
||||
resp = await client.post(f"{API}/fare_chart/rows", headers=auth["mr1"], json={"from_location": "A", "to_location": "B"})
|
||||
assert resp.status_code == 201, resp.text
|
||||
return resp.json()["id"]
|
||||
|
||||
|
||||
def _by_table(resp):
|
||||
return {a["table_name"]: a for a in resp.json()}
|
||||
|
||||
|
||||
class TestFormApproval:
|
||||
async def test_every_approval_form_starts_as_draft_for_everyone(self, client, auth):
|
||||
# An MR sees all three forms as drafts; an Area Manager or admin has nothing to act on yet.
|
||||
forms = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))
|
||||
assert set(forms) == {"tour_plan", "standard_tour_plan", "fare_chart"}
|
||||
assert {f["status"] for f in forms.values()} == {"draft"}
|
||||
for who in ("am1", "admin"):
|
||||
resp = await client.get(f"{API}/approvals", headers=auth[who])
|
||||
assert resp.status_code == 200 and resp.json() == [], (who, resp.text)
|
||||
|
||||
async def test_mr_requests_and_am_approves_and_both_see_it_immediately(self, client, auth, org, fare_chart):
|
||||
await _add_row(client, auth)
|
||||
sent = await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
assert sent.status_code == 200 and sent.json()["status"] == "pending"
|
||||
assert _by_table(await client.get(f"{API}/approvals", headers=auth["am1"]))["fare_chart"]["status"] == "pending"
|
||||
|
||||
done = await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])
|
||||
assert done.status_code == 200, done.text
|
||||
assert done.json()["status"] == "approved" and done.json()["approved_by_name"] == "Suresh Behera"
|
||||
# The MR's very next read shows the AM's approval — no shared browser needed.
|
||||
seen = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]
|
||||
assert (seen["status"], seen["approved_by_name"]) == ("approved", "Suresh Behera")
|
||||
|
||||
async def test_an_empty_form_cannot_be_sent_for_approval(self, client, auth, fare_chart):
|
||||
resp = await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
assert resp.status_code == 422, resp.text
|
||||
assert _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]["status"] == "draft"
|
||||
|
||||
async def test_nothing_can_be_approved_until_it_has_been_sent(self, client, auth, org, fare_chart):
|
||||
await _add_row(client, auth)
|
||||
early = await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])
|
||||
assert early.status_code == 409, early.text
|
||||
assert _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]["status"] == "draft"
|
||||
assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # a draft is nothing for the AM to act on
|
||||
|
||||
async def test_double_clicks_are_harmless(self, client, auth, org, fare_chart):
|
||||
await _add_row(client, auth)
|
||||
for _ in range(2):
|
||||
assert (await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])).json()["status"] == "pending"
|
||||
for _ in range(2):
|
||||
assert (await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])).json()["status"] == "approved"
|
||||
# Once approved, sending again is refused until something changes.
|
||||
assert (await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])).status_code == 409
|
||||
|
||||
async def test_only_the_right_role_can_act(self, client, auth, org):
|
||||
for who in ("am1", "admin", "gm"):
|
||||
assert (await client.post(f"{API}/fare_chart/approval/request", headers=auth[who])).status_code == 403, who
|
||||
for who in ("mr1", "admin", "gm"):
|
||||
assert (await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth[who])).status_code == 403, who
|
||||
|
||||
async def test_forms_without_an_approval_step_are_not_found(self, client, auth, org):
|
||||
for table in ("weekly_report", "nonsense"):
|
||||
assert (await client.post(f"{API}/{table}/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])).status_code == 404
|
||||
|
||||
async def test_changing_the_rows_withdraws_a_pending_or_approved_form(self, client, auth, org, fare_chart):
|
||||
row_id = await _add_row(client, auth)
|
||||
for change in (
|
||||
lambda: client.patch(f"{API}/fare_chart/rows/{row_id}", headers=auth["mr1"], json={"to_location": "C"}),
|
||||
lambda: client.post(f"{API}/fare_chart/rows", headers=auth["mr1"], json={"from_location": "X", "to_location": "Y"}),
|
||||
):
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])
|
||||
assert (await change()).status_code in (200, 201)
|
||||
state = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]
|
||||
assert state["status"] == "draft" and state["approved_by_name"] is None
|
||||
# A pending (not yet approved) form is withdrawn too, so the AM never signs stale data.
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["mr1"])).status_code == 204
|
||||
assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # withdrawn: nothing left for the AM
|
||||
|
||||
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.
|
||||
mr = org["mr1"].id
|
||||
assert await _signature("fare_chart", mr, db) == ("pending", None, None)
|
||||
spoof = await client.get(f"{API}/fare_chart/pdf?approval_status=approved&am_name=Somebody", headers=auth["mr1"])
|
||||
assert spoof.status_code == 200
|
||||
await _add_row(client, auth)
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
await client.post(f"{API}/fare_chart/approval/approve?owner_id={org['mr1'].id}", headers=auth["am1"])
|
||||
await db.rollback() # see the other session's commit
|
||||
status, name, when = await _signature("fare_chart", mr, db)
|
||||
assert (status, name) == ("approved", "Suresh Behera")
|
||||
assert when and len(when) == 16 and when[2] == "/" and when[13] == ":" # dd/mm/yyyy HH:MM
|
||||
assert await _signature("weekly_report", mr, db) == (None, None, None)
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Company forms belong to one MR; only that MR's own Area Manager receives and signs the request."""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.csv_data.config import TABLES
|
||||
from app.csv_data.router import _load_rows
|
||||
|
||||
API = "/api/v1/csv-data"
|
||||
|
||||
|
||||
async def _make_table(db, name: str, owned: bool) -> None:
|
||||
columns = "".join(f", {c} TEXT" for c in TABLES[name])
|
||||
owner = ", owner_user_id UUID" if owned else ""
|
||||
await db.execute(text(f'DROP TABLE IF EXISTS "{name}"'))
|
||||
await db.execute(text(f'CREATE TABLE "{name}" (id UUID PRIMARY KEY, source_row_number INTEGER{owner}{columns})'))
|
||||
await db.commit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def forms(db):
|
||||
for name in ("fare_chart", "tour_plan", "standard_tour_plan"):
|
||||
await _make_table(db, name, owned=True)
|
||||
|
||||
|
||||
async def _add(client, headers, place="A", **query) -> str:
|
||||
resp = await client.post(f"{API}/fare_chart/rows", headers=headers, json={"from_location": place, "to_location": "Z"}, params=query)
|
||||
assert resp.status_code == 201, resp.text
|
||||
return resp.json()["id"]
|
||||
|
||||
|
||||
async def _approvals(client, headers):
|
||||
resp = await client.get(f"{API}/approvals", headers=headers)
|
||||
assert resp.status_code == 200, resp.text
|
||||
return resp.json()
|
||||
|
||||
|
||||
class TestRowsBelongToTheirMR:
|
||||
async def test_each_mr_sees_only_their_own_rows_numbered_from_one(self, client, auth, forms):
|
||||
await _add(client, auth["mr1"], "A")
|
||||
await _add(client, auth["mr1"], "B")
|
||||
await _add(client, auth["mr2"], "C")
|
||||
mine = (await client.get(f"{API}/fare_chart/rows", headers=auth["mr1"])).json()
|
||||
theirs = (await client.get(f"{API}/fare_chart/rows", headers=auth["mr2"])).json()
|
||||
assert [r["from_location"] for r in mine] == ["A", "B"] and [r["serial_no"] for r in mine] == ["1", "2"]
|
||||
assert [r["from_location"] for r in theirs] == ["C"] and [r["serial_no"] for r in theirs] == ["1"]
|
||||
|
||||
async def test_an_mr_cannot_change_or_remove_another_mrs_row(self, client, auth, forms):
|
||||
row = await _add(client, auth["mr1"])
|
||||
assert (await client.patch(f"{API}/fare_chart/rows/{row}", headers=auth["mr2"], json={"to_location": "Q"})).status_code == 403
|
||||
assert (await client.delete(f"{API}/fare_chart/rows/{row}", headers=auth["mr2"])).status_code == 403
|
||||
assert (await client.get(f"{API}/fare_chart/rows/{row}/pdf", headers=auth["mr2"])).status_code == 403
|
||||
assert (await client.get(f"{API}/fare_chart/rows", headers=auth["mr2"])).json() == []
|
||||
|
||||
async def test_an_area_manager_sees_only_the_mrs_of_their_headquarters(self, client, auth, org, forms):
|
||||
await _add(client, auth["mr1"], "A")
|
||||
await _add(client, auth["mr2"], "C")
|
||||
assert [r["from_location"] for r in (await client.get(f"{API}/fare_chart/rows", headers=auth["am1"])).json()] == ["A"]
|
||||
assert [r["from_location"] for r in (await client.get(f"{API}/fare_chart/rows", headers=auth["am2"])).json()] == ["C"]
|
||||
other = await client.get(f"{API}/fare_chart/rows", headers=auth["am2"], params={"owner_id": str(org["mr1"].id)})
|
||||
assert other.status_code == 403
|
||||
assert (await client.get(f"{API}/fare_chart/pdf", headers=auth["am2"], params={"owner_id": str(org["mr1"].id)})).status_code == 403
|
||||
|
||||
async def test_the_admin_needs_to_say_which_mr_a_new_row_is_for(self, client, auth, org, forms):
|
||||
assert (await client.post(f"{API}/fare_chart/rows", headers=auth["admin"], json={"from_location": "A"})).status_code == 422
|
||||
made = await client.post(f"{API}/fare_chart/rows", headers=auth["admin"], json={"from_location": "A"}, params={"owner_id": str(org["mr2"].id)})
|
||||
assert made.status_code == 201 and made.json()["name"] == "Priya Nayak"
|
||||
assert len((await client.get(f"{API}/fare_chart/rows", headers=auth["mr2"])).json()) == 1
|
||||
assert (await client.get(f"{API}/fare_chart/rows", headers=auth["mr1"])).json() == []
|
||||
|
||||
|
||||
class TestOnlyTheAssignedAreaManagerGetsTheRequest:
|
||||
async def test_the_request_reaches_only_the_mrs_own_area_manager(self, client, auth, org, forms):
|
||||
await _add(client, auth["mr1"])
|
||||
assert (await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])).json()["status"] == "pending"
|
||||
mine = await _approvals(client, auth["am1"])
|
||||
assert [(a["table_name"], a["owner_name"], a["status"]) for a in mine] == [("fare_chart", "Ravi Das", "pending")]
|
||||
assert await _approvals(client, auth["am2"]) == [] # the other headquarters' manager never sees it
|
||||
assert [a["status"] for a in await _approvals(client, auth["mr2"]) if a["table_name"] == "fare_chart"] == ["draft"]
|
||||
|
||||
async def test_another_area_manager_cannot_approve_it(self, client, auth, org, forms):
|
||||
await _add(client, auth["mr1"])
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
wrong = await client.post(f"{API}/fare_chart/approval/approve", headers=auth["am2"], params={"owner_id": str(org["mr1"].id)})
|
||||
assert wrong.status_code == 403, wrong.text
|
||||
assert [a["status"] for a in await _approvals(client, auth["am1"])] == ["pending"]
|
||||
right = await client.post(f"{API}/fare_chart/approval/approve", headers=auth["am1"], params={"owner_id": str(org["mr1"].id)})
|
||||
assert right.status_code == 200 and right.json()["approved_by_name"] == "Suresh Behera"
|
||||
|
||||
async def test_one_mrs_approval_does_not_approve_another_mrs_form(self, client, auth, org, forms):
|
||||
await _add(client, auth["mr1"])
|
||||
await _add(client, auth["mr2"])
|
||||
for who in ("mr1", "mr2"):
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth[who])
|
||||
await client.post(f"{API}/fare_chart/approval/approve", headers=auth["am1"], params={"owner_id": str(org["mr1"].id)})
|
||||
status = {a["owner_name"]: a["status"] for a in await _approvals(client, auth["admin"])}
|
||||
assert status == {"Ravi Das": "approved", "Priya Nayak": "pending"}
|
||||
|
||||
async def test_editing_one_mrs_rows_only_withdraws_that_mrs_approval(self, client, auth, org, forms):
|
||||
row1 = await _add(client, auth["mr1"])
|
||||
await _add(client, auth["mr2"])
|
||||
for who in ("mr1", "mr2"):
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth[who])
|
||||
assert (await client.patch(f"{API}/fare_chart/rows/{row1}", headers=auth["mr1"], json={"to_location": "Q"})).status_code == 200
|
||||
status = {a["owner_name"]: a["status"] for a in await _approvals(client, auth["admin"]) if a["status"] != "draft"}
|
||||
assert status == {"Priya Nayak": "pending"}
|
||||
|
||||
async def test_a_form_cannot_be_sent_when_no_area_manager_is_assigned(self, client, auth, org, db, forms):
|
||||
await _add(client, auth["mr1"])
|
||||
await db.execute(text("UPDATE am_headquarters SET effective_to = current_date WHERE headquarters_id = :h"), {"h": org["hq1"].id})
|
||||
await db.commit()
|
||||
resp = await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
assert resp.status_code == 422 and "Area Manager" in resp.text
|
||||
|
||||
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
|
||||
|
||||
await _add(client, auth["mr1"])
|
||||
await _add(client, auth["mr2"])
|
||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||
await client.post(f"{API}/fare_chart/approval/approve", headers=auth["am1"], params={"owner_id": str(org["mr1"].id)})
|
||||
await db.rollback() # see the other session's commit
|
||||
assert (await _signature("fare_chart", org["mr1"].id, db))[:2] == ("approved", "Suresh Behera")
|
||||
assert (await _signature("fare_chart", org["mr2"].id, db)) == ("pending", None, None)
|
||||
assert (await _signature("fare_chart", None, db)) == ("pending", None, None) # several MRs at once: unsigned
|
||||
|
||||
|
||||
class TestMonthlyDownload:
|
||||
@pytest.fixture
|
||||
async def weekly(self, db):
|
||||
await _make_table(db, "weekly_report", owned=False)
|
||||
for i, month in enumerate(["November", "December", "november", None]):
|
||||
await db.execute(
|
||||
text('INSERT INTO "weekly_report" (id, source_row_number, employee_name, month) VALUES (gen_random_uuid(), :n, :name, :m)'),
|
||||
{"n": i + 1, "name": f"row{i}", "m": month},
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
async def test_only_the_chosen_month_is_returned_ignoring_case_and_spaces(self, db, org, weekly):
|
||||
november = await _load_rows("weekly_report", db, org["admin"], month=" NOVEMBER ")
|
||||
assert len(november) == 2
|
||||
assert len(await _load_rows("weekly_report", db, org["admin"])) == 4 # no month chosen = the whole form
|
||||
|
||||
async def test_downloading_a_month_gives_a_pdf_and_a_month_without_rows_is_refused(self, client, auth, weekly):
|
||||
ok = await client.get(f"{API}/weekly_report/pdf", headers=auth["mr1"], params={"month": "December"})
|
||||
assert ok.status_code == 200 and ok.headers["content-type"].startswith("application/pdf")
|
||||
assert "weekly_report-december.pdf" in ok.headers["content-disposition"]
|
||||
none = await client.get(f"{API}/weekly_report/pdf", headers=auth["mr1"], params={"month": "March"})
|
||||
assert none.status_code == 404 and "March" in none.text
|
||||
|
||||
async def test_a_form_without_a_month_rejects_the_filter(self, client, auth, forms):
|
||||
resp = await client.get(f"{API}/fare_chart/pdf", headers=auth["mr1"], params={"month": "November"})
|
||||
assert resp.status_code == 422
|
||||
@@ -0,0 +1,598 @@
|
||||
"""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_cannot_create_a_doctor(self, client, auth, org):
|
||||
"""A3/Q3 — not permitted in the MVP."""
|
||||
resp = await client.post(
|
||||
f"{API}/doctors",
|
||||
headers=auth["mr1"],
|
||||
json={
|
||||
"headquarters_id": str(org["hq1"].id),
|
||||
"name": "Dr Selfmade",
|
||||
"clinic_address": "Nowhere",
|
||||
},
|
||||
)
|
||||
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):
|
||||
doctors, chemists = await _create_masters(client, auth, org)
|
||||
today = date.today().isoformat()
|
||||
|
||||
# --- 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):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||
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):
|
||||
dcr_id = await self._submitted_report(client, auth, org)
|
||||
|
||||
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):
|
||||
dcr_id = await self._submitted_report(client, auth, org)
|
||||
|
||||
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):
|
||||
"""SEC-2 — the single most important governance rule in the design."""
|
||||
dcr_id = await self._submitted_report(client, auth, org)
|
||||
|
||||
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):
|
||||
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):
|
||||
"""A doctor from another HQ, not assigned to this MR."""
|
||||
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):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=5, n_chemists=1)
|
||||
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):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||
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):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||
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):
|
||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||
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"] == 0
|
||||
@@ -0,0 +1,78 @@
|
||||
"""An Administrator can change any user's sign-in credentials; nobody else can."""
|
||||
|
||||
from tests.conftest import DEFAULT_PASSWORD
|
||||
|
||||
API = "/api/v1"
|
||||
NEW_PASSWORD = "Brand-New-Pass-42"
|
||||
|
||||
|
||||
async def _login(client, email, password):
|
||||
return await client.post(f"{API}/auth/login", json={"email": email, "password": password})
|
||||
|
||||
|
||||
class TestAdminChangesCredentials:
|
||||
async def test_password_reset_replaces_the_old_password(self, client, auth, org):
|
||||
resp = await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"password": NEW_PASSWORD})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert "password" not in resp.json() and "password_hash" not in resp.json()
|
||||
assert (await _login(client, org["mr1"].email, DEFAULT_PASSWORD)).status_code == 401
|
||||
assert (await _login(client, org["mr1"].email, NEW_PASSWORD)).status_code == 200
|
||||
|
||||
async def test_password_reset_signs_the_user_out_everywhere(self, client, org, auth):
|
||||
first = await _login(client, org["mr1"].email, DEFAULT_PASSWORD)
|
||||
old_refresh = first.json()["refresh_token"]
|
||||
await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"password": NEW_PASSWORD})
|
||||
again = await client.post(f"{API}/auth/refresh", json={"refresh_token": old_refresh})
|
||||
assert again.status_code == 401
|
||||
|
||||
async def test_password_reset_unlocks_a_locked_account(self, client, auth, org, db):
|
||||
org["mr1"].failed_login_attempts = 99
|
||||
await db.commit()
|
||||
assert (await _login(client, org["mr1"].email, DEFAULT_PASSWORD)).status_code == 401
|
||||
await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"password": NEW_PASSWORD})
|
||||
assert (await _login(client, org["mr1"].email, NEW_PASSWORD)).status_code == 200
|
||||
|
||||
async def test_email_change_moves_the_login(self, client, auth, org):
|
||||
resp = await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"email": "Ravi.New@Acmepharma.in"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["email"] == "ravi.new@acmepharma.in" # stored lower-case, as at creation
|
||||
assert (await _login(client, org["mr1"].email, DEFAULT_PASSWORD)).status_code == 401
|
||||
assert (await _login(client, "ravi.new@acmepharma.in", DEFAULT_PASSWORD)).status_code == 200
|
||||
|
||||
async def test_employee_code_and_phone_can_change(self, client, auth, org):
|
||||
resp = await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"employee_code": "MR777", "phone": "9000000001"})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["employee_code"] == "MR777"
|
||||
|
||||
async def test_duplicate_email_or_code_is_a_clean_409(self, client, auth, org):
|
||||
dup_email = await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"email": org["mr2"].email})
|
||||
assert dup_email.status_code == 409, dup_email.text
|
||||
dup_code = await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"employee_code": org["mr2"].employee_code})
|
||||
assert dup_code.status_code == 409, dup_code.text
|
||||
# ...and the user is untouched afterwards.
|
||||
assert (await _login(client, org["mr1"].email, DEFAULT_PASSWORD)).status_code == 200
|
||||
|
||||
async def test_weak_password_and_bad_email_are_rejected(self, client, auth, org):
|
||||
assert (await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"password": "short"})).status_code == 422
|
||||
assert (await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"email": "not-an-email"})).status_code == 422
|
||||
|
||||
async def test_only_the_admin_can_change_credentials(self, client, auth, org):
|
||||
for who in ("gm", "am1", "mr1", "mr2"):
|
||||
resp = await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth[who], json={"password": NEW_PASSWORD})
|
||||
assert resp.status_code == 403, (who, resp.text)
|
||||
|
||||
async def test_the_password_never_reaches_the_audit_log(self, client, auth, org, db):
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.audit.models import AuditLog
|
||||
|
||||
await client.patch(f"{API}/users/{org['mr1'].id}", headers=auth["admin"], json={"password": NEW_PASSWORD})
|
||||
rows = (await db.execute(select(AuditLog).where(AuditLog.entity_id == org["mr1"].id))).scalars().all()
|
||||
blob = " ".join(f"{r.before_data} {r.after_data}" for r in rows)
|
||||
assert NEW_PASSWORD not in blob and "password_hash" not in blob
|
||||
assert any(r.after_data and r.after_data.get("password_reset") for r in rows)
|
||||
|
||||
async def test_admin_can_reset_their_own_password(self, client, auth, org):
|
||||
resp = await client.patch(f"{API}/users/{org['admin'].id}", headers=auth["admin"], json={"password": NEW_PASSWORD})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert (await _login(client, org["admin"].email, NEW_PASSWORD)).status_code == 200
|
||||
Reference in New Issue
Block a user