export.py 12 KB

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