spool.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. pass
  147. class SpoolBulkCreate(BaseModel):
  148. spool: SpoolCreate
  149. quantity: int = Field(default=1, ge=1, le=100)
  150. class SpoolUpdate(IgnoresNullForRequiredColumns):
  151. __orm_table__ = "spool"
  152. material: str | None = None
  153. subtype: str | None = None
  154. color_name: str | None = None
  155. rgba: str | None = Field(None, pattern=r"^[0-9A-Fa-f]{8}$")
  156. extra_colors: str | None = None
  157. effect_type: str | None = None
  158. brand: str | None = None
  159. @field_validator("extra_colors")
  160. @classmethod
  161. def _validate_extra_colors(cls, v: str | None) -> str | None:
  162. return normalize_extra_colors(v)
  163. @field_validator("effect_type")
  164. @classmethod
  165. def _validate_effect_type(cls, v: str | None) -> str | None:
  166. return normalize_effect_type(v)
  167. label_weight: int | None = None
  168. core_weight: int | None = None
  169. core_weight_catalog_id: int | None = None
  170. weight_used: float | None = None
  171. slicer_filament: str | None = None
  172. slicer_filament_name: str | None = None
  173. nozzle_temp_min: int | None = None
  174. nozzle_temp_max: int | None = None
  175. note: str | None = None
  176. tag_uid: str | None = None
  177. tray_uuid: str | None = None
  178. data_origin: str | None = None
  179. tag_type: str | None = None
  180. cost_per_kg: float | None = Field(default=None, ge=0)
  181. weight_locked: bool | None = None
  182. # Set by hand for a drying done outside an AMS; null clears it (#2863).
  183. last_dried_at: datetime | None = None
  184. @field_validator("last_dried_at")
  185. @classmethod
  186. def _validate_last_dried_at(cls, v: datetime | None) -> datetime | None:
  187. return naive_utc(v)
  188. # User-defined category + per-spool low-stock threshold override (#729).
  189. category: str | None = Field(default=None, max_length=50)
  190. low_stock_threshold_pct: int | None = Field(default=None, ge=1, le=99)
  191. # Internal material / article number (#2870).
  192. material_number: str | None = Field(default=None, max_length=64)
  193. # mode="before": trim first, so a padded value is held to the 64
  194. # characters it will store, not to the length it arrived with.
  195. @field_validator("material_number", mode="before")
  196. @classmethod
  197. def _validate_material_number(cls, v):
  198. return normalize_material_number(v) if isinstance(v, str) else v
  199. storage_location: str | None = Field(default=None, max_length=255)
  200. location_id: int | None = Field(default=None, gt=0)
  201. class SpoolKProfileBase(BaseModel):
  202. printer_id: int
  203. extruder: int = 0
  204. nozzle_diameter: str = "0.4"
  205. nozzle_type: str | None = None
  206. k_value: float
  207. name: str | None = None
  208. cali_idx: int | None = None
  209. setting_id: str | None = None
  210. class SpoolKProfileResponse(SpoolKProfileBase):
  211. id: int
  212. spool_id: int
  213. created_at: datetime
  214. class Config:
  215. from_attributes = True
  216. class SpoolFilamentPresetBase(BaseModel):
  217. """One per-printer-model slicer preset override for a spool.
  218. ``nozzle_diameter`` defaults to "" meaning "any nozzle of this model". The
  219. spool form always sends a concrete size; the empty form is for API clients
  220. that want one value to cover a model. Lengths match the columns, which are wider than
  221. ``Spool.slicer_filament`` so a preset id that fits the Spoolman write
  222. schema cannot truncate on the way in.
  223. """
  224. printer_model: str = Field(..., min_length=1, max_length=50)
  225. nozzle_diameter: str = Field(default="", max_length=10)
  226. slicer_filament: str | None = Field(default=None, max_length=128)
  227. slicer_filament_name: str | None = Field(default=None, max_length=255)
  228. class SpoolFilamentPresetResponse(SpoolFilamentPresetBase):
  229. id: int
  230. spool_id: int
  231. created_at: datetime
  232. class Config:
  233. from_attributes = True
  234. class SpoolResponse(SpoolBase):
  235. id: int
  236. # rgba is intentionally unconstrained on the response side: the write paths
  237. # (SpoolCreate, SpoolUpdate) enforce the 8-char hex pattern, but legacy rows
  238. # or data sourced from AMS firmware / backups may carry malformed values.
  239. # A single bad row must not 500 the entire inventory list endpoint (#1055).
  240. rgba: str | None = None
  241. added_full: bool | None = None
  242. last_used: datetime | None = None
  243. # Last drying (#2863). Only the date is writable, through SpoolUpdate.
  244. last_dried_at: datetime | None = None
  245. last_dried_temp: int | None = None
  246. last_dried_hours: float | None = None
  247. encode_time: datetime | None = None
  248. tag_uid: str | None = None
  249. tray_uuid: str | None = None
  250. data_origin: str | None = None
  251. tag_type: str | None = None
  252. archived_at: datetime | None = None
  253. created_at: datetime
  254. updated_at: datetime
  255. k_profiles: list[SpoolKProfileResponse] = []
  256. # Supplier assignments (#2988): where this product can be bought, with
  257. # per-assignment article number / price and a purchase-source marker.
  258. # Reads the ORM relationship `supplier_links`, which every route
  259. # answering with this schema loads explicitly (see spool_response_loads).
  260. suppliers: list[SpoolSupplierResponse] = Field(default=[], validation_alias="supplier_links")
  261. class Config:
  262. from_attributes = True
  263. populate_by_name = True
  264. class MaterialNumberStats(BaseModel):
  265. """Per-material-number inventory aggregate (#2870).
  266. ``spool_count`` and ``remaining_g`` cover active (non-archived) spools;
  267. ``consumed_g`` and ``cost`` sum the recorded usage history of every spool
  268. carrying the number, archived included — consumption doesn't disappear
  269. when a spool is archived.
  270. """
  271. material_number: str
  272. spool_count: int
  273. remaining_g: float
  274. consumed_g: float
  275. cost: float
  276. class SpoolAssignmentCreate(BaseModel):
  277. spool_id: int
  278. printer_id: int
  279. ams_id: int
  280. tray_id: int
  281. class SpoolAssignmentResponse(BaseModel):
  282. id: int
  283. spool_id: int
  284. printer_id: int
  285. printer_name: str | None = None
  286. ams_id: int
  287. tray_id: int
  288. fingerprint_color: str | None = None
  289. fingerprint_type: str | None = None
  290. created_at: datetime
  291. spool: SpoolResponse | None = None
  292. configured: bool = False
  293. pending_config: bool = False # True when slot was empty at assign time; will configure on insert
  294. ams_label: str | None = None # User-defined friendly name for the AMS unit
  295. class Config:
  296. from_attributes = True