Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
View File
+187
View File
@@ -0,0 +1,187 @@
"""Test fixtures.
Tests run against a REAL PostgreSQL database, never SQLite. This system depends on
constraints that SQLite does not implement the same way — partial unique indexes,
composite uniques, jsonb — so testing on SQLite would mean testing a different system
from the one that ships.
Set TEST_DATABASE_URL to point at a scratch database. Docker Compose provides one:
postgresql+asyncpg://pharma:pharma@localhost:5432/pharma_test
"""
import os
import uuid
from collections.abc import AsyncGenerator
from datetime import date
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
os.environ.setdefault("SECRET_KEY", "test-secret-not-for-production")
os.environ.setdefault("ENVIRONMENT", "test")
TEST_DATABASE_URL = os.environ.get(
"TEST_DATABASE_URL", "postgresql+asyncpg://pharma:pharma@127.0.0.1:5432/pharma_test"
)
from app.auth.security import hash_password # noqa: E402
from app.common.enums import Role # noqa: E402
from app.database.all_models import Base # noqa: E402
from app.database.session import get_db # noqa: E402
from app.main import app as fastapi_app # noqa: E402
from app.organization.models import AMHeadquarters, Company, Headquarters # noqa: E402
from app.users.models import User # noqa: E402
TABLES = [
"audit_log",
"product",
"doctor_call",
"chemist_call",
"daily_call_report",
"doctor_assignment",
"chemist_assignment",
"doctor",
"chemist",
"am_headquarters",
"form_approval",
"refresh_token",
'"user"',
"headquarters",
"company",
]
@pytest.fixture(scope="session")
def anyio_backend() -> str:
return "asyncio"
@pytest.fixture(scope="session")
async def engine():
eng = create_async_engine(TEST_DATABASE_URL, poolclass=None)
async with eng.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield eng
await eng.dispose()
@pytest.fixture
async def session_factory(engine):
factory = async_sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
async with engine.begin() as conn:
await conn.execute(text(f"TRUNCATE {', '.join(TABLES)} RESTART IDENTITY CASCADE"))
return factory
@pytest.fixture
async def db(session_factory) -> AsyncGenerator[AsyncSession, None]:
async with session_factory() as s:
yield s
@pytest.fixture
async def client(session_factory, tmp_path) -> AsyncGenerator[AsyncClient, None]:
from app.config.settings import settings
settings.PDF_STORAGE_PATH = str(tmp_path / "pdf")
async def _override_get_db() -> AsyncGenerator[AsyncSession, None]:
async with session_factory() as s:
try:
yield s
except Exception:
await s.rollback()
raise
fastapi_app.dependency_overrides[get_db] = _override_get_db
transport = ASGITransport(app=fastapi_app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
yield ac
fastapi_app.dependency_overrides.clear()
# ---------------------------------------------------------------------------
# Organisation fixture: the minimum MVP system — 1 company, 2 HQs, GM, 2 AMs, 2 MRs.
# The second HQ/AM/MR exist purely so the negative-scope tests (X1, X2) have someone
# to be denied.
# ---------------------------------------------------------------------------
DEFAULT_PASSWORD = "Str0ngPassw0rd!"
@pytest.fixture
async def org(db: AsyncSession) -> dict:
company = Company(id=uuid.uuid4(), name="Acme Pharma Pvt Ltd")
db.add(company)
await db.flush()
hq1 = Headquarters(
id=uuid.uuid4(), company_id=company.id, code="BBSR", name="Bhubaneswar",
district="Khordha", state="Odisha",
)
hq2 = Headquarters(
id=uuid.uuid4(), company_id=company.id, code="SBP", name="Sambalpur",
district="Sambalpur", state="Odisha",
)
db.add_all([hq1, hq2])
await db.flush()
def make(role: Role, name: str, code: str, hq_id=None) -> User:
return User(
id=uuid.uuid4(),
company_id=company.id,
email=f"{code.lower()}@acmepharma.in",
password_hash=hash_password(DEFAULT_PASSWORD),
full_name=name,
employee_code=code,
role=role,
headquarters_id=hq_id,
)
admin = make(Role.ADMIN, "System Admin", "ADM001")
gm = make(Role.GM, "Anita Mohanty", "GM001")
am1 = make(Role.AM, "Suresh Behera", "AM001")
am2 = make(Role.AM, "Rakesh Sahu", "AM002")
mr1 = make(Role.MR, "Ravi Das", "MR001", hq1.id)
mr2 = make(Role.MR, "Priya Nayak", "MR002", hq2.id)
db.add_all([admin, gm, am1, am2, mr1, mr2])
await db.flush()
db.add_all(
[
AMHeadquarters(
area_manager_user_id=am1.id, headquarters_id=hq1.id,
effective_from=date.today(),
),
AMHeadquarters(
area_manager_user_id=am2.id, headquarters_id=hq2.id,
effective_from=date.today(),
),
]
)
await db.commit()
return {
"company": company, "hq1": hq1, "hq2": hq2,
"admin": admin, "gm": gm, "am1": am1, "am2": am2, "mr1": mr1, "mr2": mr2,
}
async def login(client: AsyncClient, user: User) -> dict[str, str]:
resp = await client.post(
"/api/v1/auth/login",
json={"email": user.email, "password": DEFAULT_PASSWORD},
)
assert resp.status_code == 200, resp.text
return {"Authorization": f"Bearer {resp.json()['access_token']}"}
@pytest.fixture
async def auth(client: AsyncClient, org: dict) -> dict[str, dict[str, str]]:
"""Ready-made Authorization headers for every role."""
return {
key: await login(client, org[key])
for key in ("admin", "gm", "am1", "am2", "mr1", "mr2")
}
View File
+100
View File
@@ -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
+193
View File
@@ -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
+145
View File
@@ -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
+114
View File
@@ -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)
+153
View File
@@ -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
+598
View File
@@ -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
+78
View File
@@ -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
View File
+195
View File
@@ -0,0 +1,195 @@
"""Database-level guarantees.
These are the constraints the service layer alone cannot guarantee — under
concurrency, only the database can. Each of these was called out in the report as a
schema-level rule that cannot be retrofitted cheaply.
"""
import uuid
from datetime import date, time, timedelta
import pytest
from sqlalchemy.exc import IntegrityError
from app.common.enums import CallOutcome, DCRStatus
from app.doctors.models import Doctor
from app.organization.models import AMHeadquarters
from app.reports.models import DailyCallReport, DoctorCall
async def _doctor(db, hq_id, name="Dr Sen", clinic="MG Road"):
doc = Doctor(id=uuid.uuid4(), headquarters_id=hq_id, name=name, clinic_address=clinic)
db.add(doc)
await db.flush()
return doc
class TestOneReportPerMRPerDay:
"""V1 / A9 — the constraint the report flagged as the missing piece of the MVP."""
async def test_duplicate_date_rejected(self, db, org):
for _ in range(2):
db.add(
DailyCallReport(
id=uuid.uuid4(),
mr_user_id=org["mr1"].id,
headquarters_id=org["hq1"].id,
report_date=date.today(),
status=DCRStatus.DRAFT,
)
)
with pytest.raises(IntegrityError):
await db.flush()
async def test_different_dates_allowed(self, db, org):
for offset in (0, 1):
db.add(
DailyCallReport(
id=uuid.uuid4(),
mr_user_id=org["mr1"].id,
headquarters_id=org["hq1"].id,
report_date=date.today() - timedelta(days=offset),
status=DCRStatus.DRAFT,
)
)
await db.flush() # must not raise
async def test_different_mrs_same_date_allowed(self, db, org):
for mr, hq in (("mr1", "hq1"), ("mr2", "hq2")):
db.add(
DailyCallReport(
id=uuid.uuid4(),
mr_user_id=org[mr].id,
headquarters_id=org[hq].id,
report_date=date.today(),
status=DCRStatus.DRAFT,
)
)
await db.flush() # must not raise
class TestNoDuplicateDoctorCall:
"""V5 / A11."""
async def test_same_doctor_twice_on_one_report_rejected(self, db, org):
doctor = await _doctor(db, org["hq1"].id)
dcr = DailyCallReport(
id=uuid.uuid4(),
mr_user_id=org["mr1"].id,
headquarters_id=org["hq1"].id,
report_date=date.today(),
status=DCRStatus.DRAFT,
)
db.add(dcr)
await db.flush()
for hour in (10, 16):
db.add(
DoctorCall(
dcr_id=dcr.id,
doctor_id=doctor.id,
visit_time=time(hour, 0),
call_outcome=CallOutcome.MET,
)
)
with pytest.raises(IntegrityError):
await db.flush()
class TestOneActiveAreaManagerPerHQ:
"""The partial unique index `uq_active_am_per_hq`."""
async def test_second_active_am_rejected(self, db, org):
db.add(
AMHeadquarters(
area_manager_user_id=org["am2"].id,
headquarters_id=org["hq1"].id, # already managed by am1
effective_from=date.today(),
)
)
with pytest.raises(IntegrityError):
await db.flush()
async def test_allowed_once_previous_mapping_is_closed(self, db, org):
existing = (
await db.execute(
AMHeadquarters.__table__.select().where(
AMHeadquarters.headquarters_id == org["hq1"].id
)
)
).first()
assert existing is not None
await db.execute(
AMHeadquarters.__table__.update()
.where(AMHeadquarters.headquarters_id == org["hq1"].id)
.values(effective_to=date.today())
)
db.add(
AMHeadquarters(
area_manager_user_id=org["am2"].id,
headquarters_id=org["hq1"].id,
effective_from=date.today(),
)
)
await db.flush() # must not raise
class TestMRRequiresHeadquarters:
"""The `ck_user_mr_requires_hq` check — R4/R8 enforced in the schema."""
async def test_mr_without_hq_rejected(self, db, org):
from app.auth.security import hash_password
from app.common.enums import Role
from app.users.models import User
db.add(
User(
id=uuid.uuid4(),
company_id=org["company"].id,
email="orphan@acmepharma.in",
password_hash=hash_password("x" * 12),
full_name="Orphan MR",
employee_code="MR999",
role=Role.MR,
headquarters_id=None,
)
)
with pytest.raises(IntegrityError):
await db.flush()
async def test_gm_with_hq_rejected(self, db, org):
from app.auth.security import hash_password
from app.common.enums import Role
from app.users.models import User
db.add(
User(
id=uuid.uuid4(),
company_id=org["company"].id,
email="gm2@acmepharma.in",
password_hash=hash_password("x" * 12),
full_name="Wrong GM",
employee_code="GM999",
role=Role.GM,
headquarters_id=org["hq1"].id,
)
)
with pytest.raises(IntegrityError):
await db.flush()
class TestApprovedAtConsistency:
async def test_approved_without_timestamp_rejected(self, db, org):
db.add(
DailyCallReport(
id=uuid.uuid4(),
mr_user_id=org["mr1"].id,
headquarters_id=org["hq1"].id,
report_date=date.today(),
status=DCRStatus.APPROVED,
approved_at=None,
)
)
with pytest.raises(IntegrityError):
await db.flush()
View File
+71
View File
@@ -0,0 +1,71 @@
"""Visit times and report dates are judged in the company's timezone, not the server's UTC.
Regression: the server clock is UTC, so at 12:35 IST (07:05 UTC) an MR who logged a
09:00 visit was told it was "in the future", and around midnight IST "today" was
still yesterday.
"""
from datetime import date, datetime, time
from types import SimpleNamespace
from zoneinfo import ZoneInfo
import pytest
from app.common.exceptions import ValidationError
from app.reports import service as svc
IST = ZoneInfo("Asia/Kolkata")
@pytest.fixture
def at(monkeypatch):
"""Freeze 'now' to a given IST moment and switch the production-only rule on."""
def _freeze(year, month, day, hour, minute):
now = datetime(year, month, day, hour, minute, tzinfo=IST)
monkeypatch.setattr(svc, "local_now", lambda: now)
monkeypatch.setattr(svc, "local_today", lambda: now.date())
monkeypatch.setattr(svc.settings, "ENVIRONMENT", "production")
return now
return _freeze
def _service() -> svc.DCRService:
return svc.DCRService.__new__(svc.DCRService) # the checks under test need no database
def _report(day: date) -> SimpleNamespace:
return SimpleNamespace(report_date=day)
class TestVisitTime:
def test_a_morning_visit_is_accepted_at_lunchtime_ist(self, at):
at(2026, 9, 21, 12, 35) # 07:05 UTC — the old code rejected everything after 07:05
_service()._validate_visit_time(_report(date(2026, 9, 21)), time(9, 0))
def test_a_visit_later_today_is_still_rejected(self, at):
at(2026, 9, 21, 12, 35)
with pytest.raises(ValidationError):
_service()._validate_visit_time(_report(date(2026, 9, 21)), time(18, 0))
def test_past_days_accept_any_time(self, at):
at(2026, 9, 21, 12, 35)
_service()._validate_visit_time(_report(date(2026, 9, 20)), time(23, 59))
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))
def test_tomorrow_is_rejected(self, at):
at(2026, 9, 21, 1, 0)
with pytest.raises(ValidationError):
_service()._validate_report_date(date(2026, 9, 22))
def test_local_helpers_use_the_configured_timezone():
from app.common.utils import local_now
assert str(local_now().tzinfo) == "Asia/Kolkata"
+38
View File
@@ -0,0 +1,38 @@
import pytest
from sqlalchemy import text
pytestmark = pytest.mark.anyio
API = "/api/v1"
async def test_am_can_list_only_approval_csv_tables_and_download_approval_pdf(client, auth, db):
await db.execute(
text(
'''
CREATE TABLE IF NOT EXISTS "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()
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 "daily_call_report_csv" not in table_names
pdf = await client.get(f"{API}/csv-data/fare_chart/pdf", headers=auth["am1"])
assert pdf.status_code == 200, pdf.text
assert pdf.headers["content-type"].startswith("application/pdf")
+205
View File
@@ -0,0 +1,205 @@
"""Company-form PDF layouts: what each form prints, independent of the PDF engine."""
import pytest
from app.csv_data.config import CSV_LABELS, TABLES
from app.pdf.forms import build_form_context
from app.pdf.service import _html_to_text, _minimal_pdf, csv_pdf_bytes, csv_table_pdf_bytes
def _rows(table: str, count: int = 2, **values) -> list[dict[str, object]]:
return [
{**{c: "" for c in TABLES[table]}, "serial_no": str(i + 1), **values} for i in range(count)
]
def _ctx(table: str, rows, **kw):
return build_form_context(table, CSV_LABELS[table], TABLES[table], rows, **kw)
def test_every_form_has_its_own_template():
templates = {_ctx(name, [])["template"] for name in TABLES}
assert len(templates) == len(TABLES)
def test_every_stored_row_is_printed_and_blank_lines_pad_to_the_form_length():
ctx = _ctx("tour_plan", _rows("tour_plan", 3, from_location="BBSR", pob="10"))
body = ctx["grids"]["main"]["rows"]
assert len(body) == 25
assert [r["blank"] for r in body[:4]] == [False, False, False, True]
assert body[0]["cells"][2] == "BBSR"
def test_rows_beyond_the_printed_form_length_are_not_dropped():
ctx = _ctx("standard_tour_plan", _rows("standard_tour_plan", 40, place="Puri"))
assert len(ctx["grids"]["main"]["rows"]) == 40
def test_identity_is_gathered_from_all_rows_not_just_the_first():
rows = _rows("fare_chart", 2)
rows[0]["name"], rows[1]["name"] = "", "Ravi Das"
assert _ctx("fare_chart", rows)["meta_rows"][0][0] == ("NAME:", "Ravi Das")
# Headings exactly as printed on the company forms, in printed order.
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"],
"core_dr_call_conversion": ["DOCTOR NAME", "DATE OF VISIT", "PRODUCT TARGETED", "STATUS"],
"field_activity_report": [
"DATE",
"STATION WORKED",
"NO. OF DOCTORS CALLED",
"NO. OF CHEMISTS/PDS CALLED",
],
"sales_and_stock_statement": [
"Sl.No.",
"Name of the Product",
"Opening",
"Receipt",
"Sale",
"Closing",
"Value in PTS",
],
"sales_projection": [
"SL. No.",
"NAME OF THE PRODUCT",
"PTS",
"SEC. QTY",
"VALUE",
"CLOSING",
"SEC. VALUE",
"AUG. SALES",
"VALUE",
],
}
PRINTED_LINES = {
"tour_plan": 25,
"standard_tour_plan": 25,
"fare_chart": 25,
"area_covered": 28,
"core_dr_call_conversion": 28,
"field_activity_report": 25,
"sales_and_stock_statement": 26,
"sales_projection": 26,
}
@pytest.mark.parametrize("table", list(PRINTED_HEADERS))
def test_form_headings_and_ruled_lines_match_the_printed_form(table):
grid = _ctx(table, [])["grids"]["main"]
assert grid["headers"] == PRINTED_HEADERS[table]
assert len(grid["rows"]) == PRINTED_LINES[table]
assert all(r["blank"] for r in grid["rows"])
def test_daily_call_report_has_both_printed_tables():
grids = _ctx("daily_call_report_csv", [])["grids"]
assert grids["doctors"]["headers"] == [
"SR. NO.",
"DR. NAME",
"QUALIFICATION",
"PRODUCT PROMOTE",
"PRODUCT SAMPLE",
"REMARKS",
]
assert len(grids["doctors"]["rows"]) == 10
assert grids["chemists"]["headers"] == ["SR. NO.", "NAME OF THE CHEMIST", "POB"]
assert len(grids["chemists"]["rows"]) == 5
def test_blank_lines_carry_on_numbering_and_tour_plan_numbers_have_a_dot():
body = _ctx("tour_plan", _rows("tour_plan", 2))["grids"]["main"]["rows"]
assert [r["cells"][0] for r in body[:4]] == ["1.", "2.", "3.", "4."]
body = _ctx("sales_projection", _rows("sales_projection", 1))["grids"]["main"]["rows"]
assert [r["cells"][0] for r in body[:3]] == ["1", "2", "3"]
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")
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"]
def test_no_form_prints_dashboard_extras():
for table in TABLES:
ctx = _ctx(table, _rows(table, 2, pob="5", kilometers_km="9"))
for grid in ctx["grids"].values():
assert "totals" not in grid
assert "stats_items" not in ctx
def test_import_script_columns_match_the_tables():
"""A drifted column list rolled back the whole import, leaving the product lists empty."""
from scripts.import_csv_data import CSV_TABLES
for table, columns in CSV_TABLES.values():
assert tuple(columns) == TABLES[table], table
def test_iso_dates_print_day_first_and_free_text_is_untouched():
rows = _rows("fare_chart", 2)
rows[0]["report_date"], rows[1]["report_date"] = "2026-09-18", "week 3"
cells = [r["cells"][1] for r in _ctx("fare_chart", rows)["grids"]["main"]["rows"][:2]]
assert cells == ["18/09/2026", "week 3"]
def test_stored_serial_numbers_are_kept_for_single_row_pdfs():
rows = _rows("tour_plan", 1)
rows[0]["serial_no"] = "7"
assert _ctx("tour_plan", rows)["grids"]["main"]["rows"][0]["cells"][0] == "7."
def test_weekly_report_prints_one_report_per_stored_row():
rows = _rows("weekly_report", 3, employee_name="Ravi", pob_booked="5")
assert len(_ctx("weekly_report", rows)["reports"]) == 3
def test_daily_call_report_splits_doctor_and_chemist_lines():
rows = _rows("daily_call_report_csv", 3)
rows[0]["doctor_name"] = "Dr. A"
rows[1]["chemist_name"], rows[1]["pob"] = "Sahu Medical", "100"
rows[2]["stockist_visit"], rows[2]["order_value"] = "Yes", "5000"
ctx = _ctx("daily_call_report_csv", rows)
assert ctx["grids"]["doctors"]["rows"][0]["cells"][:2] == ["1", "Dr. A"]
assert ctx["grids"]["chemists"]["rows"][0]["cells"][:2] == ["1", "Sahu Medical"]
assert (ctx["stockist_visit"], ctx["order_value"]) == ("Yes", "5000")
def test_only_approval_forms_carry_an_approval_block():
assert _ctx("fare_chart", [], approval_status="approved", am_name="Meera")["approval"][
"line"
] == ("APPROVAL SIGNATURE: Meera")
assert _ctx("fare_chart", [])["approval"]["value"] == "PENDING"
assert _ctx("sales_and_stock_statement", [])["approval"] is None
@pytest.mark.parametrize("table", list(TABLES))
def test_every_form_renders_a_pdf_even_when_empty_or_hostile(table):
rows = _rows(table, 2, **{c: "<script>&\"'" for c in TABLES[table] if c != "serial_no"})
for data in (rows, []):
pdf = csv_table_pdf_bytes(table, CSV_LABELS[table], TABLES[table], data)
assert pdf.startswith(b"%PDF")
def test_unknown_table_row_pdf_still_renders():
assert csv_pdf_bytes("Some Row", {"id": "x", "a": "1"}).startswith(b"%PDF")
def test_plain_text_fallback_keeps_the_form_content_readable():
from app.pdf.service import _env
ctx = _ctx(
"fare_chart",
_rows("fare_chart", 1, from_location="Puri", kilometers_km="60"),
approval_status="approved",
am_name="Meera",
)
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")
+32
View File
@@ -0,0 +1,32 @@
import pytest
from app.pdf.service import _approval_signature_line
@pytest.mark.parametrize(
("approval_status", "am_name", "expected"),
[
("pending", "", "APPROVAL SIGNATURE: PENDING"),
("approved", "Ravi Das", "APPROVAL SIGNATURE: Ravi Das"),
("approved", " ", "APPROVAL SIGNATURE: PENDING"),
],
)
def test_approval_signature_has_correct_state(approval_status, am_name, expected):
result = _approval_signature_line(
"fare_chart", approval_status=approval_status, am_name=am_name
)
assert result == expected
def test_forms_without_approval_have_no_signature_line():
assert _approval_signature_line("weekly_report", approval_status="approved", am_name="X") == ""
def test_an_approved_form_prints_the_approval_date_beside_the_name():
from app.pdf.forms import build_form_context
ctx = build_form_context("fare_chart", "Fare Chart", ("name",), [{"name": "Sumit Patel"}], "approved", "Suresh Behera", "21/09/2026 13:05")
assert ctx["approval"]["value"] == "Suresh Behera" and ctx["approval"]["when"] == "21/09/2026 13:05"
assert ctx["approval"]["mr_name"] == "Sumit Patel"
pending = build_form_context("fare_chart", "Fare Chart", ("name",), [], "pending", None, "21/09/2026 13:05")
assert pending["approval"]["value"] == "PENDING" and pending["approval"]["when"] == "" and pending["approval"]["mr_name"] == ""
+100
View File
@@ -0,0 +1,100 @@
"""The approved Daily Call Report PDF is a copy of the company's printed form."""
from datetime import date, datetime, timezone
from types import SimpleNamespace as NS
from app.pdf.forms import build_dcr_context
from app.pdf.service import _env
def _doctor(name, promote="", sample="", remarks="", outcome="MET", qualification="MBBS"):
return NS(
doctor=NS(name=name, qualification=qualification), product_promote=promote,
product_sample=sample, remarks=remarks, call_outcome=NS(value=outcome),
)
def _context(doctors, chemists=(), approval=None, **dcr_overrides):
dcr = NS(
mr=NS(full_name="Sumit Patel", employee_code="MR001"), headquarters=NS(name="Bhubaneswar"),
report_date=date(2026, 9, 21), stockist_visit="Ganesh Distributors", order_value="45,000",
mr_remarks="", approved_at=datetime(2026, 9, 21, tzinfo=timezone.utc), id="abc",
)
for key, value in dcr_overrides.items():
setattr(dcr, key, value)
return build_dcr_context(dcr, list(doctors), list(chemists), approval)
def _render(ctx) -> str:
return _env.get_template("dcr.html").render(**ctx)
class TestReferenceLayout:
def test_header_and_headings_match_the_printed_form(self):
html = _render(_context([_doctor("Dr Sen")]))
for text in (
"CELTIC LIFE SCIENCE PVT LTD", "DAILY CALL REPORT", "NAME:", "HEADQUARTER:", "Date:", "Month:",
"SR. NO.", "DR. NAME", "QUALIFICATION", "PRODUCT PROMOTE", "PRODUCT SAMPLE", "REMARKS",
"CHEMIST VISIT", "NAME OF THE CHEMIST", "POB", "STOCKIST VISIT :", "ORDER :", "MR Signature",
):
assert text in html, text
def test_ten_doctor_lines_and_five_chemist_lines_like_the_paper(self):
ctx = _context([_doctor("Dr Sen")], [NS(chemist=NS(name="Konark"), pob="100")])
assert len(ctx["grids"]["doctors"]["rows"]) == 10
assert len(ctx["grids"]["chemists"]["rows"]) == 5
assert [r["cells"][0] for r in ctx["grids"]["doctors"]["rows"]] == [str(i) for i in range(1, 11)]
def test_more_than_ten_visits_continue_rather_than_get_dropped(self):
ctx = _context([_doctor(f"Dr {i}") for i in range(13)])
assert len(ctx["grids"]["doctors"]["rows"]) == 13
def test_cells_are_filled_from_the_top_in_column_order(self):
ctx = _context([_doctor("Dr Sen", "Calcium", "Vit D", "Follow up", qualification="MBBS, MD")])
assert ctx["grids"]["doctors"]["rows"][0]["cells"] == ["1", "Dr Sen", "MBBS, MD", "Calcium", "Vit D", "Follow up"]
assert ctx["grids"]["doctors"]["rows"][1]["cells"] == ["2", "", "", "", "", ""]
def test_meta_block_uses_local_date_format_and_month_name(self):
meta = _context([])["meta_rows"]
assert meta[0] == [("NAME:", "Sumit Patel"), ("Date:", "21/09/2026")]
assert meta[1] == [("HEADQUARTER:", "Bhubaneswar"), ("Month:", "September 2026")]
def test_a_visit_that_did_not_happen_is_flagged_in_remarks(self):
ctx = _context([_doctor("Dr Rout", outcome="NOT_AVAILABLE", remarks="Try Monday")])
assert ctx["grids"]["doctors"]["rows"][0]["cells"][5] == "Not available. Try Monday"
def test_chemist_pob_stockist_and_order_are_printed(self):
ctx = _context([], [NS(chemist=NS(name="Konark Medical Stores"), pob="12,500")])
html = _render(ctx)
assert ctx["grids"]["chemists"]["rows"][0]["cells"] == ["1", "Konark Medical Stores", "12,500"]
assert "Ganesh Distributors" in html and "45,000" in html
def test_the_old_report_layout_is_gone(self):
html = _render(_context([_doctor("Dr Sen")]))
assert "Approval Trail" not in html and "Doctor Calls (" not in html
def test_nothing_is_printed_that_is_not_on_the_paper_form(self):
html = _render(_context([_doctor("Dr Sen")], mr_remarks="Good Day"))
assert "Good Day" not in html and "Approved by" not in html and "Report ID" not in html
class TestSignatures:
APPROVAL = {"name": "Shubhankar Patel", "at": "21/09/2026 13:05"}
def test_an_approved_report_carries_both_signatures(self):
html = _render(_context([_doctor("Dr Sen")], approval=self.APPROVAL))
assert "MR Signature" in html and "Sumit Patel (MR001)" in html
assert "APPROVAL SIGNATURE:" in html and "Shubhankar Patel" in html and "21/09/2026 13:05" in html
def test_without_an_approval_there_is_no_approval_signature(self):
html = _render(_context([_doctor("Dr Sen")]))
assert "MR Signature" in html
assert "APPROVAL SIGNATURE" not in html
def test_signature_text_is_escaped(self):
html = _render(_context([_doctor("Dr Sen")], approval={"name": "<b>x</b>", "at": "now"}))
assert "<b>x</b>" not in html
def test_user_text_is_escaped(self):
html = _render(_context([_doctor("<script>alert(1)</script>")]))
assert "<script>" not in html
+33
View File
@@ -0,0 +1,33 @@
from datetime import date, datetime, timedelta, timezone
from app.common.enums import DCRStatus
from app.reports.models import DailyCallReport
from app.reports.repository import DCRRepository
async def test_list_scoped_orders_newest_created_report_first(db, org):
mr = org["mr1"]
hq = org["hq1"]
today = date.today()
yesterday = today - timedelta(days=1)
first = DailyCallReport(
mr_user_id=mr.id,
headquarters_id=hq.id,
report_date=today,
status=DCRStatus.DRAFT,
created_at=datetime(2024, 1, 1, 8, 0, tzinfo=timezone.utc),
)
second = DailyCallReport(
mr_user_id=mr.id,
headquarters_id=hq.id,
report_date=yesterday,
status=DCRStatus.DRAFT,
created_at=datetime(2024, 1, 1, 9, 0, tzinfo=timezone.utc),
)
db.add_all([first, second])
await db.commit()
reports = await DCRRepository(db).list_scoped(mr_user_id=mr.id, hq_ids={hq.id})
assert [r.id for r in reports] == [second.id, first.id]
+106
View File
@@ -0,0 +1,106 @@
"""Unit tests for the approval state machine — pure logic, no database."""
import pytest
from app.approvals.state_machine import TRANSITIONS, assert_editable, assert_transition
from app.common.enums import DCRStatus, Role, WorkflowAction
from app.common.exceptions import (
ForbiddenError,
InvalidStateTransitionError,
ReportLockedError,
)
class TestHappyPath:
def test_mr_submits_draft(self):
t = assert_transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, Role.MR)
assert t.to_status == DCRStatus.PENDING_AM
def test_mr_resubmits_returned(self):
t = assert_transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, Role.MR)
assert t.to_status == DCRStatus.PENDING_AM
def test_am_approves(self):
t = assert_transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, Role.AM)
assert t.to_status == DCRStatus.APPROVED
def test_am_returns_requires_reason(self):
t = assert_transition(DCRStatus.PENDING_AM, WorkflowAction.RETURN, Role.AM)
assert t.to_status == DCRStatus.RETURNED
assert t.requires_reason is True
def test_gm_cannot_approve_or_return(self):
for action in (WorkflowAction.APPROVE, WorkflowAction.RETURN):
with pytest.raises(ForbiddenError):
assert_transition(DCRStatus.PENDING_AM, action, Role.GM)
class TestAreaManagerIsTheFinalApprover:
"""There is no General Manager stage: the AM approves or returns."""
def test_no_general_manager_status_or_action_exists(self):
assert "PENDING_GM" not in {s.value for s in DCRStatus}
assert "FORWARD" not in {a.value for a in WorkflowAction}
assert not [t for t in TRANSITIONS if t.allowed_role == Role.GM]
def test_only_the_area_manager_can_decide_a_pending_report(self):
for role in (Role.MR, Role.GM, Role.ADMIN):
for action in (WorkflowAction.APPROVE, WorkflowAction.RETURN):
with pytest.raises(ForbiddenError):
assert_transition(DCRStatus.PENDING_AM, action, role)
class TestAdminCanNeverApprove:
"""SEC-2 — if ADMIN could approve, the audit trail would be worthless."""
@pytest.mark.parametrize("status", list(DCRStatus))
@pytest.mark.parametrize("action", list(WorkflowAction))
def test_admin_matches_no_transition(self, status, action):
with pytest.raises((ForbiddenError, InvalidStateTransitionError)):
assert_transition(status, action, Role.ADMIN)
class TestApprovedIsTerminal:
"""A6/Q6 — no reopen path exists in the MVP."""
@pytest.mark.parametrize("action", list(WorkflowAction))
@pytest.mark.parametrize("role", list(Role))
def test_nothing_leaves_approved(self, action, role):
with pytest.raises(InvalidStateTransitionError):
assert_transition(DCRStatus.APPROVED, action, role)
def test_no_transition_originates_from_approved(self):
assert not [t for t in TRANSITIONS if t.from_status == DCRStatus.APPROVED]
class TestEditability:
"""V9/V10 — data changes only in DRAFT or RETURNED."""
@pytest.mark.parametrize("status", [DCRStatus.DRAFT, DCRStatus.RETURNED])
def test_editable(self, status):
assert_editable(status) # must not raise
@pytest.mark.parametrize("status", [DCRStatus.PENDING_AM, DCRStatus.APPROVED])
def test_not_editable(self, status):
with pytest.raises(ReportLockedError):
assert_editable(status)
class TestWrongRoleAtRightStage:
def test_mr_cannot_approve(self):
with pytest.raises(ForbiddenError):
assert_transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, Role.MR)
def test_gm_cannot_submit(self):
with pytest.raises(ForbiddenError):
assert_transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, Role.GM)
def test_mr_cannot_return_its_own_report(self):
with pytest.raises(InvalidStateTransitionError):
assert_transition(DCRStatus.DRAFT, WorkflowAction.RETURN, Role.MR)
def test_exactly_four_transitions():
"""submit (x2), then the Area Manager approves or returns."""
assert len(TRANSITIONS) == 4
assert len(DCRStatus) == 4