export.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import csv
  2. import io
  3. from datetime import datetime
  4. from typing import Any
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from sqlalchemy.orm import selectinload
  8. from backend.app.models.archive import PrintArchive
  9. class ExportService:
  10. """Service for exporting archive data to CSV/Excel formats."""
  11. # Default fields to export
  12. DEFAULT_FIELDS = [
  13. "id",
  14. "print_name",
  15. "filename",
  16. "status",
  17. "quantity",
  18. "printer_id",
  19. "project_name",
  20. "filament_type",
  21. "filament_used_grams",
  22. "print_time_seconds",
  23. "layer_height",
  24. "nozzle_diameter",
  25. "bed_temperature",
  26. "nozzle_temperature",
  27. "total_layers",
  28. "cost",
  29. "designer",
  30. "tags",
  31. "notes",
  32. "failure_reason",
  33. "started_at",
  34. "completed_at",
  35. "created_at",
  36. ]
  37. # Field labels for headers
  38. FIELD_LABELS = {
  39. "id": "ID",
  40. "print_name": "Print Name",
  41. "filename": "Filename",
  42. "status": "Status",
  43. "quantity": "Items Printed",
  44. "printer_id": "Printer ID",
  45. "project_name": "Project",
  46. "filament_type": "Filament Type",
  47. "filament_used_grams": "Filament (g)",
  48. "print_time_seconds": "Print Time (s)",
  49. "layer_height": "Layer Height (mm)",
  50. "nozzle_diameter": "Nozzle (mm)",
  51. "bed_temperature": "Bed Temp (°C)",
  52. "nozzle_temperature": "Nozzle Temp (°C)",
  53. "total_layers": "Total Layers",
  54. "cost": "Cost",
  55. "designer": "Designer",
  56. "tags": "Tags",
  57. "notes": "Notes",
  58. "failure_reason": "Failure Reason",
  59. "started_at": "Started At",
  60. "completed_at": "Completed At",
  61. "created_at": "Created At",
  62. }
  63. def __init__(self, db: AsyncSession):
  64. self.db = db
  65. async def export_archives(
  66. self,
  67. format: str = "csv",
  68. fields: list[str] | None = None,
  69. printer_id: int | None = None,
  70. project_id: int | None = None,
  71. status: str | None = None,
  72. date_from: datetime | None = None,
  73. date_to: datetime | None = None,
  74. search: str | None = None,
  75. visible_to_user_id: int | None = None,
  76. ) -> tuple[bytes, str, str]:
  77. """Export archives to CSV or Excel format.
  78. Args:
  79. format: Export format ('csv' or 'xlsx')
  80. fields: List of fields to include (None = all default fields)
  81. printer_id: Filter by printer
  82. project_id: Filter by project
  83. status: Filter by status
  84. date_from: Filter by start date
  85. date_to: Filter by end date
  86. search: Search filter
  87. visible_to_user_id: Scope rows to those owned by this user (used
  88. when the caller has ARCHIVES_READ_OWN but not _ALL).
  89. Returns:
  90. Tuple of (file_bytes, filename, content_type)
  91. """
  92. # Build query
  93. query = (
  94. select(PrintArchive).options(selectinload(PrintArchive.project)).order_by(PrintArchive.created_at.desc())
  95. )
  96. # Apply filters
  97. if printer_id:
  98. query = query.where(PrintArchive.printer_id == printer_id)
  99. if project_id:
  100. query = query.where(PrintArchive.project_id == project_id)
  101. if status:
  102. query = query.where(PrintArchive.status == status)
  103. if date_from:
  104. query = query.where(PrintArchive.created_at >= date_from)
  105. if date_to:
  106. query = query.where(PrintArchive.created_at <= date_to)
  107. if visible_to_user_id is not None:
  108. query = query.where(PrintArchive.created_by_id == visible_to_user_id)
  109. if search:
  110. like_pattern = f"%{search}%"
  111. query = query.where(
  112. (PrintArchive.print_name.ilike(like_pattern))
  113. | (PrintArchive.filename.ilike(like_pattern))
  114. | (PrintArchive.tags.ilike(like_pattern))
  115. | (PrintArchive.notes.ilike(like_pattern))
  116. | (PrintArchive.designer.ilike(like_pattern))
  117. )
  118. # Execute query
  119. result = await self.db.execute(query)
  120. archives = list(result.scalars().all())
  121. # Determine fields to export
  122. export_fields = fields if fields else self.DEFAULT_FIELDS
  123. # Convert to rows
  124. rows = []
  125. for archive in archives:
  126. row = self._archive_to_row(archive, export_fields)
  127. rows.append(row)
  128. # Generate headers
  129. headers = [self.FIELD_LABELS.get(f, f) for f in export_fields]
  130. # Generate file
  131. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  132. if format == "xlsx":
  133. file_bytes = self._generate_xlsx(headers, rows, export_fields)
  134. filename = f"archives_export_{timestamp}.xlsx"
  135. content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  136. else:
  137. file_bytes = self._generate_csv(headers, rows)
  138. filename = f"archives_export_{timestamp}.csv"
  139. content_type = "text/csv"
  140. return file_bytes, filename, content_type
  141. async def export_stats(
  142. self,
  143. format: str = "csv",
  144. days: int = 30,
  145. printer_id: int | None = None,
  146. project_id: int | None = None,
  147. created_by_id: int | None = None,
  148. ) -> tuple[bytes, str, str]:
  149. """Export statistics summary to CSV or Excel format.
  150. Args:
  151. format: Export format ('csv' or 'xlsx')
  152. days: Number of days to include in stats
  153. printer_id: Filter by printer
  154. project_id: Filter by project
  155. created_by_id: Filter by user who created the print (-1 for no user)
  156. Returns:
  157. Tuple of (file_bytes, filename, content_type)
  158. """
  159. from backend.app.services.failure_analysis import FailureAnalysisService
  160. # Get failure analysis data (includes stats)
  161. analysis_service = FailureAnalysisService(self.db)
  162. analysis = await analysis_service.analyze_failures(
  163. days=days,
  164. printer_id=printer_id,
  165. project_id=project_id,
  166. created_by_id=created_by_id,
  167. )
  168. # Build stats rows
  169. rows = [
  170. ["Metric", "Value"],
  171. ["Period (days)", analysis["period_days"]],
  172. ["Total Prints", analysis["total_prints"]],
  173. ["Failed Prints", analysis["failed_prints"]],
  174. ["Failure Rate (%)", analysis["failure_rate"]],
  175. [""],
  176. ["Failures by Reason", ""],
  177. ]
  178. for reason, count in analysis["failures_by_reason"].items():
  179. rows.append([reason, count])
  180. rows.append([""])
  181. rows.append(["Failures by Filament", ""])
  182. for filament, count in analysis["failures_by_filament"].items():
  183. rows.append([filament, count])
  184. rows.append([""])
  185. rows.append(["Failures by Printer", ""])
  186. for printer, count in analysis["failures_by_printer"].items():
  187. rows.append([printer, count])
  188. rows.append([""])
  189. rows.append(["Weekly Trend", ""])
  190. rows.append(["Week", "Total", "Failed", "Rate (%)"])
  191. for week in analysis["trend"]:
  192. rows.append(
  193. [
  194. week["week_start"],
  195. week["total_prints"],
  196. week["failed_prints"],
  197. week["failure_rate"],
  198. ]
  199. )
  200. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  201. if format == "xlsx":
  202. file_bytes = self._generate_xlsx_simple(rows)
  203. filename = f"stats_export_{timestamp}.xlsx"
  204. content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  205. else:
  206. file_bytes = self._generate_csv_simple(rows)
  207. filename = f"stats_export_{timestamp}.csv"
  208. content_type = "text/csv"
  209. return file_bytes, filename, content_type
  210. def _archive_to_row(self, archive: PrintArchive, fields: list[str]) -> list[Any]:
  211. """Convert an archive to a row of values."""
  212. row = []
  213. for field in fields:
  214. if field == "project_name":
  215. value = archive.project.name if archive.project else None
  216. elif field in ("started_at", "completed_at", "created_at"):
  217. value = getattr(archive, field)
  218. if value:
  219. value = value.isoformat()
  220. else:
  221. value = getattr(archive, field, None)
  222. row.append(value)
  223. return row
  224. def _generate_csv(self, headers: list[str], rows: list[list]) -> bytes:
  225. """Generate CSV file content."""
  226. output = io.StringIO()
  227. writer = csv.writer(output)
  228. writer.writerow(headers)
  229. writer.writerows(rows)
  230. return output.getvalue().encode("utf-8")
  231. def _generate_csv_simple(self, rows: list[list]) -> bytes:
  232. """Generate CSV file content from simple rows (no separate headers)."""
  233. output = io.StringIO()
  234. writer = csv.writer(output)
  235. writer.writerows(rows)
  236. return output.getvalue().encode("utf-8")
  237. def _generate_xlsx(self, headers: list[str], rows: list[list], fields: list[str]) -> bytes:
  238. """Generate Excel file content."""
  239. try:
  240. from openpyxl import Workbook
  241. from openpyxl.styles import Alignment, Font, PatternFill
  242. from openpyxl.utils import get_column_letter
  243. except ImportError:
  244. raise ImportError("openpyxl is required for Excel export. Install with: pip install openpyxl")
  245. wb = Workbook()
  246. ws = wb.active
  247. ws.title = "Archives"
  248. # Header style
  249. header_font = Font(bold=True, color="FFFFFF")
  250. header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
  251. header_alignment = Alignment(horizontal="center")
  252. # Write headers
  253. for col, header in enumerate(headers, 1):
  254. cell = ws.cell(row=1, column=col, value=header)
  255. cell.font = header_font
  256. cell.fill = header_fill
  257. cell.alignment = header_alignment
  258. # Write data
  259. for row_idx, row in enumerate(rows, 2):
  260. for col_idx, value in enumerate(row, 1):
  261. ws.cell(row=row_idx, column=col_idx, value=value)
  262. # Auto-adjust column widths
  263. for col_idx, _field in enumerate(fields, 1):
  264. column_letter = get_column_letter(col_idx)
  265. max_length = len(headers[col_idx - 1])
  266. for row in rows:
  267. cell_value = row[col_idx - 1]
  268. if cell_value is not None:
  269. max_length = max(max_length, len(str(cell_value)))
  270. ws.column_dimensions[column_letter].width = min(max_length + 2, 50)
  271. # Freeze header row
  272. ws.freeze_panes = "A2"
  273. output = io.BytesIO()
  274. wb.save(output)
  275. return output.getvalue()
  276. def _generate_xlsx_simple(self, rows: list[list]) -> bytes:
  277. """Generate Excel file content from simple rows."""
  278. try:
  279. from openpyxl import Workbook
  280. from openpyxl.styles import Font
  281. except ImportError:
  282. raise ImportError("openpyxl is required for Excel export. Install with: pip install openpyxl")
  283. wb = Workbook()
  284. ws = wb.active
  285. ws.title = "Statistics"
  286. bold_font = Font(bold=True)
  287. for row_idx, row in enumerate(rows, 1):
  288. for col_idx, value in enumerate(row, 1):
  289. cell = ws.cell(row=row_idx, column=col_idx, value=value)
  290. # Bold section headers
  291. if col_idx == 1 and value and isinstance(value, str) and value.endswith(":"):
  292. cell.font = bold_font
  293. output = io.BytesIO()
  294. wb.save(output)
  295. return output.getvalue()