archive.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. wear_cost: float | None = None # Printer wear, #694
  108. created_at: datetime | None
  109. # User tracking (Issue #206)
  110. created_by_id: int | None = None
  111. created_by_username: str | None = None
  112. # Per-archive run aggregates (#1378). Computed from PrintLogEntry — one
  113. # row per actual print event — so reprints contribute to these counters
  114. # without overwriting the source archive's first-run data.
  115. run_count: int = 0
  116. last_run_at: datetime | None = None
  117. total_filament_actual_grams: float | None = None
  118. successful_run_count: int = 0
  119. failed_run_count: int = 0
  120. @model_validator(mode="after")
  121. def compute_object_count(self) -> "ArchiveResponse":
  122. """Compute object_count from extra_data.printable_objects if not set."""
  123. if self.object_count is None and self.extra_data:
  124. printable_objects = self.extra_data.get("printable_objects")
  125. if printable_objects and isinstance(printable_objects, dict):
  126. self.object_count = len(printable_objects)
  127. return self
  128. class Config:
  129. from_attributes = True
  130. class ArchiveSlim(BaseModel):
  131. """Lightweight archive response for stats/dashboard widgets."""
  132. printer_id: int | None
  133. print_name: str | None
  134. print_time_seconds: int | None
  135. actual_time_seconds: int | None = None
  136. filament_used_grams: float | None
  137. filament_type: str | None
  138. filament_color: str | None
  139. status: str
  140. started_at: datetime | None
  141. completed_at: datetime | None
  142. cost: float | None
  143. energy_kwh: float | None = None
  144. energy_cost: float | None = None
  145. wear_cost: float | None = None # Printer wear, #694
  146. quantity: int = 1
  147. created_at: datetime | None
  148. class Config:
  149. from_attributes = True
  150. class ArchiveStats(BaseModel):
  151. total_prints: int
  152. successful_prints: int
  153. failed_prints: int
  154. # User/system-stopped prints (PrintLogEntry.status in stopped/cancelled/
  155. # skipped). Defaulted so older clients that don't send this field still
  156. # validate against historical fixtures.
  157. cancelled_prints: int = 0
  158. total_print_time_hours: float
  159. total_filament_grams: float
  160. total_cost: float
  161. prints_by_filament_type: dict
  162. prints_by_printer: dict
  163. # Name each printer id was last recorded under in the print log. Lets the
  164. # client keep labelling history that belongs to a deleted printer (#2873);
  165. # a printer that still exists is named from the live record instead.
  166. printer_names: dict[str, str] = {}
  167. # Time accuracy stats
  168. # Average across all prints with data
  169. average_time_accuracy: float | None = None
  170. time_accuracy_by_printer: dict | None = None # Per-printer accuracy
  171. # Energy stats
  172. total_energy_kwh: float = 0.0
  173. total_energy_cost: float = 0.0
  174. # Printer wear across the runs counted above (#694)
  175. total_wear_cost: float = 0.0
  176. # Set when the date-range query in "total consumption" mode is running on
  177. # incomplete snapshot history — e.g. right after a fresh upgrade before the
  178. # hourly snapshot loop has built up a baseline. Frontend shows a tooltip.
  179. energy_data_warming_up: bool = False
  180. class ProjectPageImage(BaseModel):
  181. """Image embedded in 3MF project page."""
  182. name: str
  183. path: str # Path within 3MF
  184. url: str # API URL to fetch image
  185. class ProjectPageResponse(BaseModel):
  186. """Project page data extracted from 3MF file."""
  187. # Model info
  188. title: str | None = None
  189. description: str | None = None # HTML content
  190. designer: str | None = None
  191. designer_user_id: str | None = None
  192. license: str | None = None
  193. copyright: str | None = None
  194. creation_date: str | None = None
  195. modification_date: str | None = None
  196. origin: str | None = None # "original" or "remix"
  197. # Profile info
  198. profile_title: str | None = None
  199. profile_description: str | None = None
  200. profile_cover: str | None = None
  201. profile_user_id: str | None = None
  202. profile_user_name: str | None = None
  203. # MakerWorld info
  204. design_model_id: str | None = None
  205. design_profile_id: str | None = None
  206. design_region: str | None = None
  207. # Images
  208. model_pictures: list[ProjectPageImage] = []
  209. profile_pictures: list[ProjectPageImage] = []
  210. thumbnails: list[ProjectPageImage] = []
  211. class ProjectPageUpdate(BaseModel):
  212. """Update project page data in 3MF file."""
  213. title: str | None = None
  214. description: str | None = None
  215. designer: str | None = None
  216. license: str | None = None
  217. copyright: str | None = None
  218. profile_title: str | None = None
  219. profile_description: str | None = None