spool.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from datetime import datetime
  2. from pydantic import BaseModel, Field, field_validator
  3. # Visual variant applied to a spool's swatch — purely cosmetic, does not
  4. # affect MQTT/firmware. Kept independent of `subtype` so users can override
  5. # the rendering hint without touching Bambu's categorical filament label.
  6. # Mirrors the visual variants the spool form's `KNOWN_VARIANTS` exposes so
  7. # the catalog and spool form share one vocabulary; structural variants like
  8. # gradient/dual-color/tri-color/multicolor combine with `extra_colors` for
  9. # rendering, surface effects (sparkle/wood/marble/glow/matte) layer overlays.
  10. ALLOWED_EFFECT_TYPES = frozenset(
  11. {
  12. # Surface effects
  13. "sparkle",
  14. "wood",
  15. "marble",
  16. "glow",
  17. "matte",
  18. # Sheen / finish variants
  19. "silk",
  20. "galaxy",
  21. "rainbow",
  22. "metal",
  23. "translucent",
  24. # Multi-colour structures (drive gradient rendering when paired with extra_colors)
  25. "gradient",
  26. "dual-color",
  27. "tri-color",
  28. "multicolor",
  29. }
  30. )
  31. # Cap how many gradient stops we accept on input so a paste of arbitrary text
  32. # can't blow up the stored value or downstream rendering.
  33. MAX_EXTRA_COLOR_STOPS = 8
  34. def normalize_extra_colors(value: str | None) -> str | None:
  35. """Parse comma-separated hex tokens into canonical lowercase form.
  36. Accepts 6- or 8-char hex per token, with or without leading `#`. Returns
  37. None for blank input, raises ValueError for malformed tokens or too many
  38. stops. Output is the comma-joined canonical form (no `#`, lowercase).
  39. """
  40. if value is None:
  41. return None
  42. raw = value.strip()
  43. if not raw:
  44. return None
  45. tokens = [tok.strip().lstrip("#").lower() for tok in raw.split(",") if tok.strip()]
  46. if not tokens:
  47. return None
  48. if len(tokens) > MAX_EXTRA_COLOR_STOPS:
  49. raise ValueError(f"extra_colors accepts at most {MAX_EXTRA_COLOR_STOPS} stops")
  50. for tok in tokens:
  51. if len(tok) not in (6, 8):
  52. raise ValueError(f"extra_colors token '{tok}' must be 6 or 8 hex chars")
  53. try:
  54. int(tok, 16)
  55. except ValueError as exc:
  56. raise ValueError(f"extra_colors token '{tok}' is not valid hex") from exc
  57. return ",".join(tokens)
  58. def normalize_effect_type(value: str | None) -> str | None:
  59. if value is None:
  60. return None
  61. trimmed = value.strip().lower()
  62. if not trimmed:
  63. return None
  64. # Tolerate "Dual Color" / "dual_color" / "dual color" → "dual-color" so
  65. # users pasting from spool-subtype labels don't hit a validation wall.
  66. canonical = trimmed.replace("_", "-").replace(" ", "-")
  67. if canonical not in ALLOWED_EFFECT_TYPES:
  68. raise ValueError(f"effect_type must be one of: {sorted(ALLOWED_EFFECT_TYPES)}")
  69. return canonical
  70. class SpoolBase(BaseModel):
  71. material: str = Field(..., min_length=1, max_length=50)
  72. subtype: str | None = None
  73. color_name: str | None = None
  74. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  75. extra_colors: str | None = None
  76. effect_type: str | None = None
  77. brand: str | None = None
  78. @field_validator("extra_colors")
  79. @classmethod
  80. def _validate_extra_colors(cls, v: str | None) -> str | None:
  81. return normalize_extra_colors(v)
  82. @field_validator("effect_type")
  83. @classmethod
  84. def _validate_effect_type(cls, v: str | None) -> str | None:
  85. return normalize_effect_type(v)
  86. label_weight: int = 1000
  87. core_weight: int = 250
  88. core_weight_catalog_id: int | None = None
  89. weight_used: float = 0
  90. # Anchor for the resettable "Total Consumed" display. The Inventory
  91. # page shows `weight_used - weight_used_baseline`; the per-spool /
  92. # bulk "Reset usage to 0" action sets baseline = weight_used so the
  93. # counter zeroes without touching remaining (#1390).
  94. weight_used_baseline: float = 0
  95. slicer_filament: str | None = None
  96. slicer_filament_name: str | None = None
  97. nozzle_temp_min: int | None = None
  98. nozzle_temp_max: int | None = None
  99. note: str | None = None
  100. tag_uid: str | None = None
  101. tray_uuid: str | None = None
  102. data_origin: str | None = None
  103. tag_type: str | None = None
  104. cost_per_kg: float | None = Field(default=None, ge=0)
  105. weight_locked: bool = False
  106. last_scale_weight: int | None = None
  107. last_weighed_at: datetime | None = None
  108. # User-defined category + per-spool low-stock threshold override (#729).
  109. category: str | None = Field(default=None, max_length=50)
  110. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  111. # Free-text storage location, distinct from `location` (AMS slot
  112. # assignment). Column has lived on the ORM since the inventory rework
  113. # but was missing from this schema, so writes were silently dropped (#1291).
  114. storage_location: str | None = Field(default=None, max_length=255)
  115. location_id: int | None = Field(default=None, gt=0)
  116. class SpoolCreate(SpoolBase):
  117. pass
  118. class SpoolBulkCreate(BaseModel):
  119. spool: SpoolCreate
  120. quantity: int = Field(default=1, ge=1, le=100)
  121. class SpoolUpdate(BaseModel):
  122. material: str | None = None
  123. subtype: str | None = None
  124. color_name: str | None = None
  125. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  126. extra_colors: str | None = None
  127. effect_type: str | None = None
  128. brand: str | None = None
  129. @field_validator("extra_colors")
  130. @classmethod
  131. def _validate_extra_colors(cls, v: str | None) -> str | None:
  132. return normalize_extra_colors(v)
  133. @field_validator("effect_type")
  134. @classmethod
  135. def _validate_effect_type(cls, v: str | None) -> str | None:
  136. return normalize_effect_type(v)
  137. label_weight: int | None = None
  138. core_weight: int | None = None
  139. core_weight_catalog_id: int | None = None
  140. weight_used: float | None = None
  141. slicer_filament: str | None = None
  142. slicer_filament_name: str | None = None
  143. nozzle_temp_min: int | None = None
  144. nozzle_temp_max: int | None = None
  145. note: str | None = None
  146. tag_uid: str | None = None
  147. tray_uuid: str | None = None
  148. data_origin: str | None = None
  149. tag_type: str | None = None
  150. cost_per_kg: float | None = Field(default=None, ge=0)
  151. weight_locked: bool | None = None
  152. # User-defined category + per-spool low-stock threshold override (#729).
  153. category: str | None = Field(default=None, max_length=50)
  154. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  155. storage_location: str | None = Field(default=None, max_length=255)
  156. location_id: int | None = Field(default=None, gt=0)
  157. class SpoolKProfileBase(BaseModel):
  158. printer_id: int
  159. extruder: int = 0
  160. nozzle_diameter: str = "0.4"
  161. nozzle_type: str | None = None
  162. k_value: float
  163. name: str | None = None
  164. cali_idx: int | None = None
  165. setting_id: str | None = None
  166. class SpoolKProfileResponse(SpoolKProfileBase):
  167. id: int
  168. spool_id: int
  169. created_at: datetime
  170. class Config:
  171. from_attributes = True
  172. class SpoolFilamentPresetBase(BaseModel):
  173. """One per-printer-model slicer preset override for a spool.
  174. ``nozzle_diameter`` defaults to "" meaning "any nozzle of this model". The
  175. spool form always sends a concrete size; the empty form is for API clients
  176. that want one value to cover a model. Lengths match the columns, which are wider than
  177. ``Spool.slicer_filament`` so a preset id that fits the Spoolman write
  178. schema cannot truncate on the way in.
  179. """
  180. printer_model: str = Field(..., min_length=1, max_length=50)
  181. nozzle_diameter: str = Field(default="", max_length=10)
  182. slicer_filament: str | None = Field(default=None, max_length=128)
  183. slicer_filament_name: str | None = Field(default=None, max_length=255)
  184. class SpoolFilamentPresetResponse(SpoolFilamentPresetBase):
  185. id: int
  186. spool_id: int
  187. created_at: datetime
  188. class Config:
  189. from_attributes = True
  190. class SpoolResponse(SpoolBase):
  191. id: int
  192. # rgba is intentionally unconstrained on the response side: the write paths
  193. # (SpoolCreate, SpoolUpdate) enforce the 8-char hex pattern, but legacy rows
  194. # or data sourced from AMS firmware / backups may carry malformed values.
  195. # A single bad row must not 500 the entire inventory list endpoint (#1055).
  196. rgba: str | None = None
  197. added_full: bool | None = None
  198. last_used: datetime | None = None
  199. encode_time: datetime | None = None
  200. tag_uid: str | None = None
  201. tray_uuid: str | None = None
  202. data_origin: str | None = None
  203. tag_type: str | None = None
  204. archived_at: datetime | None = None
  205. created_at: datetime
  206. updated_at: datetime
  207. k_profiles: list[SpoolKProfileResponse] = []
  208. class Config:
  209. from_attributes = True
  210. class SpoolAssignmentCreate(BaseModel):
  211. spool_id: int
  212. printer_id: int
  213. ams_id: int
  214. tray_id: int
  215. class SpoolAssignmentResponse(BaseModel):
  216. id: int
  217. spool_id: int
  218. printer_id: int
  219. printer_name: str | None = None
  220. ams_id: int
  221. tray_id: int
  222. fingerprint_color: str | None = None
  223. fingerprint_type: str | None = None
  224. created_at: datetime
  225. spool: SpoolResponse | None = None
  226. configured: bool = False
  227. pending_config: bool = False # True when slot was empty at assign time; will configure on insert
  228. ams_label: str | None = None # User-defined friendly name for the AMS unit
  229. class Config:
  230. from_attributes = True