archive.py 8.5 KB

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