archive.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from datetime import datetime
  2. from sqlalchemy import JSON, Boolean, DateTime, Float, ForeignKey, Integer, String, Text, func
  3. from sqlalchemy.orm import Mapped, mapped_column, relationship
  4. from backend.app.core.database import Base
  5. class PrintArchive(Base):
  6. __tablename__ = "print_archives"
  7. id: Mapped[int] = mapped_column(primary_key=True)
  8. printer_id: Mapped[int | None] = mapped_column(ForeignKey("printers.id"), nullable=True)
  9. project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id", ondelete="SET NULL"), nullable=True)
  10. # Which library file this run was dispatched from (#1897). Set by the queue
  11. # scheduler when it archives a library-file print; older rows are matched by
  12. # content_hash/filename instead. SET NULL so deleting a file keeps history.
  13. library_file_id: Mapped[int | None] = mapped_column(
  14. ForeignKey("library_files.id", ondelete="SET NULL"), nullable=True
  15. )
  16. cost_center_id: Mapped[int | None] = mapped_column(
  17. ForeignKey("cost_centers.id", ondelete="SET NULL"), nullable=True
  18. )
  19. # File info
  20. filename: Mapped[str] = mapped_column(String(255))
  21. file_path: Mapped[str] = mapped_column(String(500))
  22. file_size: Mapped[int] = mapped_column(Integer)
  23. content_hash: Mapped[str | None] = mapped_column(String(64)) # SHA256 hash for duplicate detection
  24. thumbnail_path: Mapped[str | None] = mapped_column(String(500))
  25. timelapse_path: Mapped[str | None] = mapped_column(String(500))
  26. # True when Bambuddy forced timelapse recording on for this print so the
  27. # finish-photo extractor (#1397) could pull the post-park-pre-drop frame.
  28. # The cleanup path uses this to know the timelapse should be deleted
  29. # both locally and on the printer's SD after extraction — the user
  30. # didn't opt in to a timelapse recording.
  31. bambuddy_forced_timelapse: Mapped[bool] = mapped_column(Boolean, default=False, server_default="0")
  32. # Video filenames present in the printer's /timelapse directory when this
  33. # print started (#2704). The printer writes its video only at print end, so
  34. # anything not in this list belongs to this print — a comparison that needs
  35. # no clock, which matters because a LAN-only printer can't reach Bambu's NTP
  36. # server and its filename timestamps are arbitrarily wrong. Persisted (not
  37. # just held in memory) so the diff survives a restart and so the manual
  38. # "Scan for Timelapse" button can use it instead of guessing from
  39. # timestamps. NULL for archives predating this, and for baselines taken at
  40. # completion time, which are useless by construction.
  41. timelapse_baseline: Mapped[list | None] = mapped_column(JSON, nullable=True)
  42. source_3mf_path: Mapped[str | None] = mapped_column(String(500)) # Original project 3MF from slicer
  43. f3d_path: Mapped[str | None] = mapped_column(String(500)) # Fusion 360 design file
  44. # Print details from 3MF / printer
  45. print_name: Mapped[str | None] = mapped_column(String(255))
  46. print_time_seconds: Mapped[int | None] = mapped_column(Integer)
  47. filament_used_grams: Mapped[float | None] = mapped_column(Float)
  48. filament_type: Mapped[str | None] = mapped_column(String(50))
  49. filament_color: Mapped[str | None] = mapped_column(String(200))
  50. layer_height: Mapped[float | None] = mapped_column(Float)
  51. total_layers: Mapped[int | None] = mapped_column(Integer)
  52. nozzle_diameter: Mapped[float | None] = mapped_column(Float)
  53. bed_temperature: Mapped[int | None] = mapped_column(Integer)
  54. bed_type: Mapped[str | None] = mapped_column(String(64)) # e.g. "Cool Plate", "Textured PEI Plate"
  55. nozzle_temperature: Mapped[int | None] = mapped_column(Integer)
  56. # Printer model this file was sliced for (extracted from 3MF metadata)
  57. sliced_for_model: Mapped[str | None] = mapped_column(String(50), nullable=True)
  58. # Print result
  59. status: Mapped[str] = mapped_column(String(20), default="completed")
  60. started_at: Mapped[datetime | None] = mapped_column(DateTime)
  61. completed_at: Mapped[datetime | None] = mapped_column(DateTime)
  62. # Printer-assigned subtask identifier from MQTT. Used to resume the same
  63. # archive row across a backend restart during a long-running print (#972):
  64. # if the same subtask_id reappears after restart, we know it's the same
  65. # print and keep the original row instead of cancel-then-create.
  66. subtask_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
  67. # Durable Bambuddy UUID for billing idempotency. Unlike subtask_id, this is
  68. # not constrained by printer firmware and is replaced for every reprint.
  69. billing_run_id: Mapped[str | None] = mapped_column(String(36), nullable=True)
  70. # Which plate of a multi-plate 3MF this print was for (1-based), copied from
  71. # the queue item at dispatch (#2603). A whole multi-plate 3MF is uploaded
  72. # under one filename with no plate suffix, so the parser can't recover the
  73. # selected plate and extra_data holds all-plates aggregate metadata; without
  74. # this the history UI can't tell which plate was printed and falls back to
  75. # Plate 1. NULL for archives with no specific selected plate.
  76. plate_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  77. # Extended metadata (JSON blob for flexibility)
  78. extra_data: Mapped[dict | None] = mapped_column(JSON)
  79. # MakerWorld info (auto-extracted from 3MF)
  80. makerworld_url: Mapped[str | None] = mapped_column(String(500))
  81. designer: Mapped[str | None] = mapped_column(String(255))
  82. # User-defined external link (Printables, Thingiverse, etc.)
  83. external_url: Mapped[str | None] = mapped_column(String(500))
  84. # User additions
  85. is_favorite: Mapped[bool] = mapped_column(Boolean, default=False)
  86. wallet_charge_skipped: Mapped[bool] = mapped_column(Boolean, default=False)
  87. tags: Mapped[str | None] = mapped_column(Text)
  88. notes: Mapped[str | None] = mapped_column(Text)
  89. cost: Mapped[float | None] = mapped_column(Float)
  90. photos: Mapped[list | None] = mapped_column(JSON) # List of photo filenames
  91. failure_reason: Mapped[str | None] = mapped_column(String(100)) # For failed prints
  92. quantity: Mapped[int] = mapped_column(Integer, default=1) # Number of items printed
  93. # Post-print outcome confirmation (#1898). user_verdict is the USER's
  94. # quality judgement ('good' / 'reject'), deliberately orthogonal to the
  95. # machine-reported `status`: completed + reject means "printer finished
  96. # it, part is scrap". confirm_requested is copied from the queue item's
  97. # opt-in flag at dispatch (like plate_id) and drives the prompt + the
  98. # "unconfirmed" badge; confirm_token is a per-archive capability for the
  99. # one-tap verdict links in push notifications, minted when the prompt
  100. # fires. A landed verdict RETIRES the token by stamping
  101. # confirm_token_used_at rather than clearing the value: the link stays
  102. # resolvable so a second tap can say "already answered, here is what was
  103. # recorded" instead of the bare "invalid or already used" 404.
  104. # user_verdict_source records how the verdict arrived ('dialog', 'link',
  105. # 'plate_clear', 'printer_card', 'api', 'reaction') so the UI can explain
  106. # a verdict nobody remembers giving.
  107. user_verdict: Mapped[str | None] = mapped_column(String(10), nullable=True)
  108. user_verdict_source: Mapped[str | None] = mapped_column(String(16), nullable=True)
  109. # When the verdict on file was recorded (#1898). Written with every verdict,
  110. # unlike `confirm_token_used_at`, which marks the one moment the one-tap
  111. # capability was spent — a verdict changed later in the app must not be
  112. # dated by that older event.
  113. user_verdict_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  114. # Nullable to match the ALTER that adds it to an existing install: a fresh
  115. # database would otherwise get NOT NULL while an upgraded one gets a
  116. # nullable column, and the two would disagree about the same table. The
  117. # default still means every row written by Bambuddy is True or False; only
  118. # `is_(True)` and truthiness read it, both of which treat NULL as off.
  119. confirm_requested: Mapped[bool | None] = mapped_column(Boolean, nullable=True, default=False, server_default="0")
  120. # Indexed and unique: the one-tap route is reachable with no credential
  121. # at all, so an unindexed lookup would let anyone turn a stream of
  122. # garbage tokens into a stream of full scans of this table. Uniqueness
  123. # costs nothing (the only writer is secrets.token_urlsafe(32)) and keeps
  124. # scalar_one_or_none from ever raising MultipleResultsFound.
  125. confirm_token: Mapped[str | None] = mapped_column(String(64), nullable=True, unique=True, index=True)
  126. confirm_token_used_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  127. # Energy tracking
  128. energy_kwh: Mapped[float | None] = mapped_column(Float) # Energy consumed in kWh
  129. energy_cost: Mapped[float | None] = mapped_column(Float) # Cost of energy consumed
  130. # Plug lifetime counter captured at print start; delta at print end becomes energy_kwh.
  131. # Persisted so per-print tracking survives backend restarts mid-print (#941).
  132. energy_start_kwh: Mapped[float | None] = mapped_column(Float)
  133. # Timestamps
  134. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  135. # Soft-delete sentinel (#1343). When non-null, the UI hides this archive
  136. # from listings (its files have already been removed from disk) but the
  137. # stats endpoint keeps counting it — deleting nine of ten Benchies no
  138. # longer wipes their filament / time / cost contribution from Quick Stats.
  139. # The opt-in "Also remove from statistics" checkbox in the delete dialog
  140. # bypasses the soft-delete path and hard-deletes the row.
  141. deleted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None, index=True)
  142. # User tracking (who uploaded/created this archive)
  143. created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
  144. # Relationships
  145. printer: Mapped["Printer | None"] = relationship(back_populates="archives")
  146. project: Mapped["Project | None"] = relationship(back_populates="archives")
  147. cost_center: Mapped["CostCenter | None"] = relationship()
  148. created_by: Mapped["User | None"] = relationship()
  149. from backend.app.models.finance import CostCenter # noqa: E402, F811
  150. from backend.app.models.printer import Printer # noqa: E402, F811
  151. from backend.app.models.project import Project # noqa: E402, F811
  152. from backend.app.models.user import User # noqa: E402, F811