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
+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
}
+236
View File
@@ -0,0 +1,236 @@
"""Approved-report and company-form PDF generation.
WeasyPrint (BSD-3-Clause) renders Jinja2 HTML templates, so every layout is plain
HTML/CSS that anyone on the team can edit. The approved Daily Call Report and every
company form (tour plan, fare chart, sales & stock, ...) extend
``templates/forms/_form_base.html``, because each is a copy of the company's printed form;
each has its own template (``dcr.html`` or one under ``templates/forms/``). What a form
shows is decided in ``app.pdf.forms``.
WeasyPrint needs system libraries (Pango, HarfBuzz) and DejaVu fonts. They are pinned in
the Dockerfile. If they are genuinely absent (a bare dev machine, CI without the apt
step) the service falls back to a minimal built-in writer so the workflow still
completes and tests still run — and logs a loud warning, because that fallback
produces a plain-text PDF, not the designed layout. Production must have WeasyPrint;
``pdf_engine_ready()`` lets the health check and startup log say so.
"""
import logging
import uuid
from html.parser import HTMLParser
from pathlib import Path
from zoneinfo import ZoneInfo
from jinja2 import Environment, FileSystemLoader, select_autoescape
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.common.enums import AuditAction, EntityType
from app.config.settings import settings
from app.pdf.forms import approval_signature_line, build_dcr_context, build_form_context
from app.reports.models import DailyCallReport
from app.users.models import User
logger = logging.getLogger(__name__)
_TEMPLATE_DIR = Path(__file__).parent / "templates"
_env = Environment(
loader=FileSystemLoader(_TEMPLATE_DIR),
autoescape=select_autoescape(["html"]),
)
_env.globals.update(
company_name=settings.PDF_COMPANY_NAME,
company_address=settings.PDF_COMPANY_ADDRESS,
company_website=settings.PDF_COMPANY_WEBSITE,
company_email=settings.PDF_COMPANY_EMAIL,
company_phone=settings.PDF_COMPANY_PHONE,
)
try: # pragma: no cover - depends on system libraries
from weasyprint import HTML as _WeasyHTML
WEASYPRINT_AVAILABLE = True
except Exception: # noqa: BLE001 - ImportError or OSError from missing libs
_WeasyHTML = None
WEASYPRINT_AVAILABLE = False
def pdf_engine_ready() -> bool:
"""True when the designed (WeasyPrint) layout can be rendered."""
return WEASYPRINT_AVAILABLE
def _minimal_pdf(text: str) -> bytes:
"""Fallback renderer: a valid single-page PDF containing plain text.
Used ONLY when WeasyPrint's system libraries are unavailable. It exists so the
approval workflow and its tests never depend on native libraries being present.
"""
lines = [ln[:95] for ln in text.splitlines()][:52]
content = ["BT", "/F1 9 Tf", "40 780 Td", "11 TL"]
for line in lines:
escaped = line.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")
content.append(f"({escaped}) Tj T*")
content.append("ET")
stream = "\n".join(content).encode("latin-1", "replace")
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] "
b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
]
out = bytearray(b"%PDF-1.4\n")
offsets = [0]
for i, body in enumerate(objects, start=1):
offsets.append(len(out))
out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n"
xref_pos = len(out)
out += f"xref\n0 {len(objects) + 1}\n".encode()
out += b"0000000000 65535 f \n"
for off in offsets[1:]:
out += f"{off:010d} 00000 n \n".encode()
out += (
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
f"startxref\n{xref_pos}\n%%EOF\n"
).encode()
return bytes(out)
class _TextExtractor(HTMLParser):
"""Flattens a rendered form to lines of text for the plain-text fallback."""
_SKIP = {"style", "title", "script"}
_BREAK = {"tr", "div", "h1", "h2", "p", "br", "table"}
def __init__(self) -> None:
super().__init__()
self.parts: list[str] = []
self._skipping = 0
def handle_starttag(self, tag: str, attrs: list) -> None:
if tag in self._SKIP:
self._skipping += 1
def handle_endtag(self, tag: str) -> None:
if tag in self._SKIP:
self._skipping -= 1
elif tag in {"td", "th"}:
self.parts.append(" | ")
elif tag in self._BREAK:
self.parts.append("\n")
def handle_data(self, data: str) -> None:
if not self._skipping and data.strip():
self.parts.append(" ".join(data.split()) + " ")
def _html_to_text(html: str) -> str:
parser = _TextExtractor()
parser.feed(html)
lines = ("".join(parser.parts)).splitlines()
cleaned = (" ".join(line.split()).strip(" |") for line in lines)
return "\n".join(line for line in cleaned if line)
def _approval_signature_line(
table_name: str,
approval_status: str | None = None,
am_name: str | None = None,
am_role: str = "Area Manager",
) -> str:
return approval_signature_line(table_name, approval_status, am_name)
def csv_table_pdf_bytes(
table_name: str,
table_label: str,
columns: tuple[str, ...],
rows: list[dict[str, object]],
approval_status: str | None = None,
am_name: str | None = None,
am_role: str = "Area Manager",
approved_at: str | None = None,
) -> bytes:
"""Render every stored row of an imported table on its own company-form layout."""
context = build_form_context(
table_name, table_label, columns, rows, approval_status, am_name, approved_at
)
html = _env.get_template(f"forms/{context['template']}.html").render(**context)
if WEASYPRINT_AVAILABLE:
return _WeasyHTML(string=html).write_pdf()
logger.warning(
"WeasyPrint unavailable — using the plain-text fallback renderer for %s. "
"Install Pango/HarfBuzz (see Dockerfile) before production use.",
table_name,
)
return _minimal_pdf(_html_to_text(html))
def csv_pdf_bytes(table_label: str, row: dict[str, object]) -> bytes:
"""Render one imported table row for the row-level PDF action."""
columns = tuple(key for key in row if key not in {"id", "source_row_number"})
return csv_table_pdf_bytes("row", table_label, columns, [row])
class PDFService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def _approval(self, dcr: DailyCallReport) -> dict[str, str] | None:
"""Who approved the report and when, from the audit trail — the signature cannot be typed in."""
if dcr.approved_at is None:
return None
approvals = [h for h in await self.audit.approval_history_for(dcr.id) if h.action == AuditAction.APPROVE]
if not approvals:
return None
approver = await self.db.get(User, approvals[-1].actor_user_id)
if approver is None:
return None
when = dcr.approved_at.astimezone(ZoneInfo(settings.APP_TIMEZONE)).strftime("%d/%m/%Y %H:%M")
return {"name": approver.full_name, "at": when}
async def _context(self, dcr: DailyCallReport) -> dict:
return build_dcr_context(
dcr,
sorted(dcr.doctor_calls, key=lambda c: c.visit_time),
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
await self._approval(dcr),
)
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
"""The report as a PDF in the current layout — a pure function of the stored report."""
context = await self._context(dcr)
html = _env.get_template("dcr.html").render(**context)
if WEASYPRINT_AVAILABLE:
return _WeasyHTML(string=html).write_pdf()
logger.warning(
"WeasyPrint unavailable — using the plain-text fallback renderer. "
"Install Pango/cairo (see Dockerfile) before production use."
)
return _minimal_pdf(_env.get_template("dcr.txt").render(**context))
async def render_and_store(self, dcr: DailyCallReport, approver: User) -> str:
pdf_bytes = await self.render_bytes(dcr)
directory = Path(settings.PDF_STORAGE_PATH) / str(dcr.report_date.year)
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"DCR-{dcr.report_date.isoformat()}-{dcr.id}.pdf"
path.write_bytes(pdf_bytes)
await self.audit.log(
actor_user_id=approver.id,
entity_type=EntityType.DCR,
entity_id=dcr.id,
action=AuditAction.UPDATE,
after={"pdf_generated": str(path)},
)
return str(path)
+46
View File
@@ -0,0 +1,46 @@
{# The approved Daily Call Report — a copy of the company's printed form, filled in. #}
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 6mm 0 3mm; font-size: 13pt; text-decoration: none; letter-spacing: .3px; }
table.grid th { height: 7.5mm; font-size: 9pt; }
table.grid td { font-size: 10pt; }
h2.section { margin: 6mm 0 1.5mm; text-align: center; font-size: 11pt; }
.visit { margin: 6mm 0 0 14mm; font-size: 10.5pt; line-height: 1.7; }
.visit b { display: inline-block; min-width: 30mm; }
table.dcr-sign { width: 100%; margin-top: 12mm; border-collapse: collapse; page-break-inside: avoid; }
table.dcr-sign td { vertical-align: top; padding: 0; }
table.dcr-sign td.mr { width: 52%; padding-left: 14mm; }
.sign-label { font-size: 10.5pt; font-weight: bold; }
.signed { display: inline-block; min-width: 62mm; margin-top: 4mm; padding-bottom: 1mm; border-bottom: .7pt solid #000; font-family: "Liberation Serif", "Times New Roman", serif; font-style: italic; font-size: 12pt; }
.signed-when { margin-top: 1.2mm; font-size: 8.5pt; }
{% endblock %}
{% block form %}
{{ grid(grids.doctors, left=True) }}
<h2 class="section">CHEMIST VISIT</h2>
{{ grid(grids.chemists, left=True) }}
<div class="visit">
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
<div><b>ORDER :</b> {{ order_value }}</div>
</div>
{% endblock %}
{% block signature %}
<table class="dcr-sign">
<tr>
<td class="mr">
<div class="sign-label">MR Signature</div>
<div class="signed">{{ mr_signed }}</div>
</td>
<td class="am">
{% if approval %}
<div class="sign-label">APPROVAL SIGNATURE:</div>
<div class="signed">{{ approval.name }}</div>
<div class="signed-when">Area Manager &middot; {{ approval.at }}</div>
{% endif %}
</td>
</tr>
</table>
{% endblock %}
+19
View File
@@ -0,0 +1,19 @@
{{ company_name }}
{{ company_address }}
Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_phone }}
DAILY CALL REPORT
{% for pair in meta_rows %}{% for slot in pair %}{% if slot %}{{ slot[0] }} {{ slot[1] }} {% endif %}{% endfor %}
{% endfor %}
SR.NO | DR. NAME | QUALIFICATION | PRODUCT PROMOTE | PRODUCT SAMPLE | REMARKS
{% for r in grids.doctors.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
CHEMIST VISIT
SR.NO | NAME OF THE CHEMIST | POB
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
{% endfor %}
STOCKIST VISIT : {{ stockist_visit }}
ORDER : {{ order_value }}
MR Signature: {{ mr_signed }}
{% if approval %}APPROVAL SIGNATURE: {{ approval.name }} ({{ approval.at }})
{% endif %}
+108
View File
@@ -0,0 +1,108 @@
{# Base for every company form. Standalone on purpose: the forms copy the printed
originals and must not inherit the DCR report's look (base.html). #}
{% from "forms/_macros.html" import letterhead, meta_block, grid, sign_right, sign_approval %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ label }}{% if title_suffix %} — {{ title_suffix }}{% endif %}</title>
<style>
@page {
size: A4;
margin: 12mm 16mm;
{% block page_box %}{% endblock %}
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Carlito, Calibri, "Liberation Sans", "DejaVu Sans", sans-serif;
font-size: 11.5pt;
line-height: 1.2;
color: #000;
}
.company { text-align: center; }
.company .name {
font-family: "Liberation Sans", Arial, Helvetica, "DejaVu Sans", sans-serif;
font-size: 21pt;
font-weight: bold;
line-height: 1.15;
color: #000;
}
.company .line { font-size: 11pt; line-height: 1.35; }
h1.title {
margin: 7mm 0 4mm;
text-align: center;
font-size: 18pt;
line-height: 1.1;
text-decoration: underline;
}
table.meta { width: 100%; border-collapse: collapse; margin: 0 0 2.5mm; }
table.meta td { padding: .6mm 0; font-size: 12pt; vertical-align: top; }
table.meta td.ml { width: 62%; padding-left: 1.5mm; }
table.grid { border-collapse: collapse; table-layout: fixed; margin: 0 auto; }
table.grid.left { margin: 0; }
table.grid th, table.grid td { border: .7pt solid #000; padding: 0 1.6mm; }
table.grid th {
background: #fff;
height: 9mm;
font-size: 11.5pt;
line-height: 1.15;
text-align: center;
}
table.grid td {
height: 6.4mm;
font-size: 11.5pt;
line-height: 1.15;
vertical-align: middle;
overflow-wrap: anywhere;
}
table.grid tr { page-break-inside: avoid; }
th.l, td.l { text-align: left; }
th.c, td.c { text-align: center; }
th.r, td.r { text-align: right; }
/* A fill-in line: the printed underscore rule, holding the value when there is one. */
.ln {
display: inline-block;
min-width: 42mm;
height: 4.4mm;
border-bottom: .7pt solid #000;
text-align: center;
font-weight: normal;
vertical-align: bottom;
}
.sign-right {
margin: 16mm 0 0 68%;
font-size: 10.5pt;
font-weight: bold;
page-break-inside: avoid;
}
table.sign-approval { width: 100%; margin-top: 14mm; border-collapse: collapse; page-break-inside: avoid; }
table.sign-approval td { padding: 0; font-size: 8.5pt; font-weight: bold; }
table.sign-approval td:first-child { width: 56%; }
table.sign-approval .sign-when { margin: 1.5mm 0 0 0; font-size: 8pt; font-weight: normal; text-align: right; }
table.sign-approval .ln { font-size: 9pt; }
{% block form_styles %}{% endblock %}
</style>
</head>
<body>
{% block body %}
{{ letterhead(full_letterhead) }}
<h1 class="title">{{ title }}</h1>
{{ meta_block(meta_rows) }}
{% block form %}{% endblock %}
{% block signature %}{{ sign_right() }}{% endblock %}
{% endblock %}
</body>
</html>
+56
View File
@@ -0,0 +1,56 @@
{# Building blocks shared by the company-form PDFs. Each mirrors a part of the printed form. #}
{% macro letterhead(full) %}
<div class="company">
<div class="name">{{ company_name }}</div>
{% if full %}
<div class="line">{{ company_address }}</div>
<div class="line">Website: {{ company_website }} E-Mail:{{ company_email }}</div>
<div class="line">PHONE: {{ company_phone }}</div>
{% endif %}
</div>
{% endmacro %}
{# NAME / HEADQUARTER on the left, DATE / MONTH on the right — empty slots stay empty. #}
{% macro meta_block(rows) %}
{% if rows %}
<table class="meta">
{% for pair in rows %}
<tr>
{% for slot in pair %}
<td class="{{ 'ml' if loop.first else 'mr' }}">{% if slot %}<b>{{ slot[0] }}</b> {{ slot[1] }}{% endif %}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endif %}
{% endmacro %}
{% macro grid(g, left=False) %}
<table class="grid{% if left %} left{% endif %}" style="width:{{ g.width }}">
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
<thead>
<tr>{% for h in g.headers %}<th>{{ h }}</th>{% endfor %}</tr>
</thead>
<tbody>
{% for r in g.rows %}
<tr>{% for c in r.cells %}<td class="{{ g.aligns[loop.index0] }}">{{ c }}</td>{% endfor %}</tr>
{% endfor %}
</tbody>
</table>
{% endmacro %}
{# "SIGNATURE" alone, low on the right — the sales / activity / call-report forms. #}
{% macro sign_right(text="SIGNATURE") %}
<div class="sign-right">{{ text }}</div>
{% endmacro %}
{# Tour plan, standard tour plan and fare chart: MR signature plus the AM approval. #}
{% macro sign_approval(approval) %}
<table class="sign-approval">
<tr>
<td>SIGNATURE: <span class="ln">{{ approval.mr_name }}</span></td>
<td>{{ approval.label }} <span class="ln">{{ approval.value }}</span>{% if approval.when %}<div class="sign-when">{{ approval.when }}</div>{% endif %}</td>
</tr>
</table>
{% endmacro %}
+11
View File
@@ -0,0 +1,11 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 0 0 5mm; font-size: 10pt; }
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,11 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 0 0 5mm; font-size: 10pt; }
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,24 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { margin: 6mm 0 3mm; font-size: 13pt; text-decoration: none; letter-spacing: .3px; }
table.grid th { height: 7.5mm; font-size: 9pt; }
table.grid td { font-size: 10pt; }
h2.section { margin: 6mm 0 1.5mm; text-align: center; font-size: 11pt; }
.visit { margin: 6mm 0 0 14mm; font-size: 10.5pt; line-height: 1.7; }
.visit b { display: inline-block; min-width: 30mm; }
.sign-left { margin: 12mm 0 0 14mm; font-size: 10.5pt; font-weight: bold; }
{% endblock %}
{% block form %}
{{ grid(grids.doctors, left=True) }}
<h2 class="section">CHEMIST VISIT</h2>
{{ grid(grids.chemists, left=True) }}
<div class="visit">
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
<div><b>ORDER :</b> {{ order_value }}</div>
</div>
{% endblock %}
{% block signature %}<div class="sign-left">MR Signature</div>{% endblock %}
+8
View File
@@ -0,0 +1,8 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_approval %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
@@ -0,0 +1,20 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_right %}
{% block form_styles %}
h1.title { margin: 0 0 5mm; font-size: 13pt; }
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
table.avg { width: 100%; margin-top: 7mm; border-collapse: collapse; }
table.avg td { padding: 0; font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 9.5pt; font-weight: bold; white-space: nowrap; }
table.avg .ln { min-width: 44mm; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
<table class="avg">
<tr>
<td>DOCTOR CALL AVG <span class="ln">{{ doctor_call_avg }}</span></td>
<td>CHEMIST CALL AVG. <span class="ln">{{ chemist_call_avg }}</span></td>
</tr>
</table>
{% endblock %}
+6
View File
@@ -0,0 +1,6 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,11 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{% block form_styles %}
h1.title { font-size: 14pt; margin: 6mm 0 3mm; }
table.grid th { font-size: 11pt; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,20 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid %}
{# Arial throughout, title tucked directly under the company name — as printed. #}
{% block form_styles %}
.company .name { font-size: 20pt; }
h1.title {
margin: 0 0 4mm;
font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif;
font-size: 14pt;
}
table.grid th, table.grid td { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; }
table.grid th { height: 10mm; font-size: 9.5pt; }
table.grid td { font-size: 9.5pt; }
table.grid td:nth-child(2) { font-weight: bold; }
{% endblock %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
@@ -0,0 +1,8 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_approval %}
{% block form %}
{{ grid(grids.main, left=True) }}
{% endblock %}
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
+8
View File
@@ -0,0 +1,8 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import grid, sign_approval %}
{% block form %}
{{ grid(grids.main) }}
{% endblock %}
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
@@ -0,0 +1,64 @@
{% extends "forms/_form_base.html" %}
{% from "forms/_macros.html" import letterhead, sign_right %}
{# The weekly report is boxed: the whole page carries a border, as printed. #}
{% block page_box %}margin: 8mm; padding: 9mm 8mm 6mm; border: .8pt solid #000;{% endblock %}
{% macro items(rows, label_width) %}
<table class="items">
{% for label, value in rows %}
<tr>
<td class="bul">o</td>
<td class="lbl" style="width:{{ label_width }}">{{ label }}</td>
<td>: <span class="ln">{{ value }}</span></td>
</tr>
{% endfor %}
</table>
{% endmacro %}
{% block form_styles %}
.weekly + .weekly { page-break-before: always; }
.weekly h1.title { margin: 2mm 0 0; font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 11pt; }
table.wmeta { width: 100%; margin: 9mm 0 7mm; border: .75pt solid #000; border-collapse: collapse; }
table.wmeta td { padding: 1.4mm 3mm; font-size: 10.5pt; }
table.wmeta td:first-child { width: 68%; }
.weekly h2 {
margin: 0 0 .6mm;
font-family: "Liberation Serif", "Times New Roman", "DejaVu Serif", serif;
font-size: 11.5pt;
}
.weekly h2.gap { margin-top: 2mm; }
table.items { width: 100%; margin: 0 0 4mm; border: .75pt solid #000; border-collapse: collapse; }
table.items td {
padding: .5mm 0;
font-family: "Liberation Serif", "Times New Roman", "DejaVu Serif", serif;
font-size: 11pt;
line-height: 1.25;
white-space: nowrap;
}
table.items tr:last-child td { padding-bottom: 2mm; }
table.items td.bul { width: 9mm; padding-left: 3mm; font-family: "Liberation Mono", "Courier New", monospace; }
table.items .ln { min-width: 60mm; text-align: left; height: 4.6mm; }
.weekly .sign-right { margin-top: 26mm; font-size: 10.5pt; }
{% endblock %}
{% block body %}
{% for report in reports %}
<div class="weekly">
{{ letterhead(false) }}
<h1 class="title" style="text-decoration: underline">{{ title }}</h1>
<table class="wmeta">
{% for pair in report.meta_rows %}
<tr>
{% for slot in pair %}<td><b>{{ slot[0] }}</b> {{ slot[1] }}</td>{% endfor %}
</tr>
{% endfor %}
</table>
<h2>1. Work Summary &amp; Sales Performance</h2>
{{ items(report.summary, "40mm") }}
<h2 class="gap">2. Additional Schemes &amp; Projects</h2>
{{ items(report.schemes, "64mm") }}
{{ sign_right("Signature") }}
</div>
{% endfor %}
{% endblock %}