"""Company forms belong to one MR; only that MR's own Area Business 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 Business Manager" in resp.text async def test_the_pdf_is_signed_by_the_approver_of_that_mr_only(self, client, auth, org, db, forms): 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 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"