database.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  2. from sqlalchemy.orm import DeclarativeBase
  3. from backend.app.core.config import settings
  4. engine = create_async_engine(
  5. settings.database_url,
  6. echo=settings.debug,
  7. )
  8. async_session = async_sessionmaker(
  9. engine,
  10. class_=AsyncSession,
  11. expire_on_commit=False,
  12. )
  13. class Base(DeclarativeBase):
  14. pass
  15. async def get_db() -> AsyncSession:
  16. async with async_session() as session:
  17. try:
  18. yield session
  19. await session.commit()
  20. except Exception:
  21. await session.rollback()
  22. raise
  23. finally:
  24. await session.close()
  25. async def init_db():
  26. # Import models to register them with SQLAlchemy
  27. from backend.app.models import ( # noqa: F401
  28. ams_history,
  29. api_key,
  30. archive,
  31. external_link,
  32. filament,
  33. github_backup,
  34. group,
  35. kprofile_note,
  36. library,
  37. maintenance,
  38. notification,
  39. notification_template,
  40. pending_upload,
  41. print_queue,
  42. printer,
  43. project,
  44. project_bom,
  45. settings,
  46. slot_preset,
  47. smart_plug,
  48. user,
  49. )
  50. async with engine.begin() as conn:
  51. await conn.run_sync(Base.metadata.create_all)
  52. # Run migrations for new columns (SQLite doesn't auto-add columns)
  53. await run_migrations(conn)
  54. # Seed default notification templates
  55. await seed_notification_templates()
  56. # Seed default groups and migrate existing users
  57. await seed_default_groups()
  58. async def run_migrations(conn):
  59. """Add new columns to existing tables if they don't exist."""
  60. from sqlalchemy import text
  61. # Migration: Add is_favorite column to print_archives
  62. try:
  63. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  64. except Exception:
  65. # Column already exists
  66. pass
  67. # Migration: Add content_hash column to print_archives for duplicate detection
  68. try:
  69. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  70. except Exception:
  71. # Column already exists
  72. pass
  73. # Migration: Add auto_off_executed column to smart_plugs
  74. try:
  75. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  76. except Exception:
  77. # Column already exists
  78. pass
  79. # Migration: Add on_print_stopped column to notification_providers
  80. try:
  81. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  82. except Exception:
  83. # Column already exists
  84. pass
  85. # Migration: Add source_3mf_path column to print_archives
  86. try:
  87. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  88. except Exception:
  89. # Column already exists
  90. pass
  91. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  92. try:
  93. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  94. except Exception:
  95. # Column already exists
  96. pass
  97. # Migration: Add on_maintenance_due column to notification_providers
  98. try:
  99. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  100. except Exception:
  101. # Column already exists
  102. pass
  103. # Migration: Add location column to printers for grouping
  104. try:
  105. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  106. except Exception:
  107. # Column already exists
  108. pass
  109. # Migration: Add interval_type column to maintenance_types
  110. try:
  111. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  112. except Exception:
  113. # Column already exists
  114. pass
  115. # Migration: Add custom_interval_type column to printer_maintenance
  116. try:
  117. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  118. except Exception:
  119. # Column already exists
  120. pass
  121. # Migration: Add power alert columns to smart_plugs
  122. try:
  123. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  124. except Exception:
  125. pass
  126. try:
  127. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  128. except Exception:
  129. pass
  130. try:
  131. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  132. except Exception:
  133. pass
  134. try:
  135. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  136. except Exception:
  137. pass
  138. # Migration: Add schedule columns to smart_plugs
  139. try:
  140. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  141. except Exception:
  142. pass
  143. try:
  144. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  145. except Exception:
  146. pass
  147. try:
  148. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  149. except Exception:
  150. pass
  151. # Migration: Add daily digest columns to notification_providers
  152. try:
  153. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  154. except Exception:
  155. pass
  156. try:
  157. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  158. except Exception:
  159. pass
  160. # Migration: Add project_id column to print_archives
  161. try:
  162. await conn.execute(
  163. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  164. )
  165. except Exception:
  166. pass
  167. # Migration: Add project_id column to print_queue
  168. try:
  169. await conn.execute(
  170. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  171. )
  172. except Exception:
  173. pass
  174. # Migration: Create FTS5 virtual table for archive full-text search
  175. try:
  176. await conn.execute(
  177. text("""
  178. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  179. print_name,
  180. filename,
  181. tags,
  182. notes,
  183. designer,
  184. filament_type,
  185. content='print_archives',
  186. content_rowid='id'
  187. )
  188. """)
  189. )
  190. except Exception:
  191. pass
  192. # Migration: Create triggers to keep FTS index in sync
  193. try:
  194. await conn.execute(
  195. text("""
  196. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  197. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  198. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  199. END
  200. """)
  201. )
  202. except Exception:
  203. pass
  204. try:
  205. await conn.execute(
  206. text("""
  207. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  208. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  209. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  210. END
  211. """)
  212. )
  213. except Exception:
  214. pass
  215. try:
  216. await conn.execute(
  217. text("""
  218. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  219. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  220. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  221. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  222. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  223. END
  224. """)
  225. )
  226. except Exception:
  227. pass
  228. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  229. try:
  230. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  231. except Exception:
  232. pass
  233. try:
  234. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  235. except Exception:
  236. pass
  237. # Migration: Add AMS alarm notification columns to notification_providers
  238. try:
  239. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  240. except Exception:
  241. pass
  242. try:
  243. await conn.execute(
  244. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  245. )
  246. except Exception:
  247. pass
  248. # Migration: Add AMS-HT alarm notification columns to notification_providers
  249. try:
  250. await conn.execute(
  251. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  252. )
  253. except Exception:
  254. pass
  255. try:
  256. await conn.execute(
  257. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  258. )
  259. except Exception:
  260. pass
  261. # Migration: Add plate not empty notification column to notification_providers
  262. try:
  263. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  264. except Exception:
  265. pass
  266. # Migration: Add notes column to projects (Phase 2)
  267. try:
  268. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  269. except Exception:
  270. pass
  271. # Migration: Add attachments column to projects (Phase 3)
  272. try:
  273. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  274. except Exception:
  275. pass
  276. # Migration: Add tags column to projects (Phase 4)
  277. try:
  278. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  279. except Exception:
  280. pass
  281. # Migration: Add due_date column to projects (Phase 5)
  282. try:
  283. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  284. except Exception:
  285. pass
  286. # Migration: Add priority column to projects (Phase 5)
  287. try:
  288. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  289. except Exception:
  290. pass
  291. # Migration: Add budget column to projects (Phase 6)
  292. try:
  293. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  294. except Exception:
  295. pass
  296. # Migration: Add is_template column to projects (Phase 8)
  297. try:
  298. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  299. except Exception:
  300. pass
  301. # Migration: Add template_source_id column to projects (Phase 8)
  302. try:
  303. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  304. except Exception:
  305. pass
  306. # Migration: Add parent_id column to projects (Phase 10)
  307. try:
  308. await conn.execute(
  309. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  310. )
  311. except Exception:
  312. pass
  313. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  314. try:
  315. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  316. except Exception:
  317. pass
  318. # Migration: Add unit_price column to project_bom_items
  319. try:
  320. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  321. except Exception:
  322. pass
  323. # Migration: Add sourcing_url column to project_bom_items
  324. try:
  325. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  326. except Exception:
  327. pass
  328. # Migration: Rename notes to remarks in project_bom_items
  329. try:
  330. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  331. except Exception:
  332. pass
  333. # Migration: Add show_in_switchbar column to smart_plugs
  334. try:
  335. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  336. except Exception:
  337. pass
  338. # Migration: Add runtime tracking columns to printers
  339. try:
  340. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  341. except Exception:
  342. pass
  343. try:
  344. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  345. except Exception:
  346. pass
  347. # Migration: Add quantity column to print_archives for tracking item count
  348. try:
  349. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  350. except Exception:
  351. pass
  352. # Migration: Add manual_start column to print_queue for staged prints
  353. try:
  354. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  355. except Exception:
  356. pass
  357. # Migration: Add wiki_url column to maintenance_types for documentation links
  358. try:
  359. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  360. except Exception:
  361. pass
  362. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  363. try:
  364. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  365. except Exception:
  366. pass
  367. # Migration: Add target_parts_count column to projects for tracking total parts needed
  368. try:
  369. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  370. except Exception:
  371. pass
  372. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  373. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  374. try:
  375. # Check if printer_id is already nullable by trying to insert NULL
  376. # This is a safe check that won't affect existing data
  377. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  378. row = result.fetchone()
  379. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  380. # Need to migrate - printer_id is currently NOT NULL
  381. await conn.execute(
  382. text("""
  383. CREATE TABLE print_queue_new (
  384. id INTEGER PRIMARY KEY,
  385. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  386. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  387. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  388. position INTEGER DEFAULT 0,
  389. scheduled_time DATETIME,
  390. manual_start BOOLEAN DEFAULT 0,
  391. require_previous_success BOOLEAN DEFAULT 0,
  392. auto_off_after BOOLEAN DEFAULT 0,
  393. ams_mapping TEXT,
  394. status VARCHAR(20) DEFAULT 'pending',
  395. started_at DATETIME,
  396. completed_at DATETIME,
  397. error_message TEXT,
  398. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  399. )
  400. """)
  401. )
  402. await conn.execute(
  403. text("""
  404. INSERT INTO print_queue_new
  405. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  406. manual_start, require_previous_success, auto_off_after, ams_mapping,
  407. status, started_at, completed_at, error_message, created_at
  408. FROM print_queue
  409. """)
  410. )
  411. await conn.execute(text("DROP TABLE print_queue"))
  412. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  413. except Exception:
  414. pass
  415. # Migration: Add plug_type column to smart_plugs for HA integration
  416. try:
  417. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  418. except Exception:
  419. pass
  420. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  421. try:
  422. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  423. except Exception:
  424. pass
  425. # Migration: Add project_id column to library_folders for linking folders to projects
  426. try:
  427. await conn.execute(
  428. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  429. )
  430. except Exception:
  431. pass
  432. # Migration: Add archive_id column to library_folders for linking folders to archives
  433. try:
  434. await conn.execute(
  435. text(
  436. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  437. )
  438. )
  439. except Exception:
  440. pass
  441. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  442. try:
  443. # Check if ip_address is currently NOT NULL
  444. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  445. row = result.fetchone()
  446. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  447. # Need to migrate - ip_address is currently NOT NULL
  448. await conn.execute(
  449. text("""
  450. CREATE TABLE smart_plugs_new (
  451. id INTEGER PRIMARY KEY,
  452. name VARCHAR(100) NOT NULL,
  453. ip_address VARCHAR(45),
  454. plug_type VARCHAR(20) DEFAULT 'tasmota',
  455. ha_entity_id VARCHAR(100),
  456. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  457. enabled BOOLEAN NOT NULL DEFAULT 1,
  458. auto_on BOOLEAN NOT NULL DEFAULT 1,
  459. auto_off BOOLEAN NOT NULL DEFAULT 1,
  460. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  461. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  462. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  463. username VARCHAR(50),
  464. password VARCHAR(100),
  465. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  466. power_alert_high FLOAT,
  467. power_alert_low FLOAT,
  468. power_alert_last_triggered DATETIME,
  469. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  470. schedule_on_time VARCHAR(5),
  471. schedule_off_time VARCHAR(5),
  472. show_in_switchbar BOOLEAN DEFAULT 0,
  473. last_state VARCHAR(10),
  474. last_checked DATETIME,
  475. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  476. auto_off_pending BOOLEAN DEFAULT 0,
  477. auto_off_pending_since DATETIME,
  478. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  479. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  480. )
  481. """)
  482. )
  483. await conn.execute(
  484. text("""
  485. INSERT INTO smart_plugs_new
  486. SELECT id, name, ip_address,
  487. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  488. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  489. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  490. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  491. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  492. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  493. FROM smart_plugs
  494. """)
  495. )
  496. await conn.execute(text("DROP TABLE smart_plugs"))
  497. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  498. except Exception:
  499. pass
  500. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  501. try:
  502. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  503. except Exception:
  504. pass
  505. # Migration: Add print options columns to print_queue
  506. try:
  507. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  508. except Exception:
  509. pass
  510. try:
  511. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  512. except Exception:
  513. pass
  514. try:
  515. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  516. except Exception:
  517. pass
  518. try:
  519. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  520. except Exception:
  521. pass
  522. try:
  523. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  524. except Exception:
  525. pass
  526. try:
  527. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  528. except Exception:
  529. pass
  530. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  531. # This allows queue items to reference library files directly (archive created at print start)
  532. try:
  533. await conn.execute(
  534. text(
  535. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  536. )
  537. )
  538. except Exception:
  539. pass
  540. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  541. try:
  542. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  543. row = result.fetchone()
  544. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  545. # Need to migrate - archive_id is currently NOT NULL
  546. await conn.execute(
  547. text("""
  548. CREATE TABLE print_queue_new2 (
  549. id INTEGER PRIMARY KEY,
  550. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  551. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  552. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  553. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  554. position INTEGER DEFAULT 0,
  555. scheduled_time DATETIME,
  556. manual_start BOOLEAN DEFAULT 0,
  557. require_previous_success BOOLEAN DEFAULT 0,
  558. auto_off_after BOOLEAN DEFAULT 0,
  559. ams_mapping TEXT,
  560. plate_id INTEGER,
  561. bed_levelling BOOLEAN DEFAULT 1,
  562. flow_cali BOOLEAN DEFAULT 0,
  563. vibration_cali BOOLEAN DEFAULT 1,
  564. layer_inspect BOOLEAN DEFAULT 0,
  565. timelapse BOOLEAN DEFAULT 0,
  566. use_ams BOOLEAN DEFAULT 1,
  567. status VARCHAR(20) DEFAULT 'pending',
  568. started_at DATETIME,
  569. completed_at DATETIME,
  570. error_message TEXT,
  571. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  572. )
  573. """)
  574. )
  575. await conn.execute(
  576. text("""
  577. INSERT INTO print_queue_new2
  578. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  579. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  580. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  581. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  582. status, started_at, completed_at, error_message, created_at
  583. FROM print_queue
  584. """)
  585. )
  586. await conn.execute(text("DROP TABLE print_queue"))
  587. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  588. except Exception:
  589. pass
  590. # Migration: Add HA energy sensor entity columns to smart_plugs
  591. try:
  592. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  593. except Exception:
  594. pass
  595. try:
  596. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  597. except Exception:
  598. pass
  599. try:
  600. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  601. except Exception:
  602. pass
  603. # Migration: Create users table for authentication
  604. try:
  605. await conn.execute(
  606. text("""
  607. CREATE TABLE IF NOT EXISTS users (
  608. id INTEGER PRIMARY KEY,
  609. username VARCHAR(100) NOT NULL UNIQUE,
  610. password_hash VARCHAR(255) NOT NULL,
  611. role VARCHAR(20) NOT NULL DEFAULT 'user',
  612. is_active BOOLEAN NOT NULL DEFAULT 1,
  613. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  614. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  615. )
  616. """)
  617. )
  618. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  619. except Exception:
  620. pass
  621. # Migration: Add external camera columns to printers
  622. try:
  623. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  624. except Exception:
  625. pass
  626. try:
  627. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  628. except Exception:
  629. pass
  630. try:
  631. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  632. except Exception:
  633. pass
  634. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  635. try:
  636. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  637. except Exception:
  638. pass
  639. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  640. try:
  641. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)"))
  642. except Exception:
  643. pass
  644. # Migration: Add is_external column to library_files for external cloud files
  645. try:
  646. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  647. except Exception:
  648. pass
  649. # Migration: Add project_id column to library_files
  650. try:
  651. await conn.execute(
  652. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  653. )
  654. except Exception:
  655. pass
  656. # Migration: Add is_external column to library_folders for external cloud folders
  657. try:
  658. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  659. except Exception:
  660. pass
  661. # Migration: Add external folder settings columns to library_folders
  662. try:
  663. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  664. except Exception:
  665. pass
  666. try:
  667. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  668. except Exception:
  669. pass
  670. try:
  671. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  672. except Exception:
  673. pass
  674. # Migration: Add plate_detection_enabled column to printers
  675. try:
  676. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  677. except Exception:
  678. pass
  679. # Migration: Add plate detection ROI columns to printers
  680. try:
  681. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  682. except Exception:
  683. pass
  684. try:
  685. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  686. except Exception:
  687. pass
  688. try:
  689. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  690. except Exception:
  691. pass
  692. try:
  693. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  694. except Exception:
  695. pass
  696. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  697. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  698. # SQLite requires table recreation to drop constraints
  699. try:
  700. # Check if we need to migrate (if UNIQUE constraint exists)
  701. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  702. row = result.fetchone()
  703. if row and "printer_id INTEGER UNIQUE" in (row[0] or ""):
  704. # Create new table without UNIQUE constraint on printer_id
  705. await conn.execute(
  706. text("""
  707. CREATE TABLE smart_plugs_temp (
  708. id INTEGER PRIMARY KEY,
  709. name VARCHAR(100) NOT NULL,
  710. ip_address VARCHAR(45),
  711. plug_type VARCHAR(20) DEFAULT 'tasmota',
  712. ha_entity_id VARCHAR(100),
  713. ha_power_entity VARCHAR(100),
  714. ha_energy_today_entity VARCHAR(100),
  715. ha_energy_total_entity VARCHAR(100),
  716. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  717. enabled BOOLEAN NOT NULL DEFAULT 1,
  718. auto_on BOOLEAN NOT NULL DEFAULT 1,
  719. auto_off BOOLEAN NOT NULL DEFAULT 1,
  720. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  721. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  722. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  723. username VARCHAR(50),
  724. password VARCHAR(100),
  725. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  726. power_alert_high FLOAT,
  727. power_alert_low FLOAT,
  728. power_alert_last_triggered DATETIME,
  729. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  730. schedule_on_time VARCHAR(5),
  731. schedule_off_time VARCHAR(5),
  732. show_in_switchbar BOOLEAN DEFAULT 0,
  733. last_state VARCHAR(10),
  734. last_checked DATETIME,
  735. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  736. auto_off_pending BOOLEAN DEFAULT 0,
  737. auto_off_pending_since DATETIME,
  738. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  739. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  740. )
  741. """)
  742. )
  743. # Copy data
  744. await conn.execute(
  745. text("""
  746. INSERT INTO smart_plugs_temp
  747. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  748. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  749. auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  750. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  751. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  752. show_in_switchbar, last_state, last_checked, auto_off_executed,
  753. auto_off_pending, auto_off_pending_since, created_at, updated_at
  754. FROM smart_plugs
  755. """)
  756. )
  757. # Drop old table and rename new one
  758. await conn.execute(text("DROP TABLE smart_plugs"))
  759. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  760. except Exception:
  761. pass
  762. # Migration: Add show_on_printer_card column to smart_plugs
  763. try:
  764. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1"))
  765. except Exception:
  766. pass
  767. # Migration: Add MQTT smart plug fields (legacy)
  768. try:
  769. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)"))
  770. except Exception:
  771. pass
  772. try:
  773. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)"))
  774. except Exception:
  775. pass
  776. try:
  777. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)"))
  778. except Exception:
  779. pass
  780. try:
  781. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)"))
  782. except Exception:
  783. pass
  784. try:
  785. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0"))
  786. except Exception:
  787. pass
  788. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  789. try:
  790. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)"))
  791. except Exception:
  792. pass
  793. try:
  794. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0"))
  795. except Exception:
  796. pass
  797. try:
  798. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)"))
  799. except Exception:
  800. pass
  801. try:
  802. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0"))
  803. except Exception:
  804. pass
  805. try:
  806. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)"))
  807. except Exception:
  808. pass
  809. try:
  810. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)"))
  811. except Exception:
  812. pass
  813. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  814. try:
  815. await conn.execute(
  816. text("""
  817. UPDATE smart_plugs
  818. SET mqtt_power_topic = mqtt_topic,
  819. mqtt_power_multiplier = mqtt_multiplier
  820. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  821. """)
  822. )
  823. except Exception:
  824. pass
  825. # Migration: Create groups table for permission-based access control
  826. try:
  827. await conn.execute(
  828. text("""
  829. CREATE TABLE IF NOT EXISTS groups (
  830. id INTEGER PRIMARY KEY,
  831. name VARCHAR(100) NOT NULL UNIQUE,
  832. description VARCHAR(500),
  833. permissions JSON,
  834. is_system BOOLEAN NOT NULL DEFAULT 0,
  835. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  836. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  837. )
  838. """)
  839. )
  840. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  841. except Exception:
  842. pass
  843. # Migration: Create user_groups association table
  844. try:
  845. await conn.execute(
  846. text("""
  847. CREATE TABLE IF NOT EXISTS user_groups (
  848. user_id INTEGER NOT NULL,
  849. group_id INTEGER NOT NULL,
  850. PRIMARY KEY (user_id, group_id),
  851. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  852. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  853. )
  854. """)
  855. )
  856. except Exception:
  857. pass
  858. # Migration: Add model-based queue assignment columns to print_queue
  859. try:
  860. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  861. except Exception:
  862. pass
  863. try:
  864. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  865. except Exception:
  866. pass
  867. try:
  868. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  869. except Exception:
  870. pass
  871. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  872. try:
  873. await conn.execute(text("ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1"))
  874. except Exception:
  875. pass
  876. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  877. try:
  878. await conn.execute(text("ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0"))
  879. except Exception:
  880. pass
  881. # Migration: Add queue notification event columns to notification_providers
  882. try:
  883. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0"))
  884. except Exception:
  885. pass
  886. try:
  887. await conn.execute(
  888. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  889. )
  890. except Exception:
  891. pass
  892. try:
  893. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0"))
  894. except Exception:
  895. pass
  896. try:
  897. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1"))
  898. except Exception:
  899. pass
  900. try:
  901. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1"))
  902. except Exception:
  903. pass
  904. try:
  905. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1"))
  906. except Exception:
  907. pass
  908. try:
  909. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0"))
  910. except Exception:
  911. pass
  912. async def seed_notification_templates():
  913. """Seed default notification templates if they don't exist."""
  914. from sqlalchemy import select
  915. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  916. async with async_session() as session:
  917. # Get existing template event types
  918. result = await session.execute(select(NotificationTemplate.event_type))
  919. existing_types = {row[0] for row in result.fetchall()}
  920. if not existing_types:
  921. # No templates exist - insert all defaults
  922. for template_data in DEFAULT_TEMPLATES:
  923. template = NotificationTemplate(
  924. event_type=template_data["event_type"],
  925. name=template_data["name"],
  926. title_template=template_data["title_template"],
  927. body_template=template_data["body_template"],
  928. is_default=True,
  929. )
  930. session.add(template)
  931. else:
  932. # Templates exist - only add missing ones
  933. for template_data in DEFAULT_TEMPLATES:
  934. if template_data["event_type"] not in existing_types:
  935. template = NotificationTemplate(
  936. event_type=template_data["event_type"],
  937. name=template_data["name"],
  938. title_template=template_data["title_template"],
  939. body_template=template_data["body_template"],
  940. is_default=True,
  941. )
  942. session.add(template)
  943. await session.commit()
  944. async def seed_default_groups():
  945. """Seed default groups and migrate existing users to appropriate groups.
  946. Creates the default system groups (Administrators, Operators, Viewers) if they
  947. don't exist, then migrates existing users:
  948. - Users with role='admin' -> Administrators group
  949. - Users with role='user' -> Operators group
  950. """
  951. import logging
  952. from sqlalchemy import select
  953. from backend.app.core.permissions import DEFAULT_GROUPS
  954. from backend.app.models.group import Group
  955. from backend.app.models.user import User
  956. logger = logging.getLogger(__name__)
  957. async with async_session() as session:
  958. # Get existing groups
  959. result = await session.execute(select(Group.name))
  960. existing_groups = {row[0] for row in result.fetchall()}
  961. # Create default groups if they don't exist
  962. groups_created = []
  963. for group_name, group_config in DEFAULT_GROUPS.items():
  964. if group_name not in existing_groups:
  965. group = Group(
  966. name=group_name,
  967. description=group_config["description"],
  968. permissions=group_config["permissions"],
  969. is_system=group_config["is_system"],
  970. )
  971. session.add(group)
  972. groups_created.append(group_name)
  973. logger.info(f"Created default group: {group_name}")
  974. await session.commit()
  975. # Migrate existing users to groups if they're not already in any group
  976. if groups_created:
  977. # Get the groups we need
  978. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  979. admin_group = admin_result.scalar_one_or_none()
  980. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  981. operators_group = operators_result.scalar_one_or_none()
  982. # Get all users
  983. users_result = await session.execute(select(User))
  984. users = users_result.scalars().all()
  985. for user in users:
  986. # Skip if user already has groups
  987. if user.groups:
  988. continue
  989. if user.role == "admin" and admin_group:
  990. user.groups.append(admin_group)
  991. logger.info(f"Migrated admin user '{user.username}' to Administrators group")
  992. elif operators_group:
  993. user.groups.append(operators_group)
  994. logger.info(f"Migrated user '{user.username}' to Operators group")
  995. await session.commit()