database.py 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  1. from sqlalchemy import event
  2. from sqlalchemy.exc import OperationalError
  3. from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
  4. from sqlalchemy.orm import DeclarativeBase
  5. from backend.app.core.config import settings
  6. def _set_sqlite_pragmas(dbapi_conn, connection_record):
  7. """Set SQLite pragmas on each new connection for concurrency and performance."""
  8. cursor = dbapi_conn.cursor()
  9. # WAL mode allows concurrent readers + one writer (vs default DELETE mode which locks entirely)
  10. cursor.execute("PRAGMA journal_mode = WAL")
  11. # Wait up to 5 seconds when the database is locked instead of failing immediately
  12. cursor.execute("PRAGMA busy_timeout = 5000")
  13. cursor.execute("PRAGMA synchronous = NORMAL")
  14. cursor.close()
  15. engine = create_async_engine(
  16. settings.database_url,
  17. echo=settings.debug,
  18. pool_size=10,
  19. max_overflow=20,
  20. )
  21. # Register the pragma listener on the underlying sync engine
  22. event.listen(engine.sync_engine, "connect", _set_sqlite_pragmas)
  23. async_session = async_sessionmaker(
  24. engine,
  25. class_=AsyncSession,
  26. expire_on_commit=False,
  27. )
  28. async def close_all_connections():
  29. """Close all database connections for backup/restore operations."""
  30. global engine
  31. await engine.dispose()
  32. async def reinitialize_database():
  33. """Reinitialize database connection after restore."""
  34. global engine, async_session
  35. engine = create_async_engine(
  36. settings.database_url,
  37. echo=settings.debug,
  38. pool_size=10,
  39. max_overflow=20,
  40. )
  41. event.listen(engine.sync_engine, "connect", _set_sqlite_pragmas)
  42. async_session = async_sessionmaker(
  43. engine,
  44. class_=AsyncSession,
  45. expire_on_commit=False,
  46. )
  47. class Base(DeclarativeBase):
  48. pass
  49. async def get_db() -> AsyncSession:
  50. async with async_session() as session:
  51. try:
  52. yield session
  53. await session.commit()
  54. except Exception:
  55. await session.rollback()
  56. raise
  57. finally:
  58. await session.close()
  59. async def init_db():
  60. # Import models to register them with SQLAlchemy
  61. from backend.app.models import ( # noqa: F401
  62. active_print_spoolman,
  63. ams_history,
  64. ams_label,
  65. api_key,
  66. archive,
  67. bug_report,
  68. color_catalog,
  69. external_link,
  70. filament,
  71. github_backup,
  72. group,
  73. kprofile_note,
  74. library,
  75. local_preset,
  76. maintenance,
  77. notification,
  78. notification_template,
  79. orca_base_cache,
  80. pending_upload,
  81. print_log,
  82. print_queue,
  83. printer,
  84. project,
  85. project_bom,
  86. settings,
  87. slot_preset,
  88. smart_plug,
  89. spool,
  90. spool_assignment,
  91. spool_catalog,
  92. spool_k_profile,
  93. spool_usage_history,
  94. spoolbuddy_device,
  95. user,
  96. user_email_pref,
  97. virtual_printer,
  98. )
  99. async with engine.begin() as conn:
  100. await conn.run_sync(Base.metadata.create_all)
  101. # Run migrations for new columns (SQLite doesn't auto-add columns)
  102. await run_migrations(conn)
  103. # Seed default notification templates
  104. await seed_notification_templates()
  105. # Seed default groups and migrate existing users
  106. await seed_default_groups()
  107. # Seed default catalog entries
  108. await seed_spool_catalog()
  109. await seed_color_catalog()
  110. async def run_migrations(conn):
  111. """Add new columns to existing tables if they don't exist."""
  112. from sqlalchemy import text
  113. # Migration: Add is_favorite column to print_archives
  114. try:
  115. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN is_favorite BOOLEAN DEFAULT 0"))
  116. except OperationalError:
  117. # Column already exists
  118. pass
  119. # Migration: Add content_hash column to print_archives for duplicate detection
  120. try:
  121. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN content_hash VARCHAR(64)"))
  122. except OperationalError:
  123. # Column already exists
  124. pass
  125. # Migration: Add auto_off_executed column to smart_plugs
  126. try:
  127. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_executed BOOLEAN DEFAULT 0"))
  128. except OperationalError:
  129. # Column already exists
  130. pass
  131. # Migration: Add on_print_stopped column to notification_providers
  132. try:
  133. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_print_stopped BOOLEAN DEFAULT 1"))
  134. except OperationalError:
  135. # Column already exists
  136. pass
  137. # Migration: Add source_3mf_path column to print_archives
  138. try:
  139. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN source_3mf_path VARCHAR(500)"))
  140. except OperationalError:
  141. # Column already exists
  142. pass
  143. # Migration: Add f3d_path column to print_archives for Fusion 360 design files
  144. try:
  145. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN f3d_path VARCHAR(500)"))
  146. except OperationalError:
  147. # Column already exists
  148. pass
  149. # Migration: Add on_maintenance_due column to notification_providers
  150. try:
  151. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_maintenance_due BOOLEAN DEFAULT 0"))
  152. except OperationalError:
  153. # Column already exists
  154. pass
  155. # Migration: Add location column to printers for grouping
  156. try:
  157. await conn.execute(text("ALTER TABLE printers ADD COLUMN location VARCHAR(100)"))
  158. except OperationalError:
  159. # Column already exists
  160. pass
  161. # Migration: Add interval_type column to maintenance_types
  162. try:
  163. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN interval_type VARCHAR(20) DEFAULT 'hours'"))
  164. except OperationalError:
  165. # Column already exists
  166. pass
  167. # Migration: Add is_deleted column to maintenance_types for soft-deletes
  168. try:
  169. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN is_deleted BOOLEAN DEFAULT 0"))
  170. except OperationalError:
  171. # Column already exists
  172. pass
  173. # Migration: Add custom_interval_type column to printer_maintenance
  174. try:
  175. await conn.execute(text("ALTER TABLE printer_maintenance ADD COLUMN custom_interval_type VARCHAR(20)"))
  176. except OperationalError:
  177. # Column already exists
  178. pass
  179. # Migration: Add power alert columns to smart_plugs
  180. try:
  181. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_enabled BOOLEAN DEFAULT 0"))
  182. except OperationalError:
  183. pass # Already applied
  184. try:
  185. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_high REAL"))
  186. except OperationalError:
  187. pass # Already applied
  188. try:
  189. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_low REAL"))
  190. except OperationalError:
  191. pass # Already applied
  192. try:
  193. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN power_alert_last_triggered DATETIME"))
  194. except OperationalError:
  195. pass # Already applied
  196. # Migration: Add schedule columns to smart_plugs
  197. try:
  198. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_enabled BOOLEAN DEFAULT 0"))
  199. except OperationalError:
  200. pass # Already applied
  201. try:
  202. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_on_time VARCHAR(5)"))
  203. except OperationalError:
  204. pass # Already applied
  205. try:
  206. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN schedule_off_time VARCHAR(5)"))
  207. except OperationalError:
  208. pass # Already applied
  209. # Migration: Add daily digest columns to notification_providers
  210. try:
  211. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_enabled BOOLEAN DEFAULT 0"))
  212. except OperationalError:
  213. pass # Already applied
  214. try:
  215. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN daily_digest_time VARCHAR(5)"))
  216. except OperationalError:
  217. pass # Already applied
  218. # Migration: Add missing-spool-assignment print-start notification toggle
  219. try:
  220. await conn.execute(
  221. text("ALTER TABLE notification_providers ADD COLUMN on_print_missing_spool_assignment BOOLEAN DEFAULT 0")
  222. )
  223. except OperationalError:
  224. pass # Already applied
  225. # Migration: Add project_id column to print_archives
  226. try:
  227. await conn.execute(
  228. text("ALTER TABLE print_archives ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  229. )
  230. except OperationalError:
  231. pass # Already applied
  232. # Migration: Add project_id column to print_queue
  233. try:
  234. await conn.execute(
  235. text("ALTER TABLE print_queue ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  236. )
  237. except OperationalError:
  238. pass # Already applied
  239. # Migration: Create FTS5 virtual table for archive full-text search
  240. try:
  241. await conn.execute(
  242. text("""
  243. CREATE VIRTUAL TABLE IF NOT EXISTS archive_fts USING fts5(
  244. print_name,
  245. filename,
  246. tags,
  247. notes,
  248. designer,
  249. filament_type,
  250. content='print_archives',
  251. content_rowid='id'
  252. )
  253. """)
  254. )
  255. except OperationalError:
  256. pass # Already applied
  257. # Migration: Create triggers to keep FTS index in sync
  258. try:
  259. await conn.execute(
  260. text("""
  261. CREATE TRIGGER IF NOT EXISTS archive_fts_insert AFTER INSERT ON print_archives BEGIN
  262. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  263. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  264. END
  265. """)
  266. )
  267. except OperationalError:
  268. pass # Already applied
  269. try:
  270. await conn.execute(
  271. text("""
  272. CREATE TRIGGER IF NOT EXISTS archive_fts_delete AFTER DELETE ON print_archives BEGIN
  273. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  274. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  275. END
  276. """)
  277. )
  278. except OperationalError:
  279. pass # Already applied
  280. try:
  281. await conn.execute(
  282. text("""
  283. CREATE TRIGGER IF NOT EXISTS archive_fts_update AFTER UPDATE ON print_archives BEGIN
  284. INSERT INTO archive_fts(archive_fts, rowid, print_name, filename, tags, notes, designer, filament_type)
  285. VALUES ('delete', old.id, old.print_name, old.filename, old.tags, old.notes, old.designer, old.filament_type);
  286. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  287. VALUES (new.id, new.print_name, new.filename, new.tags, new.notes, new.designer, new.filament_type);
  288. END
  289. """)
  290. )
  291. except OperationalError:
  292. pass # Already applied
  293. # Migration: Add auto_off_pending columns to smart_plugs (for restart recovery)
  294. try:
  295. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending BOOLEAN DEFAULT 0"))
  296. except OperationalError:
  297. pass # Already applied
  298. try:
  299. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN auto_off_pending_since DATETIME"))
  300. except OperationalError:
  301. pass # Already applied
  302. # Migration: Add AMS alarm notification columns to notification_providers
  303. try:
  304. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_ams_humidity_high BOOLEAN DEFAULT 0"))
  305. except OperationalError:
  306. pass # Already applied
  307. try:
  308. await conn.execute(
  309. text("ALTER TABLE notification_providers ADD COLUMN on_ams_temperature_high BOOLEAN DEFAULT 0")
  310. )
  311. except OperationalError:
  312. pass # Already applied
  313. # Migration: Add AMS-HT alarm notification columns to notification_providers
  314. try:
  315. await conn.execute(
  316. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_humidity_high BOOLEAN DEFAULT 0")
  317. )
  318. except OperationalError:
  319. pass # Already applied
  320. try:
  321. await conn.execute(
  322. text("ALTER TABLE notification_providers ADD COLUMN on_ams_ht_temperature_high BOOLEAN DEFAULT 0")
  323. )
  324. except OperationalError:
  325. pass # Already applied
  326. # Migration: Add plate not empty notification column to notification_providers
  327. try:
  328. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_plate_not_empty BOOLEAN DEFAULT 1"))
  329. except OperationalError:
  330. pass # Already applied
  331. # Migration: Add notes column to projects (Phase 2)
  332. try:
  333. await conn.execute(text("ALTER TABLE projects ADD COLUMN notes TEXT"))
  334. except OperationalError:
  335. pass # Already applied
  336. # Migration: Add attachments column to projects (Phase 3)
  337. try:
  338. await conn.execute(text("ALTER TABLE projects ADD COLUMN attachments JSON"))
  339. except OperationalError:
  340. pass # Already applied
  341. # Migration: Add tags column to projects (Phase 4)
  342. try:
  343. await conn.execute(text("ALTER TABLE projects ADD COLUMN tags TEXT"))
  344. except OperationalError:
  345. pass # Already applied
  346. # Migration: Add due_date column to projects (Phase 5)
  347. try:
  348. await conn.execute(text("ALTER TABLE projects ADD COLUMN due_date DATETIME"))
  349. except OperationalError:
  350. pass # Already applied
  351. # Migration: Add priority column to projects (Phase 5)
  352. try:
  353. await conn.execute(text("ALTER TABLE projects ADD COLUMN priority VARCHAR(20) DEFAULT 'normal'"))
  354. except OperationalError:
  355. pass # Already applied
  356. # Migration: Add budget column to projects (Phase 6)
  357. try:
  358. await conn.execute(text("ALTER TABLE projects ADD COLUMN budget REAL"))
  359. except OperationalError:
  360. pass # Already applied
  361. # Migration: Add is_template column to projects (Phase 8)
  362. try:
  363. await conn.execute(text("ALTER TABLE projects ADD COLUMN is_template BOOLEAN DEFAULT 0"))
  364. except OperationalError:
  365. pass # Already applied
  366. # Migration: Add template_source_id column to projects (Phase 8)
  367. try:
  368. await conn.execute(text("ALTER TABLE projects ADD COLUMN template_source_id INTEGER"))
  369. except OperationalError:
  370. pass # Already applied
  371. # Migration: Add parent_id column to projects (Phase 10)
  372. try:
  373. await conn.execute(
  374. text("ALTER TABLE projects ADD COLUMN parent_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  375. )
  376. except OperationalError:
  377. pass # Already applied
  378. # Migration: Rename quantity_printed to quantity_acquired in project_bom_items
  379. try:
  380. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN quantity_printed TO quantity_acquired"))
  381. except OperationalError:
  382. pass # Already applied
  383. # Migration: Add unit_price column to project_bom_items
  384. try:
  385. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN unit_price REAL"))
  386. except OperationalError:
  387. pass # Already applied
  388. # Migration: Add sourcing_url column to project_bom_items
  389. try:
  390. await conn.execute(text("ALTER TABLE project_bom_items ADD COLUMN sourcing_url VARCHAR(512)"))
  391. except OperationalError:
  392. pass # Already applied
  393. # Migration: Rename notes to remarks in project_bom_items
  394. try:
  395. await conn.execute(text("ALTER TABLE project_bom_items RENAME COLUMN notes TO remarks"))
  396. except OperationalError:
  397. pass # Already applied
  398. # Migration: Add show_in_switchbar column to smart_plugs
  399. try:
  400. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_in_switchbar BOOLEAN DEFAULT 0"))
  401. except OperationalError:
  402. pass # Already applied
  403. # Migration: Add runtime tracking columns to printers
  404. try:
  405. await conn.execute(text("ALTER TABLE printers ADD COLUMN runtime_seconds INTEGER DEFAULT 0"))
  406. except OperationalError:
  407. pass # Already applied
  408. try:
  409. await conn.execute(text("ALTER TABLE printers ADD COLUMN last_runtime_update DATETIME"))
  410. except OperationalError:
  411. pass # Already applied
  412. # Migration: Add quantity column to print_archives for tracking item count
  413. try:
  414. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN quantity INTEGER DEFAULT 1"))
  415. except OperationalError:
  416. pass # Already applied
  417. # Migration: Add manual_start column to print_queue for staged prints
  418. try:
  419. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN manual_start BOOLEAN DEFAULT 0"))
  420. except OperationalError:
  421. pass # Already applied
  422. # Migration: Add wiki_url column to maintenance_types for documentation links
  423. try:
  424. await conn.execute(text("ALTER TABLE maintenance_types ADD COLUMN wiki_url VARCHAR(500)"))
  425. except OperationalError:
  426. pass # Already applied
  427. # Migration: Add ams_mapping column to print_queue for storing filament slot assignments
  428. try:
  429. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN ams_mapping TEXT"))
  430. except OperationalError:
  431. pass # Already applied
  432. # Migration: Add target_parts_count column to projects for tracking total parts needed
  433. try:
  434. await conn.execute(text("ALTER TABLE projects ADD COLUMN target_parts_count INTEGER"))
  435. except OperationalError:
  436. pass # Already applied
  437. # Migration: Make printer_id nullable in print_queue for unassigned queue items
  438. # SQLite doesn't support ALTER COLUMN, so we need to recreate the table
  439. try:
  440. # Check if printer_id is already nullable by trying to insert NULL
  441. # This is a safe check that won't affect existing data
  442. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  443. row = result.fetchone()
  444. if row and "printer_id INTEGER NOT NULL" in (row[0] or ""):
  445. # Need to migrate - printer_id is currently NOT NULL
  446. await conn.execute(
  447. text("""
  448. CREATE TABLE print_queue_new (
  449. id INTEGER PRIMARY KEY,
  450. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  451. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  452. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  453. position INTEGER DEFAULT 0,
  454. scheduled_time DATETIME,
  455. manual_start BOOLEAN DEFAULT 0,
  456. require_previous_success BOOLEAN DEFAULT 0,
  457. auto_off_after BOOLEAN DEFAULT 0,
  458. ams_mapping TEXT,
  459. status VARCHAR(20) DEFAULT 'pending',
  460. started_at DATETIME,
  461. completed_at DATETIME,
  462. error_message TEXT,
  463. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  464. )
  465. """)
  466. )
  467. await conn.execute(
  468. text("""
  469. INSERT INTO print_queue_new
  470. SELECT id, printer_id, archive_id, project_id, position, scheduled_time,
  471. manual_start, require_previous_success, auto_off_after, ams_mapping,
  472. status, started_at, completed_at, error_message, created_at
  473. FROM print_queue
  474. """)
  475. )
  476. await conn.execute(text("DROP TABLE print_queue"))
  477. await conn.execute(text("ALTER TABLE print_queue_new RENAME TO print_queue"))
  478. except OperationalError:
  479. pass # Already applied
  480. # Migration: Add plug_type column to smart_plugs for HA integration
  481. try:
  482. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN plug_type VARCHAR(20) DEFAULT 'tasmota'"))
  483. except OperationalError:
  484. pass # Already applied
  485. # Migration: Add ha_entity_id column to smart_plugs for HA integration
  486. try:
  487. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_entity_id VARCHAR(100)"))
  488. except OperationalError:
  489. pass # Already applied
  490. # Migration: Add project_id column to library_folders for linking folders to projects
  491. try:
  492. await conn.execute(
  493. text("ALTER TABLE library_folders ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  494. )
  495. except OperationalError:
  496. pass # Already applied
  497. # Migration: Add archive_id column to library_folders for linking folders to archives
  498. try:
  499. await conn.execute(
  500. text(
  501. "ALTER TABLE library_folders ADD COLUMN archive_id INTEGER REFERENCES print_archives(id) ON DELETE SET NULL"
  502. )
  503. )
  504. except OperationalError:
  505. pass # Already applied
  506. # Migration: Make ip_address nullable for HA plugs (SQLite requires table recreation)
  507. try:
  508. # Check if ip_address is currently NOT NULL
  509. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  510. row = result.fetchone()
  511. if row and "ip_address VARCHAR(45) NOT NULL" in (row[0] or ""):
  512. # Need to migrate - ip_address is currently NOT NULL
  513. await conn.execute(
  514. text("""
  515. CREATE TABLE smart_plugs_new (
  516. id INTEGER PRIMARY KEY,
  517. name VARCHAR(100) NOT NULL,
  518. ip_address VARCHAR(45),
  519. plug_type VARCHAR(20) DEFAULT 'tasmota',
  520. ha_entity_id VARCHAR(100),
  521. printer_id INTEGER UNIQUE REFERENCES printers(id) ON DELETE SET NULL,
  522. enabled BOOLEAN NOT NULL DEFAULT 1,
  523. auto_on BOOLEAN NOT NULL DEFAULT 1,
  524. auto_off BOOLEAN NOT NULL DEFAULT 1,
  525. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  526. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  527. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  528. username VARCHAR(50),
  529. password VARCHAR(100),
  530. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  531. power_alert_high FLOAT,
  532. power_alert_low FLOAT,
  533. power_alert_last_triggered DATETIME,
  534. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  535. schedule_on_time VARCHAR(5),
  536. schedule_off_time VARCHAR(5),
  537. show_in_switchbar BOOLEAN DEFAULT 0,
  538. last_state VARCHAR(10),
  539. last_checked DATETIME,
  540. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  541. auto_off_pending BOOLEAN DEFAULT 0,
  542. auto_off_pending_since DATETIME,
  543. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  544. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  545. )
  546. """)
  547. )
  548. await conn.execute(
  549. text("""
  550. INSERT INTO smart_plugs_new
  551. SELECT id, name, ip_address,
  552. COALESCE(plug_type, 'tasmota'), ha_entity_id, printer_id,
  553. enabled, auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  554. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  555. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  556. COALESCE(show_in_switchbar, 0), last_state, last_checked, auto_off_executed,
  557. COALESCE(auto_off_pending, 0), auto_off_pending_since, created_at, updated_at
  558. FROM smart_plugs
  559. """)
  560. )
  561. await conn.execute(text("DROP TABLE smart_plugs"))
  562. await conn.execute(text("ALTER TABLE smart_plugs_new RENAME TO smart_plugs"))
  563. except OperationalError:
  564. pass # Already applied
  565. # Migration: Add plate_id column to print_queue for multi-plate 3MF support
  566. try:
  567. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN plate_id INTEGER"))
  568. except OperationalError:
  569. pass # Already applied
  570. # Migration: Add print options columns to print_queue
  571. try:
  572. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN bed_levelling BOOLEAN DEFAULT 1"))
  573. except OperationalError:
  574. pass # Already applied
  575. try:
  576. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN flow_cali BOOLEAN DEFAULT 0"))
  577. except OperationalError:
  578. pass # Already applied
  579. try:
  580. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN vibration_cali BOOLEAN DEFAULT 1"))
  581. except OperationalError:
  582. pass # Already applied
  583. try:
  584. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN layer_inspect BOOLEAN DEFAULT 0"))
  585. except OperationalError:
  586. pass # Already applied
  587. try:
  588. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN timelapse BOOLEAN DEFAULT 0"))
  589. except OperationalError:
  590. pass # Already applied
  591. try:
  592. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN use_ams BOOLEAN DEFAULT 1"))
  593. except OperationalError:
  594. pass # Already applied
  595. # Migration: Add library_file_id column to print_queue and make archive_id nullable
  596. # This allows queue items to reference library files directly (archive created at print start)
  597. try:
  598. await conn.execute(
  599. text(
  600. "ALTER TABLE print_queue ADD COLUMN library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE"
  601. )
  602. )
  603. except OperationalError:
  604. pass # Already applied
  605. # Check if archive_id needs to be made nullable (requires table recreation in SQLite)
  606. try:
  607. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='print_queue'"))
  608. row = result.fetchone()
  609. if row and "archive_id INTEGER NOT NULL" in (row[0] or ""):
  610. # Need to migrate - archive_id is currently NOT NULL
  611. await conn.execute(
  612. text("""
  613. CREATE TABLE print_queue_new2 (
  614. id INTEGER PRIMARY KEY,
  615. printer_id INTEGER REFERENCES printers(id) ON DELETE CASCADE,
  616. archive_id INTEGER REFERENCES print_archives(id) ON DELETE CASCADE,
  617. library_file_id INTEGER REFERENCES library_files(id) ON DELETE CASCADE,
  618. project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
  619. position INTEGER DEFAULT 0,
  620. scheduled_time DATETIME,
  621. manual_start BOOLEAN DEFAULT 0,
  622. require_previous_success BOOLEAN DEFAULT 0,
  623. auto_off_after BOOLEAN DEFAULT 0,
  624. ams_mapping TEXT,
  625. plate_id INTEGER,
  626. bed_levelling BOOLEAN DEFAULT 1,
  627. flow_cali BOOLEAN DEFAULT 0,
  628. vibration_cali BOOLEAN DEFAULT 1,
  629. layer_inspect BOOLEAN DEFAULT 0,
  630. timelapse BOOLEAN DEFAULT 0,
  631. use_ams BOOLEAN DEFAULT 1,
  632. status VARCHAR(20) DEFAULT 'pending',
  633. started_at DATETIME,
  634. completed_at DATETIME,
  635. error_message TEXT,
  636. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  637. )
  638. """)
  639. )
  640. await conn.execute(
  641. text("""
  642. INSERT INTO print_queue_new2
  643. SELECT id, printer_id, archive_id, NULL, project_id, position, scheduled_time,
  644. manual_start, require_previous_success, auto_off_after, ams_mapping, plate_id,
  645. COALESCE(bed_levelling, 1), COALESCE(flow_cali, 0), COALESCE(vibration_cali, 1),
  646. COALESCE(layer_inspect, 0), COALESCE(timelapse, 0), COALESCE(use_ams, 1),
  647. status, started_at, completed_at, error_message, created_at
  648. FROM print_queue
  649. """)
  650. )
  651. await conn.execute(text("DROP TABLE print_queue"))
  652. await conn.execute(text("ALTER TABLE print_queue_new2 RENAME TO print_queue"))
  653. except OperationalError:
  654. pass # Already applied
  655. # Migration: Add HA energy sensor entity columns to smart_plugs
  656. try:
  657. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_power_entity VARCHAR(100)"))
  658. except OperationalError:
  659. pass # Already applied
  660. try:
  661. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_today_entity VARCHAR(100)"))
  662. except OperationalError:
  663. pass # Already applied
  664. try:
  665. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN ha_energy_total_entity VARCHAR(100)"))
  666. except OperationalError:
  667. pass # Already applied
  668. # Migration: Create users table for authentication
  669. try:
  670. await conn.execute(
  671. text("""
  672. CREATE TABLE IF NOT EXISTS users (
  673. id INTEGER PRIMARY KEY,
  674. username VARCHAR(100) NOT NULL UNIQUE,
  675. password_hash VARCHAR(255) NOT NULL,
  676. role VARCHAR(20) NOT NULL DEFAULT 'user',
  677. is_active BOOLEAN NOT NULL DEFAULT 1,
  678. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  679. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  680. )
  681. """)
  682. )
  683. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_users_username ON users(username)"))
  684. except OperationalError:
  685. pass # Already applied
  686. # Migration: Add external camera columns to printers
  687. try:
  688. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_url VARCHAR(500)"))
  689. except OperationalError:
  690. pass # Already applied
  691. try:
  692. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_type VARCHAR(20)"))
  693. except OperationalError:
  694. pass # Already applied
  695. try:
  696. await conn.execute(text("ALTER TABLE printers ADD COLUMN external_camera_enabled BOOLEAN DEFAULT 0"))
  697. except OperationalError:
  698. pass # Already applied
  699. # Migration: Add external_url column to print_archives for user-defined links (Printables, etc.)
  700. try:
  701. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN external_url VARCHAR(500)"))
  702. except OperationalError:
  703. pass # Already applied
  704. # Migration: Add sliced_for_model column to print_archives for model-based queue assignment
  705. try:
  706. await conn.execute(text("ALTER TABLE print_archives ADD COLUMN sliced_for_model VARCHAR(50)"))
  707. except OperationalError:
  708. pass # Already applied
  709. # Migration: Add is_external column to library_files for external cloud files
  710. try:
  711. await conn.execute(text("ALTER TABLE library_files ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  712. except OperationalError:
  713. pass # Already applied
  714. # Migration: Add project_id column to library_files
  715. try:
  716. await conn.execute(
  717. text("ALTER TABLE library_files ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL")
  718. )
  719. except OperationalError:
  720. pass # Already applied
  721. # Migration: Add is_external column to library_folders for external cloud folders
  722. try:
  723. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN is_external BOOLEAN DEFAULT 0"))
  724. except OperationalError:
  725. pass # Already applied
  726. # Migration: Add external folder settings columns to library_folders
  727. try:
  728. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_readonly BOOLEAN DEFAULT 0"))
  729. except OperationalError:
  730. pass # Already applied
  731. try:
  732. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_show_hidden BOOLEAN DEFAULT 0"))
  733. except OperationalError:
  734. pass # Already applied
  735. try:
  736. await conn.execute(text("ALTER TABLE library_folders ADD COLUMN external_path VARCHAR(500)"))
  737. except OperationalError:
  738. pass # Already applied
  739. # Migration: Add plate_detection_enabled column to printers
  740. try:
  741. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_enabled BOOLEAN DEFAULT 0"))
  742. except OperationalError:
  743. pass # Already applied
  744. # Migration: Add plate detection ROI columns to printers
  745. try:
  746. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_x REAL"))
  747. except OperationalError:
  748. pass # Already applied
  749. try:
  750. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_y REAL"))
  751. except OperationalError:
  752. pass # Already applied
  753. try:
  754. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_w REAL"))
  755. except OperationalError:
  756. pass # Already applied
  757. try:
  758. await conn.execute(text("ALTER TABLE printers ADD COLUMN plate_detection_roi_h REAL"))
  759. except OperationalError:
  760. pass # Already applied
  761. # Migration: Remove UNIQUE constraint from smart_plugs.printer_id
  762. # This allows HA scripts to coexist with regular plugs (scripts are for multi-device control)
  763. # SQLite requires table recreation to drop constraints
  764. try:
  765. # Check if we need to migrate — look for UNIQUE on printer_id in the
  766. # CREATE TABLE statement OR as a separate UNIQUE index.
  767. needs_migration = False
  768. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='smart_plugs'"))
  769. row = result.fetchone()
  770. table_sql = (row[0] or "").upper() if row else ""
  771. if "PRINTER_ID" in table_sql and "UNIQUE" in table_sql:
  772. # Check if UNIQUE appears near printer_id — inline or table-level constraint.
  773. # Handle quoted ("PRINTER_ID") and unquoted column names.
  774. import re
  775. if re.search(r'"?PRINTER_ID"?\s+\w+\s+UNIQUE', table_sql) or re.search(
  776. r'UNIQUE\s*\([^)]*"?PRINTER_ID"?', table_sql
  777. ):
  778. needs_migration = True
  779. # Also check for separate UNIQUE indexes on printer_id
  780. idx_result = await conn.execute(
  781. text("SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name='smart_plugs' AND sql IS NOT NULL")
  782. )
  783. for idx_row in idx_result.fetchall():
  784. idx_sql = (idx_row[0] or "").upper()
  785. if "UNIQUE" in idx_sql and "PRINTER_ID" in idx_sql:
  786. needs_migration = True
  787. break
  788. if needs_migration:
  789. # Create new table without UNIQUE constraint on printer_id
  790. await conn.execute(
  791. text("""
  792. CREATE TABLE smart_plugs_temp (
  793. id INTEGER PRIMARY KEY,
  794. name VARCHAR(100) NOT NULL,
  795. ip_address VARCHAR(45),
  796. plug_type VARCHAR(20) DEFAULT 'tasmota',
  797. ha_entity_id VARCHAR(100),
  798. ha_power_entity VARCHAR(100),
  799. ha_energy_today_entity VARCHAR(100),
  800. ha_energy_total_entity VARCHAR(100),
  801. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  802. enabled BOOLEAN NOT NULL DEFAULT 1,
  803. auto_on BOOLEAN NOT NULL DEFAULT 1,
  804. auto_off BOOLEAN NOT NULL DEFAULT 1,
  805. off_delay_mode VARCHAR(20) NOT NULL DEFAULT 'time',
  806. off_delay_minutes INTEGER NOT NULL DEFAULT 5,
  807. off_temp_threshold INTEGER NOT NULL DEFAULT 70,
  808. username VARCHAR(50),
  809. password VARCHAR(100),
  810. power_alert_enabled BOOLEAN NOT NULL DEFAULT 0,
  811. power_alert_high FLOAT,
  812. power_alert_low FLOAT,
  813. power_alert_last_triggered DATETIME,
  814. schedule_enabled BOOLEAN NOT NULL DEFAULT 0,
  815. schedule_on_time VARCHAR(5),
  816. schedule_off_time VARCHAR(5),
  817. show_in_switchbar BOOLEAN DEFAULT 0,
  818. last_state VARCHAR(10),
  819. last_checked DATETIME,
  820. auto_off_executed BOOLEAN NOT NULL DEFAULT 0,
  821. auto_off_pending BOOLEAN DEFAULT 0,
  822. auto_off_pending_since DATETIME,
  823. created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
  824. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
  825. )
  826. """)
  827. )
  828. # Copy data
  829. await conn.execute(
  830. text("""
  831. INSERT INTO smart_plugs_temp
  832. SELECT id, name, ip_address, plug_type, ha_entity_id, ha_power_entity,
  833. ha_energy_today_entity, ha_energy_total_entity, printer_id, enabled,
  834. auto_on, auto_off, off_delay_mode, off_delay_minutes, off_temp_threshold,
  835. username, password, power_alert_enabled, power_alert_high, power_alert_low,
  836. power_alert_last_triggered, schedule_enabled, schedule_on_time, schedule_off_time,
  837. show_in_switchbar, last_state, last_checked, auto_off_executed,
  838. auto_off_pending, auto_off_pending_since, created_at, updated_at
  839. FROM smart_plugs
  840. """)
  841. )
  842. # Drop old table and rename new one
  843. await conn.execute(text("DROP TABLE smart_plugs"))
  844. await conn.execute(text("ALTER TABLE smart_plugs_temp RENAME TO smart_plugs"))
  845. except OperationalError:
  846. pass # Already applied
  847. # Migration: Add show_on_printer_card column to smart_plugs
  848. try:
  849. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN show_on_printer_card BOOLEAN DEFAULT 1"))
  850. except OperationalError:
  851. pass # Already applied
  852. # Migration: Add MQTT smart plug fields (legacy)
  853. try:
  854. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_topic VARCHAR(200)"))
  855. except OperationalError:
  856. pass # Already applied
  857. try:
  858. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_path VARCHAR(100)"))
  859. except OperationalError:
  860. pass # Already applied
  861. try:
  862. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_path VARCHAR(100)"))
  863. except OperationalError:
  864. pass # Already applied
  865. try:
  866. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_path VARCHAR(100)"))
  867. except OperationalError:
  868. pass # Already applied
  869. try:
  870. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_multiplier REAL DEFAULT 1.0"))
  871. except OperationalError:
  872. pass # Already applied
  873. # Migration: Add enhanced MQTT smart plug fields (separate topics and multipliers)
  874. try:
  875. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_topic VARCHAR(200)"))
  876. except OperationalError:
  877. pass # Already applied
  878. try:
  879. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_power_multiplier REAL DEFAULT 1.0"))
  880. except OperationalError:
  881. pass # Already applied
  882. try:
  883. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_topic VARCHAR(200)"))
  884. except OperationalError:
  885. pass # Already applied
  886. try:
  887. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_energy_multiplier REAL DEFAULT 1.0"))
  888. except OperationalError:
  889. pass # Already applied
  890. try:
  891. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_topic VARCHAR(200)"))
  892. except OperationalError:
  893. pass # Already applied
  894. try:
  895. await conn.execute(text("ALTER TABLE smart_plugs ADD COLUMN mqtt_state_on_value VARCHAR(50)"))
  896. except OperationalError:
  897. pass # Already applied
  898. # Migration: Copy existing mqtt_topic to mqtt_power_topic for backward compatibility
  899. try:
  900. await conn.execute(
  901. text("""
  902. UPDATE smart_plugs
  903. SET mqtt_power_topic = mqtt_topic,
  904. mqtt_power_multiplier = mqtt_multiplier
  905. WHERE mqtt_topic IS NOT NULL AND mqtt_power_topic IS NULL
  906. """)
  907. )
  908. except OperationalError:
  909. pass # Already applied
  910. # Migration: Create groups table for permission-based access control
  911. try:
  912. await conn.execute(
  913. text("""
  914. CREATE TABLE IF NOT EXISTS groups (
  915. id INTEGER PRIMARY KEY,
  916. name VARCHAR(100) NOT NULL UNIQUE,
  917. description VARCHAR(500),
  918. permissions JSON,
  919. is_system BOOLEAN NOT NULL DEFAULT 0,
  920. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  921. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  922. )
  923. """)
  924. )
  925. await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_groups_name ON groups(name)"))
  926. except OperationalError:
  927. pass # Already applied
  928. # Migration: Create user_groups association table
  929. try:
  930. await conn.execute(
  931. text("""
  932. CREATE TABLE IF NOT EXISTS user_groups (
  933. user_id INTEGER NOT NULL,
  934. group_id INTEGER NOT NULL,
  935. PRIMARY KEY (user_id, group_id),
  936. FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  937. FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
  938. )
  939. """)
  940. )
  941. except OperationalError:
  942. pass # Already applied
  943. # Migration: Add model-based queue assignment columns to print_queue
  944. try:
  945. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_model VARCHAR(50)"))
  946. except OperationalError:
  947. pass # Already applied
  948. try:
  949. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN required_filament_types TEXT"))
  950. except OperationalError:
  951. pass # Already applied
  952. try:
  953. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN waiting_reason TEXT"))
  954. except OperationalError:
  955. pass # Already applied
  956. # Migration: Add nozzle_count column to printers (for dual-extruder detection)
  957. try:
  958. await conn.execute(text("ALTER TABLE printers ADD COLUMN nozzle_count INTEGER DEFAULT 1"))
  959. except OperationalError:
  960. pass # Already applied
  961. # Migration: Add print_hours_offset column to printers (baseline hours adjustment)
  962. try:
  963. await conn.execute(text("ALTER TABLE printers ADD COLUMN print_hours_offset REAL DEFAULT 0.0"))
  964. except OperationalError:
  965. pass # Already applied
  966. # Migration: Add queue notification event columns to notification_providers
  967. try:
  968. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_added BOOLEAN DEFAULT 0"))
  969. except OperationalError:
  970. pass # Already applied
  971. try:
  972. await conn.execute(
  973. text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_assigned BOOLEAN DEFAULT 0")
  974. )
  975. except OperationalError:
  976. pass # Already applied
  977. try:
  978. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_started BOOLEAN DEFAULT 0"))
  979. except OperationalError:
  980. pass # Already applied
  981. try:
  982. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_waiting BOOLEAN DEFAULT 1"))
  983. except OperationalError:
  984. pass # Already applied
  985. try:
  986. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_skipped BOOLEAN DEFAULT 1"))
  987. except OperationalError:
  988. pass # Already applied
  989. try:
  990. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_job_failed BOOLEAN DEFAULT 1"))
  991. except OperationalError:
  992. pass # Already applied
  993. try:
  994. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_queue_completed BOOLEAN DEFAULT 0"))
  995. except OperationalError:
  996. pass # Already applied
  997. # Migration: Add created_by_id column to print_archives for user tracking (Issue #206)
  998. try:
  999. await conn.execute(
  1000. text("ALTER TABLE print_archives ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  1001. )
  1002. except OperationalError:
  1003. pass # Already applied
  1004. # Migration: Add created_by_id column to print_queue for user tracking (Issue #206)
  1005. try:
  1006. await conn.execute(
  1007. text("ALTER TABLE print_queue ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  1008. )
  1009. except OperationalError:
  1010. pass # Already applied
  1011. # Migration: Add created_by_id column to library_files for user tracking (Issue #206)
  1012. try:
  1013. await conn.execute(
  1014. text("ALTER TABLE library_files ADD COLUMN created_by_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
  1015. )
  1016. except OperationalError:
  1017. pass # Already applied
  1018. # Migration: Add target_location column to print_queue for location-based filtering (Issue #220)
  1019. try:
  1020. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN target_location VARCHAR(100)"))
  1021. except OperationalError:
  1022. pass # Already applied
  1023. # Migration: Convert absolute paths to relative paths in library_files table
  1024. # This ensures backup/restore portability across different installations
  1025. try:
  1026. base_dir_str = str(settings.base_dir)
  1027. # Ensure we have a trailing slash for clean replacement
  1028. if not base_dir_str.endswith("/"):
  1029. base_dir_str += "/"
  1030. # Update file_path - remove base_dir prefix from absolute paths
  1031. await conn.execute(
  1032. text("""
  1033. UPDATE library_files
  1034. SET file_path = SUBSTR(file_path, LENGTH(:base_dir) + 1)
  1035. WHERE file_path LIKE :pattern
  1036. """),
  1037. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1038. )
  1039. # Update thumbnail_path - remove base_dir prefix from absolute paths
  1040. await conn.execute(
  1041. text("""
  1042. UPDATE library_files
  1043. SET thumbnail_path = SUBSTR(thumbnail_path, LENGTH(:base_dir) + 1)
  1044. WHERE thumbnail_path LIKE :pattern
  1045. """),
  1046. {"base_dir": base_dir_str, "pattern": base_dir_str + "%"},
  1047. )
  1048. except OperationalError:
  1049. pass # Already applied
  1050. # Create active_print_spoolman table for Spoolman per-filament tracking
  1051. try:
  1052. await conn.execute(
  1053. text("""
  1054. CREATE TABLE IF NOT EXISTS active_print_spoolman (
  1055. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1056. printer_id INTEGER NOT NULL REFERENCES printers(id) ON DELETE CASCADE,
  1057. archive_id INTEGER NOT NULL REFERENCES print_archives(id) ON DELETE CASCADE,
  1058. filament_usage TEXT NOT NULL,
  1059. ams_trays TEXT NOT NULL,
  1060. slot_to_tray TEXT,
  1061. layer_usage TEXT,
  1062. filament_properties TEXT,
  1063. UNIQUE(printer_id, archive_id)
  1064. )
  1065. """)
  1066. )
  1067. except OperationalError:
  1068. pass # Already applied
  1069. # Migration: Add preset_source column to slot_preset_mappings for local preset support
  1070. try:
  1071. await conn.execute(
  1072. text("ALTER TABLE slot_preset_mappings ADD COLUMN preset_source VARCHAR(20) DEFAULT 'cloud'")
  1073. )
  1074. except OperationalError:
  1075. pass # Already applied
  1076. # Migration: Add email column to users for Advanced Auth (PR #322)
  1077. try:
  1078. await conn.execute(text("ALTER TABLE users ADD COLUMN email VARCHAR(255)"))
  1079. except OperationalError:
  1080. pass # Already applied
  1081. # Migration: Add inventory spool tracking columns
  1082. try:
  1083. await conn.execute(text("ALTER TABLE spool ADD COLUMN added_full BOOLEAN"))
  1084. except OperationalError:
  1085. pass # Already applied
  1086. try:
  1087. await conn.execute(text("ALTER TABLE spool ADD COLUMN last_used DATETIME"))
  1088. except OperationalError:
  1089. pass # Already applied
  1090. try:
  1091. await conn.execute(text("ALTER TABLE spool ADD COLUMN encode_time DATETIME"))
  1092. except OperationalError:
  1093. pass # Already applied
  1094. # Migration: Add RFID tag matching columns to spool
  1095. try:
  1096. await conn.execute(text("ALTER TABLE spool ADD COLUMN tag_uid VARCHAR(16)"))
  1097. except OperationalError:
  1098. pass # Already applied
  1099. try:
  1100. await conn.execute(text("ALTER TABLE spool ADD COLUMN tray_uuid VARCHAR(32)"))
  1101. except OperationalError:
  1102. pass # Already applied
  1103. try:
  1104. await conn.execute(text("ALTER TABLE spool ADD COLUMN data_origin VARCHAR(20)"))
  1105. except OperationalError:
  1106. pass # Already applied
  1107. try:
  1108. await conn.execute(text("ALTER TABLE spool ADD COLUMN tag_type VARCHAR(20)"))
  1109. except OperationalError:
  1110. pass # Already applied
  1111. # Migration: Add core_weight_catalog_id to track which catalog entry was used for empty spool weight
  1112. try:
  1113. await conn.execute(text("ALTER TABLE spool ADD COLUMN core_weight_catalog_id INTEGER"))
  1114. except OperationalError:
  1115. pass # Already applied
  1116. # Migration: Create spool_usage_history table for filament consumption tracking
  1117. try:
  1118. await conn.execute(
  1119. text("""
  1120. CREATE TABLE IF NOT EXISTS spool_usage_history (
  1121. id INTEGER PRIMARY KEY AUTOINCREMENT,
  1122. spool_id INTEGER NOT NULL REFERENCES spool(id) ON DELETE CASCADE,
  1123. printer_id INTEGER REFERENCES printers(id) ON DELETE SET NULL,
  1124. print_name VARCHAR(500),
  1125. weight_used REAL NOT NULL DEFAULT 0,
  1126. percent_used INTEGER NOT NULL DEFAULT 0,
  1127. status VARCHAR(20) NOT NULL DEFAULT 'completed',
  1128. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1129. )
  1130. """)
  1131. )
  1132. except OperationalError:
  1133. pass # Already applied
  1134. # Migration: Add open_in_new_tab column to external_links
  1135. try:
  1136. await conn.execute(text("ALTER TABLE external_links ADD COLUMN open_in_new_tab BOOLEAN DEFAULT 0"))
  1137. except OperationalError:
  1138. pass # Already applied
  1139. # Migration: Add bed cooled notification column to notification_providers
  1140. try:
  1141. await conn.execute(text("ALTER TABLE notification_providers ADD COLUMN on_bed_cooled BOOLEAN DEFAULT 0"))
  1142. except OperationalError:
  1143. pass # Already applied
  1144. # Migration: Add first layer complete notification column to notification_providers
  1145. try:
  1146. await conn.execute(
  1147. text("ALTER TABLE notification_providers ADD COLUMN on_first_layer_complete BOOLEAN DEFAULT 0")
  1148. )
  1149. except OperationalError:
  1150. pass # Already applied
  1151. # Migration: Add weight_locked flag to spool table (skip AMS auto-sync for manually-entered weights)
  1152. try:
  1153. await conn.execute(text("ALTER TABLE spool ADD COLUMN weight_locked BOOLEAN DEFAULT 0"))
  1154. except OperationalError:
  1155. pass # Already applied
  1156. # Migration: Add SpoolBuddy scale weight tracking columns to spool table
  1157. try:
  1158. await conn.execute(text("ALTER TABLE spool ADD COLUMN last_scale_weight INTEGER"))
  1159. except OperationalError:
  1160. pass # Already applied
  1161. try:
  1162. await conn.execute(text("ALTER TABLE spool ADD COLUMN last_weighed_at DATETIME"))
  1163. except OperationalError:
  1164. pass # Already applied
  1165. # Migration: Add cost tracking fields to spool table
  1166. try:
  1167. await conn.execute(text("ALTER TABLE spool ADD COLUMN cost_per_kg REAL"))
  1168. except OperationalError:
  1169. pass # Already applied
  1170. # Migration: Add cost field to spool_usage_history table
  1171. try:
  1172. await conn.execute(text("ALTER TABLE spool_usage_history ADD COLUMN cost REAL"))
  1173. except OperationalError:
  1174. pass # Already applied
  1175. # Migration: Add archive_id field to spool_usage_history table
  1176. try:
  1177. await conn.execute(
  1178. text("ALTER TABLE spool_usage_history ADD COLUMN archive_id INTEGER REFERENCES print_archives(id)")
  1179. )
  1180. except OperationalError:
  1181. pass # Already applied
  1182. # Migration: Migrate single virtual printer key-value settings to virtual_printers table
  1183. try:
  1184. # Check if virtual_printers table has any rows
  1185. result = await conn.execute(text("SELECT COUNT(*) FROM virtual_printers"))
  1186. count = result.scalar() or 0
  1187. if count == 0:
  1188. # Check if old key-value settings exist
  1189. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_enabled'"))
  1190. row = result.fetchone()
  1191. if row:
  1192. # Old settings exist — migrate to first virtual printer row
  1193. old_enabled = row[0] == "true" if row[0] else False
  1194. result = await conn.execute(
  1195. text("SELECT value FROM settings WHERE key = 'virtual_printer_access_code'")
  1196. )
  1197. row = result.fetchone()
  1198. old_access_code = row[0] if row else None
  1199. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_mode'"))
  1200. row = result.fetchone()
  1201. old_mode = row[0] if row else "immediate"
  1202. if old_mode == "queue":
  1203. old_mode = "review"
  1204. result = await conn.execute(text("SELECT value FROM settings WHERE key = 'virtual_printer_model'"))
  1205. row = result.fetchone()
  1206. old_model = row[0] if row else "BL-P001"
  1207. result = await conn.execute(
  1208. text("SELECT value FROM settings WHERE key = 'virtual_printer_target_printer_id'")
  1209. )
  1210. row = result.fetchone()
  1211. old_target_id = int(row[0]) if row and row[0] else None
  1212. result = await conn.execute(
  1213. text("SELECT value FROM settings WHERE key = 'virtual_printer_remote_interface_ip'")
  1214. )
  1215. row = result.fetchone()
  1216. old_remote_iface = row[0] if row else None
  1217. await conn.execute(
  1218. text("""
  1219. INSERT INTO virtual_printers
  1220. (name, enabled, mode, model, access_code, target_printer_id,
  1221. bind_ip, remote_interface_ip, serial_suffix, position)
  1222. VALUES
  1223. (:name, :enabled, :mode, :model, :access_code, :target_id,
  1224. NULL, :remote_iface, '391800001', 0)
  1225. """),
  1226. {
  1227. "name": "Bambuddy",
  1228. "enabled": old_enabled,
  1229. "mode": old_mode or "immediate",
  1230. "model": old_model,
  1231. "access_code": old_access_code,
  1232. "target_id": old_target_id,
  1233. "remote_iface": old_remote_iface,
  1234. },
  1235. )
  1236. except OperationalError:
  1237. pass # Table may not exist yet on first run
  1238. # Migration: Add filament_overrides column to print_queue for filament override in model-based assignment
  1239. try:
  1240. await conn.execute(text("ALTER TABLE print_queue ADD COLUMN filament_overrides TEXT"))
  1241. except OperationalError:
  1242. pass # Already applied
  1243. # Migration: Add NFC reader and display control columns to spoolbuddy_devices
  1244. try:
  1245. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_reader_type VARCHAR(20)"))
  1246. except OperationalError:
  1247. pass # Already applied
  1248. try:
  1249. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN nfc_connection VARCHAR(20)"))
  1250. except OperationalError:
  1251. pass # Already applied
  1252. try:
  1253. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN display_brightness INTEGER DEFAULT 100"))
  1254. except OperationalError:
  1255. pass # Already applied
  1256. try:
  1257. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN display_blank_timeout INTEGER DEFAULT 0"))
  1258. except OperationalError:
  1259. pass # Already applied
  1260. try:
  1261. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN has_backlight BOOLEAN DEFAULT 0"))
  1262. except OperationalError:
  1263. pass # Already applied
  1264. try:
  1265. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN last_calibrated_at DATETIME"))
  1266. except OperationalError:
  1267. pass # Already applied
  1268. # Migration: Add NFC tag write payload column to spoolbuddy_devices
  1269. try:
  1270. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN pending_write_payload TEXT"))
  1271. except OperationalError:
  1272. pass # Already applied
  1273. # Migration: Add OTA update tracking columns to spoolbuddy_devices
  1274. try:
  1275. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN update_status VARCHAR(20)"))
  1276. except OperationalError:
  1277. pass # Already applied
  1278. try:
  1279. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN update_message VARCHAR(255)"))
  1280. except OperationalError:
  1281. pass # Already applied
  1282. # Migration: Persist SpoolBuddy backend URL and queued system payload
  1283. try:
  1284. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN backend_url VARCHAR(255)"))
  1285. except OperationalError:
  1286. pass # Already applied
  1287. try:
  1288. await conn.execute(text("ALTER TABLE spoolbuddy_devices ADD COLUMN pending_system_payload TEXT"))
  1289. except OperationalError:
  1290. pass # Already applied
  1291. # Migration: Convert ams_labels table from (printer_id, ams_id) key to ams_serial_number key
  1292. # Labels are now keyed by AMS serial number so they persist when the AMS is moved to another printer.
  1293. try:
  1294. await conn.execute(text("DROP TABLE IF EXISTS ams_labels_new"))
  1295. result = await conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='ams_labels'"))
  1296. row = result.fetchone()
  1297. if row and "printer_id" in (row[0] or ""):
  1298. # Old schema: rebuild the table with ams_serial_number as the unique key.
  1299. # Existing rows get a synthetic serial "p{printer_id}a{ams_id}" so data is preserved.
  1300. await conn.execute(
  1301. text("""
  1302. CREATE TABLE ams_labels_new (
  1303. id INTEGER PRIMARY KEY,
  1304. ams_serial_number VARCHAR(50) NOT NULL,
  1305. ams_id INTEGER,
  1306. label VARCHAR(100) NOT NULL,
  1307. created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1308. updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  1309. CONSTRAINT uq_ams_label_serial UNIQUE (ams_serial_number)
  1310. )
  1311. """)
  1312. )
  1313. await conn.execute(
  1314. text("""
  1315. INSERT INTO ams_labels_new (id, ams_serial_number, ams_id, label, created_at, updated_at)
  1316. SELECT id,
  1317. 'p' || CAST(printer_id AS TEXT) || 'a' || CAST(ams_id AS TEXT),
  1318. ams_id,
  1319. label,
  1320. created_at,
  1321. updated_at
  1322. FROM ams_labels
  1323. """)
  1324. )
  1325. await conn.execute(text("DROP TABLE ams_labels"))
  1326. await conn.execute(text("ALTER TABLE ams_labels_new RENAME TO ams_labels"))
  1327. except OperationalError:
  1328. pass # Already migrated or table does not exist yet
  1329. # Migration: Add auto_dispatch column to virtual_printers
  1330. try:
  1331. await conn.execute(text("ALTER TABLE virtual_printers ADD COLUMN auto_dispatch BOOLEAN DEFAULT 1"))
  1332. except OperationalError:
  1333. pass # Already applied
  1334. # Migration: Fix VP model codes — convert legacy SSDP codes and display names to correct SSDP codes
  1335. # Legacy codes (from multi-VP refactor) and display names (from proxy auto-inherit)
  1336. vp_model_fixes = {
  1337. "3DPrinter-X1-Carbon": "BL-P001",
  1338. "3DPrinter-X1": "BL-P002",
  1339. "X1C": "BL-P001",
  1340. "X1": "BL-P002",
  1341. "X1E": "C13",
  1342. "P1P": "C11",
  1343. "P1S": "C12",
  1344. "P2S": "N7",
  1345. "A1": "N2S",
  1346. "A1 Mini": "N1",
  1347. "H2D": "O1D",
  1348. "H2C": "O1C",
  1349. "H2S": "O1S",
  1350. }
  1351. for old_val, new_val in vp_model_fixes.items():
  1352. await conn.execute(
  1353. text("UPDATE virtual_printers SET model = :new WHERE model = :old"),
  1354. {"old": old_val, "new": new_val},
  1355. )
  1356. await conn.execute(
  1357. text("UPDATE settings SET value = :new WHERE key = 'virtual_printer_model' AND value = :old"),
  1358. {"old": old_val, "new": new_val},
  1359. )
  1360. # Migration: Add per-user Bambu Cloud credential columns
  1361. try:
  1362. await conn.execute(text("ALTER TABLE users ADD COLUMN cloud_token VARCHAR(500)"))
  1363. except OperationalError:
  1364. pass # Already applied
  1365. try:
  1366. await conn.execute(text("ALTER TABLE users ADD COLUMN cloud_email VARCHAR(255)"))
  1367. except OperationalError:
  1368. pass # Already applied
  1369. # Cleanup: Remove obsolete settings keys that are no longer used
  1370. obsolete_keys = ["slicer_binary_path"]
  1371. for key in obsolete_keys:
  1372. await conn.execute(text("DELETE FROM settings WHERE key = :key"), {"key": key})
  1373. # Migration: Create user_email_preferences table for user-specific email notification settings
  1374. try:
  1375. await conn.execute(
  1376. text("""
  1377. CREATE TABLE IF NOT EXISTS user_email_preferences (
  1378. id INTEGER PRIMARY KEY,
  1379. user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
  1380. notify_print_start BOOLEAN NOT NULL DEFAULT 1,
  1381. notify_print_complete BOOLEAN NOT NULL DEFAULT 1,
  1382. notify_print_failed BOOLEAN NOT NULL DEFAULT 1,
  1383. notify_print_stopped BOOLEAN NOT NULL DEFAULT 1,
  1384. created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  1385. updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  1386. )
  1387. """)
  1388. )
  1389. await conn.execute(
  1390. text("CREATE INDEX IF NOT EXISTS ix_user_email_preferences_user_id ON user_email_preferences(user_id)")
  1391. )
  1392. except OperationalError:
  1393. pass # Already applied
  1394. # Legacy migration: Add notify_print_stopped column (for any existing partial tables)
  1395. try:
  1396. await conn.execute(
  1397. text("ALTER TABLE user_email_preferences ADD COLUMN notify_print_stopped BOOLEAN NOT NULL DEFAULT 1")
  1398. )
  1399. except OperationalError:
  1400. pass # Column already exists or table created with full schema
  1401. # Migration: Add camera_rotation column to printers
  1402. try:
  1403. await conn.execute(text("ALTER TABLE printers ADD COLUMN camera_rotation INTEGER DEFAULT 0"))
  1404. except OperationalError:
  1405. pass # Already applied
  1406. # Seed default settings keys that must exist on fresh install
  1407. default_settings = [
  1408. ("advanced_auth_enabled", "false"),
  1409. ("smtp_auth_enabled", "true"),
  1410. ]
  1411. for key, value in default_settings:
  1412. try:
  1413. await conn.execute(
  1414. text("INSERT OR IGNORE INTO settings (key, value) VALUES (:key, :value)"),
  1415. {"key": key, "value": value},
  1416. )
  1417. except OperationalError:
  1418. pass
  1419. async def seed_notification_templates():
  1420. """Seed default notification templates if they don't exist."""
  1421. from sqlalchemy import select
  1422. from backend.app.models.notification_template import DEFAULT_TEMPLATES, NotificationTemplate
  1423. async with async_session() as session:
  1424. # Get existing template event types
  1425. result = await session.execute(select(NotificationTemplate.event_type))
  1426. existing_types = {row[0] for row in result.fetchall()}
  1427. if not existing_types:
  1428. # No templates exist - insert all defaults
  1429. for template_data in DEFAULT_TEMPLATES:
  1430. template = NotificationTemplate(
  1431. event_type=template_data["event_type"],
  1432. name=template_data["name"],
  1433. title_template=template_data["title_template"],
  1434. body_template=template_data["body_template"],
  1435. is_default=True,
  1436. )
  1437. session.add(template)
  1438. else:
  1439. # Templates exist - only add missing ones
  1440. for template_data in DEFAULT_TEMPLATES:
  1441. if template_data["event_type"] not in existing_types:
  1442. template = NotificationTemplate(
  1443. event_type=template_data["event_type"],
  1444. name=template_data["name"],
  1445. title_template=template_data["title_template"],
  1446. body_template=template_data["body_template"],
  1447. is_default=True,
  1448. )
  1449. session.add(template)
  1450. await session.commit()
  1451. async def seed_default_groups():
  1452. """Seed default groups and migrate existing users to appropriate groups.
  1453. Creates the default system groups (Administrators, Operators, Viewers) if they
  1454. don't exist, then migrates existing users:
  1455. - Users with role='admin' -> Administrators group
  1456. - Users with role='user' -> Operators group
  1457. Also migrates old permissions to new ownership-based permissions (Issue #205).
  1458. """
  1459. import logging
  1460. from sqlalchemy import select
  1461. from backend.app.core.permissions import DEFAULT_GROUPS
  1462. from backend.app.models.group import Group
  1463. from backend.app.models.user import User
  1464. logger = logging.getLogger(__name__)
  1465. # Map old permissions to new ones for migration
  1466. # Administrators get *_all permissions, Operators get *_own permissions
  1467. PERMISSION_MIGRATION_ALL = {
  1468. "queue:update": "queue:update_all",
  1469. "queue:delete": "queue:delete_all",
  1470. "archives:update": "archives:update_all",
  1471. "archives:delete": "archives:delete_all",
  1472. "archives:reprint": "archives:reprint_all",
  1473. "library:update": "library:update_all",
  1474. "library:delete": "library:delete_all",
  1475. }
  1476. PERMISSION_MIGRATION_OWN = {
  1477. "queue:update": "queue:update_own",
  1478. "queue:delete": "queue:delete_own",
  1479. "archives:update": "archives:update_own",
  1480. "archives:delete": "archives:delete_own",
  1481. "archives:reprint": "archives:reprint_own",
  1482. "library:update": "library:update_own",
  1483. "library:delete": "library:delete_own",
  1484. }
  1485. async with async_session() as session:
  1486. # Get existing groups
  1487. result = await session.execute(select(Group))
  1488. existing_groups = {group.name: group for group in result.scalars().all()}
  1489. # Create default groups if they don't exist
  1490. groups_created = []
  1491. for group_name, group_config in DEFAULT_GROUPS.items():
  1492. if group_name not in existing_groups:
  1493. group = Group(
  1494. name=group_name,
  1495. description=group_config["description"],
  1496. permissions=group_config["permissions"],
  1497. is_system=group_config["is_system"],
  1498. )
  1499. session.add(group)
  1500. groups_created.append(group_name)
  1501. logger.info("Created default group: %s", group_name)
  1502. else:
  1503. # Migrate existing group's permissions from old to new format
  1504. group = existing_groups[group_name]
  1505. if group.permissions:
  1506. updated = False
  1507. new_permissions = list(group.permissions)
  1508. # Determine which migration map to use based on group
  1509. migration_map = (
  1510. PERMISSION_MIGRATION_ALL if group_name == "Administrators" else PERMISSION_MIGRATION_OWN
  1511. )
  1512. for old_perm, new_perm in migration_map.items():
  1513. if old_perm in new_permissions:
  1514. new_permissions.remove(old_perm)
  1515. if new_perm not in new_permissions:
  1516. new_permissions.append(new_perm)
  1517. updated = True
  1518. logger.info(
  1519. "Migrated permission '%s' to '%s' in group '%s'", old_perm, new_perm, group_name
  1520. )
  1521. # For Administrators, also ensure they get *_all permissions if they have any new *_own
  1522. if group_name == "Administrators":
  1523. for _own_perm, all_perm in [
  1524. ("queue:update_own", "queue:update_all"),
  1525. ("queue:delete_own", "queue:delete_all"),
  1526. ("archives:update_own", "archives:update_all"),
  1527. ("archives:delete_own", "archives:delete_all"),
  1528. ("archives:reprint_own", "archives:reprint_all"),
  1529. ("library:update_own", "library:update_all"),
  1530. ("library:delete_own", "library:delete_all"),
  1531. ]:
  1532. # Add *_all if not present
  1533. if all_perm not in new_permissions:
  1534. new_permissions.append(all_perm)
  1535. updated = True
  1536. if updated:
  1537. group.permissions = new_permissions
  1538. await session.commit()
  1539. # Migrate new permissions: grant printers:clear_plate to all groups with printers:control
  1540. result = await session.execute(select(Group))
  1541. all_groups = result.scalars().all()
  1542. for group in all_groups:
  1543. if (
  1544. group.permissions
  1545. and "printers:control" in group.permissions
  1546. and "printers:clear_plate" not in group.permissions
  1547. ):
  1548. group.permissions = [*group.permissions, "printers:clear_plate"]
  1549. logger.info("Added printers:clear_plate to group '%s' (has printers:control)", group.name)
  1550. await session.commit()
  1551. # Migrate existing users to groups if they're not already in any group
  1552. if groups_created:
  1553. # Refresh to get newly created groups
  1554. admin_result = await session.execute(select(Group).where(Group.name == "Administrators"))
  1555. admin_group = admin_result.scalar_one_or_none()
  1556. operators_result = await session.execute(select(Group).where(Group.name == "Operators"))
  1557. operators_group = operators_result.scalar_one_or_none()
  1558. # Get all users
  1559. users_result = await session.execute(select(User))
  1560. users = users_result.scalars().all()
  1561. for user in users:
  1562. # Skip if user already has groups
  1563. if user.groups:
  1564. continue
  1565. if user.role == "admin" and admin_group:
  1566. user.groups.append(admin_group)
  1567. logger.info("Migrated admin user '%s' to Administrators group", user.username)
  1568. elif operators_group:
  1569. user.groups.append(operators_group)
  1570. logger.info("Migrated user '%s' to Operators group", user.username)
  1571. await session.commit()
  1572. async def seed_spool_catalog():
  1573. """Seed the spool catalog with default entries if empty."""
  1574. import logging
  1575. from sqlalchemy import func, select
  1576. from backend.app.core.catalog_defaults import DEFAULT_SPOOL_CATALOG
  1577. from backend.app.models.spool_catalog import SpoolCatalogEntry
  1578. logger = logging.getLogger(__name__)
  1579. async with async_session() as session:
  1580. result = await session.execute(select(func.count()).select_from(SpoolCatalogEntry))
  1581. count = result.scalar() or 0
  1582. if count > 0:
  1583. return # Already seeded
  1584. for name, weight in DEFAULT_SPOOL_CATALOG:
  1585. session.add(SpoolCatalogEntry(name=name, weight=weight, is_default=True))
  1586. await session.commit()
  1587. logger.info("Seeded %d default spool catalog entries", len(DEFAULT_SPOOL_CATALOG))
  1588. async def seed_color_catalog():
  1589. """Seed the color catalog with default entries if empty."""
  1590. import logging
  1591. from sqlalchemy import func, select
  1592. from backend.app.core.catalog_defaults import DEFAULT_COLOR_CATALOG
  1593. from backend.app.models.color_catalog import ColorCatalogEntry
  1594. logger = logging.getLogger(__name__)
  1595. async with async_session() as session:
  1596. result = await session.execute(select(func.count()).select_from(ColorCatalogEntry))
  1597. count = result.scalar() or 0
  1598. if count > 0:
  1599. return # Already seeded
  1600. for manufacturer, color_name, hex_color, material in DEFAULT_COLOR_CATALOG:
  1601. session.add(
  1602. ColorCatalogEntry(
  1603. manufacturer=manufacturer,
  1604. color_name=color_name,
  1605. hex_color=hex_color,
  1606. material=material,
  1607. is_default=True,
  1608. )
  1609. )
  1610. await session.commit()
  1611. logger.info("Seeded %d default color catalog entries", len(DEFAULT_COLOR_CATALOG))