archive.py 9.8 KB

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