archive.py 11 KB

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