archive.py 13 KB

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