spool.py 9.8 KB

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