print_log.py 14 KB

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