--
This commit is contained in:
+248
-48
@@ -17,7 +17,7 @@ from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
DATE_FIELDS = {"report_date", "date_of_visit"}
|
||||
APPROVAL_FORMS = {"standard_tour_plan", "tour_plan", "fare_chart"}
|
||||
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"}
|
||||
|
||||
@@ -27,7 +27,7 @@ Meta = tuple[str, str] | None # (printed label, column) — None leaves the slo
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Col:
|
||||
header: str
|
||||
header: str # a "\n" starts a second line in the printed heading
|
||||
field: str
|
||||
width: float # percent of the table
|
||||
align: str = "left"
|
||||
@@ -94,20 +94,19 @@ FORMS: dict[str, FormSpec] = {
|
||||
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"),
|
||||
Col("Kilometers (KM)\n(One Way)", "kilometers_km", 17.6, "center"),
|
||||
),
|
||||
serial_field="serial_no",
|
||||
serial_dot=True,
|
||||
),
|
||||
"area_covered": FormSpec(
|
||||
"area_covered",
|
||||
"AREA COVERED",
|
||||
"AREA COVERAGE",
|
||||
_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"),
|
||||
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,
|
||||
@@ -130,8 +129,8 @@ FORMS: dict[str, FormSpec] = {
|
||||
"FIELD ACTIVITY REPORT",
|
||||
_NAME_HQ_MONTH,
|
||||
(
|
||||
Col("DATE", "report_date", 14.5, "center"),
|
||||
Col("STATION WORKED", "station_worked", 36.6),
|
||||
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"),
|
||||
),
|
||||
@@ -142,15 +141,19 @@ FORMS: dict[str, FormSpec] = {
|
||||
"sales_and_stock_statement": FormSpec(
|
||||
"sales_and_stock_statement",
|
||||
"SALES AND STOCK STATEMENT",
|
||||
_NAME_HQ_DATE_MONTH,
|
||||
# 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", 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"),
|
||||
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",
|
||||
@@ -160,17 +163,14 @@ FORMS: dict[str, FormSpec] = {
|
||||
"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"),
|
||||
# Header text is filled in per report from the "month" column — see
|
||||
# _sales_projection_columns — never a hardcoded month.
|
||||
Col("SALES", "aug_sales", 9.6, "center"),
|
||||
Col("VALUE", "value_2", 9.5, "center"),
|
||||
# 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",
|
||||
@@ -181,6 +181,16 @@ FORMS: dict[str, FormSpec] = {
|
||||
"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",
|
||||
@@ -208,6 +218,49 @@ _CHEMIST_COLS = (
|
||||
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"),
|
||||
)
|
||||
# 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"),
|
||||
@@ -234,7 +287,9 @@ def _display(field: str, value: object) -> str:
|
||||
text = _text(value)
|
||||
if field in DATE_FIELDS and text:
|
||||
try:
|
||||
return date.fromisoformat(text[:10]).strftime("%d/%m/%Y")
|
||||
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
|
||||
@@ -254,12 +309,79 @@ def _has(row: Row, fields: tuple[str, ...]) -> bool:
|
||||
return any(_text(row.get(field)) for field in fields)
|
||||
|
||||
|
||||
def _sales_projection_columns(cols: tuple[Col, ...], rows: list[Row]) -> tuple[Col, ...]:
|
||||
"""The printed form's "<Month>. Sales" column: the month it prints is whichever
|
||||
month the rows were actually filled in for, never a fixed month."""
|
||||
month = _distinct(rows, "month")
|
||||
header = f"{month[:3].upper()}. SALES" if month else "SALES"
|
||||
return tuple(Col(header, c.field, c.width, c.align) if c.field == "aug_sales" else c for c in cols)
|
||||
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(
|
||||
@@ -367,6 +489,20 @@ def build_form_context(
|
||||
)
|
||||
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"] = [
|
||||
{
|
||||
@@ -377,20 +513,19 @@ def build_form_context(
|
||||
for r in rows or [{}]
|
||||
]
|
||||
else:
|
||||
columns = spec.columns
|
||||
if table_name == "sales_projection":
|
||||
columns = _sales_projection_columns(columns, rows)
|
||||
grids["main"] = _grid(
|
||||
columns,
|
||||
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"] = _distinct(rows, "doctor_call_avg")
|
||||
extra["chemist_call_avg"] = _distinct(rows, "chemist_call_avg")
|
||||
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:
|
||||
@@ -426,12 +561,22 @@ _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."""
|
||||
"""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)), "")
|
||||
return ". ".join(part for part in (note, (call.remarks or "").strip()) if part)
|
||||
# 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) -> dict[str, object]:
|
||||
def build_dcr_context(
|
||||
dcr,
|
||||
doctor_calls,
|
||||
chemist_calls,
|
||||
approval: dict[str, str] | None = None,
|
||||
missed: list[Row] | 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
|
||||
@@ -439,13 +584,22 @@ def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str]
|
||||
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.
|
||||
|
||||
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)
|
||||
is_self = report_type == "SELF" # an Area Manager's own report: no approval signature
|
||||
doctors = [
|
||||
{
|
||||
"doctor_name": c.doctor.name,
|
||||
"qualification": c.doctor.qualification or "",
|
||||
"product_promote": c.product_promote or "",
|
||||
"product_sample": c.product_sample or "",
|
||||
"product_promote": _products(c.product_promote),
|
||||
"product_sample": _products(c.product_sample),
|
||||
"remarks": _doctor_remarks(c),
|
||||
}
|
||||
for c in doctor_calls
|
||||
@@ -457,17 +611,63 @@ def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str]
|
||||
]
|
||||
return {
|
||||
"template": "dcr",
|
||||
"label": "Daily Call Report",
|
||||
"title": "DAILY CALL REPORT",
|
||||
"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),
|
||||
**({"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 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) -> 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
|
||||
]
|
||||
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),
|
||||
},
|
||||
"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,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user