This commit is contained in:
Shubhankar45
2026-10-27 12:03:31 +00:00
parent 2ed3945b5d
commit 4e5e95775d
104 changed files with 5210 additions and 606 deletions
+29
View File
@@ -37,6 +37,7 @@ from app.users.models import User # noqa: E402
TABLES = [
"audit_log",
"product",
"missed_visit",
"doctor_call",
"chemist_call",
"daily_call_report",
@@ -169,6 +170,34 @@ async def org(db: AsyncSession) -> dict:
}
@pytest.fixture
async def approved_plan(db: AsyncSession, org: dict):
"""An empty day plan, already approved, so an end-of-day report may be filed.
For tests about end-of-day rules where the plan is incidental; the plan flow itself
is exercised through the API in tests/e2e/test_day_plan.py.
"""
from app.common.enums import DCRStatus, ReportType
from app.common.utils import utcnow
from app.reports.models import DailyCallReport
async def make(day: date | None = None, mr: str = "mr1") -> DailyCallReport:
plan = DailyCallReport(
id=uuid.uuid4(),
mr_user_id=org[mr].id,
headquarters_id=org[mr].headquarters_id,
report_date=day or date.today(),
report_type=ReportType.PLAN,
status=DCRStatus.APPROVED,
approved_at=utcnow(),
)
db.add(plan)
await db.commit()
return plan
return make
async def login(client: AsyncClient, user: User) -> dict[str, str]:
resp = await client.post(
"/api/v1/auth/login",
+16 -6
View File
@@ -38,16 +38,26 @@ class TestAreaManagerHeadquarters:
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.
async def test_a_headquarters_can_have_several_area_managers(self, client, auth, org):
# am2 manages hq2; give hq2 to am1 as well — am2 keeps it.
resp = await client.put(
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
json={"headquarters_ids": [str(org["hq1"].id), str(org["hq2"].id)]},
)
assert resp.status_code == 200, resp.text
listing = (await client.get(f"{API}/area-managers", headers=auth["admin"])).json()
managers = {r["area_manager_user_id"] for r in listing if r["headquarters_id"] == str(org["hq2"].id)}
assert managers == {str(org["am1"].id), str(org["am2"].id)}
# Both see it, so either may review its MRs' reports and forms.
for am in ("am1", "am2"):
assert str(org["hq2"].id) in {h["id"] for h in (await client.get(API, headers=auth[am])).json()}
# Saving the same set again adds nothing twice.
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)
again = (await client.get(f"{API}/area-managers", headers=auth["admin"])).json()
assert len(again) == len(listing)
async def test_omitted_headquarters_are_released(self, client, auth, org):
resp = await client.put(
+24
View File
@@ -0,0 +1,24 @@
"""The dashboard's headquarters filter narrows a manager's reports and counts, never widens them."""
API = "/api/v1"
class TestHeadquartersFilter:
async def test_reports_and_counts_narrow_to_the_chosen_headquarters(self, client, auth, org, approved_plan):
await approved_plan(mr="mr1") # hq1
await approved_plan(mr="mr2") # hq2
hq1, hq2 = str(org["hq1"].id), str(org["hq2"].id)
everything = (await client.get(f"{API}/dcr", headers=auth["gm"])).json()
assert len(everything) == 2
only_hq1 = (await client.get(f"{API}/dcr", headers=auth["gm"], params={"headquarters_id": hq1})).json()
assert [r["mr_name"] for r in only_hq1] == ["Ravi Das"]
counts = (await client.get(f"{API}/dcr/counts", headers=auth["admin"], params={"headquarters_id": hq2})).json()
assert counts["APPROVED"] == 1
async def test_a_headquarters_outside_the_users_scope_gives_nothing(self, client, auth, org, approved_plan):
await approved_plan(mr="mr2") # hq2, not am1's
outside = await client.get(f"{API}/dcr", headers=auth["am1"], params={"headquarters_id": str(org["hq2"].id)})
assert outside.status_code == 200 and outside.json() == []
counts = (await client.get(f"{API}/dcr/counts", headers=auth["am1"], params={"headquarters_id": str(org["hq2"].id)})).json()
assert counts["APPROVED"] == 0
+244
View File
@@ -0,0 +1,244 @@
"""Morning day plan → Area Manager approval → end-of-day report against it (rules P1-P5)."""
from datetime import date
from tests.e2e.test_full_approval_flow import _create_masters
API = "/api/v1"
TODAY = date.today().isoformat()
async def _plan(client, auth, doctors, chemists, *, approve=True):
"""A plan for today with the given doctors/chemists, submitted (and by default approved)."""
resp = await client.post(
f"{API}/dcr", headers=auth["mr1"],
json={
"report_date": TODAY, "report_type": "PLAN",
"doctor_calls": [{"doctor_id": d["id"], "visit_time": "23:00:00"} for d in doctors],
"chemist_calls": [{"chemist_id": c["id"], "visit_time": "23:30:00"} for c in chemists],
},
)
assert resp.status_code == 201, resp.text
plan_id = resp.json()["id"]
assert (await client.post(f"{API}/dcr/{plan_id}/submit", headers=auth["mr1"])).status_code == 200
if approve:
approved = await client.post(f"{API}/dcr/{plan_id}/approve", headers=auth["am1"], json={})
assert approved.status_code == 200, approved.text
return plan_id
async def _actual(client, auth):
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
assert resp.status_code == 201, resp.text
return resp.json()
async def _visit_doctor(client, auth, dcr_id, doctor):
return await client.post(
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
json={"doctor_id": doctor["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
)
class TestDayPlan:
async def test_a_plan_has_planned_times_and_no_outcomes(self, 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": TODAY, "report_type": "PLAN"})
assert resp.status_code == 201, resp.text
plan = resp.json()
assert plan["report_type"] == "PLAN" and plan["plan_id"] is None
# P1 — a planned time later than now is fine, and an outcome is not stored.
added = await client.post(
f"{API}/dcr/{plan['id']}/calls/doctor", headers=auth["mr1"],
json={"doctor_id": doctors[0]["id"], "visit_time": "23:59:00", "call_outcome": "MET"},
)
assert added.status_code == 201, added.text
assert added.json()["doctor_calls"][0]["call_outcome"] is None
async def test_an_empty_plan_cannot_be_submitted(self, client, auth, org):
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "PLAN"})
submit = await client.post(f"{API}/dcr/{resp.json()['id']}/submit", headers=auth["mr1"])
assert submit.status_code == 422
assert "at least one" in submit.json()["error"]["message"]
async def test_one_plan_and_one_end_of_day_report_per_day(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await _plan(client, auth, doctors[:1], [])
again = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "PLAN"})
assert again.status_code == 409
await _actual(client, auth)
twice = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
assert twice.status_code == 409
async def test_the_area_manager_can_return_a_plan(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
plan_id = await _plan(client, auth, doctors, [], approve=False)
resp = await client.post(
f"{API}/dcr/{plan_id}/return", headers=auth["am1"], json={"reason": "Add the chemists on MG Road."}
)
assert resp.status_code == 200 and resp.json()["status"] == "RETURNED"
async def test_reports_can_be_listed_by_type(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
plan_id = await _plan(client, auth, doctors, [])
actual = await _actual(client, auth)
plans = (await client.get(f"{API}/dcr?type=PLAN", headers=auth["mr1"])).json()
actuals = (await client.get(f"{API}/dcr?type=ACTUAL", headers=auth["mr1"])).json()
assert [r["id"] for r in plans] == [plan_id]
assert [r["id"] for r in actuals] == [actual["id"]]
class TestEndOfDayNeedsAnApprovedPlan:
async def test_without_a_plan_it_is_refused(self, client, auth, org):
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
assert resp.status_code == 422
assert "Daily Call Report (Plan)" in resp.json()["error"]["message"]
async def test_while_the_plan_awaits_approval_it_is_refused(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await _plan(client, auth, doctors, [], approve=False)
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
assert resp.status_code == 422
assert "approved by the Area Manager" in resp.json()["error"]["message"]
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)
plan_id = await _plan(client, auth, doctors, [])
actual = await _actual(client, auth)
assert actual["plan_id"] == plan_id
plan = (await client.get(f"{API}/dcr/{plan_id}", headers=auth["mr1"])).json()
assert plan["actual_report_id"] == actual["id"]
class TestPlanVersusActual:
async def test_every_planned_visit_must_be_made_or_explained(self, client, auth, org):
doctors, chemists = await _create_masters(client, auth, org, n_doctors=3, n_chemists=1)
await _plan(client, auth, doctors[:2], chemists)
dcr = await _actual(client, auth)
assert {p["status"] for p in dcr["planned_visits"]} == {"PENDING"}
assert len(dcr["planned_visits"]) == 3
# P5 — an unplanned visit is allowed; it is not on the checklist.
assert (await _visit_doctor(client, auth, dcr["id"], doctors[2])).status_code == 201
body = (await _visit_doctor(client, auth, dcr["id"], doctors[0])).json()
by_name = {p["name"]: p["status"] for p in body["planned_visits"]}
assert by_name[doctors[0]["name"]] == "VISITED"
# P3 — the doctor and chemist still pending block the submit, by name.
blocked = await client.post(f"{API}/dcr/{dcr['id']}/submit", headers=auth["mr1"])
assert blocked.status_code == 422
assert set(blocked.json()["error"]["details"]["pending"]) == {doctors[1]["name"], chemists[0]["name"]}
await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr1"],
json={"doctor_id": doctors[1]["id"], "reason": "Clinic closed for the day"})
explained = await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr1"],
json={"chemist_id": chemists[0]["id"], "reason": "Shop shut"})
assert explained.status_code == 200, explained.text
missed = [p for p in explained.json()["planned_visits"] if p["status"] == "MISSED"]
assert {p["missed_reason"] for p in missed} == {"Clinic closed for the day", "Shop shut"}
submit = await client.post(f"{API}/dcr/{dcr['id']}/submit", headers=auth["mr1"])
assert submit.status_code == 200, submit.text
approve = await client.post(f"{API}/dcr/{dcr['id']}/approve", headers=auth["am1"], json={})
assert approve.status_code == 200, approve.text
pdf = await client.get(f"{API}/dcr/{dcr['id']}/pdf", headers=auth["mr1"])
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
async def test_recording_the_visit_later_replaces_the_missed_note(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await _plan(client, auth, doctors, [])
dcr = await _actual(client, auth)
await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr1"],
json={"doctor_id": doctors[0]["id"], "reason": "Doctor on leave"})
body = (await _visit_doctor(client, auth, dcr["id"], doctors[0])).json()
assert body["planned_visits"][0]["status"] == "VISITED"
assert body["planned_visits"][0]["missed_reason"] is None
# ...and removing the visit brings the line back to pending, not to the old note.
call_id = body["doctor_calls"][0]["id"]
removed = (await client.delete(f"{API}/dcr/{dcr['id']}/calls/{call_id}", headers=auth["mr1"])).json()
assert removed["planned_visits"][0]["status"] == "PENDING"
async def test_missed_notes_are_validated(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
plan_id = await _plan(client, auth, doctors[:1], [])
dcr = await _actual(client, auth)
url = f"{API}/dcr/{dcr['id']}/missed"
# Not on the plan.
off_plan = await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[1]["id"], "reason": "Busy day"})
assert off_plan.status_code == 422
# Exactly one target, and a real reason.
assert (await client.put(url, headers=auth["mr1"], json={"reason": "Busy day"})).status_code == 422
assert (await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": " "})).status_code == 422
# Already visited.
await _visit_doctor(client, auth, dcr["id"], doctors[0])
visited = await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": "Busy day"})
assert visited.status_code == 409
# Not on a plan at all.
plan_note = await client.put(f"{API}/dcr/{plan_id}/missed", headers=auth["mr1"],
json={"doctor_id": doctors[0]["id"], "reason": "Busy day"})
assert plan_note.status_code in (409, 422)
async def test_a_note_can_be_reworded_and_cleared(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await _plan(client, auth, doctors, [])
dcr = await _actual(client, auth)
url = f"{API}/dcr/{dcr['id']}/missed"
await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": "Doctor on leave"})
body = (await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": "On leave till Monday"})).json()
line = body["planned_visits"][0]
assert line["missed_reason"] == "On leave till Monday"
cleared = await client.delete(f"{url}/{line['missed_visit_id']}", headers=auth["mr1"])
assert cleared.status_code == 200 and cleared.json()["planned_visits"][0]["status"] == "PENDING"
async def test_an_end_of_day_visit_needs_an_outcome(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await _plan(client, auth, doctors, [])
dcr = await _actual(client, auth)
resp = await client.post(
f"{API}/dcr/{dcr['id']}/calls/doctor", headers=auth["mr1"],
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00"},
)
assert resp.status_code == 422
assert "call_outcome" in resp.json()["error"]["message"]
async def test_only_the_owning_mr_writes_missed_notes(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await _plan(client, auth, doctors, [])
dcr = await _actual(client, auth)
body = {"doctor_id": doctors[0]["id"], "reason": "Doctor on leave"}
assert (await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["am1"], json=body)).status_code == 403
assert (await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr2"], json=body)).status_code == 403
class TestPlanPdf:
async def test_an_approved_plan_downloads_as_a_daily_call_plan(self, client, auth, org, db):
from app.pdf.service import PDFService
from app.reports.repository import DCRRepository
doctors, chemists = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
plan_id = await _plan(client, auth, doctors, chemists)
pdf = await client.get(f"{API}/dcr/{plan_id}/pdf", headers=auth["mr1"])
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
assert 'filename="PLAN-MR001-' in pdf.headers["content-disposition"]
import uuid
context = await PDFService(db)._context(await DCRRepository(db).get_full(uuid.UUID(plan_id)))
assert context["title"] == "DAILY CALL REPORT (PLAN)"
assert "PLANNED TIME" in context["grids"]["doctors"]["headers"]
assert context["grids"]["doctors"]["rows"][0]["cells"][3] == "23:00"
class TestPlanningAhead:
async def test_a_plan_may_be_made_up_to_two_days_ahead_but_a_done_report_never(self, client, auth, org):
from datetime import timedelta
from app.common.utils import local_today
day = lambda n: (local_today() + timedelta(days=n)).isoformat() # noqa: E731
made = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": day(2), "report_type": "PLAN"})
assert made.status_code == 201, made.text
too_far = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": day(3), "report_type": "PLAN"})
assert too_far.status_code == 422
done = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": day(1), "report_type": "ACTUAL"})
assert done.status_code == 422
+50 -27
View File
@@ -7,16 +7,17 @@ from tests.e2e.test_full_approval_flow import _create_masters
API = "/api/v1"
async def _draft(client, auth, org):
async def _draft(client, auth, org, approved_plan):
doctors, chemists = 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, 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)
async def test_fields_round_trip_through_the_api(self, client, auth, org, approved_plan):
dcr_id, doctors, chemists = await _draft(client, auth, org, approved_plan)
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",
@@ -35,27 +36,48 @@ class TestFormFields:
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"
# A single name is still accepted, and comes back as a one-item list.
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)
async def test_several_products_per_visit(self, client, auth, org, approved_plan):
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
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", " Vit D ", "calcium", "", "Zinc"],
"product_sample": ["Iron", "Omega 3", "B12"]},
)
assert d.status_code == 201, d.text
call = d.json()["doctor_calls"][0]
assert call["product_promote"] == ["Calcium", "Vit D", "Zinc"] # trimmed, de-duplicated
assert call["product_sample"] == ["Iron", "Omega 3", "B12"]
too_many = await client.post(
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
json={"doctor_id": doctors[1]["id"], "visit_time": "09:40:00", "call_outcome": "MET",
"product_promote": [f"P{i}" for i in range(11)]},
)
assert too_many.status_code == 422
async def test_blank_values_are_stored_as_null_and_can_be_cleared(self, client, auth, org, approved_plan):
dcr_id, _, _ = await _draft(client, auth, org, approved_plan)
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)
async def test_patching_one_field_leaves_the_others_alone(self, client, auth, org, approved_plan):
dcr_id, _, _ = await _draft(client, auth, org, approved_plan)
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)
async def test_too_long_values_are_rejected(self, client, auth, org, approved_plan):
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
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(
@@ -64,8 +86,8 @@ class TestFormFields:
)
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)
async def test_only_the_owner_can_edit_them_and_only_while_editable(self, client, auth, org, approved_plan):
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
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(
@@ -76,8 +98,8 @@ class TestFormFields:
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)
async def test_approved_pdf_is_generated_with_the_new_layout(self, client, auth, org, approved_plan):
dcr_id, doctors, chemists = await _draft(client, auth, org, approved_plan)
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"},
@@ -91,8 +113,8 @@ class TestFormFields:
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)
async def test_adding_a_visit_returns_it_in_the_same_response(self, client, auth, org, approved_plan):
dcr_id, doctors, chemists = await _draft(client, auth, org, approved_plan)
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"},
@@ -105,8 +127,8 @@ class TestResponsesReflectTheChange:
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)
async def test_removing_a_visit_returns_the_report_without_it(self, client, auth, org, approved_plan):
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
for i, doctor in enumerate(doctors):
r = await client.post(
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
@@ -123,14 +145,14 @@ class TestResponsesReflectTheChange:
class TestDownloadUsesTheCurrentLayout:
async def test_a_report_approved_under_an_older_layout_still_downloads_in_the_new_one(self, client, auth, org, db):
async def test_a_report_approved_under_an_older_layout_still_downloads_in_the_new_one(self, client, auth, org, db, approved_plan):
from pathlib import Path
from sqlalchemy import select
from app.reports.models import DailyCallReport
dcr_id, doctors, _ = await _draft(client, auth, org)
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
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"},
@@ -146,14 +168,15 @@ class TestDownloadUsesTheCurrentLayout:
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)
draft_id, _, _ = await _draft_second(client, auth, org, approved_plan)
assert (await client.get(f"{API}/dcr/{draft_id}/pdf", headers=auth["mr1"])).status_code == 422
async def _draft_second(client, auth, org):
async def _draft_second(client, auth, org, approved_plan):
"""A second, unapproved report (yesterday's) for the same MR."""
from datetime import timedelta
await approved_plan(date.today() - timedelta(days=1))
resp = await client.post(
f"{API}/dcr", headers=auth["mr1"], json={"report_date": (date.today() - timedelta(days=1)).isoformat()}
)
@@ -162,14 +185,14 @@ async def _draft_second(client, auth, org):
class TestApprovedPdfIsSigned:
async def test_the_pdf_names_the_approving_area_manager_from_the_audit_trail(self, client, auth, org, db):
async def test_the_pdf_names_the_approving_area_manager_from_the_audit_trail(self, client, auth, org, db, approved_plan):
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)
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
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"},
@@ -184,10 +207,10 @@ class TestApprovedPdfIsSigned:
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):
async def test_a_report_that_is_not_approved_has_no_approval_signature(self, client, auth, org, db, approved_plan):
from app.pdf.service import PDFService
from app.reports.repository import DCRRepository
dcr_id, _, _ = await _draft(client, auth, org)
dcr_id, _, _ = await _draft(client, auth, org, approved_plan)
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
+10 -9
View File
@@ -33,8 +33,9 @@ async def _audit_count(db, entity_id, action) -> int:
class TestReports:
async def _submitted(self, client, auth, org):
async def _submitted(self, client, auth, org, approved_plan):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
await approved_plan()
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"],
@@ -42,8 +43,8 @@ class TestReports:
)
return dcr, doctors
async def test_submitting_twice_is_one_submission(self, client, auth, org, db):
dcr, _ = await self._submitted(client, auth, org)
async def test_submitting_twice_is_one_submission(self, client, auth, org, db, approved_plan):
dcr, _ = await self._submitted(client, auth, org, approved_plan)
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
@@ -51,8 +52,8 @@ class TestReports:
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)
async def test_approving_twice_is_one_approval(self, client, auth, org, db, approved_plan):
dcr, _ = await self._submitted(client, auth, org, approved_plan)
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={})
@@ -60,14 +61,14 @@ class TestReports:
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)
async def test_an_area_manager_of_another_hq_still_cannot_approve(self, client, auth, org, approved_plan):
dcr, _ = await self._submitted(client, auth, org, approved_plan)
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)
async def test_adding_the_same_visit_or_creating_the_same_report_twice_is_refused(self, client, auth, org, approved_plan):
dcr, doctors = await self._submitted(client, auth, org, approved_plan)
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"},
+3 -4
View File
@@ -32,7 +32,7 @@ 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 set(forms) == {"tour_plan", "standard_tour_plan", "fare_chart", "expense_statement"}
assert {f["status"] for f in forms.values()} == {"draft"}
for who in ("am1", "admin"):
resp = await client.get(f"{API}/approvals", headers=auth[who])
@@ -94,10 +94,9 @@ class TestFormApproval:
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.
# Deleting a row is admin-only — an MR can no longer delete their own rows.
# An MR may remove a row they entered by mistake; that too withdraws the request.
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["mr1"])).status_code == 403
assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["admin"])).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
async def test_the_pdf_signature_comes_from_the_server_not_the_browser(self, client, auth, org, db, fare_chart):
+67
View File
@@ -0,0 +1,67 @@
"""Company forms: listed in the company's order, and readable (never writable) by the GM."""
from tests.e2e.test_form_ownership import forms # noqa: F401 - creates the form tables
API = "/api/v1"
ORDER = [
"standard_tour_plan",
"tour_plan",
"fare_chart",
"sales_and_stock_statement",
"sales_projection",
"field_activity_report",
"expense_statement",
"area_covered",
"weekly_report",
"core_dr_call_conversion",
]
class TestFormsForTheGeneralManager:
async def test_forms_are_listed_in_the_company_order(self, client, auth, org):
for who in ("mr1", "gm", "admin"):
tables = (await client.get(f"{API}/csv-data/tables", headers=auth[who])).json()
assert [t["name"] for t in tables] == ORDER
async def test_gm_reads_every_mrs_rows_and_pdf(self, client, auth, org, forms): # noqa: F811
added = await client.post(
f"{API}/csv-data/tour_plan/rows", headers=auth["mr1"], json={"from_location": "Puri"}
)
assert added.status_code == 201, added.text
rows = (await client.get(f"{API}/csv-data/tour_plan/rows", headers=auth["gm"])).json()
assert [r["from_location"] for r in rows] == ["Puri"]
owners = (await client.get(f"{API}/csv-data/owners", headers=auth["gm"])).json()
assert {o["id"] for o in owners} == {str(org["mr1"].id), str(org["mr2"].id)}
mine = await client.get(
f"{API}/csv-data/tour_plan/rows?owner_id={org['mr1'].id}", headers=auth["gm"]
)
assert mine.status_code == 200 and len(mine.json()) == 1
pdf = await client.get(f"{API}/csv-data/tour_plan/pdf", headers=auth["gm"])
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
async def test_gm_cannot_change_or_approve_a_form(self, client, auth, org, forms): # noqa: F811
row = (
await client.post(
f"{API}/csv-data/tour_plan/rows", headers=auth["mr1"], json={"to_location": "Puri"}
)
).json()
add = await client.post(
f"{API}/csv-data/tour_plan/rows?owner_id={org['mr1'].id}",
headers=auth["gm"],
json={"to_location": "Cuttack"},
)
assert add.status_code == 403
edit = await client.patch(
f"{API}/csv-data/tour_plan/rows/{row['id']}", headers=auth["gm"], json={"pob": "1"}
)
assert edit.status_code == 403
delete = await client.delete(
f"{API}/csv-data/tour_plan/rows/{row['id']}", headers=auth["gm"]
)
assert delete.status_code == 403
approve = await client.post(
f"{API}/csv-data/tour_plan/approval/approve?owner_id={org['mr1'].id}",
headers=auth["gm"],
)
assert approve.status_code == 403
+45
View File
@@ -151,3 +151,48 @@ class TestMonthlyDownload:
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
class TestExpenseStatement:
async def test_the_total_is_worked_out_by_the_server(self, client, auth, db):
await _make_table(db, "expense_statement", owned=True)
made = await client.post(
f"{API}/expense_statement/rows", headers=auth["mr1"],
json={"report_date": "2026-10-01", "fare": "120.50", "da_hq": "100", "total": "1"},
)
assert made.status_code == 201, made.text
assert made.json()["total"] == "220.50" and made.json()["name"] == "Ravi Das"
row = made.json()["id"]
changed = await client.patch(f"{API}/expense_statement/rows/{row}", headers=auth["mr1"], json={"postage": "9.50", "total": "5"})
assert changed.status_code == 200 and changed.json()["total"] == "230.00"
bad = await client.patch(f"{API}/expense_statement/rows/{row}", headers=auth["mr1"], json={"fare": "abc"})
assert bad.status_code == 422
async def test_clearing_one_cell_of_a_row_that_has_other_values_is_allowed(self, client, auth, db):
await _make_table(db, "expense_statement", owned=True)
made = await client.post(f"{API}/expense_statement/rows", headers=auth["admin"], json={"from_location": "A", "fare": "10"}, params={"owner_id": str((await client.get(f"{API}/owners", headers=auth["admin"])).json()[0]["id"])})
assert made.status_code == 201, made.text
cleared = await client.patch(f"{API}/expense_statement/rows/{made.json()['id']}", headers=auth["admin"], json={"fare": ""})
assert cleared.status_code == 200, cleared.text
assert cleared.json()["fare"] == "" and cleared.json()["total"] is None
class TestRemovingAMistake:
async def test_an_mr_removes_their_own_row_and_the_rest_are_renumbered(self, client, auth, forms):
first = await _add(client, auth["mr1"], "A")
await _add(client, auth["mr1"], "B")
assert (await client.delete(f"{API}/fare_chart/rows/{first}", headers=auth["mr1"])).status_code == 204
mine = (await client.get(f"{API}/fare_chart/rows", headers=auth["mr1"])).json()
assert [(r["from_location"], r["serial_no"]) for r in mine] == [("B", "1")]
async def test_an_mr_removes_an_extra_copy_of_a_product_but_never_its_only_row(self, client, auth, db):
await _make_table(db, "sales_projection", owned=False)
made = await client.post(f"{API}/sales_projection/rows", headers=auth["admin"], json={"product_name": "INTEZOLE-PD", "pts": "106.92"})
assert made.status_code == 201, made.text
row = made.json()["id"]
extra = await client.post(f"{API}/sales_projection/rows", headers=auth["mr1"], json={"product_name": "INTEZOLE-PD", "month": "August"})
assert extra.status_code == 201, extra.text
assert (await client.delete(f"{API}/sales_projection/rows/{extra.json()['id']}", headers=auth["mr1"])).status_code == 204
assert (await client.delete(f"{API}/sales_projection/rows/{row}", headers=auth["mr1"])).status_code == 403
cleared = await client.patch(f"{API}/sales_projection/rows/{row}", headers=auth["mr1"], json={"closing_qty": "", "month": ""})
assert cleared.status_code == 200 and cleared.json()["product_name"] == "INTEZOLE-PD"
+49 -19
View File
@@ -137,18 +137,40 @@ class TestStep3And5Masters:
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."""
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["hq1"].id),
"name": "Dr Selfmade",
"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:
@@ -193,9 +215,10 @@ class TestStep4Login:
class TestFullApprovalFlow:
async def test_thirteen_step_flow(self, client, auth, org):
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(
@@ -391,8 +414,9 @@ class TestFullApprovalFlow:
class TestNegativeScope:
async def _submitted_report(self, client, auth, org):
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()}
)
@@ -409,8 +433,8 @@ class TestNegativeScope:
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)
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
@@ -420,8 +444,8 @@ class TestNegativeScope:
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)
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
@@ -435,9 +459,9 @@ class TestNegativeScope:
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):
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)
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
@@ -489,7 +513,8 @@ class TestValidationRules:
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):
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()}
)
@@ -499,8 +524,9 @@ class TestValidationRules:
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):
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"],
@@ -527,8 +553,9 @@ class TestValidationRules:
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):
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(
@@ -549,8 +576,9 @@ class TestValidationRules:
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):
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()}
)
@@ -572,8 +600,9 @@ class TestValidationRules:
assert edit.status_code == 409
assert edit.json()["error"]["code"] == "REPORT_LOCKED"
async def test_pdf_unavailable_before_approval(self, client, auth, org):
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()}
)
@@ -585,8 +614,9 @@ class TestValidationRules:
class TestStatusCounts:
async def test_counts_replace_the_dashboard(self, client, auth, org):
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()}
)
@@ -595,4 +625,4 @@ class TestStatusCounts:
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
assert counts.json()["APPROVED"] == 1 # the day plan the report follows
+102
View File
@@ -0,0 +1,102 @@
"""A doctor or chemist an MR adds waits for their Area Manager; a doctor visit records a gift."""
from datetime import date
API = "/api/v1"
async def _add_doctor(client, auth, org, name="Dr New", who="mr1", hq="hq1"):
resp = await client.post(
f"{API}/doctors", headers=auth[who],
json={"headquarters_id": str(org[hq].id), "name": name, "clinic_address": "Clinic 1, Bhubaneswar"},
)
assert resp.status_code == 201, resp.text
return resp.json()
async def _names(client, headers, path="/doctors"):
return [d["name"] for d in (await client.get(f"{API}{path}", headers=headers)).json()]
class TestAnMrsDoctorWaitsForTheAreaManager:
async def test_it_is_pending_and_unlisted_until_approved(self, client, auth, org):
doctor = await _add_doctor(client, auth, org)
assert doctor["approval_status"] == "PENDING" and doctor["requested_by_name"] == "Ravi Das"
assert "Dr New" not in await _names(client, auth["mr1"])
assert "Dr New" not in await _names(client, auth["am1"])
assert await _names(client, auth["mr1"], "/doctors/requests") == ["Dr New"]
assert await _names(client, auth["am1"], "/doctors/requests") == ["Dr New"]
assert await _names(client, auth["am2"], "/doctors/requests") == [] # another headquarters
approved = await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["am1"])
assert approved.status_code == 200 and approved.json()["approval_status"] == "APPROVED"
assert "Dr New" in await _names(client, auth["mr1"]) # in the list, assigned to the MR who asked
assert await _names(client, auth["mr1"], "/doctors/requests") == []
async def test_only_the_mrs_own_area_manager_or_the_admin_decides(self, client, auth, org):
doctor = await _add_doctor(client, auth, org)
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["am2"])).status_code == 403
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["mr1"])).status_code == 403
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["gm"])).status_code == 403
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["admin"])).status_code == 200
async def test_a_rejection_tells_the_mr_why_and_adding_it_again_resends_it(self, client, auth, org):
doctor = await _add_doctor(client, auth, org)
rejected = await client.post(f"{API}/doctors/{doctor['id']}/reject", headers=auth["am1"], json={"reason": "Wrong clinic"})
assert rejected.status_code == 200
mine = (await client.get(f"{API}/doctors/requests", headers=auth["mr1"])).json()
assert [(d["approval_status"], d["rejection_reason"]) for d in mine] == [("REJECTED", "Wrong clinic")]
assert await _names(client, auth["am1"], "/doctors/requests") == []
again = await _add_doctor(client, auth, org)
assert again["id"] == doctor["id"] and again["approval_status"] == "PENDING" and again["rejection_reason"] is None
assert await _names(client, auth["am1"], "/doctors/requests") == ["Dr New"]
async def test_a_pending_doctor_cannot_be_visited(self, client, auth, org, approved_plan):
doctor = await _add_doctor(client, auth, org)
await approved_plan()
dcr = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})
assert dcr.status_code == 201, dcr.text
visit = await client.post(
f"{API}/dcr/{dcr.json()['id']}/calls/doctor", headers=auth["mr1"],
json={"doctor_id": doctor["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
)
assert visit.status_code == 422
async def test_the_admins_own_doctor_is_approved_at_once(self, client, auth, org):
doctor = await _add_doctor(client, auth, org, who="admin")
assert doctor["approval_status"] == "APPROVED" and doctor["requested_by_name"] is None
class TestAnMrsChemistWaitsToo:
async def test_it_is_pending_until_approved(self, client, auth, org):
resp = await client.post(
f"{API}/chemists", headers=auth["mr1"],
json={"headquarters_id": str(org["hq1"].id), "name": "New Pharmacy", "shop_address": "Shop 2, Bhubaneswar"},
)
assert resp.status_code == 201 and resp.json()["approval_status"] == "PENDING"
assert "New Pharmacy" not in await _names(client, auth["mr1"], "/chemists")
assert (await client.post(f"{API}/chemists/{resp.json()['id']}/approve", headers=auth["am1"])).status_code == 200
assert "New Pharmacy" in await _names(client, auth["mr1"], "/chemists")
class TestGift:
async def test_a_doctor_visit_records_the_gift_and_the_pdf_notes_it(self, client, auth, org, approved_plan):
doctor = await _add_doctor(client, auth, org, who="admin", name="Dr Gifted")
assert (await client.post(f"{API}/doctors/{doctor['id']}/assign", headers=auth["admin"], json={"mr_user_id": str(org["mr1"].id)})).status_code == 201
await approved_plan()
dcr = (await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})).json()
visit = await client.post(
f"{API}/dcr/{dcr['id']}/calls/doctor", headers=auth["mr1"],
json={"doctor_id": doctor["id"], "visit_time": "09:30:00", "call_outcome": "MET", "gift": "Diary"},
)
assert visit.status_code == 201, visit.text
calls = (await client.get(f"{API}/dcr/{dcr['id']}", headers=auth["mr1"])).json()["doctor_calls"]
assert [c["gift"] for c in calls] == ["Diary"]
from types import SimpleNamespace
from app.pdf.forms import _doctor_remarks
call = SimpleNamespace(call_outcome="MET", gift="Diary", remarks="Interested")
assert _doctor_remarks(call) == "Gift: Diary. Interested"
+141
View File
@@ -0,0 +1,141 @@
"""An Area Manager's own Daily Call Report (Self): no plan, no approval, final on submit."""
from datetime import date
from tests.e2e.test_full_approval_flow import _create_masters
API = "/api/v1"
TODAY = date.today().isoformat()
async def _self_report(client, auth, **extra):
return await client.post(
f"{API}/dcr",
headers=auth["am1"],
json={"report_date": TODAY, "report_type": "SELF", **extra},
)
class TestSelfReport:
async def test_am_files_and_submits_without_a_plan(self, client, auth, org):
doctors, chemists = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
created = await _self_report(client, auth)
assert created.status_code == 201, created.text
report = created.json()
assert report["report_type"] == "SELF"
assert report["headquarters_id"] == str(org["hq1"].id) # the one HQ am1 manages
dcr_id = report["id"]
# Any doctor of the headquarters, though it is assigned to an MR, not to the AM.
visit = await client.post(
f"{API}/dcr/{dcr_id}/calls/doctor",
headers=auth["am1"],
json={
"doctor_id": doctors[0]["id"],
"visit_time": "09:30:00",
"call_outcome": "MET",
"product_promote": ["Calcium", "Zinc"],
"product_sample": ["Iron"],
},
)
assert visit.status_code == 201, visit.text
chem = await client.post(
f"{API}/dcr/{dcr_id}/calls/chemist",
headers=auth["am1"],
json={"chemist_id": chemists[0]["id"], "visit_time": "10:00:00"},
)
assert chem.status_code == 201, chem.text
submitted = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["am1"])
assert submitted.status_code == 200, submitted.text
assert submitted.json()["status"] == "APPROVED" # final: nobody approves it
assert submitted.json()["is_locked"] is True
locked = await client.patch(
f"{API}/dcr/{dcr_id}", headers=auth["am1"], json={"mr_remarks": "x"}
)
assert locked.status_code == 409
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["am1"])
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
async def test_self_list_is_own_and_kept_out_of_the_mr_lists(self, client, auth, org):
dcr_id = (await _self_report(client, auth)).json()["id"]
own = (await client.get(f"{API}/dcr?type=SELF", headers=auth["am1"])).json()
assert [r["id"] for r in own] == [dcr_id]
assert (await client.get(f"{API}/dcr?type=SELF", headers=auth["am2"])).json() == []
everything = (await client.get(f"{API}/dcr", headers=auth["am1"])).json()
assert dcr_id not in {r["id"] for r in everything}
counts = (await client.get(f"{API}/dcr/counts", headers=auth["am1"])).json()
assert counts["DRAFT"] == 0
async def test_one_self_report_per_date(self, client, auth, org):
assert (await _self_report(client, auth)).status_code == 201
assert (await _self_report(client, auth)).status_code == 409
async def test_needs_a_headquarters_the_am_manages(self, client, auth, org):
resp = await _self_report(client, auth, headquarters_id=str(org["hq2"].id))
assert resp.status_code == 403
async def test_only_an_am_files_one_and_an_am_files_no_plan(self, client, auth, org):
mr = await client.post(
f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "SELF"}
)
assert mr.status_code == 403
plan = await client.post(
f"{API}/dcr", headers=auth["am1"], json={"report_date": TODAY, "report_type": "PLAN"}
)
assert plan.status_code == 403
async def test_doctor_from_another_headquarters_is_refused(self, client, auth, org):
other = await client.post(
f"{API}/doctors",
headers=auth["admin"],
json={
"headquarters_id": str(org["hq2"].id),
"name": "Dr Far",
"clinic_address": "Sambalpur",
},
)
dcr_id = (await _self_report(client, auth)).json()["id"]
resp = await client.post(
f"{API}/dcr/{dcr_id}/calls/doctor",
headers=auth["am1"],
json={"doctor_id": other.json()["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
)
assert resp.status_code == 422
async def test_nobody_else_can_touch_it(self, client, auth, org):
dcr_id = (await _self_report(client, auth)).json()["id"]
assert (
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
).status_code == 403
approve = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={})
assert approve.status_code == 409 # a draft cannot be approved; submitting finalises it
class TestGeneralManagerOversight:
async def test_gm_sees_every_self_report_read_only(self, client, auth, org):
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=0)
dcr_id = (await _self_report(client, auth)).json()["id"]
await client.post(
f"{API}/dcr/{dcr_id}/calls/doctor",
headers=auth["am1"],
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["am1"])
listed = (await client.get(f"{API}/dcr?type=SELF", headers=auth["gm"])).json()
assert [r["id"] for r in listed] == [dcr_id]
assert listed[0]["mr_name"] == org["am1"].full_name
assert (await client.get(f"{API}/dcr/{dcr_id}", headers=auth["gm"])).status_code == 200
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["gm"])
assert pdf.status_code == 200
edit = await client.patch(
f"{API}/dcr/{dcr_id}", headers=auth["gm"], json={"mr_remarks": "x"}
)
assert edit.status_code == 403
own = await client.post(
f"{API}/dcr", headers=auth["gm"], json={"report_date": TODAY, "report_type": "SELF"}
)
assert own.status_code == 403
+76
View File
@@ -0,0 +1,76 @@
"""An Administrator can change another user's role; the old role's assignments end."""
import uuid
from sqlalchemy import select
from app.doctors.models import DoctorAssignment
from tests.conftest import DEFAULT_PASSWORD
API = "/api/v1"
async def _patch(client, auth, user, body, as_="admin"):
return await client.patch(f"{API}/users/{user.id}", headers=auth[as_], json=body)
class TestAdminChangesRole:
async def test_mr_becomes_am_and_loses_hq_and_doctors(self, client, auth, org, db):
doctor = await client.post(
f"{API}/doctors",
headers=auth["mr1"],
json={"headquarters_id": str(org["hq1"].id), "name": "Dr A", "clinic_address": "Puri"},
)
assert doctor.status_code == 201
resp = await _patch(client, auth, org["mr1"], {"role": "AM"})
assert resp.status_code == 200, resp.text
assert resp.json()["role"] == "AM"
assert resp.json()["headquarters_id"] is None
# The doctor stays in the headquarters but is no longer assigned to anyone.
active = await db.execute(
select(DoctorAssignment).where(
DoctorAssignment.doctor_id == uuid.UUID(doctor.json()["id"]),
DoctorAssignment.effective_to.is_(None),
)
)
assert active.scalars().first() is None
async def test_am_becomes_mr_and_releases_headquarters(self, client, auth, org):
resp = await _patch(
client, auth, org["am1"], {"role": "MR", "headquarters_id": str(org["hq2"].id)}
)
assert resp.status_code == 200, resp.text
assert resp.json()["headquarters_id"] == str(org["hq2"].id)
mappings = await client.get(f"{API}/headquarters/area-managers", headers=auth["admin"])
assert str(org["am1"].id) not in {m["area_manager_user_id"] for m in mappings.json()}
async def test_gm_becomes_am(self, client, auth, org):
resp = await _patch(client, auth, org["gm"], {"role": "AM"})
assert resp.status_code == 200, resp.text
assert resp.json()["role"] == "AM"
async def test_role_change_signs_the_user_out(self, client, auth, org):
login = await client.post(
f"{API}/auth/login",
json={"email": org["gm"].email, "password": DEFAULT_PASSWORD},
)
await _patch(client, auth, org["gm"], {"role": "AM"})
again = await client.post(
f"{API}/auth/refresh", json={"refresh_token": login.json()["refresh_token"]}
)
assert again.status_code == 401
async def test_becoming_mr_needs_a_headquarters(self, client, auth, org):
resp = await _patch(client, auth, org["gm"], {"role": "MR"})
assert resp.status_code == 422
async def test_admin_cannot_change_own_role(self, client, auth, org):
resp = await _patch(client, auth, org["admin"], {"role": "GM"})
assert resp.status_code == 422
async def test_only_admin_can_change_a_role(self, client, auth, org):
resp = await _patch(client, auth, org["mr1"], {"role": "AM"}, as_="gm")
assert resp.status_code == 403
+12 -4
View File
@@ -11,6 +11,7 @@ from zoneinfo import ZoneInfo
import pytest
from app.common.enums import ReportType
from app.common.exceptions import ValidationError
from app.reports import service as svc
@@ -36,7 +37,7 @@ def _service() -> svc.DCRService:
def _report(day: date) -> SimpleNamespace:
return SimpleNamespace(report_date=day)
return SimpleNamespace(report_date=day, report_type=ReportType.ACTUAL)
class TestVisitTime:
@@ -57,12 +58,19 @@ class TestVisitTime:
class TestReportDate:
def test_today_is_todays_ist_date_just_after_midnight(self, at):
at(2026, 9, 21, 1, 0) # still 20 Sep in UTC
_service()._validate_report_date(date(2026, 9, 21))
_service()._validate_report_date(date(2026, 9, 21), ReportType.ACTUAL)
def test_tomorrow_is_rejected(self, at):
def test_tomorrow_is_rejected_for_a_done_or_self_report(self, at):
at(2026, 9, 21, 1, 0)
for report_type in (ReportType.ACTUAL, ReportType.SELF):
with pytest.raises(ValidationError):
_service()._validate_report_date(date(2026, 9, 22), report_type)
def test_a_plan_may_be_made_up_to_two_days_ahead(self, at):
at(2026, 9, 21, 1, 0)
_service()._validate_report_date(date(2026, 9, 23), ReportType.PLAN)
with pytest.raises(ValidationError):
_service()._validate_report_date(date(2026, 9, 22))
_service()._validate_report_date(date(2026, 9, 24), ReportType.PLAN)
def test_local_helpers_use_the_configured_timezone():
+1 -1
View File
@@ -30,7 +30,7 @@ async def test_am_can_list_only_approval_csv_tables_and_download_approval_pdf(cl
resp = await client.get(f"{API}/csv-data/tables", headers=auth["am1"])
assert resp.status_code == 200, resp.text
table_names = {item["name"] for item in resp.json()}
assert table_names == {"standard_tour_plan", "tour_plan", "fare_chart"}
assert table_names == {"standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"}
assert "daily_call_report_csv" not in table_names
pdf = await client.get(f"{API}/csv-data/fare_chart/pdf", headers=auth["am1"])
+28 -14
View File
@@ -45,8 +45,8 @@ def test_identity_is_gathered_from_all_rows_not_just_the_first():
PRINTED_HEADERS = {
"tour_plan": ["Sl.No.", "Date", "From", "To", "POB", "Stockiest Visit"],
"standard_tour_plan": ["Sl.No.", "PLACE"],
"fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)"],
"area_covered": ["SALE STATUS", "AREA TO COVER", "SALE OBJECTIVE", "STATUS"],
"fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)\n(One Way)"],
"area_covered": ["AREA TO COVER", "SALE OBJECTIVE", "STATUS"],
"core_dr_call_conversion": ["DOCTOR NAME", "DATE OF VISIT", "PRODUCT TARGETED", "STATUS"],
"field_activity_report": [
"DATE",
@@ -57,21 +57,19 @@ PRINTED_HEADERS = {
"sales_and_stock_statement": [
"Sl.No.",
"Name of the Product",
"Value in PTS",
"Opening",
"Receipt",
"Sale",
"Closing",
"Value in PTS",
],
"sales_projection": [
"SL. No.",
"NAME OF THE PRODUCT",
"PTS",
"SEC. QTY",
"QUANTITY",
"VALUE",
"CLOSING",
"SEC. VALUE",
"SALES",
"QUANTITY",
"VALUE",
],
}
@@ -120,10 +118,10 @@ def test_blank_lines_carry_on_numbering_and_tour_plan_numbers_have_a_dot():
def test_product_lists_print_in_their_own_columns():
rows = _rows("sales_projection", 2)
rows[0].update(product_name="INTEZOLE-PD", pts="106.92")
rows[1].update(product_name="INTEZOLE-RD", pts="93.59", secondary_qty="4")
rows[1].update(product_name="INTEZOLE-RD", pts="93.59", closing_qty="4", projection_value="250")
cells = [r["cells"] for r in _ctx("sales_projection", rows)["grids"]["main"]["rows"][:2]]
assert cells[0][:3] == ["1", "INTEZOLE-PD", "106.92"]
assert cells[1][:4] == ["2", "INTEZOLE-RD", "93.59", "4"]
assert cells[1] == ["2", "INTEZOLE-RD", "93.59", "4", "", "", "250"]
def test_printing_every_month_together_renumbers_instead_of_repeating():
@@ -140,11 +138,11 @@ def test_printing_every_month_together_renumbers_instead_of_repeating():
assert [r["cells"][0] for r in body[:2]] == ["1", "1"]
def test_sales_projection_sales_column_names_the_actual_month():
rows = _rows("sales_projection", 2, month="September")
assert _ctx("sales_projection", rows)["grids"]["main"]["headers"][7] == "SEP. SALES"
# No month on any row (e.g. a blank template): a generic label, never a hardcoded month.
assert _ctx("sales_projection", _rows("sales_projection", 2))["grids"]["main"]["headers"][7] == "SALES"
def test_sales_projection_groups_closing_and_projection_under_their_own_headings():
from app.pdf.service import _env
html = _env.get_template("forms/sales_projection.html").render(**_ctx("sales_projection", _rows("sales_projection", 1)))
assert '<th colspan="2">CLOSING</th>' in html and '<th colspan="2">PROJECTION</th>' in html
def test_no_form_prints_dashboard_extras():
@@ -224,3 +222,19 @@ def test_plain_text_fallback_keeps_the_form_content_readable():
text = _html_to_text(_env.get_template("forms/fare_chart.html").render(**ctx))
assert "Puri" in text and "APPROVAL SIGNATURE: Meera" in text and "<" not in text
assert _minimal_pdf(text).startswith(b"%PDF")
def test_expense_statement_splits_rupees_and_paise_and_totals_every_column():
rows = _rows("expense_statement", 2, from_location="BBSR")
rows[0].update(report_date="2026-10-03", fare="120.5", da_ex="150", other_expense="20")
rows[1].update(report_date="2026-10-01", da_hq="100", postage="15.75", total="999") # a stale total is ignored
ctx = _ctx("expense_statement", rows, approval_status="approved", am_name="Anita Das")
body = ctx["grids"]["main"]["rows"]
assert len(body) == 27
assert body[0]["cells"][4:9] == ["120", "50", "", "150", ""]
assert body[0]["cells"][13:15] == ["290", "50"]
assert body[1]["cells"][13:15] == ["115", "75"]
assert ctx["sums"]["total_rs"] == "406" and ctx["sums"]["total_p"] == "25"
assert ctx["sums"]["claimed"] == "406.25"
assert (ctx["period_from"], ctx["period_to"]) == ("01/10/2026", "03/10/2026")
assert ctx["approval"]["value"] == "Anita Das"