Files
poona-ams/backend/app/services/exports.py
T

271 lines
10 KiB
Python

import csv
from io import BytesIO, StringIO
import re
from typing import Any
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
from ..core.time_utils import format_datetime, utc_now
def _sanitize_sheet_title(title: str) -> str:
"""Sanitize Excel sheet title to comply with openpyxl / Excel naming rules."""
cleaned = re.sub(r'[\\/*?:\[\]]', '_', title or "Report").strip()
return cleaned[:31] or "Report"
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())
# Styling constants for executive Excel reports
_NAVY_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
_ZEBRA_FILL = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
_WHITE_FILL = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
_SUMMARY_FILL = PatternFill(start_color="EFF6FF", end_color="EFF6FF", fill_type="solid")
_TOTAL_FILL = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
_TITLE_FONT = Font(name="Calibri", size=14, bold=True, color="0F172A")
_META_FONT = Font(name="Calibri", size=9, italic=True, color="475569")
_SUMMARY_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
_HEADER_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
_DATA_FONT = Font(name="Calibri", size=10, color="0F172A")
_TOTAL_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
_THIN_SIDE = Side(style="thin", color="CBD5E1")
_CELL_BORDER = Border(left=_THIN_SIDE, right=_THIN_SIDE, top=_THIN_SIDE, bottom=_THIN_SIDE)
_HEADER_BORDER = Border(
left=Side(style="thin", color="334155"),
right=Side(style="thin", color="334155"),
top=Side(style="thin", color="334155"),
bottom=Side(style="medium", color="0F172A"),
)
_TOTAL_BORDER = Border(
left=_THIN_SIDE,
right=_THIN_SIDE,
top=Side(style="thin", color="94A3B8"),
bottom=Side(style="double", color="1E3A8A"),
)
def _detect_cell_format(col_key: str, col_label: str, val: Any) -> tuple[Alignment, str | None]:
"""Determine alignment and Excel number format from column metadata and value."""
key_lower = col_key.lower()
lbl_lower = col_label.lower()
# Currency / Financial costs
if any(k in key_lower or k in lbl_lower for k in ["cost", "value", "price", "amount", "budget", "estimate"]):
align = Alignment(horizontal="right", vertical="center")
num_fmt = '"₹"#,##0.00' if isinstance(val, float) else '"₹"#,##0'
return align, num_fmt
# Percentages
if any(k in key_lower or k in lbl_lower for k in ["pct", "percent", "rate", "uptime"]):
align = Alignment(horizontal="right", vertical="center")
num_fmt = '0.0"%"' if isinstance(val, (int, float)) else None
return align, num_fmt
# Numeric counts / durations / minutes
if isinstance(val, (int, float)) and not isinstance(val, bool):
align = Alignment(horizontal="right", vertical="center")
num_fmt = "#,##0" if isinstance(val, int) else "#,##0.0"
return align, num_fmt
# Dates, codes, status, IDs, booleans
if any(k in key_lower or k in lbl_lower for k in ["date", "code", "no", "status", "priority", "criticality", "mode"]):
align = Alignment(horizontal="center", vertical="center")
return align, None
# Text / Names / Descriptions
align = Alignment(horizontal="left", vertical="center")
return align, None
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
wb = Workbook()
ws = wb.active
ws.title = _sanitize_sheet_title(report_payload.get("title", "Report"))
# Explicitly show grid lines in Excel view
ws.views.sheetView[0].showGridLines = True
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", {}))
# Row 1: Hospital Title
ws.row_dimensions[1].height = 28
c1 = ws.cell(row=1, column=1, value=title_text)
c1.font = _TITLE_FONT
c1.alignment = Alignment(vertical="center")
# Row 2: Metadata & Filters
ws.row_dimensions[2].height = 18
c2 = ws.cell(row=2, column=1, value=meta_text)
c2.font = _META_FONT
c2.alignment = Alignment(vertical="center")
# Row 3: Summary KPIs strip
ws.row_dimensions[3].height = 24
c3 = ws.cell(row=3, column=1, value=summary_text)
c3.font = _SUMMARY_FONT
c3.fill = _SUMMARY_FILL
c3.border = Border(
top=Side(style="thin", color="BFDBFE"),
bottom=Side(style="thin", color="BFDBFE"),
left=Side(style="thin", color="BFDBFE"),
right=Side(style="thin", color="BFDBFE"),
)
c3.alignment = Alignment(vertical="center", indent=1)
# Row 4: Spacer
ws.row_dimensions[4].height = 10
columns: list[dict[str, str]] = report_payload.get("columns", [])
rows: list[dict[str, Any]] = report_payload.get("rows", [])
# Span summary strip styling across header columns
if columns and len(columns) > 1:
for c_idx in range(2, len(columns) + 1):
sc = ws.cell(row=3, column=c_idx)
sc.fill = _SUMMARY_FILL
sc.border = Border(
top=Side(style="thin", color="BFDBFE"),
bottom=Side(style="thin", color="BFDBFE"),
left=Side(style="thin", color="BFDBFE"),
right=Side(style="thin", color="BFDBFE"),
)
header_row = 5
ws.row_dimensions[header_row].height = 28
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 = _NAVY_HEADER_FILL
cell.font = _HEADER_FONT
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.border = _HEADER_BORDER
col_widths.append(len(str(col["label"])))
# Freeze header panes
ws.freeze_panes = "A6"
# Data rows
last_data_row = header_row
for r_offset, row_data in enumerate(rows):
excel_row = header_row + 1 + r_offset
last_data_row = excel_row
ws.row_dimensions[excel_row].height = 20
row_fill = _ZEBRA_FILL if r_offset % 2 == 1 else _WHITE_FILL
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"
cell = ws.cell(row=excel_row, column=c_idx, value=val)
cell.fill = row_fill
cell.font = _DATA_FONT
cell.border = _CELL_BORDER
align, num_fmt = _detect_cell_format(col["key"], col["label"], val)
cell.alignment = align
if num_fmt and isinstance(val, (int, float)):
cell.number_format = num_fmt
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
# Add native Excel AutoFilter on header row
if columns:
last_col_letter = get_column_letter(len(columns))
ws.auto_filter.ref = f"A{header_row}:{last_col_letter}{last_data_row}"
# Total summary row at bottom
if rows:
summary_row = last_data_row + 1
ws.row_dimensions[summary_row].height = 22
for c_idx in range(1, len(columns) + 1):
tot_cell = ws.cell(row=summary_row, column=c_idx)
tot_cell.fill = _TOTAL_FILL
tot_cell.border = _TOTAL_BORDER
tot_cell.font = _TOTAL_FONT
if c_idx == 1:
tot_cell.value = f"Total Records: {len(rows)}"
tot_cell.alignment = Alignment(horizontal="left", vertical="center")
else:
tot_cell.alignment = Alignment(horizontal="center", vertical="center")
for c_idx, width in enumerate(col_widths, start=1):
ws.column_dimensions[get_column_letter(c_idx)].width = min(50, max(14, width + 4))
# Pre-configure page setup for professional A4 Landscape printing / PDF conversion from Excel
try:
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
ws.page_setup.paperSize = ws.PAPERSIZE_A4
ws.page_setup.fitToPage = True
ws.page_setup.fitToWidth = 1
ws.page_setup.fitToHeight = 0
ws.sheet_properties.pageSetUpPr.fitToPage = True
ws.print_title_rows = f"{header_row}:{header_row}"
ws.oddHeader.left.text = "&BPoona Hospital & Research Centre&B"
ws.oddHeader.right.text = report_payload.get("title", "Operational Report")
ws.oddFooter.left.text = "Confidential • Biomedical Asset Management System"
ws.oddFooter.right.text = "Page &P of &N"
except Exception:
pass
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