archive.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. from datetime import datetime
  2. from typing import Annotated
  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. class ArchiveResponse(BaseModel):
  57. id: int
  58. printer_id: int | None
  59. project_id: int | None = None
  60. project_name: str | None = None # Included for convenience
  61. filename: str
  62. file_path: str
  63. file_size: int
  64. content_hash: str | None
  65. thumbnail_path: str | None
  66. timelapse_path: str | None
  67. source_3mf_path: str | None = None # Original project 3MF from slicer
  68. f3d_path: str | None = None # Fusion 360 design file
  69. # Duplicate detection
  70. duplicates: list[ArchiveDuplicate] | None = None
  71. duplicate_count: int = 0 # Quick count for list views
  72. duplicate_sequence: int = 0 # 0 = original, 1+ = nth duplicate
  73. original_archive_id: int | None = None # ID of the first/original archive
  74. # Object count (computed from extra_data.printable_objects)
  75. object_count: int | None = None
  76. print_name: str | None
  77. plate_id: int | None = None # Selected plate of a multi-plate 3MF (#2603)
  78. print_time_seconds: int | None # Estimated time from slicer
  79. actual_time_seconds: int | None = None # Computed from started_at/completed_at
  80. # Percentage: 100 = perfect, >100 = faster than estimated
  81. time_accuracy: float | None = None
  82. filament_used_grams: float | None
  83. filament_type: str | None
  84. filament_color: str | None
  85. layer_height: float | None
  86. total_layers: int | None = None
  87. nozzle_diameter: float | None
  88. bed_temperature: int | None
  89. bed_type: str | None = None # e.g. "Cool Plate", "Textured PEI Plate" (from 3MF curr_bed_type)
  90. nozzle_temperature: int | None
  91. sliced_for_model: str | None = None # Printer model this file was sliced for
  92. status: str
  93. started_at: datetime | None
  94. completed_at: datetime | None
  95. extra_data: dict | None
  96. makerworld_url: str | None
  97. designer: str | None
  98. # User-defined link (Printables, Thingiverse, etc.)
  99. external_url: str | None = None
  100. is_favorite: bool
  101. tags: str | None
  102. notes: str | None
  103. cost: float | None
  104. photos: list | None
  105. failure_reason: str | None
  106. quantity: int = 1 # Number of items printed
  107. # Post-print outcome confirmation (#1898)
  108. user_verdict: str | None = None
  109. user_verdict_source: str | None = None
  110. user_verdict_at: datetime | None = None
  111. confirm_requested: bool = False
  112. # The run (print log entry) whose outcome this response shows, when it
  113. # shows one run of the archive rather than its latest (#1898).
  114. run_id: int | None = None
  115. # Energy tracking
  116. energy_kwh: float | None = None
  117. energy_cost: float | None = None
  118. wear_cost: float | None = None # Printer wear, #694
  119. created_at: datetime | None
  120. # User tracking (Issue #206)
  121. created_by_id: int | None = None
  122. created_by_username: str | None = None
  123. # Per-archive run aggregates (#1378). Computed from PrintLogEntry — one
  124. # row per actual print event — so reprints contribute to these counters
  125. # without overwriting the source archive's first-run data.
  126. run_count: int = 0
  127. last_run_at: datetime | None = None
  128. total_filament_actual_grams: float | None = None
  129. successful_run_count: int = 0
  130. failed_run_count: int = 0
  131. @model_validator(mode="after")
  132. def compute_object_count(self) -> "ArchiveResponse":
  133. """Compute object_count from extra_data.printable_objects if not set."""
  134. if self.object_count is None and self.extra_data:
  135. printable_objects = self.extra_data.get("printable_objects")
  136. if printable_objects and isinstance(printable_objects, dict):
  137. self.object_count = len(printable_objects)
  138. return self
  139. class Config:
  140. from_attributes = True
  141. class ArchiveSlim(BaseModel):
  142. """Lightweight archive response for stats/dashboard widgets."""
  143. printer_id: int | None
  144. print_name: str | None
  145. print_time_seconds: int | None
  146. actual_time_seconds: int | None = None
  147. filament_used_grams: float | None
  148. filament_type: str | None
  149. filament_color: str | None
  150. status: str
  151. started_at: datetime | None
  152. completed_at: datetime | None
  153. cost: float | None
  154. energy_kwh: float | None = None
  155. energy_cost: float | None = None
  156. wear_cost: float | None = None # Printer wear, #694
  157. quantity: int = 1
  158. created_at: datetime | None
  159. class Config:
  160. from_attributes = True
  161. class ArchiveStats(BaseModel):
  162. total_prints: int
  163. successful_prints: int
  164. failed_prints: int
  165. # User/system-stopped prints (PrintLogEntry.status in stopped/cancelled/
  166. # skipped). Defaulted so older clients that don't send this field still
  167. # validate against historical fixtures.
  168. cancelled_prints: int = 0
  169. total_print_time_hours: float
  170. total_filament_grams: float
  171. total_cost: float
  172. prints_by_filament_type: dict
  173. prints_by_printer: dict
  174. # Name each printer id was last recorded under in the print log. Lets the
  175. # client keep labelling history that belongs to a deleted printer (#2873);
  176. # a printer that still exists is named from the live record instead.
  177. printer_names: dict[str, str] = {}
  178. # Time accuracy stats
  179. # Average across all prints with data
  180. average_time_accuracy: float | None = None
  181. time_accuracy_by_printer: dict | None = None # Per-printer accuracy
  182. # Energy stats
  183. total_energy_kwh: float = 0.0
  184. total_energy_cost: float = 0.0
  185. # Printer wear across the runs counted above (#694)
  186. total_wear_cost: float = 0.0
  187. # Set when the date-range query in "total consumption" mode is running on
  188. # incomplete snapshot history — e.g. right after a fresh upgrade before the
  189. # hourly snapshot loop has built up a baseline. Frontend shows a tooltip.
  190. energy_data_warming_up: bool = False
  191. class ProjectPageImage(BaseModel):
  192. """Image embedded in 3MF project page."""
  193. name: str
  194. path: str # Path within 3MF
  195. url: str # API URL to fetch image
  196. class ProjectPageResponse(BaseModel):
  197. """Project page data extracted from 3MF file."""
  198. # Model info
  199. title: str | None = None
  200. description: str | None = None # HTML content
  201. designer: str | None = None
  202. designer_user_id: str | None = None
  203. license: str | None = None
  204. copyright: str | None = None
  205. creation_date: str | None = None
  206. modification_date: str | None = None
  207. origin: str | None = None # "original" or "remix"
  208. # Profile info
  209. profile_title: str | None = None
  210. profile_description: str | None = None
  211. profile_cover: str | None = None
  212. profile_user_id: str | None = None
  213. profile_user_name: str | None = None
  214. # MakerWorld info
  215. design_model_id: str | None = None
  216. design_profile_id: str | None = None
  217. design_region: str | None = None
  218. # Images
  219. model_pictures: list[ProjectPageImage] = []
  220. profile_pictures: list[ProjectPageImage] = []
  221. thumbnails: list[ProjectPageImage] = []