Files
celtic-life-science/app/pdf/forms.py
T
Shubhankar45 0d30c58bf0 Server backup 2026-11-07 of uncommitted work in projects/pharma-web-celtic
Snapshot of the working tree on srv1071960 (branch main), taken during
server cleanup. .env files, node_modules, builds, logs and media were excluded.
2026-11-07 05:43:12 +00:00

703 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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", "expense_statement"}
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 # a "\n" starts a second line in the printed heading
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("Stockist 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)\n(One Way)", "kilometers_km", 17.6, "center"),
),
serial_field="serial_no",
serial_dot=True,
),
"area_covered": FormSpec(
"area_covered",
"AREA COVERAGE",
_NAME_HQ_MONTH,
(
Col("AREA TO COVER", "area_to_cover", 40.0),
Col("SALE OBJECTIVE", "sale_objective", 30.0),
Col("STATUS", "status", 30.0, "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", 17.5, "center"),
Col("STATION WORKED", "station_worked", 33.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",
# No date: the statement is for a month, not a day.
(
(("NAME:", "name"), None),
(("HEADQUARTER:", "headquarter"), ("Month:", "month")),
),
(
_serial("Sl.No.", 7.0),
Col("Name of the Product", "product_name", 27.0),
Col("Value in PTS", "value_in_pts", 15.0, "center"),
Col("Opening", "opening", 13.0, "center"),
Col("Receipt", "receipt", 13.0, "center"),
Col("Sale", "sale", 12.5, "center"),
Col("Closing", "closing", 12.5, "center"),
),
min_rows=26,
serial_field="serial_no",
),
"sales_projection": FormSpec(
"sales_projection",
"SALES PROJECTION",
_NAME_HQ_MONTH,
(
# Printed under two group headings: CLOSING and PROJECTION (see the template).
_serial("SL. No.", 7.0),
Col("NAME OF THE PRODUCT", "product_name", 29.0),
Col("PTS", "pts", 12.0, "center"),
Col("QUANTITY", "closing_qty", 13.0, "center"),
Col("VALUE", "closing_value", 13.0, "center"),
Col("QUANTITY", "projection_qty", 13.0, "center"),
Col("VALUE", "projection_value", 13.0, "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,
),
"expense_statement": FormSpec(
"expense_statement",
"Expenses Statement",
(
(("Name", "name"), ("Designation", "designation")),
(("H.Q.", "headquarter"), None),
),
min_rows=27,
serial_field="serial_no",
),
"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)
# The morning day plan: who the MR intends to visit, and when. No outcomes yet.
_PLAN_DOCTOR_COLS = (
_serial("SR. NO.", 8.6),
Col("DR. NAME", "doctor_name", 32.0),
Col("QUALIFICATION", "qualification", 17.0),
Col("PLANNED TIME", "planned_time", 14.0, "center"),
Col("REMARKS", "remarks", 28.4),
)
_PLAN_CHEMIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE CHEMIST", "chemist_name", 52.8),
Col("PLANNED TIME", "planned_time", 37.0, "center"),
)
# Stockist visits: printed only when the report has any, so other reports keep their layout.
_STOCKIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE STOCKIST", "stockist_name", 32.8),
Col("POB", "pob", 57.0),
)
_PLAN_STOCKIST_COLS = (
_serial("SR. NO.", 10.2),
Col("NAME OF THE STOCKIST", "stockist_name", 52.8),
Col("PLANNED TIME", "planned_time", 37.0, "center"),
)
# End-of-day report: the planned visits that were not made, and why.
_MISSED_COLS = (
_serial("SR. NO.", 8.6),
Col("NAME", "name", 33.0),
Col("TYPE", "kind", 14.0, "center"),
Col("REASON NOT VISITED", "reason", 44.4),
)
# Expense Statement: money columns print as Rs | P pairs, like the printed form.
_EXPENSE_COLS = (
_serial("", 3.0),
Col("DATE", "report_date", 8.6, "center"),
Col("From", "from_location", 11.6),
Col("To", "to_location", 11.6),
Col("Rs", "fare_rs", 6.0, "right"),
Col("P.", "fare_p", 3.2, "center"),
Col("H.Q", "da_hq", 5.6, "right"),
Col("EX", "da_ex", 5.6, "right"),
Col("OUT", "da_out", 5.6, "right"),
Col("Rs", "postage_rs", 5.4, "right"),
Col("P.", "postage_p", 3.2, "center"),
Col("Rs", "other_expense_rs", 6.0, "right"),
Col("P.", "other_expense_p", 3.2, "center"),
Col("Rs", "total_rs", 7.0, "right"),
Col("P.", "total_p", 3.2, "center"),
Col("Business Achived", "business_achieved", 11.2, "center"),
)
_EXPENSE_SPLIT = ("fare", "postage", "other_expense", "total")
_EXPENSE_WHOLE = ("da_hq", "da_ex", "da_out")
_EXPENSE_AMOUNTS = ("fare", "da_hq", "da_ex", "da_out", "postage", "other_expense")
_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:
day = date.fromisoformat(text[:10])
# Core Doctor Call Conversion prints just the day of the month (13, 25…).
return str(day.day) if field == "date_of_visit" else day.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 _amount(value: object) -> float | None:
text = _text(value).replace(",", "")
try:
return float(text) if text else None
except ValueError:
return None
def _rupees(amount: float | None) -> tuple[str, str]:
"""(Rs, P) as the printed form splits money: 1234.5 -> ("1234", "50")."""
if amount is None:
return "", ""
paise = round(amount * 100)
return str(paise // 100), f"{paise % 100:02d}"
def _whole(amount: float | None) -> str:
if amount is None:
return ""
return f"{amount:.0f}" if amount == int(amount) else f"{amount:.2f}"
def call_average(rows: list[Row], field: str) -> str:
"""Field Activity Report: calls in `field` summed over the days worked, divided by those days.
A working day is a distinct date with a row (rows without a date count one day each); the MR
never types an average — it is always worked out from the figures."""
days = {_text(r.get("report_date"))[:10] or f"row-{i}" for i, r in enumerate(rows) if _has(r, ("report_date", field))}
if not days:
return ""
total = sum(v for v in (_amount(r.get(field)) for r in rows) if v is not None)
average = round(total / len(days), 2)
return f"{average:g}" if average == int(average) else f"{average:.2f}"
def _sales_projection_totals(rows: list[Row]) -> list[str]:
"""The TOTAL line under the Sales Projection: one sum per figure column (blank when nothing is filled in)."""
totals: list[str] = []
for field in ("closing_qty", "closing_value", "projection_qty", "projection_value"):
values = [v for v in (_amount(r.get(field)) for r in rows) if v is not None]
totals.append(_whole(round(sum(values), 2)) if values else "")
return totals
def _expense_row(row: Row) -> Row:
out: Row = dict(row)
amounts = {f: _amount(row.get(f)) for f in _EXPENSE_AMOUNTS}
# The total is always the sum of the day's amounts, whatever was stored.
present = [a for a in amounts.values() if a is not None]
amounts["total"] = sum(present) if present else None
for field in _EXPENSE_SPLIT:
out[f"{field}_rs"], out[f"{field}_p"] = _rupees(amounts[field])
for field in _EXPENSE_WHOLE:
if amounts[field] is not None:
out[field] = _whole(amounts[field])
return out
def _expense_totals(rows: list[Row]) -> dict[str, str]:
"""The TOTAL line under the table, one figure per money column."""
sums: dict[str, float | None] = {}
for field in _EXPENSE_AMOUNTS:
values = [v for v in (_amount(r.get(field)) for r in rows) if v is not None]
sums[field] = sum(values) if values else None
present = [v for v in sums.values() if v is not None]
sums["total"] = sum(present) if present else None
totals: dict[str, str] = {}
for field in _EXPENSE_SPLIT:
totals[f"{field}_rs"], totals[f"{field}_p"] = _rupees(sums[field])
for field in _EXPENSE_WHOLE:
totals[field] = _whole(sums[field])
totals["claimed"] = f"{sums['total']:,.2f}" if sums["total"] is not None else ""
return totals
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,
renumber: bool = False,
) -> dict[str, object]:
"""Everything a form template needs, for all stored rows of ``table_name``.
``renumber``: for a table whose stored Sl. No. restarts at 1 each month (see
MONTH_NUMBERED_TABLES in app/csv_data/router.py), the caller sets this when the rows
span more than one month — e.g. every month printed together — so the stored numbers
(1, 2… 1, 2…) are ignored in favour of one plain running count over what is printed.
"""
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 == "expense_statement":
printed = [_expense_row(r) for r in rows]
grids["main"] = _grid(
_EXPENSE_COLS,
printed,
min_rows=spec.min_rows,
serial_field=None if renumber else spec.serial_field,
)
extra["sums"] = _expense_totals(rows)
dates = sorted(
{_text(r.get("report_date"))[:10] for r in rows if _text(r.get("report_date"))}
)
extra["period_from"] = _display("report_date", dates[0]) if dates else ""
extra["period_to"] = _display("report_date", dates[-1]) if dates else ""
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=None if renumber else spec.serial_field,
serial_dot=spec.serial_dot,
table_width=spec.table_width,
)
if table_name == "sales_projection":
extra["totals"] = _sales_projection_totals(rows)
if table_name == "field_activity_report":
extra["doctor_call_avg"] = call_average(rows, "no_of_doctors_called")
extra["chemist_call_avg"] = call_average(rows, "no_of_chemists_pds_called")
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,
and so is any gift given."""
note = _OUTCOME_NOTE.get(getattr(call.call_outcome, "value", str(call.call_outcome)), "")
# The printed form has no gift column either, so a gift is noted with the remarks.
gift = (getattr(call, "gift", None) or "").strip()
gift = f"Gift: {gift}" if gift else ""
return ". ".join(part for part in (note, gift, (call.remarks or "").strip()) if part)
def build_dcr_context(
dcr,
doctor_calls,
chemist_calls,
approval: dict[str, str] | None = None,
missed: list[Row] | None = None,
stockist_calls=(),
) -> 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 Business Manager's
approval signature with its date and time.
A morning day plan uses the same form with a PLANNED TIME column in place of the
visit details. An end-of-day report adds the planned visits that were not made
(``missed``: name / kind / reason rows).
"""
report_type = getattr(dcr, "report_type", None)
report_type = getattr(report_type, "value", report_type)
if report_type == "PLAN":
return _build_plan_context(dcr, doctor_calls, chemist_calls, approval, stockist_calls)
is_self = report_type == "SELF" # an Area Business Manager's own report: no approval signature
doctors = [
{
"doctor_name": c.doctor.name,
"qualification": c.doctor.qualification or "",
"product_promote": _products(c.product_promote),
"product_sample": _products(c.product_sample),
"remarks": _doctor_remarks(c),
}
for c in doctor_calls
]
chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_calls]
stockists = [{"stockist_name": c.stockist.name, "pob": c.pob or ""} for c in stockist_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 (Self)" if is_self else "Daily Call Report",
"title": "DAILY CALL REPORT (SELF)" if is_self else "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),
**(
{"stockists": _grid(_STOCKIST_COLS, stockists, min_rows=0, table_width=84)}
if stockists
else {}
),
**({"missed": _grid(_MISSED_COLS, missed, min_rows=0)} if missed else {}),
},
"is_plan": False,
"stockist_visit": dcr.stockist_visit or "",
"order_value": dcr.order_value or "",
"signer_label": "Area Business Manager Signature" if is_self else "MR Signature",
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
}
def _products(names: list[str] | str | None) -> str:
"""Several products share one cell of the printed form."""
return names if isinstance(names, str) else ", ".join(names or [])
def _build_plan_context(
dcr, doctor_calls, chemist_calls, approval, stockist_calls=()
) -> dict[str, object]:
doctors = [
{
"doctor_name": c.doctor.name,
"qualification": c.doctor.qualification or "",
"planned_time": c.visit_time.strftime("%H:%M"),
"remarks": (c.remarks or "").strip(),
}
for c in doctor_calls
]
chemists = [
{"chemist_name": c.chemist.name, "planned_time": c.visit_time.strftime("%H:%M")}
for c in chemist_calls
]
stockists = [
{"stockist_name": c.stockist.name, "planned_time": c.visit_time.strftime("%H:%M")}
for c in stockist_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 (Plan)",
"title": "DAILY CALL REPORT (PLAN)",
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
"full_letterhead": True,
"meta_rows": meta,
"grids": {
"doctors": _grid(_PLAN_DOCTOR_COLS, doctors, min_rows=10),
"chemists": _grid(_PLAN_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
**(
{"stockists": _grid(_PLAN_STOCKIST_COLS, stockists, min_rows=0, table_width=84)}
if stockists
else {}
),
},
"is_plan": True,
"stockist_visit": "",
"order_value": "",
"mr_remarks": dcr.mr_remarks or "",
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
"approval": approval,
}