database.py 48 KB

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