database.py 71 KB

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