From a0f05791f8faffc976bb27147fd3bc41c2dff9fc Mon Sep 17 00:00:00 2001 From: Jocadbz Date: Wed, 3 Jun 2026 23:11:15 -0300 Subject: [PATCH] Initial commit: Go + HTMX network mapping tool - Database schema (SQLite) with migrations - Data models: racks, devices, device models, ports, connections - CRUD store layer in internal/db/ - Connection tracing service - HTTP handlers for overview, rack, device, model, connection, wall sockets - HTML templates with HTMX for connection modal - Dark-themed CSS - Vanilla JS for modal overlay management --- .gitignore | 4 + data.db-shm | Bin 0 -> 32768 bytes data.db-wal | Bin 0 -> 164832 bytes go.mod | 5 + go.sum | 2 + internal/db/connections.go | 192 +++++++++++++++++++++ internal/db/db.go | 41 +++++ internal/db/device_models.go | 159 ++++++++++++++++++ internal/db/devices.go | 170 +++++++++++++++++++ internal/db/ports.go | 74 +++++++++ internal/db/racks.go | 70 ++++++++ internal/db/schema.sql | 94 +++++++++++ internal/handlers/connections.go | 221 ++++++++++++++++++++++++ internal/handlers/devices.go | 141 ++++++++++++++++ internal/handlers/handlers.go | 95 +++++++++++ internal/handlers/models.go | 199 ++++++++++++++++++++++ internal/handlers/overview.go | 98 +++++++++++ internal/handlers/racks.go | 268 ++++++++++++++++++++++++++++++ internal/handlers/wall_sockets.go | 73 ++++++++ internal/models/models.go | 84 ++++++++++ internal/services/connection.go | 220 ++++++++++++++++++++++++ main.go | 61 +++++++ static/js/app.js | 24 +++ static/js/htmx.min.js | 1 + static/style.css | 185 +++++++++++++++++++++ templates/base.html | 27 +++ templates/connection_modal.html | 94 +++++++++++ templates/device.html | 66 ++++++++ templates/model_form.html | 58 +++++++ templates/model_list.html | 30 ++++ templates/overview.html | 74 +++++++++ templates/rack.html | 148 +++++++++++++++++ templates/wall_sockets.html | 51 ++++++ uploads/.gitkeep | 0 34 files changed, 3029 insertions(+) create mode 100644 .gitignore create mode 100644 data.db-shm create mode 100644 data.db-wal create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/db/connections.go create mode 100644 internal/db/db.go create mode 100644 internal/db/device_models.go create mode 100644 internal/db/devices.go create mode 100644 internal/db/ports.go create mode 100644 internal/db/racks.go create mode 100644 internal/db/schema.sql create mode 100644 internal/handlers/connections.go create mode 100644 internal/handlers/devices.go create mode 100644 internal/handlers/handlers.go create mode 100644 internal/handlers/models.go create mode 100644 internal/handlers/overview.go create mode 100644 internal/handlers/racks.go create mode 100644 internal/handlers/wall_sockets.go create mode 100644 internal/models/models.go create mode 100644 internal/services/connection.go create mode 100644 main.go create mode 100644 static/js/app.js create mode 100644 static/js/htmx.min.js create mode 100644 static/style.css create mode 100644 templates/base.html create mode 100644 templates/connection_modal.html create mode 100644 templates/device.html create mode 100644 templates/model_form.html create mode 100644 templates/model_list.html create mode 100644 templates/overview.html create mode 100644 templates/rack.html create mode 100644 templates/wall_sockets.html create mode 100644 uploads/.gitkeep diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6bca722 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/wireplanner +/data.db +/uploads/* +!.gitkeep diff --git a/data.db-shm b/data.db-shm new file mode 100644 index 0000000000000000000000000000000000000000..4ecdfa489742f8199b07aa1d262c0883bf20f440 GIT binary patch literal 32768 zcmeI*J4!=Q5XSK@QFBdV%u~I-H9i|#D_ge{MEonz|*Tf?WftJ_xh?zuR>e|@+<8(rL-UcNt$%0K?z zj`}J;_v1&!>+fcFt7^;pjICK)bMah@URa-xecgH^_RZ)E)?2Y(jNXpki5@xCi|2lH z&+PY&&+u>Y=kcAkr4T>>0R#|0009ILKmY**5I_I{1Q0*~0R#|0009ILKmY**5I_I{ z1Q0*~0R#|0009ILKmY**5I_I{1Q0*~0R#|0009ILKmY**5I_I{1ST#}u~`#^>NfSE zZ4)pCT2`qwZD>n76TgcC5tuH4st%^>gZLT*{!PFq3{eQ=6!6(r6aqN~Y8vV=XLM4h z7w{R16aqN~8am1uoYV-YDWAkkA&^nPr$bW+MX8AgzFaKw5#-w8;sMz&Zp7q!rjqo1EYXY(s!RT7liP$q9}C0>2gb E1Ur+I@cC-}iU@?cpD2<#5f;faX!m#>|@ z^?lj?_%q|Rlk;R2=beAgE9y=E^2S47%6&MknW}I?uT>ONI7nItgMpg_fvg*}e`zy1 z(DpmnnDvKk&ojN;XfSZi{ZDj}C0ydO0rGvEp(d7@v>?ZN@_)sPpdUU)2sfe;AmD7^OBGkN79nuUnca$1v1#}go#XE`hb)b zj$|h$#q2TRuyib*BD-YI`A&bqnDkt{KlAJB=rgujYF^rBied=nwx_I!)%2(DIKE_f@5)A^~13~4XG|6Y3?Uz*TWXY84Rn0Vej>A9rQkA++r;(9!uR*I$5)VgLaU009sH0T2KI5CDP8o4}cLM}!|5;?9n;>~C-0 zu{^8SOkWPWH7DFOk=m@v-gS*Wt(X#~GQyaYmWVm} zsF)iS$Ly@|r77}O`nI7J8&l^;KPZhJ?qdrkGD2UHC9x;_g(OW@ck{kybwe|WF}suS zzBFNcFrI?H0Q?1r7eD+3TGu0>&-h_SFYu=ieB|M0zVP;&pclBjzm9PBAOHd&00JNY z0w4eaAOHd&00Nf{0iRyrmXCk#D+AZ$l@@vd=8k9+qFRBr^#YODIgef-cCPc*%Z58n z6a+v31V8`;KmY{VB=Cu$aD?Z1?vo-5C{uHBgZ+v4!p3aYnj^(agStN7bLM1j-Zr~@ zfOl~zi}F@gb55_#&^WK5)=2eiH_}^FXU$TBZ@LvDwwAEwMu~Wi6I*c7yr`_wW7%6N@@_9jDITVyZHN;+1~lw72 zM-Ypo8}bMu>DXVic_wHE0w4eaAOHfJh``zYXoTO4l*!IL z$L=vRW0L9y6SJI@7c$f7w6$N>xL(yv*)Wxw>4+me3m5&&ELk#Z(aOtgBShu{u`n<8 zHWQiK?+|&&9*HB5Ks#A7W%}A1&dZKG0+HDK<;9V-DC8E9{H~`$RpT9H!3m00ck)1V8`;KmY_l00cl_6A|#`5qy5{ z{uf@XeD={6c?6xFYFuXv~{e&fbJIvyn$&CmA4*zlA zK(a$@4|>!iKs^HIz0fM>XI3{fmZdb2$x9!QvP*^VgYgvd2#`l02*O6>haC!q`N`zU z`C)QJFREq3$r7_C>C-i<09fK8d@98)bh0}yf0Y6M)J3RAK%enD9lgM}|NVudC*OJS ze&i8sw%c(W4+ww&2!H?xfB*=900@8p2!H?xtP263ULg02XTJAOx9=>r&aQ9edwB+$i-9d-x=m}1I@av8}}>^HO}dRUSP&8p1!IW74!no3*@Ez#H6$| zgbBR>iQZYN0On)q3MwpfNazKi7l2-1IzKg$AvXwrZ;>6nz}1ZWpPm(wqB^r>Ax6>=ZD5x#?) z;mEkwF zm5p$jK^}qcE$)5A*PIn$H-_)vG2yUuOc0mqN^L^SwW!r4z`L&J^WQ?6S~o~ZYPm=< zU~1Ydv-e`U??zc_L9bNQs=0jaYWNN=k@F&t0C@zb%9^RlO5N18YEhkM_2h~57%eMr zM3F~;Jc6ay`xX~#Tx3(K`N4VAU2H*{t zY_Z2t94-ie00@8p2!H?xfB*=900@8p2((AQrx*BdL7czuY!(2Cx<2|LI+kr|VY3eDRH zQyJoxw79iCdqOLwpcjaf5Rl+R`k@zSkd4515PAV}6*8mGbyvT|U(a5XJ%A7HcgJo&AICCN+^d(Q!^s1Tc7m~-x%C4{EM#Pm+rx0}tXP_6z zF9v+A4=m~w!gnw&I07|K@Sj*G&MD=xZ0Lm<)f7girqUAh0$GWeA_{qNBrOU48iw}$ z*J-t85Fc#kt5P_UotPA}Op+K+kw-52jGu7y0+EN`@xI5d>NDXl(B8u+T7duvfB*=9 z00@8p2!H?xfB*=9z!oFm(+g;Sm3#5ypV?n+p%>WgIY-)s(6(M65xjOqy#QH^Ve=DM z=uSlV!$aJ{!N%ac6~bbf4$G#$G&` z{qPsKL{(|vFR)A?+>+`*F95y3(Yzb^aVlo90KUgV!gJMPsn#nRk+8<~ss_CP%}Qsy zBEAnGo3-XoUW+_tMxEAOZ77E3QDm^COp#Gl%{jd`Lp2$OS|iaaSCxS}h42?3_bHaR zXHnPVnsGocfI5ZFy)5(sDQ=;YX;A$t0RL3bck%ZxTcuurKI89p^a4*LKX}!F-7oBb zUSRV-jN=GF00ck)1V8`;KmY_l00ck)1VG>-5b)^*qJKF2+Yf#9o?BYz1-d=^?Ih!E z>jidm|I%nEqn37KPb}FDC3%9%_VueFtUM~_M#VAPhIncC z^HRj9&h|$md~Yvz*R`yh-#$+JKllqkFJNjFwJ%xKtt$uo1>i3Le*q#Waxe1G3qUUb zy#RRzEO8M&b*c0M^cla~(F^>CF!t=dU(H?ty}-qI6vs9|00ck)1V8`;KmY_l00ck) z1VCWZ6Y%K;zS#ZCN1lA`?@qVS3+(Zn)lM?rwqBr{JJC`vKvvnN!%TOCKeV4)h`2HQ z#r$uBCF9CNo;iD#gz`NL?bT^C-!r$*^@UGCFJQ+VEwclA!qG`ssn4iKz%oUxC~8?b zu9oFt&zyo@)@u#9q)x(Da{qe=>A$4a*nQu*ey2-9yB6|>_-;+~!FURK0sERz)(eVBEs$AR0QbUSFSWI2%YD*Wa{P)H3f36@0%etBJl+Gn0DT=WfB*=900@8p2!H?x zfB*=900@A$}TeAwqBqoaNp|m0{5vs5&pVfZ!W&o zr((!X#d>>s?~)LH{JoA|;9tN0#*goL^}?5-7x46aU=##E00ck)1V8`;KmY_l z00ck)1hy}M4ti=%zre%VLnpaAj&@Mf050)jfc#(p0T2KI5C8!X009sH0T2KI5C8!X z*zyGSa-jjP(RPfw8PGa|Zok0uuipO3r;{T$(SCtw;%kA#uM^KDo=!ZO_)g**iN7Z^ zFn|CEfB*=900@8p2!H?xfB*=900>-q0^w*V&@-JIiA6$zeTG`olyWp23h+w3sOixT zGIm-ks(N$>8JpGT)LJ-18sx-WA{YuB7}t*1)X|bst*YftE)=*zGD~W$s+#0PXcvH+ zN5Eeg`pQ52=CPwRk06>j7fAdj@sq?eiF1i>Ccc;Wdg9+M{fT3bAOHd&00JNY0w4ea zAOHd&00JNY0)apz)WeZ}foMFmkF)v(BC!z9v3`Lt9b^3h9dwNK3+$i`NWVa6cjy4; z?H34khOUTt`UQf7uG=qg;2-nm^JjuVE05syK;m_<2LTWO0T2KI5C8!X009sH0T2KI z5ZI0cf*kD<2>AR3&VNMxpFNaOP>1&MB)}Or`KkTl2R_~bMG1+9DdKhAo+Q> zFgSd}(BKURuU}>sfkeFr-8_Pi{{H@V+}7PSNBsr3#H#`Fg8>9U00ck)1V8`;KmY_l V00ck)1VCV05r~EM#jMVR{|9sXgSY?y literal 0 HcmV?d00001 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..d16aafe --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module lostcavewireplanner + +go 1.26.3 + +require github.com/mattn/go-sqlite3 v1.14.44 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..cf1e561 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8= +github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= diff --git a/internal/db/connections.go b/internal/db/connections.go new file mode 100644 index 0000000..9a0fa29 --- /dev/null +++ b/internal/db/connections.go @@ -0,0 +1,192 @@ +package db + +import ( + "database/sql" + "fmt" + "lostcavewireplanner/internal/models" +) + +func (s *Store) ConnectionTypeGetAll() ([]models.ConnectionType, error) { + rows, err := s.DB.Query(`SELECT id, name FROM connection_types ORDER BY id`) + if err != nil { + return nil, err + } + defer rows.Close() + + var types []models.ConnectionType + for rows.Next() { + var ct models.ConnectionType + if err := rows.Scan(&ct.ID, &ct.Name); err != nil { + return nil, err + } + types = append(types, ct) + } + return types, rows.Err() +} + +func (s *Store) ConnectionGetByPortID(portID int64) (*models.Connection, error) { + c := &models.Connection{} + err := s.DB.QueryRow(`SELECT id, connection_type_id, label_1, label_2, color, port_id_1, port_id_2, created_at, updated_at FROM connections WHERE port_id_1 = ? OR port_id_2 = ?`, portID, portID). + Scan(&c.ID, &c.ConnectionTypeID, &c.Label1, &c.Label2, &c.Color, &c.PortID1, &c.PortID2, &c.CreatedAt, &c.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + s.populateConnection(c) + return c, nil +} + +func (s *Store) ConnectionGetByPortIDExcluding(portID int64, excludeConnID int64) (*models.Connection, error) { + c := &models.Connection{} + err := s.DB.QueryRow(`SELECT id, connection_type_id, label_1, label_2, color, port_id_1, port_id_2, created_at, updated_at FROM connections WHERE (port_id_1 = ? OR port_id_2 = ?) AND id != ?`, portID, portID, excludeConnID). + Scan(&c.ID, &c.ConnectionTypeID, &c.Label1, &c.Label2, &c.Color, &c.PortID1, &c.PortID2, &c.CreatedAt, &c.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + s.populateConnection(c) + return c, nil +} + +func (s *Store) ConnectionGetByID(id int64) (*models.Connection, error) { + c := &models.Connection{} + err := s.DB.QueryRow(`SELECT id, connection_type_id, label_1, label_2, color, port_id_1, port_id_2, created_at, updated_at FROM connections WHERE id = ?`, id). + Scan(&c.ID, &c.ConnectionTypeID, &c.Label1, &c.Label2, &c.Color, &c.PortID1, &c.PortID2, &c.CreatedAt, &c.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + s.populateConnection(c) + return c, nil +} + +func (s *Store) ConnectionGetAllForRack(rackID int64) ([]models.Connection, error) { + rows, err := s.DB.Query(` + SELECT c.id, c.connection_type_id, c.label_1, c.label_2, c.color, c.port_id_1, c.port_id_2, c.created_at, c.updated_at + FROM connections c + WHERE (port_id_1 IN (SELECT dp.id FROM device_ports dp JOIN devices d ON d.id = dp.device_id WHERE d.rack_id = ?)) + OR (port_id_2 IN (SELECT dp.id FROM device_ports dp JOIN devices d ON d.id = dp.device_id WHERE d.rack_id = ?))`, rackID, rackID) + if err != nil { + return nil, err + } + defer rows.Close() + + var conns []models.Connection + for rows.Next() { + var c models.Connection + if err := rows.Scan(&c.ID, &c.ConnectionTypeID, &c.Label1, &c.Label2, &c.Color, &c.PortID1, &c.PortID2, &c.CreatedAt, &c.UpdatedAt); err != nil { + return nil, err + } + s.populateConnection(&c) + conns = append(conns, c) + } + return conns, rows.Err() +} + +func (s *Store) ConnectionGetAll() ([]models.Connection, error) { + rows, err := s.DB.Query(`SELECT id, connection_type_id, label_1, label_2, color, port_id_1, port_id_2, created_at, updated_at FROM connections`) + if err != nil { + return nil, err + } + defer rows.Close() + + var conns []models.Connection + for rows.Next() { + var c models.Connection + if err := rows.Scan(&c.ID, &c.ConnectionTypeID, &c.Label1, &c.Label2, &c.Color, &c.PortID1, &c.PortID2, &c.CreatedAt, &c.UpdatedAt); err != nil { + return nil, err + } + conns = append(conns, c) + } + return conns, rows.Err() +} + +func (s *Store) ConnectionCreate(c *models.Connection) error { + tx, err := s.DB.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + if c.PortID1 != nil { + exists, err := s.portConnectedTx(tx, *c.PortID1) + if err != nil { + return err + } + if exists { + return fmt.Errorf("port %d is already connected", *c.PortID1) + } + } + if c.PortID2 != nil { + exists, err := s.portConnectedTx(tx, *c.PortID2) + if err != nil { + return err + } + if exists { + return fmt.Errorf("port %d is already connected", *c.PortID2) + } + } + + res, err := tx.Exec(`INSERT INTO connections (connection_type_id, label_1, label_2, color, port_id_1, port_id_2) VALUES (?, ?, ?, ?, ?, ?)`, + c.ConnectionTypeID, c.Label1, c.Label2, c.Color, c.PortID1, c.PortID2) + if err != nil { + return err + } + c.ID, err = res.LastInsertId() + if err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) ConnectionUpdate(c *models.Connection) error { + _, err := s.DB.Exec(`UPDATE connections SET connection_type_id=?, label_1=?, label_2=?, color=?, port_id_1=?, port_id_2=?, updated_at=datetime('now') WHERE id=?`, + c.ConnectionTypeID, c.Label1, c.Label2, c.Color, c.PortID1, c.PortID2, c.ID) + return err +} + +func (s *Store) ConnectionDelete(id int64) error { + _, err := s.DB.Exec(`DELETE FROM connections WHERE id=?`, id) + return err +} + +func (s *Store) portConnectedTx(tx *sql.Tx, portID int64) (bool, error) { + var count int + err := tx.QueryRow(`SELECT COUNT(*) FROM connections WHERE port_id_1 = ? OR port_id_2 = ?`, portID, portID).Scan(&count) + return count > 0, err +} + +func (s *Store) populateConnection(c *models.Connection) { + if c.PortID1 != nil { + c.Port1, _ = s.PortGetByID(*c.PortID1) + if c.Port1 != nil { + c.Device1, _ = s.DeviceGetByID(c.Port1.DeviceID) + } + } + if c.PortID2 != nil { + c.Port2, _ = s.PortGetByID(*c.PortID2) + if c.Port2 != nil { + c.Device2, _ = s.DeviceGetByID(c.Port2.DeviceID) + } + } + ct, _ := s.ConnectionTypeGetByID(c.ConnectionTypeID) + c.ConnectionType = ct +} + +func (s *Store) ConnectionTypeGetByID(id int64) (*models.ConnectionType, error) { + ct := &models.ConnectionType{} + err := s.DB.QueryRow(`SELECT id, name FROM connection_types WHERE id = ?`, id).Scan(&ct.ID, &ct.Name) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return ct, nil +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..7b1c198 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,41 @@ +package db + +import ( + "database/sql" + _ "embed" + "fmt" + + _ "github.com/mattn/go-sqlite3" +) + +//go:embed schema.sql +var schemaSQL string + +type Store struct { + DB *sql.DB +} + +func Init(path string) (*Store, error) { + db, err := sql.Open("sqlite3", path+"?_journal_mode=WAL&_foreign_keys=on") + if err != nil { + return nil, fmt.Errorf("open db: %w", err) + } + + db.SetMaxOpenConns(1) + + if _, err := db.Exec(schemaSQL); err != nil { + db.Close() + return nil, fmt.Errorf("run schema: %w", err) + } + + if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil { + db.Close() + return nil, fmt.Errorf("wal mode: %w", err) + } + + return &Store{DB: db}, nil +} + +func (s *Store) Close() error { + return s.DB.Close() +} diff --git a/internal/db/device_models.go b/internal/db/device_models.go new file mode 100644 index 0000000..ce8c4d0 --- /dev/null +++ b/internal/db/device_models.go @@ -0,0 +1,159 @@ +package db + +import ( + "database/sql" + "lostcavewireplanner/internal/models" +) + +func (s *Store) ModelGetAll() ([]models.DeviceModel, error) { + rows, err := s.DB.Query(`SELECT id, name, manufacturer, is_rack_mountable, height_units, front_image, back_image, is_patch_panel, is_wall_socket, created_at, updated_at FROM device_models ORDER BY name`) + if err != nil { + return nil, err + } + defer rows.Close() + + var list []models.DeviceModel + for rows.Next() { + var m models.DeviceModel + if err := rows.Scan(&m.ID, &m.Name, &m.Manufacturer, &m.IsRackMountable, &m.HeightUnits, + &m.FrontImage, &m.BackImage, &m.IsPatchPanel, &m.IsWallSocket, &m.CreatedAt, &m.UpdatedAt); err != nil { + return nil, err + } + list = append(list, m) + } + return list, rows.Err() +} + +func (s *Store) ModelGetByID(id int64) (*models.DeviceModel, error) { + m := &models.DeviceModel{} + err := s.DB.QueryRow(`SELECT id, name, manufacturer, is_rack_mountable, height_units, front_image, back_image, is_patch_panel, is_wall_socket, created_at, updated_at FROM device_models WHERE id = ?`, id). + Scan(&m.ID, &m.Name, &m.Manufacturer, &m.IsRackMountable, &m.HeightUnits, + &m.FrontImage, &m.BackImage, &m.IsPatchPanel, &m.IsWallSocket, &m.CreatedAt, &m.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + + m.Ports, err = s.ModelPortGetByModelID(m.ID) + if err != nil { + return nil, err + } + return m, nil +} + +func (s *Store) modelGetByIDTx(tx *sql.Tx, id int64) (*models.DeviceModel, error) { + m := &models.DeviceModel{} + err := tx.QueryRow(`SELECT id, name, manufacturer, is_rack_mountable, height_units, front_image, back_image, is_patch_panel, is_wall_socket FROM device_models WHERE id = ?`, id). + Scan(&m.ID, &m.Name, &m.Manufacturer, &m.IsRackMountable, &m.HeightUnits, + &m.FrontImage, &m.BackImage, &m.IsPatchPanel, &m.IsWallSocket) + if err != nil { + return nil, err + } + + portRows, err := tx.Query(`SELECT id, device_model_id, name, side, position FROM device_model_ports WHERE device_model_id = ? ORDER BY side, position`, id) + if err != nil { + return nil, err + } + defer portRows.Close() + for portRows.Next() { + var p models.DeviceModelPort + if err := portRows.Scan(&p.ID, &p.DeviceModelID, &p.Name, &p.Side, &p.Position); err != nil { + return nil, err + } + m.Ports = append(m.Ports, p) + } + return m, portRows.Err() +} + +func (s *Store) ModelCreate(m *models.DeviceModel, imageDir string) (int64, error) { + tx, err := s.DB.Begin() + if err != nil { + return 0, err + } + defer tx.Rollback() + + res, err := tx.Exec(`INSERT INTO device_models (name, manufacturer, is_rack_mountable, height_units, front_image, back_image, is_patch_panel, is_wall_socket) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + m.Name, m.Manufacturer, m.IsRackMountable, m.HeightUnits, m.FrontImage, m.BackImage, m.IsPatchPanel, m.IsWallSocket) + if err != nil { + return 0, err + } + modelID, err := res.LastInsertId() + if err != nil { + return 0, err + } + + for i := range m.Ports { + m.Ports[i].DeviceModelID = modelID + } + if err := s.modelPortCreateTx(tx, modelID, m.Ports); err != nil { + return 0, err + } + + if err := tx.Commit(); err != nil { + return 0, err + } + return modelID, nil +} + +func (s *Store) ModelUpdate(m *models.DeviceModel) error { + tx, err := s.DB.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + _, err = tx.Exec(`UPDATE device_models SET name=?, manufacturer=?, is_rack_mountable=?, height_units=?, front_image=?, back_image=?, is_patch_panel=?, is_wall_socket=?, updated_at=datetime('now') WHERE id=?`, + m.Name, m.Manufacturer, m.IsRackMountable, m.HeightUnits, m.FrontImage, m.BackImage, m.IsPatchPanel, m.IsWallSocket, m.ID) + if err != nil { + return err + } + + if _, err := tx.Exec(`DELETE FROM device_model_ports WHERE device_model_id = ?`, m.ID); err != nil { + return err + } + + for i := range m.Ports { + m.Ports[i].DeviceModelID = m.ID + } + if err := s.modelPortCreateTx(tx, m.ID, m.Ports); err != nil { + return err + } + + return tx.Commit() +} + +func (s *Store) ModelDelete(id int64) error { + _, err := s.DB.Exec(`DELETE FROM device_models WHERE id=?`, id) + return err +} + +func (s *Store) ModelPortGetByModelID(modelID int64) ([]models.DeviceModelPort, error) { + rows, err := s.DB.Query(`SELECT id, device_model_id, name, side, position FROM device_model_ports WHERE device_model_id = ? ORDER BY side, position`, modelID) + if err != nil { + return nil, err + } + defer rows.Close() + + var ports []models.DeviceModelPort + for rows.Next() { + var p models.DeviceModelPort + if err := rows.Scan(&p.ID, &p.DeviceModelID, &p.Name, &p.Side, &p.Position); err != nil { + return nil, err + } + ports = append(ports, p) + } + return ports, rows.Err() +} + +func (s *Store) modelPortCreateTx(tx *sql.Tx, modelID int64, ports []models.DeviceModelPort) error { + for _, p := range ports { + _, err := tx.Exec(`INSERT INTO device_model_ports (device_model_id, name, side, position) VALUES (?, ?, ?, ?)`, + modelID, p.Name, p.Side, p.Position) + if err != nil { + return err + } + } + return nil +} diff --git a/internal/db/devices.go b/internal/db/devices.go new file mode 100644 index 0000000..de8943f --- /dev/null +++ b/internal/db/devices.go @@ -0,0 +1,170 @@ +package db + +import ( + "database/sql" + "lostcavewireplanner/internal/models" +) + +func scanDevice(scanner interface{ Scan(dest ...any) error }, d *models.Device) error { + return scanner.Scan(&d.ID, &d.DeviceModelID, &d.Name, &d.UsageDescription, &d.Comment, + &d.Location, &d.RackID, &d.RackUnitStart, &d.RackSide, &d.CreatedAt, &d.UpdatedAt) +} + +const deviceColumns = `d.id, d.device_model_id, d.name, d.usage_description, d.comment, d.location, d.rack_id, d.rack_unit_start, d.rack_side, d.created_at, d.updated_at` + +func (s *Store) DeviceGetByID(id int64) (*models.Device, error) { + d := &models.Device{} + err := s.DB.QueryRow(`SELECT `+deviceColumns+` FROM devices d WHERE d.id = ?`, id).Scan( + &d.ID, &d.DeviceModelID, &d.Name, &d.UsageDescription, &d.Comment, + &d.Location, &d.RackID, &d.RackUnitStart, &d.RackSide, &d.CreatedAt, &d.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + + d.Model, _ = s.ModelGetByID(d.DeviceModelID) + d.Ports, _ = s.PortGetByDeviceID(d.ID) + if d.RackID != nil { + d.Rack, _ = s.RackGetByID(*d.RackID) + } + return d, nil +} + +func (s *Store) DeviceGetAllUnracked() ([]models.Device, error) { + rows, err := s.DB.Query(`SELECT ` + deviceColumns + ` FROM devices d WHERE d.rack_id IS NULL ORDER BY d.name`) + if err != nil { + return nil, err + } + defer rows.Close() + + var devices []models.Device + for rows.Next() { + var d models.Device + if err := scanDevice(rows, &d); err != nil { + return nil, err + } + d.Model, _ = s.ModelGetByID(d.DeviceModelID) + d.Ports, _ = s.PortGetByDeviceID(d.ID) + devices = append(devices, d) + } + return devices, rows.Err() +} + +func (s *Store) DeviceGetByRackID(rackID int64) ([]models.Device, error) { + rows, err := s.DB.Query(`SELECT `+deviceColumns+` FROM devices d WHERE d.rack_id = ? AND d.rack_unit_start IS NOT NULL ORDER BY d.rack_unit_start`, rackID) + if err != nil { + return nil, err + } + defer rows.Close() + + var devices []models.Device + for rows.Next() { + var d models.Device + if err := scanDevice(rows, &d); err != nil { + return nil, err + } + d.Model, _ = s.ModelGetByID(d.DeviceModelID) + d.Ports, _ = s.PortGetByDeviceID(d.ID) + devices = append(devices, d) + } + return devices, rows.Err() +} + +func (s *Store) DeviceGetUnrackedByRackID(rackID int64) ([]models.Device, error) { + rows, err := s.DB.Query(`SELECT `+deviceColumns+` FROM devices d WHERE d.rack_id = ? AND d.rack_unit_start IS NULL ORDER BY d.name`, rackID) + if err != nil { + return nil, err + } + defer rows.Close() + + var devices []models.Device + for rows.Next() { + var d models.Device + if err := scanDevice(rows, &d); err != nil { + return nil, err + } + d.Model, _ = s.ModelGetByID(d.DeviceModelID) + d.Ports, _ = s.PortGetByDeviceID(d.ID) + devices = append(devices, d) + } + return devices, rows.Err() +} + +func (s *Store) DeviceCreate(d *models.Device) (int64, error) { + tx, err := s.DB.Begin() + if err != nil { + return 0, err + } + defer tx.Rollback() + + res, err := tx.Exec(`INSERT INTO devices (device_model_id, name, usage_description, comment, location, rack_id, rack_unit_start, rack_side) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + d.DeviceModelID, d.Name, d.UsageDescription, d.Comment, d.Location, d.RackID, d.RackUnitStart, d.RackSide) + if err != nil { + return 0, err + } + deviceID, err := res.LastInsertId() + if err != nil { + return 0, err + } + + model, err := s.modelGetByIDTx(tx, d.DeviceModelID) + if err != nil { + return 0, err + } + + if err := s.portCreateFromModelTx(tx, deviceID, model); err != nil { + return 0, err + } + + if err := tx.Commit(); err != nil { + return 0, err + } + return deviceID, nil +} + +func (s *Store) DeviceUpdate(d *models.Device) error { + _, err := s.DB.Exec(`UPDATE devices SET name=?, usage_description=?, comment=?, location=?, rack_id=?, rack_unit_start=?, rack_side=?, updated_at=datetime('now') WHERE id=?`, + d.Name, d.UsageDescription, d.Comment, d.Location, d.RackID, d.RackUnitStart, d.RackSide, d.ID) + return err +} + +func (s *Store) DeviceDelete(id int64) error { + _, err := s.DB.Exec(`DELETE FROM devices WHERE id=?`, id) + return err +} + +func (s *Store) DeviceGetByName(name string) (*models.Device, error) { + d := &models.Device{} + err := s.DB.QueryRow(`SELECT `+deviceColumns+` FROM devices d WHERE d.name = ?`, name).Scan( + &d.ID, &d.DeviceModelID, &d.Name, &d.UsageDescription, &d.Comment, + &d.Location, &d.RackID, &d.RackUnitStart, &d.RackSide, &d.CreatedAt, &d.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return d, nil +} + +func (s *Store) DeviceGetAllWallSockets() ([]models.Device, error) { + rows, err := s.DB.Query(`SELECT ` + deviceColumns + ` FROM devices d JOIN device_models dm ON dm.id = d.device_model_id WHERE dm.is_wall_socket = TRUE ORDER BY d.location, d.name`) + if err != nil { + return nil, err + } + defer rows.Close() + + var devices []models.Device + for rows.Next() { + var d models.Device + if err := scanDevice(rows, &d); err != nil { + return nil, err + } + d.Model, _ = s.ModelGetByID(d.DeviceModelID) + d.Ports, _ = s.PortGetByDeviceID(d.ID) + devices = append(devices, d) + } + return devices, rows.Err() +} diff --git a/internal/db/ports.go b/internal/db/ports.go new file mode 100644 index 0000000..992225c --- /dev/null +++ b/internal/db/ports.go @@ -0,0 +1,74 @@ +package db + +import ( + "database/sql" + "lostcavewireplanner/internal/models" +) + +func (s *Store) PortGetByDeviceID(deviceID int64) ([]models.DevicePort, error) { + rows, err := s.DB.Query(`SELECT id, device_id, name, side, position FROM device_ports WHERE device_id = ? ORDER BY side, position`, deviceID) + if err != nil { + return nil, err + } + defer rows.Close() + + var ports []models.DevicePort + for rows.Next() { + var p models.DevicePort + if err := rows.Scan(&p.ID, &p.DeviceID, &p.Name, &p.Side, &p.Position); err != nil { + return nil, err + } + ports = append(ports, p) + } + return ports, rows.Err() +} + +func (s *Store) PortGetByID(id int64) (*models.DevicePort, error) { + p := &models.DevicePort{} + err := s.DB.QueryRow(`SELECT id, device_id, name, side, position FROM device_ports WHERE id = ?`, id). + Scan(&p.ID, &p.DeviceID, &p.Name, &p.Side, &p.Position) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return p, nil +} + +func (s *Store) PortGetPaired(deviceID int64, name string, side string) (*models.DevicePort, error) { + p := &models.DevicePort{} + err := s.DB.QueryRow(`SELECT id, device_id, name, side, position FROM device_ports WHERE device_id = ? AND name = ? AND side = ?`, deviceID, name, side). + Scan(&p.ID, &p.DeviceID, &p.Name, &p.Side, &p.Position) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return p, nil +} + +func (s *Store) portCreateFromModelTx(tx *sql.Tx, deviceID int64, model *models.DeviceModel) error { + for _, mp := range model.Ports { + if model.IsPatchPanel || model.IsWallSocket { + _, err := tx.Exec(`INSERT INTO device_ports (device_id, name, side, position) VALUES (?, ?, 'front', ?)`, + deviceID, mp.Name, mp.Position) + if err != nil { + return err + } + _, err = tx.Exec(`INSERT INTO device_ports (device_id, name, side, position) VALUES (?, ?, 'back', ?)`, + deviceID, mp.Name, mp.Position) + if err != nil { + return err + } + } else { + _, err := tx.Exec(`INSERT INTO device_ports (device_id, name, side, position) VALUES (?, ?, ?, ?)`, + deviceID, mp.Name, mp.Side, mp.Position) + if err != nil { + return err + } + } + } + return nil +} diff --git a/internal/db/racks.go b/internal/db/racks.go new file mode 100644 index 0000000..c4b7de8 --- /dev/null +++ b/internal/db/racks.go @@ -0,0 +1,70 @@ +package db + +import ( + "database/sql" + "lostcavewireplanner/internal/models" +) + +func (s *Store) RackGetAll() ([]models.Rack, error) { + rows, err := s.DB.Query(`SELECT id, name, rack_type, depth, height_units, comment, created_at, updated_at FROM racks ORDER BY name`) + if err != nil { + return nil, err + } + defer rows.Close() + + var racks []models.Rack + for rows.Next() { + var r models.Rack + if err := rows.Scan(&r.ID, &r.Name, &r.RackType, &r.Depth, &r.HeightUnits, &r.Comment, &r.CreatedAt, &r.UpdatedAt); err != nil { + return nil, err + } + racks = append(racks, r) + } + return racks, rows.Err() +} + +func (s *Store) RackGetByID(id int64) (*models.Rack, error) { + r := &models.Rack{} + err := s.DB.QueryRow(`SELECT id, name, rack_type, depth, height_units, comment, created_at, updated_at FROM racks WHERE id = ?`, id). + Scan(&r.ID, &r.Name, &r.RackType, &r.Depth, &r.HeightUnits, &r.Comment, &r.CreatedAt, &r.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return r, nil +} + +func (s *Store) RackCreate(r *models.Rack) (int64, error) { + res, err := s.DB.Exec(`INSERT INTO racks (name, rack_type, depth, height_units, comment) VALUES (?, ?, ?, ?, ?)`, + r.Name, r.RackType, r.Depth, r.HeightUnits, r.Comment) + if err != nil { + return 0, err + } + return res.LastInsertId() +} + +func (s *Store) RackUpdate(r *models.Rack) error { + _, err := s.DB.Exec(`UPDATE racks SET name=?, rack_type=?, depth=?, height_units=?, comment=?, updated_at=datetime('now') WHERE id=?`, + r.Name, r.RackType, r.Depth, r.HeightUnits, r.Comment, r.ID) + return err +} + +func (s *Store) RackDelete(id int64) error { + _, err := s.DB.Exec(`DELETE FROM racks WHERE id=?`, id) + return err +} + +func (s *Store) RackGetByName(name string) (*models.Rack, error) { + r := &models.Rack{} + err := s.DB.QueryRow(`SELECT id, name, rack_type, depth, height_units, comment, created_at, updated_at FROM racks WHERE name = ?`, name). + Scan(&r.ID, &r.Name, &r.RackType, &r.Depth, &r.HeightUnits, &r.Comment, &r.CreatedAt, &r.UpdatedAt) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + return r, nil +} diff --git a/internal/db/schema.sql b/internal/db/schema.sql new file mode 100644 index 0000000..ace6649 --- /dev/null +++ b/internal/db/schema.sql @@ -0,0 +1,94 @@ +CREATE TABLE IF NOT EXISTS schema_version ( + version INTEGER PRIMARY KEY +); + +CREATE TABLE IF NOT EXISTS device_models ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + manufacturer TEXT NOT NULL DEFAULT '', + is_rack_mountable BOOLEAN NOT NULL DEFAULT TRUE, + height_units INTEGER, + front_image TEXT DEFAULT '', + back_image TEXT DEFAULT '', + is_patch_panel BOOLEAN NOT NULL DEFAULT FALSE, + is_wall_socket BOOLEAN NOT NULL DEFAULT FALSE, + created_at DATETIME NOT NULL DEFAULT (datetime('now')), + updated_at DATETIME NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS device_model_ports ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + device_model_id INTEGER NOT NULL REFERENCES device_models(id) ON DELETE CASCADE, + name TEXT NOT NULL, + side TEXT NOT NULL CHECK(side IN ('front', 'back')), + position INTEGER NOT NULL DEFAULT 0 +); + +CREATE TABLE IF NOT EXISTS racks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + rack_type TEXT NOT NULL CHECK(rack_type IN ('network', 'server')), + depth TEXT NOT NULL CHECK(depth IN ('shallow', 'deep')), + height_units INTEGER NOT NULL, + comment TEXT DEFAULT '', + created_at DATETIME NOT NULL DEFAULT (datetime('now')), + updated_at DATETIME NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS devices ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + device_model_id INTEGER NOT NULL REFERENCES device_models(id), + name TEXT NOT NULL UNIQUE, + usage_description TEXT DEFAULT '', + comment TEXT DEFAULT '', + location TEXT DEFAULT '', + rack_id INTEGER REFERENCES racks(id) ON DELETE SET NULL, + rack_unit_start INTEGER, + rack_side TEXT CHECK(rack_side IN ('front', 'back')), + created_at DATETIME NOT NULL DEFAULT (datetime('now')), + updated_at DATETIME NOT NULL DEFAULT (datetime('now')) +); + +CREATE TABLE IF NOT EXISTS device_ports ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + device_id INTEGER NOT NULL REFERENCES devices(id) ON DELETE CASCADE, + name TEXT NOT NULL, + side TEXT NOT NULL CHECK(side IN ('front', 'back')), + position INTEGER NOT NULL DEFAULT 0 +); + +CREATE TABLE IF NOT EXISTS connection_types ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE +); + +CREATE TABLE IF NOT EXISTS connections ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + connection_type_id INTEGER NOT NULL REFERENCES connection_types(id), + label_1 TEXT, + label_2 TEXT, + color TEXT NOT NULL DEFAULT '#808080', + port_id_1 INTEGER REFERENCES device_ports(id) ON DELETE SET NULL, + port_id_2 INTEGER REFERENCES device_ports(id) ON DELETE SET NULL, + created_at DATETIME NOT NULL DEFAULT (datetime('now')), + updated_at DATETIME NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS idx_device_ports_device_id ON device_ports(device_id); +CREATE INDEX IF NOT EXISTS idx_device_model_ports_model_id ON device_model_ports(device_model_id); +CREATE INDEX IF NOT EXISTS idx_devices_rack_id ON devices(rack_id); +CREATE INDEX IF NOT EXISTS idx_connections_port_1 ON connections(port_id_1); +CREATE INDEX IF NOT EXISTS idx_connections_port_2 ON connections(port_id_2); +CREATE INDEX IF NOT EXISTS idx_devices_model_id ON devices(device_model_id); + +INSERT OR IGNORE INTO connection_types (name) VALUES + ('Ethernet'), + ('FibreChannel'), + ('SAS'), + ('power'), + ('video'), + ('audio'), + ('serial'), + ('USB'); + +INSERT OR IGNORE INTO schema_version (version) VALUES (1); diff --git a/internal/handlers/connections.go b/internal/handlers/connections.go new file mode 100644 index 0000000..2bd87c6 --- /dev/null +++ b/internal/handlers/connections.go @@ -0,0 +1,221 @@ +package handlers + +import ( + "net/http" + "strconv" + "strings" + + "lostcavewireplanner/internal/models" + "lostcavewireplanner/internal/services" +) + +func (h *Handlers) ConnectionModal(w http.ResponseWriter, r *http.Request) { + portIDStr := r.PathValue("portId") + portID, err := strconv.ParseInt(portIDStr, 10, 64) + if err != nil { + http.Error(w, "invalid port id", http.StatusBadRequest) + return + } + + trace, err := services.TraceConnection(h.Store, portID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + connTypes, _ := h.Store.ConnectionTypeGetAll() + if connTypes == nil { + connTypes = []models.ConnectionType{} + } + + type ConnectionModalData struct { + Trace *services.TraceResult + ConnectionTypes []models.ConnectionType + AllPorts []FlatPort + Error string + } + + allDevices, _ := h.Store.DeviceGetAllUnracked() + rackedDevicesMap := map[int64]bool{} + + var flatPorts []FlatPort + addDevicePorts := func(devices []models.Device) { + for _, d := range devices { + if rackedDevicesMap[d.ID] { + continue + } + rackedDevicesMap[d.ID] = true + for _, p := range d.Ports { + flatPorts = append(flatPorts, FlatPort{ + ID: p.ID, + Name: p.Name, + Side: p.Side, + DeviceID: d.ID, + DeviceName: d.Name, + DeviceModel: "", + }) + if d.Model != nil { + flatPorts[len(flatPorts)-1].DeviceModel = d.Model.Name + } + } + } + } + + addDevicePorts(allDevices) + for _, rack := range h.mustGetAllRacks() { + if devs, err := h.Store.DeviceGetByRackID(rack.ID); err == nil { + addDevicePorts(devs) + } + if devs, err := h.Store.DeviceGetUnrackedByRackID(rack.ID); err == nil { + addDevicePorts(devs) + } + } + + h.render(w, "connection_modal.html", ConnectionModalData{ + Trace: trace, + ConnectionTypes: connTypes, + AllPorts: flatPorts, + }) +} + +type FlatPort struct { + ID int64 + Name string + Side string + DeviceID int64 + DeviceName string + DeviceModel string +} + +func (h *Handlers) mustGetAllRacks() []models.Rack { + racks, _ := h.Store.RackGetAll() + if racks == nil { + return []models.Rack{} + } + return racks +} + +func (h *Handlers) ConnectionCreate(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + + connTypeID, _ := strconv.ParseInt(r.FormValue("connection_type_id"), 10, 64) + portID1Str := r.FormValue("port_id_1") + portID2Str := r.FormValue("port_id_2") + label1 := r.FormValue("label_1") + label2 := r.FormValue("label_2") + color := r.FormValue("color") + returnPortID := r.FormValue("return_port_id") + + if color == "" { + color = "#808080" + } + + var p1, p2 *int64 + if portID1Str != "" { + v, _ := strconv.ParseInt(portID1Str, 10, 64) + p1 = &v + } + if portID2Str != "" { + v, _ := strconv.ParseInt(portID2Str, 10, 64) + p2 = &v + } + + var label1Ptr, label2Ptr *string + if label1 != "" { + label1Ptr = &label1 + } + if label2 != "" { + label2Ptr = &label2 + } + + conn := &models.Connection{ + ConnectionTypeID: connTypeID, + Label1: label1Ptr, + Label2: label2Ptr, + Color: color, + PortID1: p1, + PortID2: p2, + } + + if err := h.Store.ConnectionCreate(conn); err != nil { + h.redirect(w, r, "/connections/"+returnPortID) + return + } + + if returnPortID != "" { + h.redirect(w, r, "/connections/"+returnPortID) + return + } + h.redirect(w, r, "/") +} + +func (h *Handlers) ConnectionEdit(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + r.ParseForm() + + conn, err := h.Store.ConnectionGetByID(id) + if err != nil || conn == nil { + http.Error(w, "connection not found", http.StatusNotFound) + return + } + + connTypeID, _ := strconv.ParseInt(r.FormValue("connection_type_id"), 10, 64) + label1 := r.FormValue("label_1") + label2 := r.FormValue("label_2") + color := r.FormValue("color") + returnPortID := r.FormValue("return_port_id") + + if color == "" { + color = "#808080" + } + + conn.ConnectionTypeID = connTypeID + if label1 != "" { + conn.Label1 = &label1 + } else { + conn.Label1 = nil + } + if label2 != "" { + conn.Label2 = &label2 + } else { + conn.Label2 = nil + } + conn.Color = color + + if err := h.Store.ConnectionUpdate(conn); err != nil { + if returnPortID != "" { + h.redirect(w, r, "/connections/"+returnPortID) + return + } + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + if returnPortID != "" { + h.redirect(w, r, "/connections/"+returnPortID) + return + } + h.redirect(w, r, "/") +} + +func (h *Handlers) ConnectionDelete(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + returnPortID := r.URL.Query().Get("return_port_id") + + h.Store.ConnectionDelete(id) + + if returnPortID != "" { + h.redirect(w, r, "/connections/"+returnPortID) + return + } + h.redirect(w, r, "/") +} + +func (h *Handlers) ConnectionGetByID(id int64) (*models.Connection, error) { + conn, err := h.Store.ConnectionGetByID(id) + return conn, err +} + +func lower(s string) string { return strings.ToLower(s) } diff --git a/internal/handlers/devices.go b/internal/handlers/devices.go new file mode 100644 index 0000000..aa3d784 --- /dev/null +++ b/internal/handlers/devices.go @@ -0,0 +1,141 @@ +package handlers + +import ( + "net/http" + "strconv" + + "lostcavewireplanner/internal/models" +) + +type DeviceViewData struct { + Device models.Device + ConnectionTypes []models.ConnectionType + AllPorts []models.DevicePort + Error string +} + +func (h *Handlers) DeviceView(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, err := strconv.ParseInt(idStr, 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + device, err := h.Store.DeviceGetByID(id) + if err != nil || device == nil { + http.NotFound(w, r) + return + } + + connTypes, _ := h.Store.ConnectionTypeGetAll() + if connTypes == nil { + connTypes = []models.ConnectionType{} + } + + h.render(w, "device.html", DeviceViewData{ + Device: *device, + ConnectionTypes: connTypes, + }) +} + +func (h *Handlers) DeviceCreate(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + + name := r.FormValue("name") + modelIDStr := r.FormValue("device_model_id") + modelID, _ := strconv.ParseInt(modelIDStr, 10, 64) + usage := r.FormValue("usage_description") + comment := r.FormValue("comment") + location := r.FormValue("location") + + if name == "" || modelID == 0 { + h.redirect(w, r, "/") + return + } + + device := &models.Device{ + DeviceModelID: modelID, + Name: name, + UsageDescription: usage, + Comment: comment, + Location: location, + } + + id, err := h.Store.DeviceCreate(device) + if err != nil { + h.redirect(w, r, "/") + return + } + + h.redirect(w, r, "/devices/"+strconv.FormatInt(id, 10)) +} + +func (h *Handlers) DeviceEdit(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + r.ParseForm() + + device, err := h.Store.DeviceGetByID(id) + if err != nil || device == nil { + http.NotFound(w, r) + return + } + + device.Name = r.FormValue("name") + device.UsageDescription = r.FormValue("usage_description") + device.Comment = r.FormValue("comment") + device.Location = r.FormValue("location") + + if rackSide := r.FormValue("rack_side"); rackSide != "" { + device.RackSide = &rackSide + } else { + device.RackSide = nil + } + + if unitStartStr := r.FormValue("rack_unit_start"); unitStartStr != "" { + us, _ := strconv.Atoi(unitStartStr) + device.RackUnitStart = &us + } else { + device.RackUnitStart = nil + } + + if err := h.Store.DeviceUpdate(device); err != nil { + h.renderDeviceError(w, *device, err.Error()) + return + } + + redirectTo := "/devices/" + idStr + if device.RackID != nil { + redirectTo = "/racks/" + strconv.FormatInt(*device.RackID, 10) + } + h.redirect(w, r, redirectTo) +} + +func (h *Handlers) DeviceDelete(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + + device, _ := h.Store.DeviceGetByID(id) + rackID := device.RackID + + h.Store.DeviceDelete(id) + + if rackID != nil { + h.redirect(w, r, "/racks/"+strconv.FormatInt(*rackID, 10)) + } else { + h.redirect(w, r, "/") + } +} + +func (h *Handlers) renderDeviceError(w http.ResponseWriter, device models.Device, errMsg string) { + connTypes, _ := h.Store.ConnectionTypeGetAll() + if connTypes == nil { + connTypes = []models.ConnectionType{} + } + h.render(w, "device.html", DeviceViewData{ + Device: device, + ConnectionTypes: connTypes, + Error: errMsg, + }) +} diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go new file mode 100644 index 0000000..1cbead3 --- /dev/null +++ b/internal/handlers/handlers.go @@ -0,0 +1,95 @@ +package handlers + +import ( + "fmt" + "html/template" + "net/http" + "path/filepath" + + "lostcavewireplanner/internal/db" +) + +type Handlers struct { + Store *db.Store + tmpl map[string]*template.Template +} + +func New(store *db.Store) *Handlers { + funcMap := template.FuncMap{ + "dict": func(values ...interface{}) (map[string]interface{}, error) { + if len(values)%2 != 0 { + return nil, fmt.Errorf("dict requires even arguments") + } + d := make(map[string]interface{}, len(values)/2) + for i := 0; i < len(values); i += 2 { + key, ok := values[i].(string) + if !ok { + return nil, fmt.Errorf("dict keys must be strings") + } + d[key] = values[i+1] + } + return d, nil + }, + "add": func(a, b int) int { return a + b }, + "sub": func(a, b int) int { return a - b }, + "safe": func(s string) template.HTML { return template.HTML(s) }, + } + + pages := []string{ + "overview.html", + "rack.html", + "device.html", + "model_list.html", + "model_form.html", + "wall_sockets.html", + } + + fragments := []string{ + "connection_modal.html", + } + + tmpl := make(map[string]*template.Template) + baseFiles := []string{filepath.Join("templates", "base.html")} + + for _, page := range pages { + files := append(baseFiles, filepath.Join("templates", page)) + t, err := template.New("base.html").Funcs(funcMap).ParseFiles(files...) + if err != nil { + panic(fmt.Errorf("parse %s: %w", page, err)) + } + tmpl[page] = t + } + + for _, frag := range fragments { + t, err := template.New(frag).Funcs(funcMap).ParseFiles(filepath.Join("templates", frag)) + if err != nil { + panic(fmt.Errorf("parse fragment %s: %w", frag, err)) + } + tmpl[frag] = t + } + + return &Handlers{Store: store, tmpl: tmpl} +} + +func (h *Handlers) render(w http.ResponseWriter, name string, data interface{}) { + t, ok := h.tmpl[name] + if !ok { + http.Error(w, "template not found: "+name, http.StatusInternalServerError) + return + } + execName := name + if _, isPage := map[string]bool{ + "overview.html": true, "rack.html": true, "device.html": true, + "model_list.html": true, "model_form.html": true, "wall_sockets.html": true, + }[name]; isPage { + execName = "base.html" + } + if err := t.ExecuteTemplate(w, execName, data); err != nil { + http.Error(w, "Template error: "+err.Error(), http.StatusInternalServerError) + } +} + +func (h *Handlers) redirect(w http.ResponseWriter, r *http.Request, url string) { + w.Header().Set("HX-Redirect", url) + http.Redirect(w, r, url, http.StatusSeeOther) +} diff --git a/internal/handlers/models.go b/internal/handlers/models.go new file mode 100644 index 0000000..b96b8a9 --- /dev/null +++ b/internal/handlers/models.go @@ -0,0 +1,199 @@ +package handlers + +import ( + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "lostcavewireplanner/internal/models" +) + +type ModelListData struct { + Models []models.DeviceModel + Error string +} + +type ModelFormData struct { + Model *models.DeviceModel + Error string + IsEdit bool +} + +func (h *Handlers) ModelList(w http.ResponseWriter, r *http.Request) { + list, _ := h.Store.ModelGetAll() + if list == nil { + list = []models.DeviceModel{} + } + h.render(w, "model_list.html", ModelListData{Models: list}) +} + +func (h *Handlers) ModelCreateForm(w http.ResponseWriter, r *http.Request) { + h.render(w, "model_form.html", ModelFormData{IsEdit: false}) +} + +func (h *Handlers) ModelEditForm(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + + model, err := h.Store.ModelGetByID(id) + if err != nil || model == nil { + http.NotFound(w, r) + return + } + + h.render(w, "model_form.html", ModelFormData{Model: model, IsEdit: true}) +} + +func (h *Handlers) ModelCreate(w http.ResponseWriter, r *http.Request) { + if err := r.ParseMultipartForm(10 << 20); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + m := &models.DeviceModel{ + Name: r.FormValue("name"), + Manufacturer: r.FormValue("manufacturer"), + IsPatchPanel: r.FormValue("is_patch_panel") == "on", + IsWallSocket: r.FormValue("is_wall_socket") == "on", + } + + isRack := r.FormValue("is_rack_mountable") == "on" + m.IsRackMountable = isRack + if isRack { + if huStr := r.FormValue("height_units"); huStr != "" { + hu, _ := strconv.Atoi(huStr) + m.HeightUnits = &hu + } + } + + m.FrontImage = saveUploadedFile(r, "front_image", "uploads") + m.BackImage = saveUploadedFile(r, "back_image", "uploads") + + parsePortsFromForm(r, m) + + if m.Name == "" { + h.render(w, "model_form.html", ModelFormData{Model: m, IsEdit: false, Error: "Name is required"}) + return + } + + _, err := h.Store.ModelCreate(m, "uploads") + if err != nil { + h.render(w, "model_form.html", ModelFormData{Model: m, IsEdit: false, Error: err.Error()}) + return + } + + http.Redirect(w, r, "/models", http.StatusSeeOther) +} + +func (h *Handlers) ModelUpdate(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + + if err := r.ParseMultipartForm(10 << 20); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + m, err := h.Store.ModelGetByID(id) + if err != nil || m == nil { + http.NotFound(w, r) + return + } + + m.Name = r.FormValue("name") + m.Manufacturer = r.FormValue("manufacturer") + m.IsPatchPanel = r.FormValue("is_patch_panel") == "on" + m.IsWallSocket = r.FormValue("is_wall_socket") == "on" + + isRack := r.FormValue("is_rack_mountable") == "on" + m.IsRackMountable = isRack + if isRack { + if huStr := r.FormValue("height_units"); huStr != "" { + hu, _ := strconv.Atoi(huStr) + m.HeightUnits = &hu + } + } else { + m.HeightUnits = nil + } + + if frontImg := saveUploadedFile(r, "front_image", "uploads"); frontImg != "" { + m.FrontImage = frontImg + } + if backImg := saveUploadedFile(r, "back_image", "uploads"); backImg != "" { + m.BackImage = backImg + } + + parsePortsFromForm(r, m) + + if m.Name == "" { + h.render(w, "model_form.html", ModelFormData{Model: m, IsEdit: true, Error: "Name is required"}) + return + } + + if err := h.Store.ModelUpdate(m); err != nil { + h.render(w, "model_form.html", ModelFormData{Model: m, IsEdit: true, Error: err.Error()}) + return + } + + http.Redirect(w, r, "/models", http.StatusSeeOther) +} + +func (h *Handlers) ModelDelete(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + h.Store.ModelDelete(id) + http.Redirect(w, r, "/models", http.StatusSeeOther) +} + +func saveUploadedFile(r *http.Request, field, dir string) string { + file, header, err := r.FormFile(field) + if err != nil { + return "" + } + defer file.Close() + + ext := "" + if idx := strings.LastIndex(header.Filename, "."); idx >= 0 { + ext = header.Filename[idx:] + } + + safeName := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext) + fpath := filepath.Join(dir, safeName) + + dst, err := os.Create(fpath) + if err != nil { + return "" + } + defer dst.Close() + + if _, err := io.Copy(dst, file); err != nil { + return "" + } + return fpath +} + +func parsePortsFromForm(r *http.Request, m *models.DeviceModel) { + r.ParseForm() + portNames := r.Form["port_name"] + portSides := r.Form["port_side"] + + m.Ports = nil + for i := range portNames { + if i >= len(portSides) { + break + } + if portNames[i] == "" { + continue + } + m.Ports = append(m.Ports, models.DeviceModelPort{ + Name: portNames[i], + Side: portSides[i], + Position: i, + }) + } +} diff --git a/internal/handlers/overview.go b/internal/handlers/overview.go new file mode 100644 index 0000000..57150bd --- /dev/null +++ b/internal/handlers/overview.go @@ -0,0 +1,98 @@ +package handlers + +import ( + "net/http" + + "lostcavewireplanner/internal/models" +) + +type OverviewData struct { + Racks []models.Rack + Devices []models.Device + Connections []models.Connection + AllModels []models.DeviceModel + Error string +} + +func (h *Handlers) Overview(w http.ResponseWriter, r *http.Request) { + racks, _ := h.Store.RackGetAll() + devices, _ := h.Store.DeviceGetAllUnracked() + connections, _ := h.Store.ConnectionGetAll() + allModels, _ := h.Store.ModelGetAll() + + if racks == nil { + racks = []models.Rack{} + } + if devices == nil { + devices = []models.Device{} + } + if connections == nil { + connections = []models.Connection{} + } + if allModels == nil { + allModels = []models.DeviceModel{} + } + + h.render(w, "overview.html", OverviewData{ + Racks: racks, + Devices: devices, + Connections: connections, + AllModels: allModels, + }) +} + +func (h *Handlers) RackCreate(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + name := r.FormValue("name") + rackType := r.FormValue("rack_type") + depth := r.FormValue("depth") + heightUnits := 42 + + if name == "" { + h.renderError(w, "overview.html", "Name is required") + return + } + + rack := &models.Rack{ + Name: name, + RackType: rackType, + Depth: depth, + HeightUnits: heightUnits, + } + _, err := h.Store.RackCreate(rack) + if err != nil { + h.renderError(w, "overview.html", err.Error()) + return + } + h.redirect(w, r, "/") +} + +func renderOverviewError(h *Handlers, w http.ResponseWriter, errMsg string) { + racks, _ := h.Store.RackGetAll() + devices, _ := h.Store.DeviceGetAllUnracked() + connections, _ := h.Store.ConnectionGetAll() + allModels, _ := h.Store.ModelGetAll() + if racks == nil { + racks = []models.Rack{} + } + if devices == nil { + devices = []models.Device{} + } + if connections == nil { + connections = []models.Connection{} + } + if allModels == nil { + allModels = []models.DeviceModel{} + } + data := OverviewData{Racks: racks, Devices: devices, Connections: connections, AllModels: allModels, Error: errMsg} + h.render(w, "overview.html", data) +} + +func (h *Handlers) renderError(w http.ResponseWriter, page string, errMsg string) { + switch page { + case "overview.html": + renderOverviewError(h, w, errMsg) + default: + http.Error(w, errMsg, http.StatusBadRequest) + } +} diff --git a/internal/handlers/racks.go b/internal/handlers/racks.go new file mode 100644 index 0000000..8a633c1 --- /dev/null +++ b/internal/handlers/racks.go @@ -0,0 +1,268 @@ +package handlers + +import ( + "net/http" + "strconv" + "strings" + + "lostcavewireplanner/internal/models" +) + +type RackViewData struct { + Rack models.Rack + FrontSlots []RackSlot + BackSlots []RackSlot + RackedDevices []models.Device + UnrackedDevices []models.Device + Connections []models.Connection + ConnectionTypes []models.ConnectionType + AllDevices []models.Device + WallSocketModels []models.DeviceModel + Error string +} + +type RackSlot struct { + Unit int + Device *models.Device + Height int + IsStart bool +} + +func (h *Handlers) RackView(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, err := strconv.ParseInt(idStr, 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + rack, err := h.Store.RackGetByID(id) + if err != nil || rack == nil { + http.NotFound(w, r) + return + } + + rackedDevices, _ := h.Store.DeviceGetByRackID(id) + unrackedDevices, _ := h.Store.DeviceGetUnrackedByRackID(id) + connections, _ := h.Store.ConnectionGetAllForRack(id) + connTypes, _ := h.Store.ConnectionTypeGetAll() + allDevices, _ := h.Store.DeviceGetAllUnracked() + + if rackedDevices == nil { + rackedDevices = []models.Device{} + } + if unrackedDevices == nil { + unrackedDevices = []models.Device{} + } + if connections == nil { + connections = []models.Connection{} + } + if connTypes == nil { + connTypes = []models.ConnectionType{} + } + if allDevices == nil { + allDevices = []models.Device{} + } + + frontSlots, backSlots := buildRackSlots(rack.HeightUnits, rackedDevices) + + h.render(w, "rack.html", RackViewData{ + Rack: *rack, + FrontSlots: frontSlots, + BackSlots: backSlots, + RackedDevices: rackedDevices, + UnrackedDevices: unrackedDevices, + Connections: connections, + ConnectionTypes: connTypes, + AllDevices: allDevices, + }) +} + +func buildRackSlots(heightUnits int, devices []models.Device) (front, back []RackSlot) { + front = make([]RackSlot, heightUnits) + back = make([]RackSlot, heightUnits) + for i := range front { + front[i].Unit = i + 1 + back[i].Unit = i + 1 + } + + for _, d := range devices { + if d.RackUnitStart == nil || d.RackSide == nil { + continue + } + height := 1 + if d.Model != nil && d.Model.HeightUnits != nil { + height = *d.Model.HeightUnits + } + start := *d.RackUnitStart - 1 + if start < 0 || start >= heightUnits { + continue + } + end := start + height + if end > heightUnits { + end = heightUnits + } + + slots := &front + if *d.RackSide == "back" { + slots = &back + } + + for u := start; u < end; u++ { + (*slots)[u].Device = &d + (*slots)[u].Height = height + (*slots)[u].IsStart = (u == start) + } + } + return +} + +func (h *Handlers) RackDelete(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + h.Store.RackDelete(id) + h.redirect(w, r, "/") +} + +func (h *Handlers) RackEdit(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + r.ParseForm() + + rack, err := h.Store.RackGetByID(id) + if err != nil || rack == nil { + http.NotFound(w, r) + return + } + + rack.Name = r.FormValue("name") + rack.RackType = r.FormValue("rack_type") + rack.Depth = r.FormValue("depth") + if hu := r.FormValue("height_units"); hu != "" { + if n, err := strconv.Atoi(hu); err == nil { + rack.HeightUnits = n + } + } + rack.Comment = r.FormValue("comment") + + if err := h.Store.RackUpdate(rack); err != nil { + h.renderRackError(w, *rack, "Failed to update: "+err.Error()) + return + } + h.redirect(w, r, "/racks/"+idStr) +} + +func (h *Handlers) RackAddRackedDevice(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + rackID, _ := strconv.ParseInt(idStr, 10, 64) + r.ParseForm() + + deviceIDStr := r.FormValue("device_id") + deviceID, _ := strconv.ParseInt(deviceIDStr, 10, 64) + unitStartStr := r.FormValue("rack_unit_start") + unitStart, _ := strconv.Atoi(unitStartStr) + rackSide := r.FormValue("rack_side") + + device, err := h.Store.DeviceGetByID(deviceID) + if err != nil || device == nil { + h.redirect(w, r, "/racks/"+idStr) + return + } + + device.RackID = &rackID + device.RackUnitStart = &unitStart + device.RackSide = &rackSide + + if err := h.Store.DeviceUpdate(device); err != nil { + h.redirect(w, r, "/racks/"+idStr) + return + } + h.redirect(w, r, "/racks/"+idStr) +} + +func (h *Handlers) RackAddUnrackedDevice(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + rackID, _ := strconv.ParseInt(idStr, 10, 64) + r.ParseForm() + + deviceIDStr := r.FormValue("device_id") + deviceID, _ := strconv.ParseInt(deviceIDStr, 10, 64) + + device, err := h.Store.DeviceGetByID(deviceID) + if err != nil || device == nil { + h.redirect(w, r, "/racks/"+idStr) + return + } + + device.RackID = &rackID + device.RackUnitStart = nil + device.RackSide = nil + + if err := h.Store.DeviceUpdate(device); err != nil { + h.redirect(w, r, "/racks/"+idStr) + return + } + h.redirect(w, r, "/racks/"+idStr) +} + +func (h *Handlers) RackRemoveDevice(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + devIDStr := r.PathValue("devId") + rackID, _ := strconv.ParseInt(idStr, 10, 64) + devID, _ := strconv.ParseInt(devIDStr, 10, 64) + + device, err := h.Store.DeviceGetByID(devID) + if err != nil || device == nil { + h.redirect(w, r, "/racks/"+strconv.FormatInt(rackID, 10)) + return + } + + device.RackID = nil + device.RackUnitStart = nil + device.RackSide = nil + h.Store.DeviceUpdate(device) + h.redirect(w, r, "/racks/"+idStr) +} + +func (h *Handlers) renderRackError(w http.ResponseWriter, rack models.Rack, errMsg string) { + rackedDevices, _ := h.Store.DeviceGetByRackID(rack.ID) + unrackedDevices, _ := h.Store.DeviceGetUnrackedByRackID(rack.ID) + connections, _ := h.Store.ConnectionGetAllForRack(rack.ID) + connTypes, _ := h.Store.ConnectionTypeGetAll() + allDevices, _ := h.Store.DeviceGetAllUnracked() + + if rackedDevices == nil { + rackedDevices = []models.Device{} + } + if unrackedDevices == nil { + unrackedDevices = []models.Device{} + } + if connections == nil { + connections = []models.Connection{} + } + if connTypes == nil { + connTypes = []models.ConnectionType{} + } + + frontSlots, backSlots := buildRackSlots(rack.HeightUnits, rackedDevices) + + h.render(w, "rack.html", RackViewData{ + Rack: rack, + FrontSlots: frontSlots, + BackSlots: backSlots, + RackedDevices: rackedDevices, + UnrackedDevices: unrackedDevices, + Connections: connections, + ConnectionTypes: connTypes, + AllDevices: allDevices, + Error: errMsg, + }) +} + +func formatPortName(name string) string { + parts := strings.Split(name, "-") + if len(parts) > 0 { + return parts[len(parts)-1] + } + return name +} diff --git a/internal/handlers/wall_sockets.go b/internal/handlers/wall_sockets.go new file mode 100644 index 0000000..f6a396c --- /dev/null +++ b/internal/handlers/wall_sockets.go @@ -0,0 +1,73 @@ +package handlers + +import ( + "net/http" + "strconv" + + "lostcavewireplanner/internal/models" +) + +type WallSocketData struct { + Sockets []models.Device + Models []models.DeviceModel + Error string +} + +func (h *Handlers) WallSockets(w http.ResponseWriter, r *http.Request) { + sockets, _ := h.Store.DeviceGetAllWallSockets() + if sockets == nil { + sockets = []models.Device{} + } + + allModels, _ := h.Store.ModelGetAll() + wallModels := []models.DeviceModel{} + for _, m := range allModels { + if m.IsWallSocket { + wallModels = append(wallModels, m) + } + } + if wallModels == nil { + wallModels = []models.DeviceModel{} + } + + h.render(w, "wall_sockets.html", WallSocketData{ + Sockets: sockets, + Models: wallModels, + }) +} + +func (h *Handlers) WallSocketCreate(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + + name := r.FormValue("name") + modelIDStr := r.FormValue("device_model_id") + modelID, _ := strconv.ParseInt(modelIDStr, 10, 64) + location := r.FormValue("location") + comment := r.FormValue("comment") + + if name == "" || modelID == 0 { + h.redirect(w, r, "/wall-sockets") + return + } + + device := &models.Device{ + DeviceModelID: modelID, + Name: name, + Location: location, + Comment: comment, + } + + _, err := h.Store.DeviceCreate(device) + if err != nil { + h.redirect(w, r, "/wall-sockets") + return + } + h.redirect(w, r, "/wall-sockets") +} + +func (h *Handlers) WallSocketDelete(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("id") + id, _ := strconv.ParseInt(idStr, 10, 64) + h.Store.DeviceDelete(id) + h.redirect(w, r, "/wall-sockets") +} diff --git a/internal/models/models.go b/internal/models/models.go new file mode 100644 index 0000000..b92abd8 --- /dev/null +++ b/internal/models/models.go @@ -0,0 +1,84 @@ +package models + +import "time" + +type DeviceModel struct { + ID int64 + Name string + Manufacturer string + IsRackMountable bool + HeightUnits *int + FrontImage string + BackImage string + IsPatchPanel bool + IsWallSocket bool + CreatedAt time.Time + UpdatedAt time.Time + Ports []DeviceModelPort +} + +type DeviceModelPort struct { + ID int64 + DeviceModelID int64 + Name string + Side string + Position int +} + +type Rack struct { + ID int64 + Name string + RackType string + Depth string + HeightUnits int + Comment string + CreatedAt time.Time + UpdatedAt time.Time +} + +type Device struct { + ID int64 + DeviceModelID int64 + Name string + UsageDescription string + Comment string + Location string + RackID *int64 + RackUnitStart *int + RackSide *string + CreatedAt time.Time + UpdatedAt time.Time + Model *DeviceModel + Ports []DevicePort + Rack *Rack +} + +type DevicePort struct { + ID int64 + DeviceID int64 + Name string + Side string + Position int +} + +type ConnectionType struct { + ID int64 + Name string +} + +type Connection struct { + ID int64 + ConnectionTypeID int64 + Label1 *string + Label2 *string + Color string + PortID1 *int64 + PortID2 *int64 + CreatedAt time.Time + UpdatedAt time.Time + ConnectionType *ConnectionType + Port1 *DevicePort + Port2 *DevicePort + Device1 *Device + Device2 *Device +} diff --git a/internal/services/connection.go b/internal/services/connection.go new file mode 100644 index 0000000..a8647c5 --- /dev/null +++ b/internal/services/connection.go @@ -0,0 +1,220 @@ +package services + +import ( + "fmt" + + "lostcavewireplanner/internal/db" + "lostcavewireplanner/internal/models" +) + +type Segment struct { + DeviceID int64 + DeviceName string + ModelName string + PortID int64 + PortName string + Side string +} + +type TraceResult struct { + FarSegments []Segment + ConnectionID int64 + ConnectionType string + Color string + Label1 string + Label2 string + ClickedPortID int64 + ClickedPortName string + ClickedDeviceID int64 + ClickedDeviceName string + ClickedModelName string + ClickedSide string + NearSegments []Segment + HasConnection bool +} + +func TraceConnection(store *db.Store, clickedPortID int64) (*TraceResult, error) { + clickedPort, err := store.PortGetByID(clickedPortID) + if err != nil { + return nil, err + } + if clickedPort == nil { + return nil, fmt.Errorf("port not found") + } + + clickedDevice, err := store.DeviceGetByID(clickedPort.DeviceID) + if err != nil { + return nil, err + } + + result := &TraceResult{ + ClickedPortID: clickedPort.ID, + ClickedPortName: clickedPort.Name, + ClickedDeviceID: clickedDevice.ID, + ClickedDeviceName: clickedDevice.Name, + ClickedSide: clickedPort.Side, + } + if clickedDevice.Model != nil { + result.ClickedModelName = clickedDevice.Model.Name + } + + conn, err := store.ConnectionGetByPortID(clickedPortID) + if err != nil { + return nil, err + } + if conn == nil { + return result, nil + } + + result.HasConnection = true + result.ConnectionID = conn.ID + result.Color = conn.Color + if conn.Label1 != nil { + result.Label1 = *conn.Label1 + } + if conn.Label2 != nil { + result.Label2 = *conn.Label2 + } + if conn.ConnectionType != nil { + result.ConnectionType = conn.ConnectionType.Name + } + + var remotePort *models.DevicePort + if conn.PortID1 != nil && *conn.PortID1 == clickedPortID { + if conn.PortID2 != nil { + remotePort, _ = store.PortGetByID(*conn.PortID2) + } + } else if conn.PortID2 != nil && *conn.PortID2 == clickedPortID { + if conn.PortID1 != nil { + remotePort, _ = store.PortGetByID(*conn.PortID1) + } + } + + if remotePort != nil { + result.FarSegments = traceAway(store, remotePort.ID, conn.ID) + } + + result.NearSegments = traceThrough(store, clickedPortID, conn.ID) + + return result, nil +} + +func traceAway(store *db.Store, portID int64, excludeConnID int64) []Segment { + var segments []Segment + visitedPorts := map[int64]bool{} + currentPortID := portID + + for { + if visitedPorts[currentPortID] { + break + } + visitedPorts[currentPortID] = true + + port, err := store.PortGetByID(currentPortID) + if err != nil || port == nil { + break + } + + device, err := store.DeviceGetByID(port.DeviceID) + if err != nil || device == nil { + break + } + + modelName := "" + if device.Model != nil { + modelName = device.Model.Name + } + + segments = append(segments, Segment{ + DeviceID: device.ID, + DeviceName: device.Name, + ModelName: modelName, + PortID: port.ID, + PortName: port.Name, + Side: port.Side, + }) + + isPatch := device.Model != nil && (device.Model.IsPatchPanel || device.Model.IsWallSocket) + if !isPatch { + break + } + + pairedSide := "back" + if port.Side == "back" { + pairedSide = "front" + } + + pairedPort, err := store.PortGetPaired(port.DeviceID, port.Name, pairedSide) + if err != nil || pairedPort == nil { + break + } + + if visitedPorts[pairedPort.ID] { + break + } + + nextConn, err := store.ConnectionGetByPortIDExcluding(pairedPort.ID, excludeConnID) + if err != nil || nextConn == nil { + break + } + + var nextPortID int64 + if nextConn.PortID1 != nil && *nextConn.PortID1 != pairedPort.ID { + nextPortID = *nextConn.PortID1 + } else if nextConn.PortID2 != nil && *nextConn.PortID2 != pairedPort.ID { + nextPortID = *nextConn.PortID2 + } else { + break + } + + excludeConnID = nextConn.ID + currentPortID = nextPortID + } + + return segments +} + +func traceThrough(store *db.Store, portID int64, excludeConnID int64) []Segment { + var segments []Segment + + port, err := store.PortGetByID(portID) + if err != nil || port == nil { + return segments + } + + device, err := store.DeviceGetByID(port.DeviceID) + if err != nil || device == nil { + return segments + } + + isPatch := device.Model != nil && (device.Model.IsPatchPanel || device.Model.IsWallSocket) + if !isPatch { + return segments + } + + pairedSide := "back" + if port.Side == "back" { + pairedSide = "front" + } + + pairedPort, err := store.PortGetPaired(port.DeviceID, port.Name, pairedSide) + if err != nil || pairedPort == nil { + return segments + } + + nextConn, err := store.ConnectionGetByPortIDExcluding(pairedPort.ID, excludeConnID) + if err != nil || nextConn == nil { + return segments + } + + var nextPortID int64 + if nextConn.PortID1 != nil && *nextConn.PortID1 != pairedPort.ID { + nextPortID = *nextConn.PortID1 + } else if nextConn.PortID2 != nil && *nextConn.PortID2 != pairedPort.ID { + nextPortID = *nextConn.PortID2 + } else { + return segments + } + + return traceAway(store, nextPortID, nextConn.ID) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..2dd643c --- /dev/null +++ b/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "log" + "net/http" + "os" + + "lostcavewireplanner/internal/db" + "lostcavewireplanner/internal/handlers" +) + +func main() { + database, err := db.Init("data.db") + if err != nil { + log.Fatalf("failed to init database: %v", err) + } + defer database.Close() + + h := handlers.New(database) + + mux := http.NewServeMux() + + fsStatic := http.FileServer(http.Dir("static")) + mux.Handle("GET /static/", http.StripPrefix("/static/", fsStatic)) + + fsUploads := http.FileServer(http.Dir("uploads")) + mux.Handle("GET /uploads/", http.StripPrefix("/uploads/", fsUploads)) + + mux.HandleFunc("GET /{$}", h.Overview) + mux.HandleFunc("POST /racks/add", h.RackCreate) + mux.HandleFunc("GET /racks/{id}", h.RackView) + mux.HandleFunc("POST /racks/{id}/delete", h.RackDelete) + mux.HandleFunc("POST /racks/{id}/edit", h.RackEdit) + mux.HandleFunc("POST /racks/{id}/devices/add/racked", h.RackAddRackedDevice) + mux.HandleFunc("POST /racks/{id}/devices/add/unracked", h.RackAddUnrackedDevice) + mux.HandleFunc("POST /racks/{id}/devices/{devId}/remove", h.RackRemoveDevice) + mux.HandleFunc("POST /devices/{id}/edit", h.DeviceEdit) + mux.HandleFunc("POST /devices/{id}/delete", h.DeviceDelete) + mux.HandleFunc("POST /devices/add", h.DeviceCreate) + mux.HandleFunc("GET /devices/{id}", h.DeviceView) + mux.HandleFunc("GET /models", h.ModelList) + mux.HandleFunc("GET /models/new", h.ModelCreateForm) + mux.HandleFunc("POST /models/create", h.ModelCreate) + mux.HandleFunc("GET /models/{id}/edit", h.ModelEditForm) + mux.HandleFunc("POST /models/{id}/update", h.ModelUpdate) + mux.HandleFunc("POST /models/{id}/delete", h.ModelDelete) + mux.HandleFunc("GET /connections/{portId}", h.ConnectionModal) + mux.HandleFunc("POST /connections/create", h.ConnectionCreate) + mux.HandleFunc("POST /connections/{id}/edit", h.ConnectionEdit) + mux.HandleFunc("POST /connections/{id}/delete", h.ConnectionDelete) + mux.HandleFunc("GET /wall-sockets", h.WallSockets) + mux.HandleFunc("POST /wall-sockets/add", h.WallSocketCreate) + mux.HandleFunc("POST /wall-sockets/{id}/delete", h.WallSocketDelete) + + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + log.Printf("Listening on :%s", port) + log.Fatal(http.ListenAndServe(":"+port, mux)) +} diff --git a/static/js/app.js b/static/js/app.js new file mode 100644 index 0000000..ee4757e --- /dev/null +++ b/static/js/app.js @@ -0,0 +1,24 @@ +function openModal() { + document.getElementById('modal-overlay').style.display = 'flex'; +} + +function closeModal(event) { + if (event && event.target !== document.getElementById('modal-overlay')) { + if (!event.target.classList.contains('modal-overlay')) return; + } + document.getElementById('modal-overlay').style.display = 'none'; + document.getElementById('modal-content').innerHTML = ''; +} + +document.addEventListener('keydown', function(e) { + if (e.key === 'Escape') { + document.getElementById('modal-overlay').style.display = 'none'; + document.getElementById('modal-content').innerHTML = ''; + } +}); + +document.body.addEventListener('htmx:afterSwap', function(evt) { + if (evt.detail.target.id === 'modal-content') { + openModal(); + } +}); diff --git a/static/js/htmx.min.js b/static/js/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/static/js/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..0b90b47 --- /dev/null +++ b/static/style.css @@ -0,0 +1,185 @@ +*, *::before, *::after { box-sizing: border-box; } + +:root { + --bg: #1a1a2e; + --surface: #16213e; + --surface2: #0f3460; + --text: #e0e0e0; + --text-muted: #999; + --accent: #e94560; + --border: #333; + --green: #4ecca3; + --orange: #f0a500; + --red: #e94560; + --blue: #4a9ff5; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace; + color: var(--text); + background: var(--bg); + font-size: 14px; + line-height: 1.5; +} + +body { margin: 0; padding: 0; } + +a { color: var(--blue); text-decoration: none; } +a:hover { text-decoration: underline; } + +h1, h2, h3, h4, h5 { margin: 1em 0 0.5em; font-weight: 600; } +h1 { font-size: 1.6em; } +h2 { font-size: 1.3em; } +h3 { font-size: 1.1em; } + +small, .muted { color: var(--text-muted); font-size: 0.85em; } +.comment { color: var(--text-muted); font-style: italic; } + +/* NAV */ +.top-nav { + display: flex; align-items: center; gap: 1.5em; + padding: 0.6em 1.5em; background: var(--surface); + border-bottom: 1px solid var(--border); + position: sticky; top: 0; z-index: 100; +} +.nav-brand { font-weight: 700; font-size: 1.1em; color: var(--accent) !important; } +.nav-links { display: flex; gap: 1em; } +.nav-links a { color: var(--text); } + +main { max-width: 1200px; margin: 0 auto; padding: 1em 1.5em; } + +/* CARDS & GRID */ +.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 0.8em; } +.card { + display: block; padding: 0.8em; background: var(--surface); + border: 1px solid var(--border); border-radius: 4px; + transition: border-color 0.15s; +} +.card:hover { border-color: var(--accent); text-decoration: none; } +.card strong { display: block; } +.card span { display: block; color: var(--text-muted); font-size: 0.9em; } + +.alert { padding: 0.6em 1em; border-radius: 4px; margin-bottom: 1em; } +.alert-error { background: #442222; border: 1px solid var(--red); color: #ff8888; } + +/* BUTTONS */ +.btn, button { + display: inline-block; padding: 0.4em 0.9em; font-size: 0.9em; + background: var(--surface2); color: var(--text); + border: 1px solid var(--border); border-radius: 4px; cursor: pointer; + font-family: inherit; +} +.btn:hover, button:hover { border-color: var(--accent); } +.btn-danger, button.btn-danger { background: #442222; border-color: var(--red); color: #ff8888; } +.btn-danger:hover, button.btn-danger:hover { background: #552222; } +.btn-sm, button.btn-sm { padding: 0.2em 0.5em; font-size: 0.8em; } + +/* FORMS */ +label { display: block; margin-bottom: 0.3em; font-size: 0.9em; } +input, select, textarea { + display: block; width: 100%; max-width: 400px; + padding: 0.4em 0.6em; margin-bottom: 0.5em; + background: var(--bg); color: var(--text); + border: 1px solid var(--border); border-radius: 4px; + font-family: inherit; font-size: inherit; +} +fieldset { border: 1px solid var(--border); border-radius: 4px; padding: 0.8em; margin-bottom: 0.8em; } +details { margin: 0.8em 0; } +details summary { cursor: pointer; color: var(--blue); margin-bottom: 0.5em; } +.inline-form { margin-top: 0.5em; } + +/* TABLE */ +table { width: 100%; border-collapse: collapse; margin: 0.8em 0; } +th, td { padding: 0.4em 0.7em; text-align: left; border-bottom: 1px solid var(--border); font-size: 0.9em; } +th { background: var(--surface); font-weight: 600; } + +/* RACK LAYOUT */ +.rack-layout { display: flex; gap: 2em; margin: 1em 0; } +.rack-panel { flex: 1; } +.rack-panel h3 { margin-top: 0; } +.rack-slot { + display: flex; align-items: center; gap: 0.5em; + padding: 1px 0.4em; border-bottom: 1px solid #222; + font-size: 0.85em; +} +.rack-slot.occupied { background: var(--surface); } +.unit-num { color: var(--text-muted); width: 2em; text-align: right; font-size: 0.75em; flex-shrink: 0; } +.rack-device { display: flex; flex-direction: column; } +.rack-device strong { font-size: 0.9em; } +.rack-device small { font-size: 0.75em; } + +.rack-toolbar { display: flex; gap: 0.5em; align-items: center; margin-bottom: 0.5em; } + +/* DEVICE SECTIONS */ +.device-section { margin-bottom: 1.5em; padding: 0.8em; background: var(--surface); border-radius: 4px; } +.device-section h4 { margin-top: 0; } +.device-meta p { margin: 0.3em 0; } + +/* PORTS */ +.ports { display: flex; gap: 1.5em; } +.port-column { flex: 1; } +.port-column h5 { margin: 0 0 0.3em; } +.port { + display: inline-block; padding: 0.15em 0.5em; margin: 2px; + border: 1px solid var(--border); border-radius: 3px; + font-size: 0.8em; font-family: monospace; + background: var(--bg); cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} +.port:hover { border-color: var(--accent); } +.port.connected { border-color: var(--green); background: #2a4a3a; } + +/* MODAL */ +.modal-overlay { + position: fixed; top: 0; left: 0; right: 0; bottom: 0; + background: rgba(0,0,0,0.7); + display: flex; align-items: center; justify-content: center; + z-index: 1000; +} +.modal-content { + background: var(--surface); border: 1px solid var(--border); + border-radius: 6px; padding: 1.5em; + max-width: 650px; width: 95%; max-height: 85vh; overflow-y: auto; +} +.modal-inner { position: relative; } +.modal-close { + position: absolute; top: 0; right: 0; + background: none; border: none; color: var(--text); + font-size: 1.4em; cursor: pointer; padding: 0 0.3em; +} + +/* CONNECTION TRACE */ +.connection-trace { margin: 1em 0; padding: 0.8em; background: var(--bg); border-radius: 4px; } +.trace-chain { display: flex; align-items: center; gap: 0.3em; flex-wrap: wrap; } +.trace-segment { + padding: 0.3em 0.6em; background: var(--surface); border-radius: 3px; + border: 1px solid var(--border); +} +.trace-segment small { display: block; } +.trace-arrow { color: var(--text-muted); font-weight: bold; } +.trace-clicked { + padding: 0.3em 0.6em; background: var(--surface2); border-radius: 3px; + border: 2px solid var(--accent); display: inline-block; +} +.clicked-badge { + display: block; font-size: 0.65em; color: var(--accent); + text-transform: uppercase; letter-spacing: 0.1em; margin-bottom: 0.2em; +} +.port-ref { font-family: monospace; color: var(--green); font-size: 0.85em; } +.connection-details { margin: 0.8em 0; } + +/* PORT EDITOR */ +.port-entry { display: flex; gap: 0.5em; align-items: center; margin-bottom: 0.3em; } +.port-entry input { width: 18em; margin-bottom: 0; } +.port-entry select { width: 6em; margin-bottom: 0; } + +/* DEVICE TOOLBAR */ +.device-toolbar { display: flex; gap: 0.5em; align-items: center; margin-bottom: 0.5em; } + +/* BADGES */ +.badge { display: inline-block; padding: 0.1em 0.4em; font-size: 0.75em; border-radius: 3px; background: var(--surface2); } +.badge-network { background: #224444; color: var(--green); } +.badge-server { background: #332244; color: #b388ff; } + +/* SECTION */ +section { margin-bottom: 2em; } + +/* TOOLBAR */ +.toolbar { margin-bottom: 1em; } diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..e5599d5 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,27 @@ + + + + + + Lostcave Wireplanner + + + + + +
+ {{block "content" .}}{{end}} +
+ + + + diff --git a/templates/connection_modal.html b/templates/connection_modal.html new file mode 100644 index 0000000..42f5190 --- /dev/null +++ b/templates/connection_modal.html @@ -0,0 +1,94 @@ + diff --git a/templates/device.html b/templates/device.html new file mode 100644 index 0000000..37f1cef --- /dev/null +++ b/templates/device.html @@ -0,0 +1,66 @@ +{{define "content"}} +

{{.Device.Name}}

+{{if .Error}}
{{.Error}}
{{end}} + +
+ {{if .Device.Model}}

Model: {{.Device.Model.Manufacturer}} {{.Device.Model.Name}}

{{end}} + {{if .Device.UsageDescription}}

Usage: {{.Device.UsageDescription}}

{{end}} + {{if .Device.Location}}

Location: {{.Device.Location}}

{{end}} + {{if .Device.Comment}}

Comment: {{.Device.Comment}}

{{end}} + {{if .Device.Rack}} +

Rack: {{.Device.Rack.Name}} + {{if .Device.RackUnitStart}} U{{.Device.RackUnitStart}} {{.Device.RackSide}}{{end}} +

+ {{end}} +
+ +
+
+ +
+
+ Edit +
+ + + + + {{if .Device.Rack}} + + + {{end}} + +
+
+
+ +

Ports

+
+
+

Front

+ {{range .Device.Ports}}{{if eq .Side "front"}} + + {{.Name}} + + {{end}}{{end}} +
+
+

Back

+ {{range .Device.Ports}}{{if eq .Side "back"}} + + {{.Name}} + + {{end}}{{end}} +
+
+{{end}} diff --git a/templates/model_form.html b/templates/model_form.html new file mode 100644 index 0000000..9f2625f --- /dev/null +++ b/templates/model_form.html @@ -0,0 +1,58 @@ +{{define "content"}} +

{{if .IsEdit}}Edit{{else}}Create{{end}} Device Model

+{{if .Error}}
{{.Error}}
{{end}} + +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +

Ports

+
+ {{if .Model}} + {{range $i, $p := .Model.Ports}} +
+ + + +
+ {{end}} + {{end}} +
+ + +
+ + Cancel +
+
+ + +{{end}} diff --git a/templates/model_list.html b/templates/model_list.html new file mode 100644 index 0000000..f86afc8 --- /dev/null +++ b/templates/model_list.html @@ -0,0 +1,30 @@ +{{define "content"}} +

Device Models

+{{if .Error}}
{{.Error}}
{{end}} + + + + + + +{{range .Models}} + + + + + + + + + +{{end}} + +
NameManufacturerRack?UPatchWall
{{.Name}}{{.Manufacturer}}{{if .IsRackMountable}}yes{{else}}no{{end}}{{if .HeightUnits}}{{.HeightUnits}}{{else}}-{{end}}{{if .IsPatchPanel}}yes{{end}}{{if .IsWallSocket}}yes{{end}} + Edit +
+ +
+
+{{end}} diff --git a/templates/overview.html b/templates/overview.html new file mode 100644 index 0000000..e30170e --- /dev/null +++ b/templates/overview.html @@ -0,0 +1,74 @@ +{{define "content"}} +

Overview

+{{if .Error}}
{{.Error}}
{{end}} + +
+

Racks

+ +
+Add Rack +
+ + + + +
+
+
+ +
+

Devices

+ +
+Create Device +
+ + + + + + +
+
+
+ +{{if .Connections}} +
+

Connections

+ + + +{{range .Connections}} + + + + + + +{{end}} + +
TypeEndpoint AEndpoint BLabels
{{if .ConnectionType}}{{.ConnectionType.Name}}{{end}}{{if .Device1}}{{.Device1.Name}} [{{.Port1.Name}}]{{end}}{{if .Device2}}{{.Device2.Name}} [{{.Port2.Name}}]{{end}}{{.Label1}}{{if and .Label1 .Label2}} / {{end}}{{.Label2}}
+
+{{end}} +{{end}} diff --git a/templates/rack.html b/templates/rack.html new file mode 100644 index 0000000..9b9ba51 --- /dev/null +++ b/templates/rack.html @@ -0,0 +1,148 @@ +{{define "content"}} +

{{.Rack.Name}} ({{.Rack.RackType}} / {{.Rack.Depth}} / {{.Rack.HeightUnits}}U)

+{{if .Error}}
{{.Error}}
{{end}} +{{if .Rack.Comment}}

{{.Rack.Comment}}

{{end}} + +
+
+ +
+
+ Edit +
+ + + + + + +
+
+
+ +
+
+

Front

+ {{range .FrontSlots}} +
+ {{.Unit}} + {{if .IsStart}} +
+ {{.Device.Name}} + {{if .Device.Model}}{{.Device.Model.Manufacturer}} {{.Device.Model.Name}} ({{.Height}}U){{end}} + {{if .Device.UsageDescription}}{{.Device.UsageDescription}}{{end}} +
+ {{end}} +
+ {{end}} +
+
+

Back

+ {{range .BackSlots}} +
+ {{.Unit}} + {{if .IsStart}} +
+ {{.Device.Name}} + {{if .Device.Model}}{{.Device.Model.Manufacturer}} {{.Device.Model.Name}} ({{.Height}}U){{end}} +
+ {{end}} +
+ {{end}} +
+
+ +

Devices & Ports

+{{range .RackedDevices}} +
+

+ {{.Name}} + {{if .Model}}({{.Model.Manufacturer}} {{.Model.Name}}){{end}} + — U{{.RackUnitStart}} {{.RackSide}} +
+ +
+

+ {{template "port_list" dict "Device" . "Connections" $.Connections}} +
+{{end}} + +{{if .UnrackedDevices}} +

Unplaced Devices in Rack

+{{range .UnrackedDevices}} +
+

+ {{.Name}} + {{if .Model}}({{.Model.Manufacturer}} {{.Model.Name}}){{end}} +
+ +
+

+ {{template "port_list" dict "Device" . "Connections" $.Connections}} +
+{{end}} +{{end}} + +
+Add Device to Rack +
+
+ + + + + +
+
+
+
+ + + +
+
+
+{{end}} + +{{define "port_list"}} +
+
+
Front
+ {{range .Device.Ports}}{{if eq .Side "front"}} + {{$pid := .ID}} + + {{.Name}} + + {{end}}{{end}} +
+
+
Back
+ {{range .Device.Ports}}{{if eq .Side "back"}} + {{$pid := .ID}} + + {{.Name}} + + {{end}}{{end}} +
+
+{{end}} diff --git a/templates/wall_sockets.html b/templates/wall_sockets.html new file mode 100644 index 0000000..2229041 --- /dev/null +++ b/templates/wall_sockets.html @@ -0,0 +1,51 @@ +{{define "content"}} +

Wall Sockets

+{{if .Error}}
{{.Error}}
{{end}} + + + + +{{range .Sockets}} + + + + + + + + +{{end}} + +
NameLocationModelCommentPorts
{{.Name}}{{.Location}}{{if .Model}}{{.Model.Name}}{{end}}{{.Comment}} + {{range .Ports}} + + {{.Name}} + + {{end}} + +
+ +
+
+ +
+Add Wall Socket +
+ + + + + +
+
+{{end}} diff --git a/uploads/.gitkeep b/uploads/.gitkeep new file mode 100644 index 0000000..e69de29