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
+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