export.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. Soft-deleted archives (#1343) are excluded: this export
  93. # is the list the user is looking at, saved to a file, and that list
  94. # hides them — an export that silently contains rows the UI says are
  95. # gone is worse than useless for reconciling anything (#2731).
  96. query = (
  97. select(PrintArchive)
  98. .options(selectinload(PrintArchive.project))
  99. .where(PrintArchive.deleted_at.is_(None))
  100. .order_by(PrintArchive.created_at.desc())
  101. )
  102. # Apply filters
  103. if printer_id:
  104. query = query.where(PrintArchive.printer_id == printer_id)
  105. if project_id:
  106. query = query.where(PrintArchive.project_id == project_id)
  107. if status:
  108. query = query.where(PrintArchive.status == status)
  109. if date_from:
  110. query = query.where(PrintArchive.created_at >= date_from)
  111. if date_to:
  112. query = query.where(PrintArchive.created_at <= date_to)
  113. if visible_to_user_id is not None:
  114. query = query.where(PrintArchive.created_by_id == visible_to_user_id)
  115. if search:
  116. like_pattern = f"%{search}%"
  117. query = query.where(
  118. (PrintArchive.print_name.ilike(like_pattern))
  119. | (PrintArchive.filename.ilike(like_pattern))
  120. | (PrintArchive.tags.ilike(like_pattern))
  121. | (PrintArchive.notes.ilike(like_pattern))
  122. | (PrintArchive.designer.ilike(like_pattern))
  123. )
  124. # Execute query
  125. result = await self.db.execute(query)
  126. archives = list(result.scalars().all())
  127. # Determine fields to export
  128. export_fields = fields if fields else self.DEFAULT_FIELDS
  129. # Convert to rows
  130. rows = []
  131. for archive in archives:
  132. row = self._archive_to_row(archive, export_fields)
  133. rows.append(row)
  134. # Generate headers
  135. headers = [self.FIELD_LABELS.get(f, f) for f in export_fields]
  136. # Generate file
  137. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  138. if format == "xlsx":
  139. file_bytes = self._generate_xlsx(headers, rows, export_fields)
  140. filename = f"archives_export_{timestamp}.xlsx"
  141. content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  142. else:
  143. file_bytes = self._generate_csv(headers, rows)
  144. filename = f"archives_export_{timestamp}.csv"
  145. content_type = "text/csv"
  146. return file_bytes, filename, content_type
  147. async def export_stats(
  148. self,
  149. format: str = "csv",
  150. days: int = 30,
  151. printer_id: int | None = None,
  152. project_id: int | None = None,
  153. created_by_id: int | None = None,
  154. ) -> tuple[bytes, str, str]:
  155. """Export statistics summary to CSV or Excel format.
  156. Args:
  157. format: Export format ('csv' or 'xlsx')
  158. days: Number of days to include in stats
  159. printer_id: Filter by printer
  160. project_id: Filter by project
  161. created_by_id: Filter by user who created the print (-1 for no user)
  162. Returns:
  163. Tuple of (file_bytes, filename, content_type)
  164. """
  165. from backend.app.services.failure_analysis import FailureAnalysisService
  166. # Get failure analysis data (includes stats)
  167. analysis_service = FailureAnalysisService(self.db)
  168. analysis = await analysis_service.analyze_failures(
  169. days=days,
  170. printer_id=printer_id,
  171. project_id=project_id,
  172. created_by_id=created_by_id,
  173. )
  174. # Build stats rows
  175. rows = [
  176. ["Metric", "Value"],
  177. ["Period (days)", analysis["period_days"]],
  178. ["Total Prints", analysis["total_prints"]],
  179. ["Failed Prints", analysis["failed_prints"]],
  180. ["Failure Rate (%)", analysis["failure_rate"]],
  181. [""],
  182. ["Failures by Reason", ""],
  183. ]
  184. for reason, count in analysis["failures_by_reason"].items():
  185. rows.append([reason, count])
  186. rows.append([""])
  187. rows.append(["Failures by Filament", ""])
  188. for filament, count in analysis["failures_by_filament"].items():
  189. rows.append([filament, count])
  190. rows.append([""])
  191. rows.append(["Failures by Printer", ""])
  192. for printer, count in analysis["failures_by_printer"].items():
  193. rows.append([printer, count])
  194. rows.append([""])
  195. rows.append(["Weekly Trend", ""])
  196. rows.append(["Week", "Total", "Failed", "Rate (%)"])
  197. for week in analysis["trend"]:
  198. rows.append(
  199. [
  200. week["week_start"],
  201. week["total_prints"],
  202. week["failed_prints"],
  203. week["failure_rate"],
  204. ]
  205. )
  206. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  207. if format == "xlsx":
  208. file_bytes = self._generate_xlsx_simple(rows)
  209. filename = f"stats_export_{timestamp}.xlsx"
  210. content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  211. else:
  212. file_bytes = self._generate_csv_simple(rows)
  213. filename = f"stats_export_{timestamp}.csv"
  214. content_type = "text/csv"
  215. return file_bytes, filename, content_type
  216. def _archive_to_row(self, archive: PrintArchive, fields: list[str]) -> list[Any]:
  217. """Convert an archive to a row of values."""
  218. row = []
  219. for field in fields:
  220. if field == "project_name":
  221. value = archive.project.name if archive.project else None
  222. elif field in ("started_at", "completed_at", "created_at"):
  223. value = getattr(archive, field)
  224. if value:
  225. value = value.isoformat()
  226. else:
  227. value = getattr(archive, field, None)
  228. row.append(value)
  229. return row
  230. def _generate_csv(self, headers: list[str], rows: list[list]) -> bytes:
  231. """Generate CSV file content."""
  232. output = io.StringIO()
  233. writer = csv.writer(output)
  234. writer.writerow(headers)
  235. writer.writerows(rows)
  236. return output.getvalue().encode("utf-8")
  237. def _generate_csv_simple(self, rows: list[list]) -> bytes:
  238. """Generate CSV file content from simple rows (no separate headers)."""
  239. output = io.StringIO()
  240. writer = csv.writer(output)
  241. writer.writerows(rows)
  242. return output.getvalue().encode("utf-8")
  243. def _generate_xlsx(self, headers: list[str], rows: list[list], fields: list[str]) -> bytes:
  244. """Generate Excel file content."""
  245. try:
  246. from openpyxl import Workbook
  247. from openpyxl.styles import Alignment, Font, PatternFill
  248. from openpyxl.utils import get_column_letter
  249. except ImportError:
  250. raise ImportError("openpyxl is required for Excel export. Install with: pip install openpyxl")
  251. wb = Workbook()
  252. ws = wb.active
  253. ws.title = "Archives"
  254. # Header style
  255. header_font = Font(bold=True, color="FFFFFF")
  256. header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
  257. header_alignment = Alignment(horizontal="center")
  258. # Write headers
  259. for col, header in enumerate(headers, 1):
  260. cell = ws.cell(row=1, column=col, value=header)
  261. cell.font = header_font
  262. cell.fill = header_fill
  263. cell.alignment = header_alignment
  264. # Write data
  265. for row_idx, row in enumerate(rows, 2):
  266. for col_idx, value in enumerate(row, 1):
  267. ws.cell(row=row_idx, column=col_idx, value=value)
  268. # Auto-adjust column widths
  269. for col_idx, _field in enumerate(fields, 1):
  270. column_letter = get_column_letter(col_idx)
  271. max_length = len(headers[col_idx - 1])
  272. for row in rows:
  273. cell_value = row[col_idx - 1]
  274. if cell_value is not None:
  275. max_length = max(max_length, len(str(cell_value)))
  276. ws.column_dimensions[column_letter].width = min(max_length + 2, 50)
  277. # Freeze header row
  278. ws.freeze_panes = "A2"
  279. output = io.BytesIO()
  280. wb.save(output)
  281. return output.getvalue()
  282. def _generate_xlsx_simple(self, rows: list[list]) -> bytes:
  283. """Generate Excel file content from simple rows."""
  284. try:
  285. from openpyxl import Workbook
  286. from openpyxl.styles import Font
  287. except ImportError:
  288. raise ImportError("openpyxl is required for Excel export. Install with: pip install openpyxl")
  289. wb = Workbook()
  290. ws = wb.active
  291. ws.title = "Statistics"
  292. bold_font = Font(bold=True)
  293. for row_idx, row in enumerate(rows, 1):
  294. for col_idx, value in enumerate(row, 1):
  295. cell = ws.cell(row=row_idx, column=col_idx, value=value)
  296. # Bold section headers
  297. if col_idx == 1 and value and isinstance(value, str) and value.endswith(":"):
  298. cell.font = bold_font
  299. output = io.BytesIO()
  300. wb.save(output)
  301. return output.getvalue()