database.py 49 KB

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