archive.py 9.9 KB

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