phase-7: 8 operational reports, excel and csv exports, and print styles
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
import csv
|
||||
from io import BytesIO, StringIO
|
||||
from typing import Any
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from ..core.time_utils import format_datetime, utc_now
|
||||
|
||||
|
||||
def _format_filters_echo(filters_applied: dict[str, Any]) -> str:
|
||||
if not filters_applied:
|
||||
return "None"
|
||||
return ", ".join(f"{k}={v}" for k, v in filters_applied.items())
|
||||
|
||||
|
||||
def _format_summary_echo(summary: dict[str, Any]) -> str:
|
||||
if not summary:
|
||||
return ""
|
||||
return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items())
|
||||
|
||||
|
||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = report_payload["title"][:31]
|
||||
|
||||
title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}"
|
||||
meta_text = (
|
||||
f"Generated: {format_datetime(utc_now())} IST | "
|
||||
f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}"
|
||||
)
|
||||
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
||||
|
||||
ws.cell(row=1, column=1, value=title_text).font = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
||||
ws.cell(row=2, column=1, value=meta_text).font = Font(name="Calibri", size=10, color="475569")
|
||||
ws.cell(row=3, column=1, value=summary_text).font = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
|
||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||
|
||||
header_fill = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
header_font = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||
|
||||
header_row = 5
|
||||
col_widths: list[int] = []
|
||||
for c_idx, col in enumerate(columns, start=1):
|
||||
cell = ws.cell(row=header_row, column=c_idx, value=col["label"])
|
||||
cell.fill = header_fill
|
||||
cell.font = header_font
|
||||
cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
col_widths.append(len(str(col["label"])))
|
||||
|
||||
ws.freeze_panes = "A6"
|
||||
|
||||
for r_offset, row_data in enumerate(rows):
|
||||
excel_row = header_row + 1 + r_offset
|
||||
for c_idx, col in enumerate(columns, start=1):
|
||||
val = row_data.get(col["key"])
|
||||
if isinstance(val, bool):
|
||||
val = "Yes" if val else "No"
|
||||
ws.cell(row=excel_row, column=c_idx, value=val)
|
||||
val_len = len(str(val)) if val is not None else 0
|
||||
if val_len > col_widths[c_idx - 1]:
|
||||
col_widths[c_idx - 1] = val_len
|
||||
|
||||
for c_idx, width in enumerate(col_widths, start=1):
|
||||
ws.column_dimensions[get_column_letter(c_idx)].width = min(45, max(12, width + 3))
|
||||
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_csv(report_payload: dict[str, Any]) -> BytesIO:
|
||||
sio = StringIO()
|
||||
writer = csv.writer(sio)
|
||||
|
||||
writer.writerow([f"Poona Hospital & Research Centre - {report_payload['title']}"])
|
||||
writer.writerow(
|
||||
[
|
||||
f"Generated: {format_datetime(utc_now())} IST",
|
||||
f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}",
|
||||
]
|
||||
)
|
||||
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
||||
if summary_text:
|
||||
writer.writerow([f"Summary: {summary_text}"])
|
||||
writer.writerow([])
|
||||
|
||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||
|
||||
writer.writerow([col["label"] for col in columns])
|
||||
for row_data in rows:
|
||||
out_row = []
|
||||
for col in columns:
|
||||
val = row_data.get(col["key"])
|
||||
if isinstance(val, bool):
|
||||
val = "Yes" if val else "No"
|
||||
out_row.append("" if val is None else val)
|
||||
writer.writerow(out_row)
|
||||
|
||||
data = sio.getvalue().encode("utf-8-sig")
|
||||
buf = BytesIO(data)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
Reference in New Issue
Block a user