archive.py 9.6 KB

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