spool.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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_material_number(value: str | None) -> str | None:
  60. """Trim the material number and treat a blank one as unset (#2870).
  61. Every write path lands here (form, bulk edit, CSV import, direct API), so
  62. "15" and "15 " can never become two groups in the statistics aggregate or
  63. two entries in the inventory filter. Blank collapses to NULL rather than
  64. "", which keeps "has no number" a single state to query for.
  65. """
  66. if value is None:
  67. return None
  68. return value.strip() or None
  69. def normalize_effect_type(value: str | None) -> str | None:
  70. if value is None:
  71. return None
  72. trimmed = value.strip().lower()
  73. if not trimmed:
  74. return None
  75. # Tolerate "Dual Color" / "dual_color" / "dual color" → "dual-color" so
  76. # users pasting from spool-subtype labels don't hit a validation wall.
  77. canonical = trimmed.replace("_", "-").replace(" ", "-")
  78. if canonical not in ALLOWED_EFFECT_TYPES:
  79. raise ValueError(f"effect_type must be one of: {sorted(ALLOWED_EFFECT_TYPES)}")
  80. return canonical
  81. class SpoolBase(BaseModel):
  82. material: str = Field(..., min_length=1, max_length=50)
  83. subtype: str | None = None
  84. color_name: str | None = None
  85. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  86. extra_colors: str | None = None
  87. effect_type: str | None = None
  88. brand: str | None = None
  89. @field_validator("extra_colors")
  90. @classmethod
  91. def _validate_extra_colors(cls, v: str | None) -> str | None:
  92. return normalize_extra_colors(v)
  93. @field_validator("effect_type")
  94. @classmethod
  95. def _validate_effect_type(cls, v: str | None) -> str | None:
  96. return normalize_effect_type(v)
  97. label_weight: int = 1000
  98. core_weight: int = 250
  99. core_weight_catalog_id: int | None = None
  100. weight_used: float = 0
  101. # Anchor for the resettable "Total Consumed" display. The Inventory
  102. # page shows `weight_used - weight_used_baseline`; the per-spool /
  103. # bulk "Reset usage to 0" action sets baseline = weight_used so the
  104. # counter zeroes without touching remaining (#1390).
  105. weight_used_baseline: float = 0
  106. slicer_filament: str | None = None
  107. slicer_filament_name: str | None = None
  108. nozzle_temp_min: int | None = None
  109. nozzle_temp_max: int | None = None
  110. note: str | None = None
  111. tag_uid: str | None = None
  112. tray_uuid: str | None = None
  113. data_origin: str | None = None
  114. tag_type: str | None = None
  115. cost_per_kg: float | None = Field(default=None, ge=0)
  116. weight_locked: bool = False
  117. last_scale_weight: int | None = None
  118. last_weighed_at: datetime | None = None
  119. # User-defined category + per-spool low-stock threshold override (#729).
  120. category: str | None = Field(default=None, max_length=50)
  121. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  122. # Internal material / article number (#2870) — the purchasing identifier,
  123. # shared by all spools of the same product. Free text, no uniqueness.
  124. material_number: str | None = Field(default=None, max_length=64)
  125. # mode="before": trim first, so a padded value is held to the 64
  126. # characters it will store, not to the length it arrived with.
  127. @field_validator("material_number", mode="before")
  128. @classmethod
  129. def _validate_material_number(cls, v):
  130. return normalize_material_number(v) if isinstance(v, str) else v
  131. # Free-text storage location, distinct from `location` (AMS slot
  132. # assignment). Column has lived on the ORM since the inventory rework
  133. # but was missing from this schema, so writes were silently dropped (#1291).
  134. storage_location: str | None = Field(default=None, max_length=255)
  135. location_id: int | None = Field(default=None, gt=0)
  136. class SpoolCreate(SpoolBase):
  137. pass
  138. class SpoolBulkCreate(BaseModel):
  139. spool: SpoolCreate
  140. quantity: int = Field(default=1, ge=1, le=100)
  141. class SpoolUpdate(BaseModel):
  142. material: str | None = None
  143. subtype: str | None = None
  144. color_name: str | None = None
  145. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  146. extra_colors: str | None = None
  147. effect_type: str | None = None
  148. brand: str | None = None
  149. @field_validator("extra_colors")
  150. @classmethod
  151. def _validate_extra_colors(cls, v: str | None) -> str | None:
  152. return normalize_extra_colors(v)
  153. @field_validator("effect_type")
  154. @classmethod
  155. def _validate_effect_type(cls, v: str | None) -> str | None:
  156. return normalize_effect_type(v)
  157. label_weight: int | None = None
  158. core_weight: int | None = None
  159. core_weight_catalog_id: int | None = None
  160. weight_used: float | None = None
  161. slicer_filament: str | None = None
  162. slicer_filament_name: str | None = None
  163. nozzle_temp_min: int | None = None
  164. nozzle_temp_max: int | None = None
  165. note: str | None = None
  166. tag_uid: str | None = None
  167. tray_uuid: str | None = None
  168. data_origin: str | None = None
  169. tag_type: str | None = None
  170. cost_per_kg: float | None = Field(default=None, ge=0)
  171. weight_locked: bool | None = None
  172. # User-defined category + per-spool low-stock threshold override (#729).
  173. category: str | None = Field(default=None, max_length=50)
  174. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  175. # Internal material / article number (#2870).
  176. material_number: str | None = Field(default=None, max_length=64)
  177. # mode="before": trim first, so a padded value is held to the 64
  178. # characters it will store, not to the length it arrived with.
  179. @field_validator("material_number", mode="before")
  180. @classmethod
  181. def _validate_material_number(cls, v):
  182. return normalize_material_number(v) if isinstance(v, str) else v
  183. storage_location: str | None = Field(default=None, max_length=255)
  184. location_id: int | None = Field(default=None, gt=0)
  185. class SpoolKProfileBase(BaseModel):
  186. printer_id: int
  187. extruder: int = 0
  188. nozzle_diameter: str = "0.4"
  189. nozzle_type: str | None = None
  190. k_value: float
  191. name: str | None = None
  192. cali_idx: int | None = None
  193. setting_id: str | None = None
  194. class SpoolKProfileResponse(SpoolKProfileBase):
  195. id: int
  196. spool_id: int
  197. created_at: datetime
  198. class Config:
  199. from_attributes = True
  200. class SpoolFilamentPresetBase(BaseModel):
  201. """One per-printer-model slicer preset override for a spool.
  202. ``nozzle_diameter`` defaults to "" meaning "any nozzle of this model". The
  203. spool form always sends a concrete size; the empty form is for API clients
  204. that want one value to cover a model. Lengths match the columns, which are wider than
  205. ``Spool.slicer_filament`` so a preset id that fits the Spoolman write
  206. schema cannot truncate on the way in.
  207. """
  208. printer_model: str = Field(..., min_length=1, max_length=50)
  209. nozzle_diameter: str = Field(default="", max_length=10)
  210. slicer_filament: str | None = Field(default=None, max_length=128)
  211. slicer_filament_name: str | None = Field(default=None, max_length=255)
  212. class SpoolFilamentPresetResponse(SpoolFilamentPresetBase):
  213. id: int
  214. spool_id: int
  215. created_at: datetime
  216. class Config:
  217. from_attributes = True
  218. class SpoolResponse(SpoolBase):
  219. id: int
  220. # rgba is intentionally unconstrained on the response side: the write paths
  221. # (SpoolCreate, SpoolUpdate) enforce the 8-char hex pattern, but legacy rows
  222. # or data sourced from AMS firmware / backups may carry malformed values.
  223. # A single bad row must not 500 the entire inventory list endpoint (#1055).
  224. rgba: str | None = None
  225. added_full: bool | None = None
  226. last_used: datetime | None = None
  227. encode_time: datetime | None = None
  228. tag_uid: str | None = None
  229. tray_uuid: str | None = None
  230. data_origin: str | None = None
  231. tag_type: str | None = None
  232. archived_at: datetime | None = None
  233. created_at: datetime
  234. updated_at: datetime
  235. k_profiles: list[SpoolKProfileResponse] = []
  236. # Supplier assignments (#2988): where this product can be bought, with
  237. # per-assignment article number / price and a purchase-source marker.
  238. # Reads the ORM relationship `supplier_links`, which every route
  239. # answering with this schema loads explicitly (see spool_response_loads).
  240. suppliers: list[SpoolSupplierResponse] = Field(default=[], validation_alias="supplier_links")
  241. class Config:
  242. from_attributes = True
  243. populate_by_name = True
  244. class MaterialNumberStats(BaseModel):
  245. """Per-material-number inventory aggregate (#2870).
  246. ``spool_count`` and ``remaining_g`` cover active (non-archived) spools;
  247. ``consumed_g`` and ``cost`` sum the recorded usage history of every spool
  248. carrying the number, archived included — consumption doesn't disappear
  249. when a spool is archived.
  250. """
  251. material_number: str
  252. spool_count: int
  253. remaining_g: float
  254. consumed_g: float
  255. cost: float
  256. class SpoolAssignmentCreate(BaseModel):
  257. spool_id: int
  258. printer_id: int
  259. ams_id: int
  260. tray_id: int
  261. class SpoolAssignmentResponse(BaseModel):
  262. id: int
  263. spool_id: int
  264. printer_id: int
  265. printer_name: str | None = None
  266. ams_id: int
  267. tray_id: int
  268. fingerprint_color: str | None = None
  269. fingerprint_type: str | None = None
  270. created_at: datetime
  271. spool: SpoolResponse | None = None
  272. configured: bool = False
  273. pending_config: bool = False # True when slot was empty at assign time; will configure on insert
  274. ams_label: str | None = None # User-defined friendly name for the AMS unit
  275. class Config:
  276. from_attributes = True