labels.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """Spool label printing routes (#809).
  2. Two endpoints, one per inventory backend:
  3. - ``POST /inventory/labels`` — local-DB spools
  4. - ``POST /spoolman/labels`` — Spoolman-backed spools
  5. Both accept ``{spool_ids: [int], template: str, starting_position: int}`` plus
  6. the lines to print (``fields``) and the output ``format``: a PDF, or PNGs for
  7. label-printer software that takes images — one PNG as is, several in a ZIP.
  8. Each has a ``/preview`` sibling that renders one label as a PNG for the
  9. picker (#2981).
  10. The QR code on each label deep-links to ``/inventory?spool=<id>`` so a phone
  11. scan jumps straight back into Bambuddy at that spool's row.
  12. """
  13. from __future__ import annotations
  14. import asyncio
  15. import io
  16. import logging
  17. import zipfile
  18. from datetime import date, datetime
  19. from typing import Annotated, Literal
  20. from fastapi import APIRouter, Depends, HTTPException, Request
  21. from fastapi.responses import Response, StreamingResponse
  22. from pydantic import BaseModel, Field, model_validator
  23. from sqlalchemy import select
  24. from sqlalchemy.ext.asyncio import AsyncSession
  25. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  26. from backend.app.api.routes.settings import get_setting
  27. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  28. from backend.app.core.database import get_db
  29. from backend.app.core.permissions import Permission
  30. from backend.app.models.spool import Spool
  31. from backend.app.models.user import User
  32. from backend.app.services.label_renderer import (
  33. ALL_LABEL_FIELDS,
  34. DEFAULT_LABEL_FIELDS,
  35. LabelData,
  36. LabelField,
  37. TemplateName,
  38. get_sheet_capacity,
  39. pdf_to_pngs,
  40. render_label_preview_pdf,
  41. render_labels,
  42. )
  43. from backend.app.services.spoolman import get_spoolman_client
  44. from backend.app.utils.http import build_content_disposition
  45. logger = logging.getLogger(__name__)
  46. router = APIRouter(tags=["labels"])
  47. # Cap how many labels can be requested in one go. Sane upper bound for the
  48. # largest realistic batch (an Avery sheet at 30/page × ~10 pages).
  49. MAX_LABELS_PER_REQUEST = 500
  50. # Preview resolution. High enough that the browser's downscale stays sharp on
  51. # a HiDPI screen; a label is a few centimetres, so the PNG stays small.
  52. PREVIEW_DPI = 300
  53. # Spoolman's mapping rejects an id below 1, so one never reaches it.
  54. SpoolId = Annotated[int, Field(gt=0)]
  55. class LabelOptions(BaseModel):
  56. template: TemplateName
  57. # Black-and-white thermal printers: drop the colour swatch (prints as a
  58. # muddy grey block) and widen the text column instead (#1870).
  59. monochrome: bool = False
  60. # The lines to print (#2981). Omitted: what labels always carried.
  61. fields: list[LabelField] | None = Field(default=None, max_length=len(ALL_LABEL_FIELDS))
  62. def field_set(self) -> frozenset[LabelField]:
  63. return DEFAULT_LABEL_FIELDS if self.fields is None else frozenset(self.fields)
  64. class LabelRequest(LabelOptions):
  65. spool_ids: list[SpoolId] = Field(..., min_length=1, max_length=MAX_LABELS_PER_REQUEST)
  66. starting_position: int = Field(default=1, ge=1)
  67. format: Literal["pdf", "png"] = "pdf"
  68. # PNG only. 203 and 300 are the common thermal-printer resolutions; an
  69. # image at the printer's own resolution is printed dot for dot.
  70. dpi: Literal[203, 300, 600] = 300
  71. @model_validator(mode="after")
  72. def validate_starting_position(self) -> LabelRequest:
  73. capacity = get_sheet_capacity(self.template)
  74. if capacity is None:
  75. if self.starting_position != 1:
  76. raise ValueError("starting_position is only supported for sheet label templates")
  77. return self
  78. if self.starting_position > capacity:
  79. raise ValueError(f"starting_position must be between 1 and {capacity} for template {self.template}")
  80. return self
  81. class LabelPreviewRequest(LabelOptions):
  82. spool_id: SpoolId
  83. def _split_extra_colors(raw: str | None) -> list[str] | None:
  84. """Parse ``Spool.extra_colors`` (comma-separated hex tokens) into a list."""
  85. if not raw:
  86. return None
  87. parts = [p.strip().lstrip("#") for p in raw.split(",") if p.strip()]
  88. return parts or None
  89. async def _resolve_deeplink_base(request: Request, db: AsyncSession) -> str:
  90. """Where the QR codes should point. Prefers `external_url` when set so a
  91. phone scan reaches the user's public Bambuddy URL rather than an internal
  92. address; falls back to the request's own scheme+host when no setting is
  93. configured.
  94. """
  95. external = (await get_setting(db, "external_url") or "").strip().rstrip("/")
  96. if external:
  97. return external
  98. return f"{request.url.scheme}://{request.url.netloc}"
  99. def _spool_to_label_data(spool: Spool, deeplink_base: str) -> LabelData:
  100. name = spool.color_name or spool.slicer_filament_name or f"{spool.brand or ''} {spool.material}".strip()
  101. return LabelData(
  102. spool_id=spool.id,
  103. name=name or spool.material,
  104. material=spool.material,
  105. brand=spool.brand,
  106. subtype=spool.subtype,
  107. rgba=spool.rgba,
  108. extra_colors=_split_extra_colors(spool.extra_colors),
  109. storage_location=getattr(spool, "storage_location", None),
  110. deeplink_url=f"{deeplink_base}/inventory?spool={spool.id}",
  111. material_number=spool.material_number,
  112. nozzle_temp_min=spool.nozzle_temp_min,
  113. nozzle_temp_max=spool.nozzle_temp_max,
  114. label_weight=spool.label_weight,
  115. note=spool.note,
  116. added=spool.created_at.date() if spool.created_at else None,
  117. )
  118. def _parse_date(value: str | None) -> date | None:
  119. if not value:
  120. return None
  121. try:
  122. return datetime.fromisoformat(value).date()
  123. except ValueError:
  124. return None
  125. def _spoolman_dict_to_label_data(s: dict, deeplink_base: str) -> LabelData:
  126. """Build LabelData from a raw Spoolman /spool response dict.
  127. Goes through ``_map_spoolman_spool``, the mapping the inventory page shows,
  128. so a Spoolman label carries what a built-in-inventory label does: the same
  129. subtype, colour name, material number, temperature and weight.
  130. """
  131. m = _map_spoolman_spool(s)
  132. material = m["material"] or ""
  133. # Same precedence as a built-in spool: a colour name the user set, then the
  134. # filament (slicer) name. A synthesised colour name is only the subtype.
  135. color_name = None if m["color_name_is_synthesized"] else m["color_name"]
  136. name = color_name or m["slicer_filament_name"] or f"{m['brand'] or ''} {material}".strip()
  137. return LabelData(
  138. spool_id=m["id"],
  139. name=name or material or "Spool",
  140. material=material,
  141. brand=m["brand"],
  142. subtype=m["subtype"],
  143. rgba=m["rgba"],
  144. extra_colors=_split_extra_colors(m["extra_colors"]),
  145. storage_location=m["storage_location"],
  146. deeplink_url=f"{deeplink_base}/inventory?spool={m['id']}",
  147. material_number=m["material_number"],
  148. nozzle_temp_min=m["nozzle_temp_min"],
  149. nozzle_temp_max=m["nozzle_temp_max"],
  150. label_weight=m["label_weight"],
  151. note=m["note"],
  152. added=_parse_date(m["created_at"]),
  153. )
  154. def _stream_pdf(pdf: bytes, filename: str) -> StreamingResponse:
  155. return StreamingResponse(
  156. io.BytesIO(pdf),
  157. media_type="application/pdf",
  158. headers={
  159. "Content-Disposition": build_content_disposition(filename, disposition="inline"),
  160. "Content-Length": str(len(pdf)),
  161. # PDFs are deterministic per request; tell the browser not to cache
  162. # so re-printing after edits picks up the new data.
  163. "Cache-Control": "no-store",
  164. },
  165. )
  166. async def _render_response(body: LabelRequest, data_list: list[LabelData], filename_stem: str) -> Response:
  167. pdf = render_labels(
  168. body.template,
  169. data_list,
  170. monochrome=body.monochrome,
  171. starting_position=body.starting_position,
  172. fields=body.field_set(),
  173. )
  174. if body.format == "pdf":
  175. return _stream_pdf(pdf, f"{filename_stem}.pdf")
  176. # Rasterising a few hundred pages is CPU work; keep it off the event loop.
  177. pngs = await asyncio.to_thread(pdf_to_pngs, pdf, body.dpi)
  178. if len(pngs) == 1:
  179. return Response(
  180. content=pngs[0],
  181. media_type="image/png",
  182. headers={
  183. "Content-Disposition": build_content_disposition(f"{filename_stem}.png", disposition="attachment"),
  184. "Cache-Control": "no-store",
  185. },
  186. )
  187. # A roll template has one page per spool, so its files are named after
  188. # the spool; a sheet's pages are numbered.
  189. if get_sheet_capacity(body.template) is None:
  190. names = [f"label-{d.spool_id}.png" for d in data_list]
  191. else:
  192. names = [f"sheet-{n}.png" for n in range(1, len(pngs) + 1)]
  193. buf = io.BytesIO()
  194. # PNG is already compressed; deflating it again only costs time.
  195. with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as zf:
  196. for name, png in zip(names, pngs, strict=True):
  197. zf.writestr(name, png)
  198. return Response(
  199. content=buf.getvalue(),
  200. media_type="application/zip",
  201. headers={
  202. "Content-Disposition": build_content_disposition(f"{filename_stem}.zip", disposition="attachment"),
  203. "Cache-Control": "no-store",
  204. },
  205. )
  206. async def _render_preview(body: LabelPreviewRequest, data: LabelData) -> Response:
  207. pdf = render_label_preview_pdf(body.template, data, monochrome=body.monochrome, fields=body.field_set())
  208. pngs = await asyncio.to_thread(pdf_to_pngs, pdf, PREVIEW_DPI)
  209. return Response(content=pngs[0], media_type="image/png", headers={"Cache-Control": "no-store"})
  210. async def _local_label_data(spool_ids: list[int], request: Request, db: AsyncSession) -> list[LabelData]:
  211. result = await db.execute(select(Spool).where(Spool.id.in_(spool_ids)))
  212. spools = list(result.scalars().all())
  213. found_ids = {s.id for s in spools}
  214. missing = [sid for sid in spool_ids if sid not in found_ids]
  215. if missing:
  216. raise HTTPException(404, f"Spool(s) not found: {missing}")
  217. # Preserve caller's order so an Avery sheet print matches the on-screen list.
  218. ordered = sorted(spools, key=lambda s: spool_ids.index(s.id))
  219. deeplink_base = await _resolve_deeplink_base(request, db)
  220. return [_spool_to_label_data(s, deeplink_base) for s in ordered]
  221. async def _spoolman_label_data(spool_ids: list[int], request: Request, db: AsyncSession) -> list[LabelData]:
  222. """The Spoolman client doesn't expose a per-id endpoint, so this fetches the
  223. full spool list and filters in-memory. For typical libraries (~50 spools)
  224. that's negligible; for very large libraries this is the trade-off until
  225. Spoolman gains a bulk filter.
  226. """
  227. spoolman_on = (await get_setting(db, "spoolman_enabled") or "").lower() == "true"
  228. if not spoolman_on:
  229. raise HTTPException(400, "Spoolman integration is not enabled")
  230. client = await get_spoolman_client()
  231. if client is None or not client.is_connected:
  232. raise HTTPException(503, "Spoolman not reachable")
  233. try:
  234. all_spools = await client.get_spools()
  235. except Exception as exc:
  236. logger.warning("Spoolman fetch failed during label render: %s", exc)
  237. raise HTTPException(502, "Failed to fetch spools from Spoolman") from exc
  238. by_id = {int(s.get("id", 0)): s for s in all_spools if s.get("id") is not None}
  239. missing = [sid for sid in spool_ids if sid not in by_id]
  240. if missing:
  241. raise HTTPException(404, f"Spool(s) not found in Spoolman: {missing}")
  242. deeplink_base = await _resolve_deeplink_base(request, db)
  243. return [_spoolman_dict_to_label_data(by_id[sid], deeplink_base) for sid in spool_ids]
  244. @router.post("/inventory/labels")
  245. async def render_local_inventory_labels(
  246. body: LabelRequest,
  247. request: Request,
  248. db: AsyncSession = Depends(get_db),
  249. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  250. ) -> Response:
  251. """Render labels for spools in the local inventory."""
  252. data_list = await _local_label_data(body.spool_ids, request, db)
  253. return await _render_response(body, data_list, f"bambuddy-labels-{body.template}")
  254. @router.post("/inventory/labels/preview")
  255. async def preview_local_inventory_label(
  256. body: LabelPreviewRequest,
  257. request: Request,
  258. db: AsyncSession = Depends(get_db),
  259. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  260. ) -> Response:
  261. """One label for a local spool, as a PNG, for the picker's preview."""
  262. data_list = await _local_label_data([body.spool_id], request, db)
  263. return await _render_preview(body, data_list[0])
  264. @router.post("/spoolman/labels")
  265. async def render_spoolman_labels(
  266. body: LabelRequest,
  267. request: Request,
  268. db: AsyncSession = Depends(get_db),
  269. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  270. ) -> Response:
  271. """Render labels for spools tracked in Spoolman."""
  272. data_list = await _spoolman_label_data(body.spool_ids, request, db)
  273. return await _render_response(body, data_list, f"bambuddy-labels-spoolman-{body.template}")
  274. @router.post("/spoolman/labels/preview")
  275. async def preview_spoolman_label(
  276. body: LabelPreviewRequest,
  277. request: Request,
  278. db: AsyncSession = Depends(get_db),
  279. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  280. ) -> Response:
  281. """One label for a Spoolman spool, as a PNG, for the picker's preview."""
  282. data_list = await _spoolman_label_data([body.spool_id], request, db)
  283. return await _render_preview(body, data_list[0])