archive.py 9.3 KB

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