archive.py 8.2 KB

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