print_log.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Service for writing independent print log entries.
  2. Log entries are written to a separate table and never touch archives or queue items.
  3. """
  4. import logging
  5. from datetime import datetime
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.models.print_log import PrintLogEntry
  8. logger = logging.getLogger(__name__)
  9. async def write_log_entry(
  10. db: AsyncSession,
  11. *,
  12. status: str,
  13. archive_id: int | None = None,
  14. print_name: str | None = None,
  15. printer_name: str | None = None,
  16. printer_id: int | None = None,
  17. started_at: datetime | None = None,
  18. completed_at: datetime | None = None,
  19. filament_type: str | None = None,
  20. filament_color: str | None = None,
  21. filament_used_grams: float | None = None,
  22. cost: float | None = None,
  23. energy_kwh: float | None = None,
  24. energy_cost: float | None = None,
  25. failure_reason: str | None = None,
  26. thumbnail_path: str | None = None,
  27. created_by_id: int | None = None,
  28. created_by_username: str | None = None,
  29. ) -> PrintLogEntry:
  30. """Write a print log entry."""
  31. duration = None
  32. if started_at and completed_at:
  33. duration = int((completed_at - started_at).total_seconds())
  34. entry = PrintLogEntry(
  35. archive_id=archive_id,
  36. print_name=print_name,
  37. printer_name=printer_name,
  38. printer_id=printer_id,
  39. status=status,
  40. started_at=started_at,
  41. completed_at=completed_at,
  42. duration_seconds=duration,
  43. filament_type=filament_type,
  44. filament_color=filament_color,
  45. filament_used_grams=filament_used_grams,
  46. cost=cost,
  47. energy_kwh=energy_kwh,
  48. energy_cost=energy_cost,
  49. failure_reason=failure_reason,
  50. thumbnail_path=thumbnail_path,
  51. created_by_id=created_by_id,
  52. created_by_username=created_by_username,
  53. )
  54. db.add(entry)
  55. await db.flush()
  56. return entry