archive.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. from datetime import datetime
  2. from typing import Annotated, Any
  3. from pydantic import BaseModel, BeforeValidator, Field, model_validator
  4. from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
  5. from backend.app.utils.filename import clean_display_name
  6. # Free text, punctuation and all -- only control characters are taken out, and
  7. # only on the way in (#2832). Anything that turns a name into a path sanitises
  8. # it there instead, where the budget and the fallback are known.
  9. DisplayName = Annotated[str | None, BeforeValidator(clean_display_name)]
  10. class ArchiveBase(BaseModel):
  11. print_name: DisplayName = None
  12. is_favorite: bool | None = None
  13. tags: str | None = None
  14. notes: str | None = None
  15. # Added to every total: a negative (or infinite) cost would wreck them
  16. cost: Annotated[float | None, Field(ge=0, le=1_000_000)] = None
  17. failure_reason: str | None = None
  18. # Number of items printed. 0 is a legal answer -- a plate that jammed and
  19. # came off ruined produced nothing, and the project's completed-items count
  20. # sums this column (#3051). Bounded for the same reason as the grams below:
  21. # it feeds project totals, and a negative would subtract from them.
  22. quantity: Annotated[int | None, Field(ge=0, le=10_000)] = None
  23. # User-defined link (Printables, Thingiverse, etc.)
  24. external_url: str | None = None
  25. class ArchiveUpdate(IgnoresNullForRequiredColumns, ArchiveBase):
  26. __orm_table__ = "print_archives"
  27. printer_id: int | None = None
  28. project_id: int | None = None
  29. # A finished outcome only. 'printing' would be closed again at the next
  30. # reconnect as a missed completion, with notifications and a run of its own.
  31. status: str | None = Field(default=None, pattern="^(completed|failed|aborted|cancelled)$")
  32. # Post-print quality verdict (#1898): 'good' / 'reject'; null clears it.
  33. user_verdict: str | None = Field(default=None, pattern="^(good|reject)$")
  34. # Which surface the verdict came from, for the "recorded when the plate was
  35. # cleared" hint. Only the sources a client can honestly claim are accepted;
  36. # 'link', 'plate_clear' and 'reaction' are stamped server-side by the paths
  37. # that own them and must not be forgeable over this route. Omitted means
  38. # 'api' — some script or integration did it.
  39. user_verdict_source: str | None = Field(default=None, pattern="^(dialog|printer_card|api)$")
  40. # Editable because a print archived without its 3MF has no figure at all,
  41. # and nothing else can supply one after the fact -- the figure is read from
  42. # a 3MF this archive does not have (#1820). Bounded because it feeds the filament
  43. # totals: 100 kg is far past any single print and well short of a value
  44. # that would swamp a chart.
  45. filament_used_grams: Annotated[float | None, Field(ge=0, le=100_000)] = None
  46. # The run (print log entry) a verdict, status or failure reason is for:
  47. # plates of one archive are runs of their own. Omitted means the
  48. # archive's latest run.
  49. run_id: int | None = None
  50. class ArchiveDuplicate(BaseModel):
  51. """Reference to a duplicate archive."""
  52. id: int
  53. print_name: str | None
  54. created_at: datetime | None
  55. match_type: str # "exact" (hash match) or "similar" (name match)
  56. # Archive redesign: an archive is a file, each print of it a run. The fields
  57. # so marked describe one print, the latest (for a caller limited to some
  58. # printers, their latest): read them from GET /archives/{id}/runs, or with
  59. # ?run_id=, instead. Kept on the archive for one more release, flagged in the
  60. # OpenAPI schema only: a Pydantic deprecation would warn on every read inside
  61. # Bambuddy too.
  62. _PER_PRINT = (
  63. "Deprecated: the latest print's (latest_run_id). Read it from the archive's runs (GET /archives/{id}/runs)."
  64. )
  65. _FIRST_PRINT = "Deprecated: the first print's. Read it from the archive's runs (GET /archives/{id}/runs)."
  66. def _per_print(default: Any = ..., description: str = _PER_PRINT) -> Any:
  67. return Field(default, description=description, json_schema_extra={"deprecated": True})
  68. class ArchiveResponse(BaseModel):
  69. id: int
  70. printer_id: int | None = _per_print()
  71. project_id: int | None = None
  72. project_name: str | None = None # Included for convenience
  73. filename: str
  74. file_path: str
  75. file_size: int
  76. content_hash: str | None
  77. thumbnail_path: str | None
  78. timelapse_path: str | None = _per_print()
  79. source_3mf_path: str | None = None # Original project 3MF from slicer
  80. f3d_path: str | None = None # Fusion 360 design file
  81. # Duplicate detection
  82. duplicates: list[ArchiveDuplicate] | None = None
  83. duplicate_count: int = 0 # Quick count for list views
  84. duplicate_sequence: int = 0 # 0 = original, 1+ = nth duplicate
  85. original_archive_id: int | None = None # ID of the first/original archive
  86. # Object count (computed from extra_data.printable_objects)
  87. object_count: int | None = None
  88. print_name: str | None
  89. plate_id: int | None = _per_print(None) # Selected plate of a multi-plate 3MF (#2603)
  90. print_time_seconds: int | None # Estimated time from slicer
  91. actual_time_seconds: int | None = _per_print(None) # Computed from started_at/completed_at
  92. # Percentage: 100 = perfect, >100 = faster than estimated
  93. time_accuracy: float | None = _per_print(None)
  94. # The slicer's time for the plate the latest print printed (#3375), what
  95. # time_accuracy compares with; print_time_seconds adds every plate up.
  96. time_estimate_seconds: int | None = _per_print(None)
  97. filament_used_grams: float | None
  98. filament_type: str | None
  99. filament_color: str | None
  100. layer_height: float | None
  101. total_layers: int | None = None
  102. nozzle_diameter: float | None
  103. bed_temperature: int | None
  104. bed_type: str | None = None # e.g. "Cool Plate", "Textured PEI Plate" (from 3MF curr_bed_type)
  105. nozzle_temperature: int | None
  106. sliced_for_model: str | None = None # Printer model this file was sliced for
  107. status: str = _per_print()
  108. started_at: datetime | None = _per_print()
  109. completed_at: datetime | None = _per_print()
  110. extra_data: dict | None
  111. makerworld_url: str | None
  112. designer: str | None
  113. # User-defined link (Printables, Thingiverse, etc.)
  114. external_url: str | None = None
  115. is_favorite: bool
  116. tags: str | None
  117. notes: str | None
  118. cost: float | None
  119. photos: list | None = _per_print(
  120. description="Every print's finish photos and the ones uploaded by hand; a print's own are on its run."
  121. )
  122. failure_reason: str | None = _per_print()
  123. quantity: int = 1 # Number of items printed
  124. # Post-print outcome confirmation (#1898)
  125. user_verdict: str | None = _per_print(None)
  126. user_verdict_source: str | None = _per_print(None)
  127. user_verdict_at: datetime | None = _per_print(None)
  128. confirm_requested: bool = False
  129. # The run (print log entry) whose outcome this response shows, when it
  130. # shows one run of the archive rather than its latest (#1898).
  131. run_id: int | None = None
  132. # The latest print of the archive (by start, among those the caller may
  133. # see): the run the per-print fields are taken from.
  134. latest_run_id: int | None = None
  135. # Energy tracking
  136. energy_kwh: float | None = _per_print(None, _FIRST_PRINT)
  137. energy_cost: float | None = _per_print(None, _FIRST_PRINT)
  138. wear_cost: float | None = _per_print(None, _FIRST_PRINT) # Printer wear, #694
  139. created_at: datetime | None
  140. # User tracking (Issue #206)
  141. created_by_id: int | None = None
  142. created_by_username: str | None = None
  143. # Per-archive run aggregates (#1378). Computed from PrintLogEntry — one
  144. # row per actual print event — so reprints contribute to these counters
  145. # without overwriting the source archive's first-run data.
  146. run_count: int = 0
  147. last_run_at: datetime | None = None
  148. total_filament_actual_grams: float | None = None
  149. successful_run_count: int = 0
  150. failed_run_count: int = 0
  151. @model_validator(mode="after")
  152. def compute_object_count(self) -> "ArchiveResponse":
  153. """Compute object_count from extra_data.printable_objects if not set."""
  154. if self.object_count is None and self.extra_data:
  155. printable_objects = self.extra_data.get("printable_objects")
  156. if printable_objects and isinstance(printable_objects, dict):
  157. self.object_count = len(printable_objects)
  158. return self
  159. class Config:
  160. from_attributes = True
  161. class ArchiveSlim(BaseModel):
  162. """Lightweight archive response for stats/dashboard widgets."""
  163. printer_id: int | None
  164. print_name: str | None
  165. print_time_seconds: int | None
  166. actual_time_seconds: int | None = None
  167. filament_used_grams: float | None
  168. filament_type: str | None
  169. filament_color: str | None
  170. status: str
  171. started_at: datetime | None
  172. completed_at: datetime | None
  173. cost: float | None
  174. energy_kwh: float | None = None
  175. energy_cost: float | None = None
  176. wear_cost: float | None = None # Printer wear, #694
  177. quantity: int = 1
  178. created_at: datetime | None
  179. class Config:
  180. from_attributes = True
  181. class ArchiveStats(BaseModel):
  182. total_prints: int
  183. successful_prints: int
  184. failed_prints: int
  185. # User/system-stopped prints (PrintLogEntry.status in stopped/cancelled/
  186. # skipped). Defaulted so older clients that don't send this field still
  187. # validate against historical fixtures.
  188. cancelled_prints: int = 0
  189. total_print_time_hours: float
  190. total_filament_grams: float
  191. total_cost: float
  192. prints_by_filament_type: dict
  193. prints_by_printer: dict
  194. # Name each printer id was last recorded under in the print log. Lets the
  195. # client keep labelling history that belongs to a deleted printer (#2873);
  196. # a printer that still exists is named from the live record instead.
  197. printer_names: dict[str, str] = {}
  198. # Time accuracy stats
  199. # Average across all prints with data
  200. average_time_accuracy: float | None = None
  201. time_accuracy_by_printer: dict | None = None # Per-printer accuracy
  202. # Energy stats
  203. total_energy_kwh: float = 0.0
  204. total_energy_cost: float = 0.0
  205. # Printer wear across the runs counted above (#694)
  206. total_wear_cost: float = 0.0
  207. # Set when the date-range query in "total consumption" mode is running on
  208. # incomplete snapshot history — e.g. right after a fresh upgrade before the
  209. # hourly snapshot loop has built up a baseline. Frontend shows a tooltip.
  210. energy_data_warming_up: bool = False
  211. class ProjectPageImage(BaseModel):
  212. """Image embedded in 3MF project page."""
  213. name: str
  214. path: str # Path within 3MF
  215. url: str # API URL to fetch image
  216. class ProjectPageResponse(BaseModel):
  217. """Project page data extracted from 3MF file."""
  218. # Model info
  219. title: str | None = None
  220. description: str | None = None # HTML content
  221. designer: str | None = None
  222. designer_user_id: str | None = None
  223. license: str | None = None
  224. copyright: str | None = None
  225. creation_date: str | None = None
  226. modification_date: str | None = None
  227. origin: str | None = None # "original" or "remix"
  228. # Profile info
  229. profile_title: str | None = None
  230. profile_description: str | None = None
  231. profile_cover: str | None = None
  232. profile_user_id: str | None = None
  233. profile_user_name: str | None = None
  234. # MakerWorld info
  235. design_model_id: str | None = None
  236. design_profile_id: str | None = None
  237. design_region: str | None = None
  238. # Images
  239. model_pictures: list[ProjectPageImage] = []
  240. profile_pictures: list[ProjectPageImage] = []
  241. thumbnails: list[ProjectPageImage] = []