labels.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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}`` and
  6. return a PDF stream.
  7. The QR code on each label deep-links to ``/inventory?spool=<id>`` so a phone
  8. scan jumps straight back into Bambuddy at that spool's row.
  9. """
  10. from __future__ import annotations
  11. import io
  12. import logging
  13. from typing import Literal
  14. from fastapi import APIRouter, Depends, HTTPException, Request
  15. from fastapi.responses import StreamingResponse
  16. from pydantic import BaseModel, Field, model_validator
  17. from sqlalchemy import select
  18. from sqlalchemy.ext.asyncio import AsyncSession
  19. from backend.app.api.routes.settings import get_setting
  20. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  21. from backend.app.core.database import get_db
  22. from backend.app.core.permissions import Permission
  23. from backend.app.models.spool import Spool
  24. from backend.app.models.user import User
  25. from backend.app.services.label_renderer import LabelData, TemplateName, get_sheet_capacity, render_labels
  26. from backend.app.services.spoolman import get_spoolman_client
  27. from backend.app.utils.http import build_content_disposition
  28. logger = logging.getLogger(__name__)
  29. router = APIRouter(tags=["labels"])
  30. _VALID_TEMPLATES: tuple[TemplateName, ...] = (
  31. "ams_holder_74x33",
  32. "ams_holder_75x55",
  33. "box_40x30",
  34. "box_62x29",
  35. "avery_5160",
  36. "avery_l7160",
  37. )
  38. # Cap how many labels can be requested in one go. Sane upper bound for the
  39. # largest realistic batch (an Avery sheet at 30/page × ~10 pages).
  40. MAX_LABELS_PER_REQUEST = 500
  41. class LabelRequest(BaseModel):
  42. spool_ids: list[int] = Field(..., min_length=1, max_length=MAX_LABELS_PER_REQUEST)
  43. template: Literal[
  44. "ams_holder_74x33",
  45. "ams_holder_75x55",
  46. "box_40x30",
  47. "box_62x29",
  48. "avery_5160",
  49. "avery_l7160",
  50. ]
  51. # Black-and-white thermal printers: drop the colour swatch (prints as a
  52. # muddy grey block) and widen the text column instead (#1870).
  53. monochrome: bool = False
  54. starting_position: int = Field(default=1, ge=1)
  55. @model_validator(mode="after")
  56. def validate_starting_position(self) -> LabelRequest:
  57. capacity = get_sheet_capacity(self.template)
  58. if capacity is None:
  59. if self.starting_position != 1:
  60. raise ValueError("starting_position is only supported for sheet label templates")
  61. return self
  62. if self.starting_position > capacity:
  63. raise ValueError(f"starting_position must be between 1 and {capacity} for template {self.template}")
  64. return self
  65. def _split_extra_colors(raw: str | None) -> list[str] | None:
  66. """Parse ``Spool.extra_colors`` (comma-separated hex tokens) into a list."""
  67. if not raw:
  68. return None
  69. parts = [p.strip().lstrip("#") for p in raw.split(",") if p.strip()]
  70. return parts or None
  71. async def _resolve_deeplink_base(request: Request, db: AsyncSession) -> str:
  72. """Where the QR codes should point. Prefers `external_url` when set so a
  73. phone scan reaches the user's public Bambuddy URL rather than an internal
  74. address; falls back to the request's own scheme+host when no setting is
  75. configured.
  76. """
  77. external = (await get_setting(db, "external_url") or "").strip().rstrip("/")
  78. if external:
  79. return external
  80. return f"{request.url.scheme}://{request.url.netloc}"
  81. def _spool_to_label_data(spool: Spool, deeplink_base: str) -> LabelData:
  82. name = spool.color_name or spool.slicer_filament_name or f"{spool.brand or ''} {spool.material}".strip()
  83. return LabelData(
  84. spool_id=spool.id,
  85. name=name or spool.material,
  86. material=spool.material,
  87. brand=spool.brand,
  88. subtype=spool.subtype,
  89. rgba=spool.rgba,
  90. extra_colors=_split_extra_colors(spool.extra_colors),
  91. storage_location=getattr(spool, "storage_location", None),
  92. deeplink_url=f"{deeplink_base}/inventory?spool={spool.id}",
  93. )
  94. def _spoolman_dict_to_label_data(s: dict, deeplink_base: str) -> LabelData:
  95. """Build LabelData from a raw Spoolman /spool response dict.
  96. Spoolman models don't have a native 'spool name' — we derive it from the
  97. embedded filament. Material and brand come from filament/vendor.
  98. """
  99. filament = s.get("filament") or {}
  100. vendor = filament.get("vendor") or {}
  101. fname = filament.get("name") or ""
  102. material = filament.get("material") or ""
  103. brand = vendor.get("name")
  104. color_hex = filament.get("color_hex")
  105. rgba = color_hex.lstrip("#") if isinstance(color_hex, str) else None
  106. multi_colors = filament.get("multi_color_hexes")
  107. extra: list[str] | None = None
  108. if isinstance(multi_colors, str) and multi_colors.strip():
  109. extra = [tok.strip().lstrip("#") for tok in multi_colors.split(",") if tok.strip()]
  110. elif isinstance(multi_colors, list):
  111. extra = [str(t).strip().lstrip("#") for t in multi_colors if str(t).strip()]
  112. return LabelData(
  113. spool_id=int(s.get("id", 0)),
  114. name=fname or material or "Spool",
  115. material=material or "",
  116. brand=brand,
  117. subtype=None,
  118. rgba=rgba,
  119. extra_colors=extra,
  120. storage_location=s.get("location"),
  121. deeplink_url=f"{deeplink_base}/inventory?spool={int(s.get('id', 0))}",
  122. )
  123. def _stream_pdf(pdf: bytes, filename: str) -> StreamingResponse:
  124. return StreamingResponse(
  125. io.BytesIO(pdf),
  126. media_type="application/pdf",
  127. headers={
  128. "Content-Disposition": build_content_disposition(filename, disposition="inline"),
  129. "Content-Length": str(len(pdf)),
  130. # PDFs are deterministic per request; tell the browser not to cache
  131. # so re-printing after edits picks up the new data.
  132. "Cache-Control": "no-store",
  133. },
  134. )
  135. @router.post("/inventory/labels")
  136. async def render_local_inventory_labels(
  137. body: LabelRequest,
  138. request: Request,
  139. db: AsyncSession = Depends(get_db),
  140. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  141. ) -> StreamingResponse:
  142. """Render labels for spools in the local inventory."""
  143. if body.template not in _VALID_TEMPLATES:
  144. raise HTTPException(400, f"Unknown template: {body.template}")
  145. result = await db.execute(select(Spool).where(Spool.id.in_(body.spool_ids)))
  146. spools = list(result.scalars().all())
  147. found_ids = {s.id for s in spools}
  148. missing = [sid for sid in body.spool_ids if sid not in found_ids]
  149. if missing:
  150. raise HTTPException(404, f"Spool(s) not found: {missing}")
  151. # Preserve caller's order so an Avery sheet print matches the on-screen list.
  152. ordered = sorted(spools, key=lambda s: body.spool_ids.index(s.id))
  153. deeplink_base = await _resolve_deeplink_base(request, db)
  154. data_list = [_spool_to_label_data(s, deeplink_base) for s in ordered]
  155. pdf = render_labels(
  156. body.template,
  157. data_list,
  158. monochrome=body.monochrome,
  159. starting_position=body.starting_position,
  160. )
  161. filename = f"bambuddy-labels-{body.template}.pdf"
  162. return _stream_pdf(pdf, filename)
  163. @router.post("/spoolman/labels")
  164. async def render_spoolman_labels(
  165. body: LabelRequest,
  166. request: Request,
  167. db: AsyncSession = Depends(get_db),
  168. _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ),
  169. ) -> StreamingResponse:
  170. """Render labels for spools tracked in Spoolman.
  171. The Spoolman client doesn't expose a per-id endpoint, so this fetches the
  172. full spool list and filters in-memory. For typical libraries (~50 spools)
  173. that's negligible; for very large libraries this is the trade-off until
  174. Spoolman gains a bulk filter.
  175. """
  176. if body.template not in _VALID_TEMPLATES:
  177. raise HTTPException(400, f"Unknown template: {body.template}")
  178. spoolman_on = (await get_setting(db, "spoolman_enabled") or "").lower() == "true"
  179. if not spoolman_on:
  180. raise HTTPException(400, "Spoolman integration is not enabled")
  181. client = await get_spoolman_client()
  182. if client is None or not client.is_connected:
  183. raise HTTPException(503, "Spoolman not reachable")
  184. try:
  185. all_spools = await client.get_spools()
  186. except Exception as exc:
  187. logger.warning("Spoolman fetch failed during label render: %s", exc)
  188. raise HTTPException(502, "Failed to fetch spools from Spoolman") from exc
  189. by_id = {int(s.get("id", 0)): s for s in all_spools if s.get("id") is not None}
  190. missing = [sid for sid in body.spool_ids if sid not in by_id]
  191. if missing:
  192. raise HTTPException(404, f"Spool(s) not found in Spoolman: {missing}")
  193. deeplink_base = await _resolve_deeplink_base(request, db)
  194. data_list = [_spoolman_dict_to_label_data(by_id[sid], deeplink_base) for sid in body.spool_ids]
  195. pdf = render_labels(
  196. body.template,
  197. data_list,
  198. monochrome=body.monochrome,
  199. starting_position=body.starting_position,
  200. )
  201. filename = f"bambuddy-labels-spoolman-{body.template}.pdf"
  202. return _stream_pdf(pdf, filename)