archive.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. filament_used_grams: float | None
  95. filament_type: str | None
  96. filament_color: str | None
  97. layer_height: float | None
  98. total_layers: int | None = None
  99. nozzle_diameter: float | None
  100. bed_temperature: int | None
  101. bed_type: str | None = None # e.g. "Cool Plate", "Textured PEI Plate" (from 3MF curr_bed_type)
  102. nozzle_temperature: int | None
  103. sliced_for_model: str | None = None # Printer model this file was sliced for
  104. status: str = _per_print()
  105. started_at: datetime | None = _per_print()
  106. completed_at: datetime | None = _per_print()
  107. extra_data: dict | None
  108. makerworld_url: str | None
  109. designer: str | None
  110. # User-defined link (Printables, Thingiverse, etc.)
  111. external_url: str | None = None
  112. is_favorite: bool
  113. tags: str | None
  114. notes: str | None
  115. cost: float | None
  116. photos: list | None = _per_print(
  117. description="Every print's finish photos and the ones uploaded by hand; a print's own are on its run."
  118. )
  119. failure_reason: str | None = _per_print()
  120. quantity: int = 1 # Number of items printed
  121. # Post-print outcome confirmation (#1898)
  122. user_verdict: str | None = _per_print(None)
  123. user_verdict_source: str | None = _per_print(None)
  124. user_verdict_at: datetime | None = _per_print(None)
  125. confirm_requested: bool = False
  126. # The run (print log entry) whose outcome this response shows, when it
  127. # shows one run of the archive rather than its latest (#1898).
  128. run_id: int | None = None
  129. # The latest print of the archive (by start, among those the caller may
  130. # see): the run the per-print fields are taken from.
  131. latest_run_id: int | None = None
  132. # Energy tracking
  133. energy_kwh: float | None = _per_print(None, _FIRST_PRINT)
  134. energy_cost: float | None = _per_print(None, _FIRST_PRINT)
  135. wear_cost: float | None = _per_print(None, _FIRST_PRINT) # Printer wear, #694
  136. created_at: datetime | None
  137. # User tracking (Issue #206)
  138. created_by_id: int | None = None
  139. created_by_username: str | None = None
  140. # Per-archive run aggregates (#1378). Computed from PrintLogEntry — one
  141. # row per actual print event — so reprints contribute to these counters
  142. # without overwriting the source archive's first-run data.
  143. run_count: int = 0
  144. last_run_at: datetime | None = None
  145. total_filament_actual_grams: float | None = None
  146. successful_run_count: int = 0
  147. failed_run_count: int = 0
  148. @model_validator(mode="after")
  149. def compute_object_count(self) -> "ArchiveResponse":
  150. """Compute object_count from extra_data.printable_objects if not set."""
  151. if self.object_count is None and self.extra_data:
  152. printable_objects = self.extra_data.get("printable_objects")
  153. if printable_objects and isinstance(printable_objects, dict):
  154. self.object_count = len(printable_objects)
  155. return self
  156. class Config:
  157. from_attributes = True
  158. class ArchiveSlim(BaseModel):
  159. """Lightweight archive response for stats/dashboard widgets."""
  160. printer_id: int | None
  161. print_name: str | None
  162. print_time_seconds: int | None
  163. actual_time_seconds: int | None = None
  164. filament_used_grams: float | None
  165. filament_type: str | None
  166. filament_color: str | None
  167. status: str
  168. started_at: datetime | None
  169. completed_at: datetime | None
  170. cost: float | None
  171. energy_kwh: float | None = None
  172. energy_cost: float | None = None
  173. wear_cost: float | None = None # Printer wear, #694
  174. quantity: int = 1
  175. created_at: datetime | None
  176. class Config:
  177. from_attributes = True
  178. class ArchiveStats(BaseModel):
  179. total_prints: int
  180. successful_prints: int
  181. failed_prints: int
  182. # User/system-stopped prints (PrintLogEntry.status in stopped/cancelled/
  183. # skipped). Defaulted so older clients that don't send this field still
  184. # validate against historical fixtures.
  185. cancelled_prints: int = 0
  186. total_print_time_hours: float
  187. total_filament_grams: float
  188. total_cost: float
  189. prints_by_filament_type: dict
  190. prints_by_printer: dict
  191. # Name each printer id was last recorded under in the print log. Lets the
  192. # client keep labelling history that belongs to a deleted printer (#2873);
  193. # a printer that still exists is named from the live record instead.
  194. printer_names: dict[str, str] = {}
  195. # Time accuracy stats
  196. # Average across all prints with data
  197. average_time_accuracy: float | None = None
  198. time_accuracy_by_printer: dict | None = None # Per-printer accuracy
  199. # Energy stats
  200. total_energy_kwh: float = 0.0
  201. total_energy_cost: float = 0.0
  202. # Printer wear across the runs counted above (#694)
  203. total_wear_cost: float = 0.0
  204. # Set when the date-range query in "total consumption" mode is running on
  205. # incomplete snapshot history — e.g. right after a fresh upgrade before the
  206. # hourly snapshot loop has built up a baseline. Frontend shows a tooltip.
  207. energy_data_warming_up: bool = False
  208. class ProjectPageImage(BaseModel):
  209. """Image embedded in 3MF project page."""
  210. name: str
  211. path: str # Path within 3MF
  212. url: str # API URL to fetch image
  213. class ProjectPageResponse(BaseModel):
  214. """Project page data extracted from 3MF file."""
  215. # Model info
  216. title: str | None = None
  217. description: str | None = None # HTML content
  218. designer: str | None = None
  219. designer_user_id: str | None = None
  220. license: str | None = None
  221. copyright: str | None = None
  222. creation_date: str | None = None
  223. modification_date: str | None = None
  224. origin: str | None = None # "original" or "remix"
  225. # Profile info
  226. profile_title: str | None = None
  227. profile_description: str | None = None
  228. profile_cover: str | None = None
  229. profile_user_id: str | None = None
  230. profile_user_name: str | None = None
  231. # MakerWorld info
  232. design_model_id: str | None = None
  233. design_profile_id: str | None = None
  234. design_region: str | None = None
  235. # Images
  236. model_pictures: list[ProjectPageImage] = []
  237. profile_pictures: list[ProjectPageImage] = []
  238. thumbnails: list[ProjectPageImage] = []