print_cost_estimate.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. """Trusted server-side cost estimates for queued prints."""
  2. import json
  3. import logging
  4. from decimal import ROUND_HALF_UP, Decimal
  5. from pathlib import Path
  6. from sqlalchemy import select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from sqlalchemy.orm import selectinload
  9. from backend.app.core.config import settings
  10. from backend.app.models.archive import PrintArchive
  11. from backend.app.models.library import LibraryFile
  12. from backend.app.models.spool_assignment import SpoolAssignment
  13. from backend.app.services.inventory_mode import spoolman_owns_assignments
  14. from backend.app.utils import threemf_tools
  15. from backend.app.utils.safe_path import safe_join_under
  16. logger = logging.getLogger(__name__)
  17. def plate_scoped_run_estimate(
  18. archive: PrintArchive,
  19. full_path: Path | None,
  20. plate_id: int | None = None,
  21. ) -> tuple[float | None, float | None]:
  22. """Return trusted ``(grams, cost)`` for one run of an archive plate."""
  23. whole_grams = archive.filament_used_grams
  24. selected_plate = archive.plate_id if plate_id is None else plate_id
  25. if selected_plate is None or full_path is None or not full_path.exists():
  26. return whole_grams, archive.cost
  27. try:
  28. plate_grams = threemf_tools.extract_plate_metadata_from_3mf(full_path, selected_plate).filament_used_grams
  29. except Exception as exc:
  30. logger.debug(
  31. "Plate-scoped estimate failed for archive %s (plate %s): %s",
  32. archive.id,
  33. selected_plate,
  34. exc,
  35. )
  36. return whole_grams, archive.cost
  37. if not plate_grams or plate_grams <= 0:
  38. return whole_grams, archive.cost
  39. plate_cost = archive.cost
  40. if archive.cost and whole_grams and whole_grams > 0:
  41. plate_cost = round(archive.cost * (plate_grams / whole_grams), 2)
  42. return round(plate_grams, 2), plate_cost
  43. def _source_path(library_file: LibraryFile) -> Path:
  44. path = Path(library_file.file_path)
  45. if path.is_absolute():
  46. # SEC-PATH-OK: absolute paths are persisted LibraryFile locations for
  47. # configured external libraries; this branch performs no path join.
  48. return path
  49. return safe_join_under(settings.base_dir, library_file.file_path, http=False)
  50. def _parse_mapping(mapping: list[int] | str | None) -> list[int] | None:
  51. if isinstance(mapping, list):
  52. return mapping
  53. if isinstance(mapping, str):
  54. try:
  55. parsed = json.loads(mapping)
  56. except (TypeError, json.JSONDecodeError):
  57. return None
  58. return parsed if isinstance(parsed, list) else None
  59. return None
  60. def _global_tray_id(assignment) -> int:
  61. if assignment.ams_id == 255:
  62. return 254 + assignment.tray_id
  63. if assignment.ams_id >= 128:
  64. return assignment.ams_id
  65. return assignment.ams_id * 4 + assignment.tray_id
  66. async def _spoolman_cost_by_tray(db: AsyncSession, printer_id: int, trays: set[int]) -> dict[int, float | None]:
  67. """Per-kg price of the Spoolman spool in each of ``trays``, from the spool's
  68. own price or its filament's. Only those spools are fetched, after a health
  69. check: this runs on queue add and at dispatch. Empty when Spoolman cannot
  70. be asked, and the estimate uses the default rate, as for an unpriced spool.
  71. """
  72. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  73. from backend.app.services.spoolman_tracking import _get_spoolman_client_with_fallback, _spool_cost_per_gram
  74. rows = [
  75. row
  76. for row in (
  77. await db.execute(select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id))
  78. )
  79. .scalars()
  80. .all()
  81. if _global_tray_id(row) in trays
  82. ]
  83. if not rows:
  84. return {}
  85. by_tray: dict[int, float | None] = {}
  86. try:
  87. client = await _get_spoolman_client_with_fallback()
  88. if client is None:
  89. return {}
  90. for row in rows:
  91. per_gram = _spool_cost_per_gram(await client.get_spool(row.spoolman_spool_id))
  92. by_tray[_global_tray_id(row)] = per_gram * 1000.0 if per_gram is not None else None
  93. except Exception as exc: # noqa: BLE001 — an estimate falls back to the default rate
  94. logger.debug("Spoolman prices unavailable for the queue estimate: %s", exc)
  95. return by_tray
  96. async def default_cost_per_kg(db: AsyncSession) -> float:
  97. """The default filament price per kg, as the Settings page shows it: 25
  98. when it was never saved."""
  99. from backend.app.api.routes.settings import get_setting
  100. raw = await get_setting(db, "default_filament_cost")
  101. try:
  102. return float(raw) if raw not in (None, "") else 25.0
  103. except (TypeError, ValueError):
  104. return 25.0
  105. def price_one_print(
  106. grams: float | None,
  107. usage_cost: float | None,
  108. tracked_grams: float,
  109. printed_grams: float,
  110. runs: int,
  111. fallback_cost_per_kg: float,
  112. default_cost_per_kg: float,
  113. ) -> float | None:
  114. """Cost of one print of ``grams``, the figure an archive carries (#1378).
  115. ``usage_cost`` / ``tracked_grams`` are the priced spool usage recorded
  116. against the archive, over every run of it; ``printed_grams`` / ``runs`` are
  117. those runs' grams and count from Print History. The spools tracked
  118. ``tracked_grams`` of ``printed_grams``: one print gets that share at their
  119. average price per gram and the rest at the default rate (#1344). Without
  120. priced usage, everything is priced at ``fallback_cost_per_kg``.
  121. """
  122. if usage_cost and usage_cost > 0 and tracked_grams > 0:
  123. if not grams:
  124. # No figure for one print: an average run's usage is the best one.
  125. cost = usage_cost / max(1, runs)
  126. else:
  127. expected = printed_grams if printed_grams > 0 else grams
  128. covered = grams * min(1.0, tracked_grams / expected)
  129. cost = covered * (usage_cost / tracked_grams) + (grams - covered) / 1000.0 * default_cost_per_kg
  130. elif grams:
  131. cost = grams / 1000.0 * fallback_cost_per_kg
  132. else:
  133. return None
  134. return float(Decimal(str(cost)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
  135. async def estimate_queue_source_cost(
  136. db: AsyncSession,
  137. *,
  138. archive: PrintArchive | None = None,
  139. library_file: LibraryFile | None = None,
  140. plate_id: int | None = None,
  141. ams_mapping: list[int] | str | None = None,
  142. printer_id: int | None = None,
  143. ) -> float | None:
  144. """Compute a queue cost without trusting the request's display hint."""
  145. if archive is not None:
  146. archive_path = settings.base_dir / archive.file_path
  147. grams, cost = plate_scoped_run_estimate(archive, archive_path, plate_id)
  148. if cost is not None and cost > 0:
  149. return float(cost)
  150. # Older archives and imports can have trustworthy filament usage but
  151. # no stored cost. Model-based and multi-printer jobs have no single
  152. # spool mapping at enqueue time, so use the server setting rather than
  153. # requiring the browser to provide an estimate.
  154. if grams is None or grams <= 0:
  155. return None
  156. default_cost = await default_cost_per_kg(db)
  157. estimated_cost = (grams / 1000.0) * default_cost
  158. return max(0.01, round(estimated_cost, 2)) if estimated_cost > 0 else None
  159. if library_file is None:
  160. return None
  161. path = _source_path(library_file)
  162. usage: list[dict] = []
  163. if path.exists():
  164. usage = threemf_tools.extract_plate_metadata_from_3mf(path, plate_id).filament_usage
  165. metadata = library_file.file_metadata or {}
  166. if not usage:
  167. try:
  168. grams = float(metadata.get("filament_used_grams") or 0)
  169. except (TypeError, ValueError):
  170. grams = 0
  171. if grams > 0:
  172. usage = [{"slot_id": 1, "used_g": grams}]
  173. if not usage:
  174. return None
  175. default_cost = await default_cost_per_kg(db)
  176. cost_by_tray: dict[int, float | None] = {}
  177. mapping = _parse_mapping(ams_mapping)
  178. # The prices of the spools the mode's own table puts in those trays. The
  179. # built-in table may still hold rows from before a switch to Spoolman --
  180. # nothing clears it since #2812 -- and pricing from a spool the printer is
  181. # not drawing on would be worse than the default rate this falls back to.
  182. spoolman_mode = await spoolman_owns_assignments(db)
  183. if printer_id is not None and mapping and spoolman_mode:
  184. cost_by_tray = await _spoolman_cost_by_tray(db, printer_id, {t for t in mapping if t >= 0})
  185. if printer_id is not None and mapping and not spoolman_mode:
  186. assignments = (
  187. (
  188. await db.execute(
  189. select(SpoolAssignment)
  190. .options(selectinload(SpoolAssignment.spool))
  191. .where(SpoolAssignment.printer_id == printer_id)
  192. )
  193. )
  194. .scalars()
  195. .all()
  196. )
  197. cost_by_tray = {_global_tray_id(a): a.spool.cost_per_kg for a in assignments}
  198. total = 0.0
  199. for filament in usage:
  200. try:
  201. slot_id = int(filament.get("slot_id") or 0)
  202. grams = float(filament.get("used_g") or 0)
  203. except (TypeError, ValueError):
  204. continue
  205. tray_id = mapping[slot_id - 1] if mapping and 0 < slot_id <= len(mapping) else None
  206. cost_per_kg = cost_by_tray.get(tray_id) if tray_id is not None else None
  207. if cost_per_kg is None or cost_per_kg <= 0:
  208. cost_per_kg = default_cost
  209. total += (grams / 1000.0) * cost_per_kg
  210. return round(total, 2) if total > 0 else None