spool.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. from datetime import datetime, timezone
  2. from pydantic import BaseModel, Field, field_validator
  3. from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
  4. from backend.app.schemas.supplier import SpoolSupplierResponse
  5. # Visual variant applied to a spool's swatch — purely cosmetic, does not
  6. # affect MQTT/firmware. Kept independent of `subtype` so users can override
  7. # the rendering hint without touching Bambu's categorical filament label.
  8. # Mirrors the visual variants the spool form's `KNOWN_VARIANTS` exposes so
  9. # the catalog and spool form share one vocabulary; structural variants like
  10. # gradient/dual-color/tri-color/multicolor combine with `extra_colors` for
  11. # rendering, surface effects (sparkle/wood/marble/glow/matte) layer overlays.
  12. ALLOWED_EFFECT_TYPES = frozenset(
  13. {
  14. # Surface effects
  15. "sparkle",
  16. "wood",
  17. "marble",
  18. "glow",
  19. "matte",
  20. # Sheen / finish variants
  21. "silk",
  22. "galaxy",
  23. "rainbow",
  24. "metal",
  25. "translucent",
  26. # Multi-colour structures (drive gradient rendering when paired with extra_colors)
  27. "gradient",
  28. "dual-color",
  29. "tri-color",
  30. "multicolor",
  31. }
  32. )
  33. # Cap how many gradient stops we accept on input so a paste of arbitrary text
  34. # can't blow up the stored value or downstream rendering.
  35. MAX_EXTRA_COLOR_STOPS = 8
  36. def normalize_extra_colors(value: str | None) -> str | None:
  37. """Parse comma-separated hex tokens into canonical lowercase form.
  38. Accepts 6- or 8-char hex per token, with or without leading `#`. Returns
  39. None for blank input, raises ValueError for malformed tokens or too many
  40. stops. Output is the comma-joined canonical form (no `#`, lowercase).
  41. """
  42. if value is None:
  43. return None
  44. raw = value.strip()
  45. if not raw:
  46. return None
  47. tokens = [tok.strip().lstrip("#").lower() for tok in raw.split(",") if tok.strip()]
  48. if not tokens:
  49. return None
  50. if len(tokens) > MAX_EXTRA_COLOR_STOPS:
  51. raise ValueError(f"extra_colors accepts at most {MAX_EXTRA_COLOR_STOPS} stops")
  52. for tok in tokens:
  53. if len(tok) not in (6, 8):
  54. raise ValueError(f"extra_colors token '{tok}' must be 6 or 8 hex chars")
  55. try:
  56. int(tok, 16)
  57. except ValueError as exc:
  58. raise ValueError(f"extra_colors token '{tok}' is not valid hex") from exc
  59. return ",".join(tokens)
  60. def normalize_material_number(value: str | None) -> str | None:
  61. """Trim the material number and treat a blank one as unset (#2870).
  62. Every write path lands here (form, bulk edit, CSV import, direct API), so
  63. "15" and "15 " can never become two groups in the statistics aggregate or
  64. two entries in the inventory filter. Blank collapses to NULL rather than
  65. "", which keeps "has no number" a single state to query for.
  66. """
  67. if value is None:
  68. return None
  69. return value.strip() or None
  70. def normalize_effect_type(value: str | None) -> str | None:
  71. if value is None:
  72. return None
  73. trimmed = value.strip().lower()
  74. if not trimmed:
  75. return None
  76. # Tolerate "Dual Color" / "dual_color" / "dual color" → "dual-color" so
  77. # users pasting from spool-subtype labels don't hit a validation wall.
  78. canonical = trimmed.replace("_", "-").replace(" ", "-")
  79. if canonical not in ALLOWED_EFFECT_TYPES:
  80. raise ValueError(f"effect_type must be one of: {sorted(ALLOWED_EFFECT_TYPES)}")
  81. return canonical
  82. def naive_utc(value: datetime | None) -> datetime | None:
  83. """Store a datetime the way Bambuddy's naive ``DateTime`` columns hold it: UTC.
  84. A browser sends local time with an offset. Dropping the offset without
  85. converting would shift the stored moment by that offset (#2863).
  86. """
  87. if value is not None and value.tzinfo is not None:
  88. return value.astimezone(timezone.utc).replace(tzinfo=None)
  89. return value
  90. class SpoolBase(BaseModel):
  91. material: str = Field(..., min_length=1, max_length=50)
  92. subtype: str | None = None
  93. color_name: str | None = None
  94. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  95. extra_colors: str | None = None
  96. effect_type: str | None = None
  97. brand: str | None = None
  98. @field_validator("extra_colors")
  99. @classmethod
  100. def _validate_extra_colors(cls, v: str | None) -> str | None:
  101. return normalize_extra_colors(v)
  102. @field_validator("effect_type")
  103. @classmethod
  104. def _validate_effect_type(cls, v: str | None) -> str | None:
  105. return normalize_effect_type(v)
  106. label_weight: int = 1000
  107. core_weight: int = 250
  108. core_weight_catalog_id: int | None = None
  109. weight_used: float = 0
  110. # Anchor for the resettable "Total Consumed" display. The Inventory
  111. # page shows `weight_used - weight_used_baseline`; the per-spool /
  112. # bulk "Reset usage to 0" action sets baseline = weight_used so the
  113. # counter zeroes without touching remaining (#1390).
  114. weight_used_baseline: float = 0
  115. slicer_filament: str | None = None
  116. slicer_filament_name: str | None = None
  117. nozzle_temp_min: int | None = None
  118. nozzle_temp_max: int | None = None
  119. note: str | None = None
  120. tag_uid: str | None = None
  121. tray_uuid: str | None = None
  122. data_origin: str | None = None
  123. tag_type: str | None = None
  124. cost_per_kg: float | None = Field(default=None, ge=0)
  125. weight_locked: bool = False
  126. last_scale_weight: int | None = None
  127. last_weighed_at: datetime | None = None
  128. # User-defined category + per-spool low-stock threshold override (#729).
  129. category: str | None = Field(default=None, max_length=50)
  130. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  131. # Internal material / article number (#2870) — the purchasing identifier,
  132. # shared by all spools of the same product. Free text, no uniqueness.
  133. material_number: str | None = Field(default=None, max_length=64)
  134. # mode="before": trim first, so a padded value is held to the 64
  135. # characters it will store, not to the length it arrived with.
  136. @field_validator("material_number", mode="before")
  137. @classmethod
  138. def _validate_material_number(cls, v):
  139. return normalize_material_number(v) if isinstance(v, str) else v
  140. # Free-text storage location, distinct from `location` (AMS slot
  141. # assignment). Column has lived on the ORM since the inventory rework
  142. # but was missing from this schema, so writes were silently dropped (#1291).
  143. storage_location: str | None = Field(default=None, max_length=255)
  144. location_id: int | None = Field(default=None, gt=0)
  145. class SpoolCreate(SpoolBase):
  146. # Never negative from a client; more than the label is possible (print
  147. # tracking of a mis-labelled spool). Here, not on SpoolBase: a response
  148. # must still serialise a value stored before there was a bound.
  149. weight_used: float = Field(default=0, ge=0)
  150. class SpoolBulkCreate(BaseModel):
  151. spool: SpoolCreate
  152. quantity: int = Field(default=1, ge=1, le=100)
  153. class SpoolUpdate(IgnoresNullForRequiredColumns):
  154. __orm_table__ = "spool"
  155. material: str | None = None
  156. subtype: str | None = None
  157. color_name: str | None = None
  158. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  159. extra_colors: str | None = None
  160. effect_type: str | None = None
  161. brand: str | None = None
  162. @field_validator("extra_colors")
  163. @classmethod
  164. def _validate_extra_colors(cls, v: str | None) -> str | None:
  165. return normalize_extra_colors(v)
  166. @field_validator("effect_type")
  167. @classmethod
  168. def _validate_effect_type(cls, v: str | None) -> str | None:
  169. return normalize_effect_type(v)
  170. label_weight: int | None = None
  171. core_weight: int | None = None
  172. core_weight_catalog_id: int | None = None
  173. weight_used: float | None = Field(default=None, ge=0)
  174. slicer_filament: str | None = None
  175. slicer_filament_name: str | None = None
  176. nozzle_temp_min: int | None = None
  177. nozzle_temp_max: int | None = None
  178. note: str | None = None
  179. tag_uid: str | None = None
  180. tray_uuid: str | None = None
  181. data_origin: str | None = None
  182. tag_type: str | None = None
  183. cost_per_kg: float | None = Field(default=None, ge=0)
  184. weight_locked: bool | None = None
  185. # Set by hand for a drying done outside an AMS; null clears it (#2863).
  186. last_dried_at: datetime | None = None
  187. @field_validator("last_dried_at")
  188. @classmethod
  189. def _validate_last_dried_at(cls, v: datetime | None) -> datetime | None:
  190. return naive_utc(v)
  191. # User-defined category + per-spool low-stock threshold override (#729).
  192. category: str | None = Field(default=None, max_length=50)
  193. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  194. # Internal material / article number (#2870).
  195. material_number: str | None = Field(default=None, max_length=64)
  196. # mode="before": trim first, so a padded value is held to the 64
  197. # characters it will store, not to the length it arrived with.
  198. @field_validator("material_number", mode="before")
  199. @classmethod
  200. def _validate_material_number(cls, v):
  201. return normalize_material_number(v) if isinstance(v, str) else v
  202. storage_location: str | None = Field(default=None, max_length=255)
  203. location_id: int | None = Field(default=None, gt=0)
  204. class SpoolKProfileBase(BaseModel):
  205. printer_id: int
  206. extruder: int = 0
  207. nozzle_diameter: str = "0.4"
  208. nozzle_type: str | None = None
  209. k_value: float
  210. name: str | None = None
  211. cali_idx: int | None = None
  212. setting_id: str | None = None
  213. class SpoolKProfileResponse(SpoolKProfileBase):
  214. id: int
  215. spool_id: int
  216. created_at: datetime
  217. class Config:
  218. from_attributes = True
  219. class SpoolFilamentPresetBase(BaseModel):
  220. """One per-printer-model slicer preset override for a spool.
  221. ``nozzle_diameter`` defaults to "" meaning "any nozzle of this model". The
  222. spool form always sends a concrete size; the empty form is for API clients
  223. that want one value to cover a model. Lengths match the columns, which are wider than
  224. ``Spool.slicer_filament`` so a preset id that fits the Spoolman write
  225. schema cannot truncate on the way in.
  226. """
  227. printer_model: str = Field(..., min_length=1, max_length=50)
  228. nozzle_diameter: str = Field(default="", max_length=10)
  229. slicer_filament: str | None = Field(default=None, max_length=128)
  230. slicer_filament_name: str | None = Field(default=None, max_length=255)
  231. class SpoolFilamentPresetResponse(SpoolFilamentPresetBase):
  232. id: int
  233. spool_id: int
  234. created_at: datetime
  235. class Config:
  236. from_attributes = True
  237. class SpoolResponse(SpoolBase):
  238. id: int
  239. # rgba is intentionally unconstrained on the response side: the write paths
  240. # (SpoolCreate, SpoolUpdate) enforce the 8-char hex pattern, but legacy rows
  241. # or data sourced from AMS firmware / backups may carry malformed values.
  242. # A single bad row must not 500 the entire inventory list endpoint (#1055).
  243. rgba: str | None = None
  244. added_full: bool | None = None
  245. last_used: datetime | None = None
  246. # Last drying (#2863). Only the date is writable, through SpoolUpdate.
  247. last_dried_at: datetime | None = None
  248. last_dried_temp: int | None = None
  249. last_dried_hours: float | None = None
  250. encode_time: datetime | None = None
  251. tag_uid: str | None = None
  252. tray_uuid: str | None = None
  253. data_origin: str | None = None
  254. tag_type: str | None = None
  255. archived_at: datetime | None = None
  256. created_at: datetime
  257. updated_at: datetime
  258. k_profiles: list[SpoolKProfileResponse] = []
  259. # Supplier assignments (#2988): where this product can be bought, with
  260. # per-assignment article number / price and a purchase-source marker.
  261. # Reads the ORM relationship `supplier_links`, which every route
  262. # answering with this schema loads explicitly (see spool_response_loads).
  263. suppliers: list[SpoolSupplierResponse] = Field(default=[], validation_alias="supplier_links")
  264. class Config:
  265. from_attributes = True
  266. populate_by_name = True
  267. class MaterialNumberStats(BaseModel):
  268. """Per-material-number inventory aggregate (#2870).
  269. ``spool_count`` and ``remaining_g`` cover active (non-archived) spools;
  270. ``consumed_g`` and ``cost`` sum the recorded usage history of every spool
  271. carrying the number, archived included — consumption doesn't disappear
  272. when a spool is archived.
  273. """
  274. material_number: str
  275. spool_count: int
  276. remaining_g: float
  277. consumed_g: float
  278. cost: float
  279. class SpoolAssignmentCreate(BaseModel):
  280. spool_id: int
  281. printer_id: int
  282. ams_id: int
  283. tray_id: int
  284. class SpoolAssignmentResponse(BaseModel):
  285. id: int
  286. spool_id: int
  287. printer_id: int
  288. printer_name: str | None = None
  289. ams_id: int
  290. tray_id: int
  291. fingerprint_color: str | None = None
  292. fingerprint_type: str | None = None
  293. created_at: datetime
  294. spool: SpoolResponse | None = None
  295. configured: bool = False
  296. pending_config: bool = False # True when slot was empty at assign time; will configure on insert
  297. ams_label: str | None = None # User-defined friendly name for the AMS unit
  298. class Config:
  299. from_attributes = True