spool.py 13 KB

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