print_log.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import logging
  2. from datetime import datetime
  3. from fastapi import APIRouter, Depends, HTTPException, Query
  4. from fastapi.responses import FileResponse
  5. from sqlalchemy import delete, func, nullslast, select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.auth import (
  8. RequireCameraStreamTokenIfAuthEnabled,
  9. RequirePermissionIfAuthEnabled,
  10. require_ownership_permission,
  11. )
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.models.print_log import PrintLogEntry
  16. from backend.app.models.user import User
  17. from backend.app.schemas.print_log import PrintLogEntrySchema, PrintLogEntryUpdate, PrintLogResponse
  18. logger = logging.getLogger(__name__)
  19. router = APIRouter(prefix="/print-log", tags=["print-log"])
  20. # Sortable columns, keyed by the id the Print Log table uses for its columns
  21. # (#2636). An explicit map rather than getattr on a caller-supplied string:
  22. # the client picks the key, so anything else would let a request order by any
  23. # attribute it can name.
  24. #
  25. # ``date`` coalesces because the column renders ``started_at or created_at`` —
  26. # sorting on started_at alone would scatter the rows that have no start time
  27. # (queue-skipped entries) instead of interleaving them where the user sees
  28. # them.
  29. _SORTABLE_COLUMNS = {
  30. "date": func.coalesce(PrintLogEntry.started_at, PrintLogEntry.created_at),
  31. "print_name": PrintLogEntry.print_name,
  32. "printer": PrintLogEntry.printer_name,
  33. "user": PrintLogEntry.created_by_username,
  34. "status": PrintLogEntry.status,
  35. "duration": PrintLogEntry.duration_seconds,
  36. "completed_at": PrintLogEntry.completed_at,
  37. "filament": PrintLogEntry.filament_type,
  38. "filament_used": PrintLogEntry.filament_used_grams,
  39. "cost": PrintLogEntry.cost,
  40. "energy": PrintLogEntry.energy_kwh,
  41. "energy_cost": PrintLogEntry.energy_cost,
  42. }
  43. @router.get("/", response_model=PrintLogResponse)
  44. async def get_print_log(
  45. search: str | None = None,
  46. printer_id: int | None = None,
  47. created_by_username: str | None = None,
  48. status: str | None = None,
  49. date_from: datetime | None = None,
  50. date_to: datetime | None = None,
  51. limit: int = Query(default=50, ge=1, le=500),
  52. offset: int = Query(default=0, ge=0),
  53. sort_by: str = Query(default="date"),
  54. sort_dir: str = Query(default="desc", pattern="^(asc|desc)$"),
  55. db: AsyncSession = Depends(get_db),
  56. auth_result: tuple[User | None, bool] = Depends(
  57. require_ownership_permission(
  58. Permission.ARCHIVES_READ_ALL,
  59. Permission.ARCHIVES_READ_OWN,
  60. )
  61. ),
  62. ):
  63. """Get the print log."""
  64. user, can_read_all = auth_result
  65. query = select(PrintLogEntry)
  66. count_query = select(func.count(PrintLogEntry.id))
  67. if user is not None and not can_read_all:
  68. query = query.where(PrintLogEntry.created_by_id == user.id)
  69. count_query = count_query.where(PrintLogEntry.created_by_id == user.id)
  70. if printer_id is not None:
  71. query = query.where(PrintLogEntry.printer_id == printer_id)
  72. count_query = count_query.where(PrintLogEntry.printer_id == printer_id)
  73. if created_by_username:
  74. query = query.where(PrintLogEntry.created_by_username == created_by_username)
  75. count_query = count_query.where(PrintLogEntry.created_by_username == created_by_username)
  76. if status:
  77. query = query.where(PrintLogEntry.status == status)
  78. count_query = count_query.where(PrintLogEntry.status == status)
  79. if search:
  80. query = query.where(PrintLogEntry.print_name.ilike(f"%{search}%"))
  81. count_query = count_query.where(PrintLogEntry.print_name.ilike(f"%{search}%"))
  82. if date_from:
  83. query = query.where(PrintLogEntry.created_at >= date_from)
  84. count_query = count_query.where(PrintLogEntry.created_at >= date_from)
  85. if date_to:
  86. query = query.where(PrintLogEntry.created_at <= date_to)
  87. count_query = count_query.where(PrintLogEntry.created_at <= date_to)
  88. # Get total count
  89. total_result = await db.execute(count_query)
  90. total = total_result.scalar() or 0
  91. # Sorting happens here rather than in the browser because the table is
  92. # paginated server-side: ordering the 25 rows the client happens to hold
  93. # would answer "the most expensive print on this page", which is not what
  94. # clicking a column header means.
  95. sort_column = _SORTABLE_COLUMNS.get(sort_by)
  96. if sort_column is None:
  97. raise HTTPException(400, f"Cannot sort by {sort_by!r}")
  98. ordering = sort_column.asc() if sort_dir == "asc" else sort_column.desc()
  99. # NULLs last in both directions, so a column that is empty for half the
  100. # rows (cost before a spool is priced, energy without a smart plug) never
  101. # buries the rows that do have values. Left to the database this differs
  102. # per backend — Postgres sorts NULLs high, SQLite sorts them low — so the
  103. # same click would give two different first pages depending on deployment.
  104. query = query.order_by(nullslast(ordering), PrintLogEntry.id.desc())
  105. # id.desc() above is the tiebreaker: without it, rows sharing a value
  106. # (every "completed" when sorting by status) come back in whatever order
  107. # the planner picks, which can differ between pages and duplicate or drop
  108. # a row as the user pages through.
  109. query = query.offset(offset).limit(limit)
  110. result = await db.execute(query)
  111. entries = result.scalars().all()
  112. # Validate straight off the ORM rows rather than naming each field: the
  113. # hand-written version dropped whatever it forgot to mention, and a
  114. # forgotten field is indistinguishable from a NULL column on the wire.
  115. # It lost failure_reason that way (#1687 part 4), then cost / energy_kwh /
  116. # energy_cost, which were written to the table but never sent — so the
  117. # Print Log's cost and energy columns read empty for every run (#2636).
  118. return PrintLogResponse(
  119. items=[PrintLogEntrySchema.model_validate(e) for e in entries],
  120. total=total,
  121. )
  122. @router.get("/{entry_id}/thumbnail")
  123. async def get_print_log_thumbnail(
  124. entry_id: int,
  125. db: AsyncSession = Depends(get_db),
  126. _: None = RequireCameraStreamTokenIfAuthEnabled,
  127. ):
  128. """Get the thumbnail for a print log entry.
  129. Requires a stream token query param (?token=xxx) when auth is enabled.
  130. Self-heals stale entries: when thumbnail_path points to a file that no
  131. longer exists on disk (archive was deleted, or print failed before the
  132. thumbnail was ever written), NULL the path on the entry so subsequent
  133. page renders skip the request entirely. The frontend's <img> tag is
  134. gated on entry.thumbnail_path being truthy, so the next fetch of the
  135. log list will simply not request this thumbnail again.
  136. """
  137. entry = await db.get(PrintLogEntry, entry_id)
  138. if not entry or not entry.thumbnail_path:
  139. raise HTTPException(404, "Thumbnail not found")
  140. thumb_path = settings.base_dir / entry.thumbnail_path
  141. if not thumb_path.exists():
  142. entry.thumbnail_path = None
  143. await db.commit()
  144. raise HTTPException(404, "Thumbnail file not found")
  145. return FileResponse(
  146. path=thumb_path,
  147. media_type="image/png",
  148. headers={"Cache-Control": "public, max-age=86400"},
  149. )
  150. @router.delete("/")
  151. async def clear_print_log(
  152. db: AsyncSession = Depends(get_db),
  153. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_ALL),
  154. ):
  155. """Clear the print log.
  156. Only deletes log entries. Archives and queue items are never touched.
  157. """
  158. result = await db.execute(delete(PrintLogEntry))
  159. deleted = result.rowcount
  160. await db.commit()
  161. logger.info("Print log cleared: %d entries deleted", deleted)
  162. return {"deleted": deleted}
  163. @router.delete("/{entry_id}")
  164. async def delete_print_log_entry(
  165. entry_id: int,
  166. db: AsyncSession = Depends(get_db),
  167. auth_result: tuple[User | None, bool] = Depends(
  168. require_ownership_permission(
  169. Permission.ARCHIVES_DELETE_ALL,
  170. Permission.ARCHIVES_DELETE_OWN,
  171. )
  172. ),
  173. ):
  174. """Delete a single print-log entry (#1687).
  175. Removes the row entirely. Because /archives/stats aggregates over
  176. PrintLogEntry, the deleted row's filament / cost / duration / count
  177. contributions drop out of the totals in the same response cycle.
  178. The linked archive (if any) is untouched — the FK on the archive row
  179. is from PrintLogEntry, not the other way around.
  180. """
  181. user, can_modify_all = auth_result
  182. entry = await db.get(PrintLogEntry, entry_id)
  183. if not entry:
  184. raise HTTPException(404, "Print log entry not found")
  185. if not can_modify_all:
  186. if entry.created_by_id is None or (user is not None and entry.created_by_id != user.id):
  187. raise HTTPException(403, "You can only delete your own print log entries")
  188. await db.delete(entry)
  189. await db.commit()
  190. logger.info("Print log entry %d deleted", entry_id)
  191. return {"status": "deleted", "id": entry_id}
  192. # Canonical failure-reason vocabulary. Mirrors the frontend dropdown in
  193. # EditArchiveModal.tsx; the empty string is the "clear classification" value.
  194. # The catch-all "other" is the escape hatch for failures that don't fit the
  195. # enumerated list. Keep these two lists in sync if the EditArchiveModal options
  196. # ever change.
  197. _FAILURE_REASON_KEYS = frozenset(
  198. {
  199. "",
  200. "adhesionFailure",
  201. "spaghettiDetached",
  202. "layerShift",
  203. "cloggedNozzle",
  204. "filamentRunout",
  205. "warping",
  206. "stringing",
  207. "underExtrusion",
  208. "powerFailure",
  209. "userCancelled",
  210. "other",
  211. }
  212. )
  213. # Same status vocabulary the print-log column already filters by.
  214. _STATUS_KEYS = frozenset({"completed", "failed", "stopped", "cancelled", "skipped"})
  215. @router.patch("/{entry_id}", response_model=PrintLogEntrySchema)
  216. async def update_print_log_entry(
  217. entry_id: int,
  218. update: PrintLogEntryUpdate,
  219. db: AsyncSession = Depends(get_db),
  220. auth_result: tuple[User | None, bool] = Depends(
  221. require_ownership_permission(
  222. Permission.ARCHIVES_UPDATE_ALL,
  223. Permission.ARCHIVES_UPDATE_OWN,
  224. )
  225. ),
  226. ):
  227. """Edit a single Print Log row's classification (#1687 part 4, reporter
  228. IndividualGhost1905).
  229. Lets the user set ``failure_reason`` (and optionally re-classify ``status``)
  230. directly on a Print Log row — including orphan entries that have no
  231. archive to edit through. The Failure Analysis widget already groups by
  232. ``PrintLogEntry.failure_reason`` (see ``archives.py:1421`` for the
  233. archive-side mirror); this endpoint is the missing edit affordance for the
  234. log-side, mirror-less case.
  235. Ownership semantics mirror the per-row delete: archives:update_all sees
  236. everything; archives:update_own sees only rows it owns.
  237. """
  238. user, can_modify_all = auth_result
  239. entry = await db.get(PrintLogEntry, entry_id)
  240. if not entry:
  241. raise HTTPException(404, "Print log entry not found")
  242. if not can_modify_all:
  243. if entry.created_by_id is None or (user is not None and entry.created_by_id != user.id):
  244. raise HTTPException(403, "You can only update your own print log entries")
  245. payload = update.model_dump(exclude_unset=True)
  246. # Validate against the canonical vocabularies. Reject unknown values rather
  247. # than silently storing them — the Failure Analysis widget renders the
  248. # values back as i18n keys, and an unrecognised value would surface as a
  249. # raw string in the UI.
  250. if "failure_reason" in payload:
  251. new_reason = payload["failure_reason"] or ""
  252. if new_reason not in _FAILURE_REASON_KEYS:
  253. raise HTTPException(400, f"Unknown failure_reason: {new_reason!r}")
  254. # Store empty string back as NULL so the column's nullable=True intent
  255. # is preserved end-to-end.
  256. entry.failure_reason = new_reason or None
  257. if "status" in payload and payload["status"] is not None:
  258. new_status = payload["status"]
  259. if new_status not in _STATUS_KEYS:
  260. raise HTTPException(400, f"Unknown status: {new_status!r}")
  261. entry.status = new_status
  262. await db.commit()
  263. await db.refresh(entry)
  264. logger.info(
  265. "Print log entry %d updated (failure_reason=%r, status=%r)",
  266. entry_id,
  267. entry.failure_reason,
  268. entry.status,
  269. )
  270. # Same field-by-field trap as the list route: this one also omitted cost
  271. # and the energy pair, so the row the client merged back after an edit
  272. # blanked whichever columns it was showing for them.
  273. return PrintLogEntrySchema.model_validate(entry)