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
+453
View File
@@ -0,0 +1,453 @@
"""View models for the company-form PDFs (tour plan, fare chart, sales & stock, ...).
Pure Python — no WeasyPrint, no database — so every form's layout data can be unit
tested anywhere. ``build_form_context`` turns the stored rows of one CSV table into
the context its template under ``templates/forms/`` renders.
Each form here is a copy of the company's printed form: the same title, the same
column headings in the same order, the same column proportions and the same number of
ruled lines. Stored rows fill those lines from the top; the rest stay blank for
handwriting, and rows beyond the printed length simply continue on the next page.
The templates own the look; this module owns *what* each form shows.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
DATE_FIELDS = {"report_date", "date_of_visit"}
APPROVAL_FORMS = {"standard_tour_plan", "tour_plan", "fare_chart"}
SERIAL = "#" # pseudo-field: the running "Sl.No." column
_ALIGN = {"left": "l", "center": "c", "right": "r"}
Row = dict[str, object]
Meta = tuple[str, str] | None # (printed label, column) — None leaves the slot empty
@dataclass(frozen=True)
class Col:
header: str
field: str
width: float # percent of the table
align: str = "left"
@dataclass(frozen=True)
class FormSpec:
template: str
title: str
meta: tuple[tuple[Meta, Meta], ...]
columns: tuple[Col, ...] = ()
min_rows: int = 25
serial_field: str | None = None
serial_dot: bool = False # "1." (tour plan, fare chart) instead of "1"
table_width: float = 100 # percent of the printed width
full_letterhead: bool = True # address, web and phone lines under the company name
def _serial(header: str, width: float) -> Col:
return Col(header, SERIAL, width, "center")
_NAME_HQ = ((("NAME:", "name"), None), (("HEADQUARTER:", "headquarter"), None))
_NAME_HQ_DATE_MONTH = (
(("NAME:", "name"), ("Date:", "report_date")),
(("HEADQUARTER:", "headquarter"), ("Month:", "month")),
)
_NAME_HQ_MONTH = (
(("NAME :", "name"), None),
(("HEADQUARTER:", "headquarter"), ("MONTH:", "month")),
)
FORMS: dict[str, FormSpec] = {
"standard_tour_plan": FormSpec(
"standard_tour_plan",
"STANDARD TOUR PLAN",
_NAME_HQ,
(_serial("Sl.No.", 11.4), Col("PLACE", "place", 88.6, "center")),
serial_field="serial_no",
serial_dot=True,
table_width=83,
),
"tour_plan": FormSpec(
"tour_plan",
"TOUR PLAN",
_NAME_HQ,
(
_serial("Sl.No.", 9.4),
Col("Date", "report_date", 11.9, "center"),
Col("From", "from_location", 25.0),
Col("To", "to_location", 23.2),
Col("POB", "pob", 15.3, "center"),
Col("Stockiest Visit", "stockiest_visit", 15.2, "center"),
),
serial_field="serial_no",
serial_dot=True,
),
"fare_chart": FormSpec(
"fare_chart",
"FARE CHART",
_NAME_HQ,
(
_serial("Sl.No.", 9.4),
Col("Date", "report_date", 15.3, "center"),
Col("From", "from_location", 30.2),
Col("To", "to_location", 27.1),
Col("Kilometers (KM)", "kilometers_km", 17.6, "center"),
),
serial_field="serial_no",
serial_dot=True,
),
"area_covered": FormSpec(
"area_covered",
"AREA COVERED",
_NAME_HQ_MONTH,
(
Col("SALE STATUS", "sale_status", 34.0),
Col("AREA TO COVER", "area_to_cover", 24.3),
Col("SALE OBJECTIVE", "sale_objective", 20.8),
Col("STATUS", "status", 20.9, "center"),
),
min_rows=28,
full_letterhead=False,
),
"core_dr_call_conversion": FormSpec(
"core_dr_call_conversion",
"CORE Dr. CALL & CONVERSION",
_NAME_HQ_MONTH,
(
Col("DOCTOR NAME", "doctor_name", 38.3),
Col("DATE OF VISIT", "date_of_visit", 14.7, "center"),
Col("PRODUCT TARGETED", "product_targeted", 30.4),
Col("STATUS", "status", 16.6, "center"),
),
min_rows=28,
full_letterhead=False,
),
"field_activity_report": FormSpec(
"field_activity_report",
"FIELD ACTIVITY REPORT",
_NAME_HQ_MONTH,
(
Col("DATE", "report_date", 14.5, "center"),
Col("STATION WORKED", "station_worked", 36.6),
Col("NO. OF DOCTORS CALLED", "no_of_doctors_called", 19.8, "center"),
Col("NO. OF CHEMISTS/PDS CALLED", "no_of_chemists_pds_called", 29.1, "center"),
),
min_rows=25,
table_width=83,
full_letterhead=False,
),
"sales_and_stock_statement": FormSpec(
"sales_and_stock_statement",
"SALES AND STOCK STATEMENT",
_NAME_HQ_DATE_MONTH,
(
_serial("Sl.No.", 7.0),
Col("Name of the Product", "product_name", 22.6),
Col("Opening", "opening", 15.0, "center"),
Col("Receipt", "receipt", 14.7, "center"),
Col("Sale", "sale", 15.0, "center"),
Col("Closing", "closing", 12.2, "center"),
Col("Value in PTS", "value_in_pts", 13.5, "center"),
),
min_rows=26,
serial_field="serial_no",
),
"sales_projection": FormSpec(
"sales_projection",
"SALES PROJECTION",
_NAME_HQ_MONTH,
(
_serial("SL. No.", 7.1),
Col("NAME OF THE PRODUCT", "product_name", 22.7),
Col("PTS", "pts", 10.7, "center"),
Col("SEC. QTY", "secondary_qty", 9.1, "center"),
Col("VALUE", "value", 9.6, "center"),
Col("CLOSING", "closing", 11.6, "center"),
Col("SEC. VALUE", "secondary_value", 10.1, "center"),
Col("AUG. SALES", "aug_sales", 9.6, "center"),
Col("VALUE", "value_2", 9.5, "center"),
),
min_rows=26,
serial_field="serial_no",
full_letterhead=False,
),
"daily_call_report_csv": FormSpec(
"daily_call_report_csv",
"DAILY CALL REPORT",
_NAME_HQ_DATE_MONTH,
),
"weekly_report": FormSpec(
"weekly_report",
"Weekly Report",
(
(("EMPLOYEE NAME:", "employee_name"), ("DATE :", "report_date")),
(("HEADQUARTER :", "headquarter"), ("MONTH:", "month")),
),
full_letterhead=False,
),
}
# Daily Call Report: a doctor-call table and a chemist-visit table share one stored row.
_DOCTOR_COLS = (
_serial("SR. NO.", 8.6),
Col("DR. NAME", "doctor_name", 27.5),
Col("QUALIFICATION", "qualification", 14.9),
Col("PRODUCT PROMOTE", "product_promote", 14.6),
Col("PRODUCT SAMPLE", "product_sample", 18.2),
Col("REMARKS", "remarks", 16.2),
)
_DOCTOR_FIELDS = tuple(c.field for c in _DOCTOR_COLS if c.field != SERIAL)
_CHEMIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE CHEMIST", "chemist_name", 32.8),
Col("POB", "pob", 57.0),
)
_CHEMIST_FIELDS = tuple(c.field for c in _CHEMIST_COLS if c.field != SERIAL)
_WEEKLY_SUMMARY = (
("No. of Days Worked", "no_of_days_worked"),
("No. of Doctor Called", "no_of_doctor_called"),
("No. of Chemist Called", "no_of_chemist_called"),
("POB Booked", "pob_booked"),
("Secondary Sales", "secondary_sales"),
("POB Objective", "pob_objective"),
("Secondary Objective", "secondary_objective"),
)
_WEEKLY_SCHEMES = (
("Product – Offer Scheme Booked", "product_offer_scheme_booked"),
("Product – Offer Scheme Objective", "product_offer_scheme_objective"),
)
# --------------------------------------------------------------------- helpers
def _text(value: object) -> str:
return "" if value is None else str(value).strip()
def _display(field: str, value: object) -> str:
"""Stored text as printed; ISO dates become dd/mm/yyyy, anything else is untouched."""
text = _text(value)
if field in DATE_FIELDS and text:
try:
return date.fromisoformat(text[:10]).strftime("%d/%m/%Y")
except ValueError:
return text
return text
def _distinct(rows: list[Row], field: str) -> str:
"""Every different stored value of a column, in order — never just the first row's."""
seen: list[str] = []
for row in rows:
value = _display(field, row.get(field))
if value and value not in seen:
seen.append(value)
return ", ".join(seen)
def _has(row: Row, fields: tuple[str, ...]) -> bool:
return any(_text(row.get(field)) for field in fields)
def _grid(
cols: tuple[Col, ...],
rows: list[Row],
*,
min_rows: int,
serial_field: str | None = None,
serial_dot: bool = False,
table_width: float = 100,
) -> dict[str, object]:
"""One printed table: header, stored rows, then blank ruled lines up to ``min_rows``."""
suffix = "." if serial_dot else ""
body = []
next_serial = 1
for index in range(max(min_rows, len(rows))):
row = rows[index] if index < len(rows) else None
cells: list[str] = []
for col in cols:
if col.field == SERIAL:
# A stored number wins (single-row PDFs keep their real serial); blank
# lines carry on counting from the last printed number.
number = _text(row.get(serial_field)) if row and serial_field else ""
number = number or str(next_serial)
next_serial = int(number) + 1 if number.isdigit() else next_serial + 1
cells.append(number + suffix)
else:
cells.append(_display(col.field, row.get(col.field)) if row else "")
body.append({"cells": cells, "blank": row is None})
return {
"headers": [c.header for c in cols],
"aligns": [_ALIGN[c.align] for c in cols],
"widths": [f"{c.width}%" for c in cols],
"rows": body,
"width": f"{table_width}%",
}
def _meta_rows(
meta: tuple[tuple[Meta, Meta], ...], rows: list[Row]
) -> list[list[tuple[str, str] | None]]:
return [
[(slot[0], _distinct(rows, slot[1])) if slot else None for slot in pair] for pair in meta
]
def approval_signature_line(
table_name: str, approval_status: str | None = None, am_name: str | None = None
) -> str:
if table_name not in APPROVAL_FORMS:
return ""
approved = (approval_status or "pending").lower() == "approved"
name = (am_name or "").strip()
return f"APPROVAL SIGNATURE: {name}" if approved and name else "APPROVAL SIGNATURE: PENDING"
# --------------------------------------------------------------------- builder
def build_form_context(
table_name: str,
label: str,
columns: tuple[str, ...],
rows: list[Row],
approval_status: str | None = None,
am_name: str | None = None,
approved_at: str | None = None,
) -> dict[str, object]:
"""Everything a form template needs, for all stored rows of ``table_name``."""
spec = FORMS.get(table_name)
grids: dict[str, dict[str, object]] = {}
extra: dict[str, object] = {}
if spec is None: # unknown table: print every stored column generically
identity = {"name", "employee_name", "headquarter", "month"}
spec = FormSpec(
"generic",
label.upper(),
tuple(
(
(f"{c.replace('_', ' ').upper()}:", c) if c in identity else None,
None,
)
for c in columns
if c in identity
),
)
cols = tuple(
Col(c.replace("_", " ").upper(), c, 100 / max(1, len(columns)))
for c in columns
if c not in {"id", "source_row_number"}
)
grids["main"] = _grid(cols, rows, min_rows=0)
elif spec.template == "daily_call_report_csv":
doctors = [r for r in rows if _has(r, _DOCTOR_FIELDS)]
chemists = [r for r in rows if _has(r, _CHEMIST_FIELDS)]
grids["doctors"] = _grid(_DOCTOR_COLS, doctors, min_rows=10, serial_field="doctor_sr_no")
grids["chemists"] = _grid(
_CHEMIST_COLS, chemists, min_rows=5, serial_field="chemist_sr_no", table_width=84
)
extra["stockist_visit"] = _distinct(rows, "stockist_visit")
extra["order_value"] = _distinct(rows, "order_value")
elif spec.template == "weekly_report":
extra["reports"] = [
{
"meta_rows": _meta_rows(spec.meta, [r]),
"summary": [(lbl, _text(r.get(f))) for lbl, f in _WEEKLY_SUMMARY],
"schemes": [(lbl, _text(r.get(f))) for lbl, f in _WEEKLY_SCHEMES],
}
for r in rows or [{}]
]
else:
grids["main"] = _grid(
spec.columns,
rows,
min_rows=spec.min_rows,
serial_field=spec.serial_field,
serial_dot=spec.serial_dot,
table_width=spec.table_width,
)
if table_name == "field_activity_report":
extra["doctor_call_avg"] = _distinct(rows, "doctor_call_avg")
extra["chemist_call_avg"] = _distinct(rows, "chemist_call_avg")
approval = None
if table_name in APPROVAL_FORMS:
line = approval_signature_line(table_name, approval_status, am_name)
value = line.split(": ", 1)[1]
approval = {
"line": line, "label": "APPROVAL SIGNATURE:", "value": value,
"when": approved_at if value != "PENDING" and approved_at else "",
# Once approved, the MR's own signature line carries their name too.
"mr_name": _distinct(rows, "name") if value != "PENDING" else "",
}
if spec.template == "weekly_report":
meta: list[list[tuple[str, str] | None]] = []
else:
meta = _meta_rows(spec.meta, rows)
return {
"template": spec.template,
"label": label,
"title": spec.title,
"full_letterhead": spec.full_letterhead,
"title_suffix": next((s[1] for pair in meta for s in pair if s and s[1]), ""),
"meta_rows": meta,
"grids": grids,
"approval": approval,
**extra,
}
# ------------------------------------------------------------- the filed Daily Call Report
_OUTCOME_NOTE = {"NOT_AVAILABLE": "Not available", "RESCHEDULED": "Rescheduled"}
def _doctor_remarks(call) -> str:
"""The remarks column; a visit that did not happen is flagged, since the form has no outcome column."""
note = _OUTCOME_NOTE.get(getattr(call.call_outcome, "value", str(call.call_outcome)), "")
return ". ".join(part for part in (note, (call.remarks or "").strip()) if part)
def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str] | None = None) -> dict[str, object]:
"""The approved Daily Call Report, laid out exactly like the printed company form.
Same template family, headings, column widths and number of ruled lines as the
``daily_call_report_csv`` company form: 10 doctor lines and 5 chemist lines, filled
from the top in visit order; more visits simply continue on the next page. The only
additions are the signatures: the MR's name, and (once approved) the Area Manager's
approval signature with its date and time.
"""
doctors = [
{
"doctor_name": c.doctor.name,
"qualification": c.doctor.qualification or "",
"product_promote": c.product_promote or "",
"product_sample": c.product_sample or "",
"remarks": _doctor_remarks(c),
}
for c in doctor_calls
]
chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_calls]
meta = [
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))],
]
return {
"template": "dcr",
"label": "Daily Call Report",
"title": "DAILY CALL REPORT",
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
"full_letterhead": True,
"meta_rows": meta,
"grids": {
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
},
"stockist_visit": dcr.stockist_visit or "",
"order_value": dcr.order_value or "",
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
}