print_cost_estimate.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """Trusted server-side cost estimates for queued prints."""
  2. import json
  3. import logging
  4. from pathlib import Path
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from sqlalchemy.orm import selectinload
  8. from backend.app.core.config import settings
  9. from backend.app.models.archive import PrintArchive
  10. from backend.app.models.library import LibraryFile
  11. from backend.app.models.spool_assignment import SpoolAssignment
  12. from backend.app.services.inventory_mode import spoolman_owns_assignments
  13. from backend.app.utils import threemf_tools
  14. from backend.app.utils.safe_path import safe_join_under
  15. logger = logging.getLogger(__name__)
  16. def plate_scoped_run_estimate(
  17. archive: PrintArchive,
  18. full_path: Path | None,
  19. plate_id: int | None = None,
  20. ) -> tuple[float | None, float | None]:
  21. """Return trusted ``(grams, cost)`` for one run of an archive plate."""
  22. whole_grams = archive.filament_used_grams
  23. selected_plate = archive.plate_id if plate_id is None else plate_id
  24. if selected_plate is None or full_path is None or not full_path.exists():
  25. return whole_grams, archive.cost
  26. try:
  27. plate_grams = threemf_tools.extract_plate_metadata_from_3mf(full_path, selected_plate).filament_used_grams
  28. except Exception as exc:
  29. logger.debug(
  30. "Plate-scoped estimate failed for archive %s (plate %s): %s",
  31. archive.id,
  32. selected_plate,
  33. exc,
  34. )
  35. return whole_grams, archive.cost
  36. if not plate_grams or plate_grams <= 0:
  37. return whole_grams, archive.cost
  38. plate_cost = archive.cost
  39. if archive.cost and whole_grams and whole_grams > 0:
  40. plate_cost = round(archive.cost * (plate_grams / whole_grams), 2)
  41. return round(plate_grams, 2), plate_cost
  42. def _source_path(library_file: LibraryFile) -> Path:
  43. path = Path(library_file.file_path)
  44. if path.is_absolute():
  45. # SEC-PATH-OK: absolute paths are persisted LibraryFile locations for
  46. # configured external libraries; this branch performs no path join.
  47. return path
  48. return safe_join_under(settings.base_dir, library_file.file_path, http=False)
  49. def _parse_mapping(mapping: list[int] | str | None) -> list[int] | None:
  50. if isinstance(mapping, list):
  51. return mapping
  52. if isinstance(mapping, str):
  53. try:
  54. parsed = json.loads(mapping)
  55. except (TypeError, json.JSONDecodeError):
  56. return None
  57. return parsed if isinstance(parsed, list) else None
  58. return None
  59. def _global_tray_id(assignment: SpoolAssignment) -> int:
  60. if assignment.ams_id == 255:
  61. return 254 + assignment.tray_id
  62. if assignment.ams_id >= 128:
  63. return assignment.ams_id
  64. return assignment.ams_id * 4 + assignment.tray_id
  65. async def _default_cost_per_kg(db: AsyncSession) -> float:
  66. from backend.app.api.routes.settings import get_setting
  67. raw = await get_setting(db, "default_filament_cost")
  68. try:
  69. return float(raw) if raw is not None else 25.0
  70. except (TypeError, ValueError):
  71. return 25.0
  72. async def estimate_queue_source_cost(
  73. db: AsyncSession,
  74. *,
  75. archive: PrintArchive | None = None,
  76. library_file: LibraryFile | None = None,
  77. plate_id: int | None = None,
  78. ams_mapping: list[int] | str | None = None,
  79. printer_id: int | None = None,
  80. ) -> float | None:
  81. """Compute a queue cost without trusting the request's display hint."""
  82. if archive is not None:
  83. archive_path = settings.base_dir / archive.file_path
  84. grams, cost = plate_scoped_run_estimate(archive, archive_path, plate_id)
  85. if cost is not None and cost > 0:
  86. return float(cost)
  87. # Older archives and imports can have trustworthy filament usage but
  88. # no stored cost. Model-based and multi-printer jobs have no single
  89. # spool mapping at enqueue time, so use the server setting rather than
  90. # requiring the browser to provide an estimate.
  91. if grams is None or grams <= 0:
  92. return None
  93. default_cost = await _default_cost_per_kg(db)
  94. estimated_cost = (grams / 1000.0) * default_cost
  95. return max(0.01, round(estimated_cost, 2)) if estimated_cost > 0 else None
  96. if library_file is None:
  97. return None
  98. path = _source_path(library_file)
  99. usage: list[dict] = []
  100. if path.exists():
  101. usage = threemf_tools.extract_plate_metadata_from_3mf(path, plate_id).filament_usage
  102. metadata = library_file.file_metadata or {}
  103. if not usage:
  104. try:
  105. grams = float(metadata.get("filament_used_grams") or 0)
  106. except (TypeError, ValueError):
  107. grams = 0
  108. if grams > 0:
  109. usage = [{"slot_id": 1, "used_g": grams}]
  110. if not usage:
  111. return None
  112. default_cost = await _default_cost_per_kg(db)
  113. cost_by_tray: dict[int, float | None] = {}
  114. mapping = _parse_mapping(ams_mapping)
  115. # Built-in spool prices only. In Spoolman mode the built-in table may still
  116. # hold rows from before the user switched -- nothing clears it since #2812 --
  117. # and pricing an estimate from a spool the printer is not drawing on would
  118. # be worse than the default rate this falls back to.
  119. if printer_id is not None and mapping and not await spoolman_owns_assignments(db):
  120. assignments = (
  121. (
  122. await db.execute(
  123. select(SpoolAssignment)
  124. .options(selectinload(SpoolAssignment.spool))
  125. .where(SpoolAssignment.printer_id == printer_id)
  126. )
  127. )
  128. .scalars()
  129. .all()
  130. )
  131. cost_by_tray = {_global_tray_id(a): a.spool.cost_per_kg for a in assignments}
  132. total = 0.0
  133. for filament in usage:
  134. try:
  135. slot_id = int(filament.get("slot_id") or 0)
  136. grams = float(filament.get("used_g") or 0)
  137. except (TypeError, ValueError):
  138. continue
  139. tray_id = mapping[slot_id - 1] if mapping and 0 < slot_id <= len(mapping) else None
  140. cost_per_kg = cost_by_tray.get(tray_id) if tray_id is not None else None
  141. if cost_per_kg is None or cost_per_kg <= 0:
  142. cost_per_kg = default_cost
  143. total += (grams / 1000.0) * cost_per_kg
  144. return round(total, 2) if total > 0 else None