From 681a2e1e6d9a9467585dfc067cee47c447d84047 Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Thu, 21 May 2026 20:45:58 -0700 Subject: [PATCH] added access control --- internal/db/db.go | 115 ++++++- internal/db/items.go | 135 ++++---- internal/db/locations.go | 163 +++++---- internal/db/schema.sql | 2 + internal/server/handlers.go | 418 +++++++++++++++++++---- internal/server/server.go | 8 + internal/server/static/css/styles.css | 405 ++++++++++++++++++++++ internal/server/static/js/main.js | 139 ++++++++ internal/server/templates.go | 1 + internal/server/templates/base.html | 22 +- internal/server/templates/items.html | 59 +++- internal/server/templates/locations.html | 4 +- internal/slug/slug.go | 16 + schema.sql | 2 + 14 files changed, 1283 insertions(+), 206 deletions(-) diff --git a/internal/db/db.go b/internal/db/db.go index 7d88199..6114d42 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" + "Solis/internal/slug" + _ "modernc.org/sqlite" ) @@ -79,6 +81,115 @@ func migrate(conn *sql.DB) error { } } + // Ensure slug column exists in locations table (for existing databases) + { + rows, err := conn.Query("PRAGMA table_info(locations)") + if err != nil { + return fmt.Errorf("pragma table_info for locations: %w", err) + } + hasSlug := false + for rows.Next() { + var cid int + var name, ctype string + var notnull, pk int + var dfltValue interface{} + if err := rows.Scan(&cid, &name, &ctype, ¬null, &dfltValue, &pk); err != nil { + rows.Close() + return fmt.Errorf("scanning table_info for locations: %w", err) + } + if name == "slug" { + hasSlug = true + } + } + rows.Close() + + if !hasSlug { + if _, err := conn.Exec("ALTER TABLE locations ADD COLUMN slug TEXT NOT NULL DEFAULT ''"); err != nil { + return fmt.Errorf("adding slug column to locations: %w", err) + } + if _, err := conn.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_locations_slug ON locations(slug)"); err != nil { + return fmt.Errorf("creating index idx_locations_slug: %w", err) + } + } + } + + // Populate empty location slugs + { + rows, err := conn.Query("SELECT id, name FROM locations WHERE slug = '' OR slug IS NULL") + if err != nil { + return fmt.Errorf("querying locations with empty slugs: %w", err) + } + type locSlugUpdate struct { + id int64 + name string + } + var updates []locSlugUpdate + for rows.Next() { + var u locSlugUpdate + if err := rows.Scan(&u.id, &u.name); err == nil { + updates = append(updates, u) + } + } + rows.Close() + + for _, u := range updates { + slugVal := slug.Slugify(u.name) + uniqueSlug := slugVal + index := 1 + for { + var count int + err := conn.QueryRow("SELECT COUNT(*) FROM locations WHERE slug = ? AND id != ?", uniqueSlug, u.id).Scan(&count) + if err != nil { + return fmt.Errorf("checking slug uniqueness in migration: %w", err) + } + if count == 0 { + break + } + uniqueSlug = fmt.Sprintf("%s-%d", slugVal, index) + index++ + } + _, err = conn.Exec("UPDATE locations SET slug = ? WHERE id = ?", uniqueSlug, u.id) + if err != nil { + return fmt.Errorf("updating location slug in migration: %w", err) + } + } + } + + // Upgrade existing shortlinks with target `/admin?view=X` to `/{location_slug}/{item_slug}` + { + linkRows, err := conn.Query("SELECT id, url, item_id, slug FROM links WHERE url LIKE '/admin?view=%' AND item_id IS NOT NULL") + if err == nil { + type linkUpgrade struct { + id int64 + slug string + itemID int64 + } + var linkUpdates []linkUpgrade + for linkRows.Next() { + var l linkUpgrade + var rawURL string + if err := linkRows.Scan(&l.id, &rawURL, &l.itemID, &l.slug); err == nil { + linkUpdates = append(linkUpdates, l) + } + } + linkRows.Close() + + for _, l := range linkUpdates { + var locSlug string + err = conn.QueryRow(` + SELECT COALESCE(l.slug, '') + FROM items i + LEFT JOIN locations l ON i.location_id = l.id + WHERE i.id = ?`, l.itemID).Scan(&locSlug) + if err != nil || locSlug == "" { + locSlug = "default-room" + } + newURL := fmt.Sprintf("/%s/%s", locSlug, l.slug) + _, _ = conn.Exec("UPDATE links SET url = ? WHERE id = ?", newURL, l.id) + } + } + } + // Check if locations count is 0 var count int err = conn.QueryRow("SELECT COUNT(*) FROM locations").Scan(&count) @@ -87,8 +198,8 @@ func migrate(conn *sql.DB) error { } if count == 0 { - // Create the default room with explicit ID 1 - _, err = conn.Exec("INSERT INTO locations (id, name, description) VALUES (1, 'Default Room', 'Default Room for unassigned items')") + // Create the default room with explicit ID 1 and slug 'default-room' + _, err = conn.Exec("INSERT INTO locations (id, name, slug, description) VALUES (1, 'Default Room', 'default-room', 'Default Room for unassigned items')") if err != nil { return fmt.Errorf("inserting default room: %w", err) } diff --git a/internal/db/items.go b/internal/db/items.go index ae36512..a1fb8cf 100644 --- a/internal/db/items.go +++ b/internal/db/items.go @@ -28,6 +28,7 @@ type Item struct { UpdatedAt time.Time Tags []Tag // Loaded on demand ShortSlug string // Generated or loaded short URL slug + LocationSlug sql.NullString // Slug of assigned location } func (d *DB) CreateItem(item *Item, tagIDs []int64) (*Item, error) { @@ -87,7 +88,7 @@ func (d *DB) GetItem(id int64) (*Item, error) { i.id, i.name, i.description, i.quantity, i.model_number, i.serial_number, i.status, i.location_id, l.name AS location_name, i.purchase_price, i.purchase_date, i.warranty_months, i.supplier, i.custom_fields, i.image_path, i.receipt_path, i.created_at, i.updated_at, - COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state + COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state, l.slug AS location_slug FROM items i LEFT JOIN locations l ON i.location_id = l.id LEFT JOIN links lk ON lk.item_id = i.id @@ -182,7 +183,7 @@ func (d *DB) ListItems(showRemoved bool) ([]Item, error) { i.id, i.name, i.description, i.quantity, i.model_number, i.serial_number, i.status, i.location_id, l.name AS location_name, i.purchase_price, i.purchase_date, i.warranty_months, i.supplier, i.custom_fields, i.image_path, i.receipt_path, i.created_at, i.updated_at, - COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state + COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state, l.slug AS location_slug FROM items i LEFT JOIN locations l ON i.location_id = l.id LEFT JOIN links lk ON lk.item_id = i.id @@ -201,33 +202,12 @@ func (d *DB) ListItems(showRemoved bool) ([]Item, error) { var items []Item var itemIDs []int64 for rows.Next() { - var i Item - var created, updated string - var locID sql.NullInt64 - var locName sql.NullString - var price sql.NullFloat64 - var date sql.NullString - var warranty sql.NullInt64 - - err := rows.Scan( - &i.ID, &i.Name, &i.Description, &i.Quantity, &i.ModelNumber, &i.SerialNumber, &i.Status, - &locID, &locName, &price, &date, &warranty, &i.Supplier, &i.CustomFields, &i.ImagePath, - &i.ReceiptPath, &created, &updated, &i.ShortSlug, &i.LifecycleState, - ) + item, err := scanItem(rows) if err != nil { return nil, err } - - i.LocationID = locID - i.LocationName = locName - i.PurchasePrice = price - i.PurchaseDate = date - i.WarrantyMonths = warranty - i.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) - i.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated) - - items = append(items, i) - itemIDs = append(itemIDs, i.ID) + items = append(items, *item) + itemIDs = append(itemIDs, item.ID) } if len(items) == 0 { @@ -329,11 +309,12 @@ func scanItem(row interface { var price sql.NullFloat64 var date sql.NullString var warranty sql.NullInt64 + var locSlug sql.NullString err := row.Scan( &i.ID, &i.Name, &i.Description, &i.Quantity, &i.ModelNumber, &i.SerialNumber, &i.Status, &locID, &locName, &price, &date, &warranty, &i.Supplier, &i.CustomFields, &i.ImagePath, - &i.ReceiptPath, &created, &updated, &i.ShortSlug, &i.LifecycleState, + &i.ReceiptPath, &created, &updated, &i.ShortSlug, &i.LifecycleState, &locSlug, ) if err != nil { return nil, err @@ -344,6 +325,7 @@ func scanItem(row interface { i.PurchasePrice = price i.PurchaseDate = date i.WarrantyMonths = warranty + i.LocationSlug = locSlug i.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) i.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated) @@ -351,38 +333,7 @@ func scanItem(row interface { } func (d *DB) arrangeTags(roomName string, tags []Tag) []Tag { - if roomName == "" { - return tags - } - - var roomTag *Tag - var otherTags []Tag - - for i, t := range tags { - if t.Name == roomName { - roomTag = &tags[i] - } else { - otherTags = append(otherTags, t) - } - } - - if roomTag == nil { - // Room tag was not in the loaded tags, let's fetch it from db - row := d.Conn.QueryRow("SELECT id, name, color, description FROM tags WHERE name = ?", roomName) - var t Tag - if err := row.Scan(&t.ID, &t.Name, &t.Color, &t.Description); err == nil { - roomTag = &t - } else { - // fallback: construct a temporary Tag - roomTag = &Tag{ - Name: roomName, - Color: "#f59e0b", - } - } - } - - // Prepend roomTag - return append([]Tag{*roomTag}, otherTags...) + return tags } // GetLastUsedLocationID returns the location ID of the most recently created/added item. @@ -398,3 +349,69 @@ func (d *DB) GetLastUsedLocationID() (int64, error) { } return locID, nil } + +func (d *DB) ListItemsByLocation(locID int64, showRemoved bool) ([]Item, error) { + query := ` + SELECT + i.id, i.name, i.description, i.quantity, i.model_number, i.serial_number, i.status, + i.location_id, l.name AS location_name, i.purchase_price, i.purchase_date, i.warranty_months, + i.supplier, i.custom_fields, i.image_path, i.receipt_path, i.created_at, i.updated_at, + COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state, l.slug AS location_slug + FROM items i + LEFT JOIN locations l ON i.location_id = l.id + LEFT JOIN links lk ON lk.item_id = i.id + WHERE i.location_id = ? + ` + if !showRemoved { + query += " AND i.lifecycle_state != 'removed'" + } + query += " ORDER BY CASE i.lifecycle_state WHEN 'archived' THEN 1 WHEN 'removed' THEN 2 ELSE 0 END, i.id DESC" + + rows, err := d.Conn.Query(query, locID) + if err != nil { + return nil, err + } + defer rows.Close() + + var items []Item + var itemIDs []int64 + for rows.Next() { + item, err := scanItem(rows) + if err != nil { + return nil, err + } + items = append(items, *item) + itemIDs = append(itemIDs, item.ID) + } + + if len(items) == 0 { + return items, nil + } + + // Bulk load tags to avoid N+1 queries + tagMap, err := d.getBulkItemTags(itemIDs) + if err != nil { + return nil, err + } + + // Map tags to items + for idx, item := range items { + locNameStr := "" + if item.LocationName.Valid { + locNameStr = item.LocationName.String + } + if tags, exists := tagMap[item.ID]; exists { + items[idx].Tags = d.arrangeTags(locNameStr, tags) + } else { + items[idx].Tags = d.arrangeTags(locNameStr, []Tag{}) + } + } + + return items, nil +} + +func (d *DB) MoveItemLocation(itemID, newLocID int64) error { + _, err := d.Conn.Exec("UPDATE items SET location_id = ?, updated_at = datetime('now') WHERE id = ?", newLocID, itemID) + return err +} + diff --git a/internal/db/locations.go b/internal/db/locations.go index a99a62e..31297c8 100644 --- a/internal/db/locations.go +++ b/internal/db/locations.go @@ -4,11 +4,14 @@ import ( "database/sql" "fmt" "time" + + "Solis/internal/slug" ) type Location struct { ID int64 Name string + Slug string Description string ParentID sql.NullInt64 ParentName sql.NullString // Resolved parent location name @@ -25,28 +28,31 @@ func (d *DB) CreateLocation(name, description string, parentID sql.NullInt64, im } defer tx.Rollback() + slugVal := slug.Slugify(name) + uniqueSlug := slugVal + index := 1 + for { + var count int + err := tx.QueryRow("SELECT COUNT(*) FROM locations WHERE slug = ?", uniqueSlug).Scan(&count) + if err != nil { + return nil, err + } + if count == 0 { + break + } + uniqueSlug = fmt.Sprintf("%s-%d", slugVal, index) + index++ + } + res, err := tx.Exec( - "INSERT INTO locations (name, description, parent_id, image_path) VALUES (?, ?, ?, ?)", - name, description, parentID, imagePath, + "INSERT INTO locations (name, slug, description, parent_id, image_path) VALUES (?, ?, ?, ?, ?)", + name, uniqueSlug, description, parentID, imagePath, ) if err != nil { return nil, err } id, _ := res.LastInsertId() - // Automatically create a corresponding tag for the new location if it doesn't exist - var tagID int64 - err = tx.QueryRow("SELECT id FROM tags WHERE name = ?", name).Scan(&tagID) - if err != nil { - _, err = tx.Exec( - "INSERT INTO tags (name, color, description) VALUES (?, '#f59e0b', ?)", - name, "Tag representing location: "+name, - ) - if err != nil { - return nil, err - } - } - if err := tx.Commit(); err != nil { return nil, err } @@ -54,6 +60,7 @@ func (d *DB) CreateLocation(name, description string, parentID sql.NullInt64, im return &Location{ ID: id, Name: name, + Slug: uniqueSlug, Description: description, ParentID: parentID, ImagePath: imagePath, @@ -64,7 +71,7 @@ func (d *DB) CreateLocation(name, description string, parentID sql.NullInt64, im func (d *DB) GetLocation(id int64) (*Location, error) { row := d.Conn.QueryRow(` - SELECT l.id, l.name, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.lifecycle_state, l.created_at, l.updated_at + SELECT l.id, l.name, l.slug, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.lifecycle_state, l.created_at, l.updated_at FROM locations l LEFT JOIN locations p ON l.parent_id = p.id WHERE l.id = ?`, @@ -73,6 +80,17 @@ func (d *DB) GetLocation(id int64) (*Location, error) { return scanLocation(row) } +func (d *DB) GetLocationBySlug(slug string) (*Location, error) { + row := d.Conn.QueryRow(` + SELECT l.id, l.name, l.slug, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.lifecycle_state, l.created_at, l.updated_at + FROM locations l + LEFT JOIN locations p ON l.parent_id = p.id + WHERE l.slug = ?`, + slug, + ) + return scanLocation(row) +} + func (d *DB) UpdateLocation(id int64, name, description string, parentID sql.NullInt64, imagePath string) error { if id == 1 && name != "Default Room" { return fmt.Errorf("cannot rename the Default Room") @@ -90,17 +108,30 @@ func (d *DB) UpdateLocation(id int64, name, description string, parentID sql.Nul return err } + slugVal := slug.Slugify(name) + uniqueSlug := slugVal + index := 1 + for { + var count int + err := tx.QueryRow("SELECT COUNT(*) FROM locations WHERE slug = ? AND id != ?", uniqueSlug, id).Scan(&count) + if err != nil { + return err + } + if count == 0 { + break + } + uniqueSlug = fmt.Sprintf("%s-%d", slugVal, index) + index++ + } + _, err = tx.Exec( - "UPDATE locations SET name = ?, description = ?, parent_id = ?, image_path = ?, updated_at = datetime('now') WHERE id = ?", - name, description, parentID, imagePath, id, + "UPDATE locations SET name = ?, slug = ?, description = ?, parent_id = ?, image_path = ?, updated_at = datetime('now') WHERE id = ?", + name, uniqueSlug, description, parentID, imagePath, id, ) if err != nil { return err } - // Update the tag name as well - _, _ = tx.Exec("UPDATE tags SET name = ? WHERE name = ?", name, oldName) - return tx.Commit() } @@ -115,51 +146,12 @@ func (d *DB) DeleteLocation(id int64) error { } defer tx.Rollback() - // Get location name to delete the tag as well - var name string - err = tx.QueryRow("SELECT name FROM locations WHERE id = ?", id).Scan(&name) - if err != nil { - if err == sql.ErrNoRows { - return nil // already deleted - } - return err - } - // Move items in this location to Default Room (ID = 1) _, err = tx.Exec("UPDATE items SET location_id = 1 WHERE location_id = ?", id) if err != nil { return err } - // Get the Default Room tag ID - var defaultTagID int64 - _ = tx.QueryRow("SELECT id FROM tags WHERE name = 'Default Room'").Scan(&defaultTagID) - - if defaultTagID > 0 { - // Fetch all items that were just moved to Default Room (ID = 1) and insert Default Room tag reference - rows, err := tx.Query("SELECT id FROM items WHERE location_id = 1") - if err == nil { - var movedItemIDs []int64 - for rows.Next() { - var mid int64 - if err := rows.Scan(&mid); err == nil { - movedItemIDs = append(movedItemIDs, mid) - } - } - rows.Close() - for _, mid := range movedItemIDs { - _, _ = tx.Exec("INSERT OR IGNORE INTO item_tags (item_id, tag_id) VALUES (?, ?)", mid, defaultTagID) - } - } - } - - // Delete the tag representing this location - var tagID int64 - err = tx.QueryRow("SELECT id FROM tags WHERE name = ?", name).Scan(&tagID) - if err == nil && name != "Default Room" { - _, _ = tx.Exec("DELETE FROM tags WHERE id = ?", tagID) - } - // Set parent references to NULL _, err = tx.Exec("UPDATE locations SET parent_id = NULL WHERE parent_id = ?", id) if err != nil { @@ -198,7 +190,7 @@ func (d *DB) RestoreLocation(id int64) error { func (d *DB) ListLocations(showRemoved bool) ([]Location, error) { query := ` - SELECT l.id, l.name, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.lifecycle_state, l.created_at, l.updated_at + SELECT l.id, l.name, l.slug, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.lifecycle_state, l.created_at, l.updated_at FROM locations l LEFT JOIN locations p ON l.parent_id = p.id` if !showRemoved { @@ -218,7 +210,7 @@ func (d *DB) ListLocations(showRemoved bool) ([]Location, error) { var parentID sql.NullInt64 var parentName sql.NullString var created, updated string - if err := rows.Scan(&l.ID, &l.Name, &l.Description, &parentID, &parentName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { + if err := rows.Scan(&l.ID, &l.Name, &l.Slug, &l.Description, &parentID, &parentName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { return nil, err } l.ParentID = parentID @@ -230,6 +222,41 @@ func (d *DB) ListLocations(showRemoved bool) ([]Location, error) { return locations, rows.Err() } +func (d *DB) ListChildLocations(parentID int64, showRemoved bool) ([]Location, error) { + query := ` + SELECT l.id, l.name, l.slug, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.lifecycle_state, l.created_at, l.updated_at + FROM locations l + LEFT JOIN locations p ON l.parent_id = p.id + WHERE l.parent_id = ?` + if !showRemoved { + query += " AND l.lifecycle_state != 'removed'" + } + query += " ORDER BY CASE l.lifecycle_state WHEN 'archived' THEN 1 WHEN 'removed' THEN 2 ELSE 0 END, l.name ASC" + + rows, err := d.Conn.Query(query, parentID) + if err != nil { + return nil, err + } + defer rows.Close() + + var locations []Location + for rows.Next() { + var l Location + var pID sql.NullInt64 + var pName sql.NullString + var created, updated string + if err := rows.Scan(&l.ID, &l.Name, &l.Slug, &l.Description, &pID, &pName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { + return nil, err + } + l.ParentID = pID + l.ParentName = pName + l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) + l.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated) + locations = append(locations, l) + } + return locations, nil +} + func scanLocation(row interface { Scan(dest ...any) error }) (*Location, error) { @@ -237,7 +264,7 @@ func scanLocation(row interface { var parentID sql.NullInt64 var parentName sql.NullString var created, updated string - if err := row.Scan(&l.ID, &l.Name, &l.Description, &parentID, &parentName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { + if err := row.Scan(&l.ID, &l.Name, &l.Slug, &l.Description, &parentID, &parentName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { return nil, err } l.ParentID = parentID @@ -246,3 +273,13 @@ func scanLocation(row interface { l.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated) return &l, nil } + +func (d *DB) MoveLocationParent(locID, newParentID int64) error { + var pID sql.NullInt64 + if newParentID > 0 { + pID = sql.NullInt64{Int64: newParentID, Valid: true} + } + _, err := d.Conn.Exec("UPDATE locations SET parent_id = ?, updated_at = datetime('now') WHERE id = ?", pID, locID) + return err +} + diff --git a/internal/db/schema.sql b/internal/db/schema.sql index c70146e..e67dea0 100644 --- a/internal/db/schema.sql +++ b/internal/db/schema.sql @@ -5,6 +5,7 @@ CREATE TABLE IF NOT EXISTS locations ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, + slug TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, image_path TEXT NOT NULL DEFAULT '', @@ -14,6 +15,7 @@ CREATE TABLE IF NOT EXISTS locations ( ); CREATE INDEX IF NOT EXISTS idx_locations_parent ON locations(parent_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_locations_slug ON locations(slug); -- 2. Tags Table (Sleek labels for grouping items) CREATE TABLE IF NOT EXISTS tags ( diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 4ffff5d..e88eb54 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -44,11 +44,17 @@ type PageData struct { SearchQuery string SelectedStatus string SelectedLocation int64 + SelectedTag int64 CatalogJSON string SlugLength int ShowRemoved bool + IsAuthenticated bool + CurrentLocation *db.Location + Breadcrumbs []db.Location + ChildLocations []db.Location } + // ========================================== // 1. PUBLIC SHORT URL REDIRECT HANDLER // ========================================== @@ -93,7 +99,7 @@ func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) { data := PageData{ CSRFToken: csrfToken(w, r), } - renderTemplate(w, "login.html", data) + s.render(w, r, "login.html", data) } func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { @@ -104,7 +110,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { Error: "Too many login attempts. Please wait.", } w.WriteHeader(http.StatusTooManyRequests) - renderTemplate(w, "login.html", data) + s.render(w, r, "login.html", data) return } @@ -143,7 +149,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { CSRFToken: csrfToken(w, r), Error: "Invalid username or password.", } - renderTemplate(w, "login.html", data) + s.render(w, r, "login.html", data) } func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { @@ -174,30 +180,39 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { locations, _ := s.db.ListLocations(showRemoved) tags, _ := s.db.ListTags(showRemoved) - // 1. DETAIL VIEW MODE + // 1. DETAIL VIEW MODE (Upgrade / Redirect to clean URL format) if viewIDStr := r.URL.Query().Get("view"); viewIDStr != "" { id, err := strconv.ParseInt(viewIDStr, 10, 64) if err == nil { item, err := s.db.GetItem(id) if err == nil { - // Decode JSON custom fields - var cfMap map[string]string - _ = json.Unmarshal([]byte(item.CustomFields), &cfMap) + var locSlug string + if item.LocationID.Valid { + loc, err := s.db.GetLocation(item.LocationID.Int64) + if err == nil { + locSlug = loc.Slug + } + } + if locSlug == "" { + locSlug = "default-room" + } - data := PageData{ - CSRFToken: csrf, - ActiveNav: "items", - Item: item, - ViewMode: true, - CustomFieldsMap: cfMap, - Locations: locations, - Tags: tags, - ShowRemoved: showRemoved, - Toast: r.URL.Query().Get("toast"), - ToastType: r.URL.Query().Get("toast_type"), + var itemSlug string + link, err := s.db.GetLinkByItemID(item.ID) + if err == nil { + itemSlug = link.Slug + } else { + itemSlug, _ = slug.GenerateItemSlug(item.ID, s.cfg.Slugs.Length, s.db.Conn) + if itemSlug != "" { + newURL := fmt.Sprintf("/%s/%s", locSlug, itemSlug) + _, _ = s.db.CreateLink(itemSlug, newURL, "admin", sql.NullInt64{Int64: item.ID, Valid: true}) + } + } + + if itemSlug != "" { + http.Redirect(w, r, fmt.Sprintf("/%s/%s?%s", locSlug, itemSlug, r.URL.RawQuery), http.StatusMovedPermanently) + return } - renderTemplate(w, "items.html", data) - return } } } @@ -206,6 +221,7 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { searchQuery := r.URL.Query().Get("search") statusQuery := r.URL.Query().Get("status") locationQuery := r.URL.Query().Get("location") + tagQuery := r.URL.Query().Get("tag") allItems, err := s.db.ListItems(showRemoved) if err != nil { @@ -220,6 +236,11 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { locFilterID, _ = strconv.ParseInt(locationQuery, 10, 64) } + var tagFilterID int64 + if tagQuery != "" { + tagFilterID, _ = strconv.ParseInt(tagQuery, 10, 64) + } + for _, item := range allItems { matchesSearch := searchQuery == "" || strings.Contains(strings.ToLower(item.Name), strings.ToLower(searchQuery)) || @@ -230,7 +251,18 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { matchesLocation := locationQuery == "" || (item.LocationID.Valid && item.LocationID.Int64 == locFilterID) - if matchesSearch && matchesStatus && matchesLocation { + matchesTag := true + if tagFilterID > 0 { + matchesTag = false + for _, t := range item.Tags { + if t.ID == tagFilterID { + matchesTag = true + break + } + } + } + + if matchesSearch && matchesStatus && matchesLocation && matchesTag { filteredItems = append(filteredItems, item) } } @@ -244,12 +276,13 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { SearchQuery: searchQuery, SelectedStatus: statusQuery, SelectedLocation: locFilterID, + SelectedTag: tagFilterID, ShowRemoved: showRemoved, Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } - renderTemplate(w, "items.html", data) + s.render(w, r, "items.html", data) } func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) { @@ -269,7 +302,7 @@ func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) { FormMode: true, CatalogJSON: string(catalogJSON), } - renderTemplate(w, "items.html", data) + s.render(w, r, "items.html", data) } func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { @@ -343,12 +376,8 @@ func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { return } - // 6. Generate collision-resistant short slug (using Glimmer SHA-256 slug engine) - slugVal, err := slug.GenerateItemSlug(createdItem.ID, s.cfg.Slugs.Length, s.db.Conn) - if err == nil && slugVal != "" { - targetURL := fmt.Sprintf("/admin?view=%d", createdItem.ID) - _, _ = s.db.CreateLink(slugVal, targetURL, "admin", sql.NullInt64{Int64: createdItem.ID, Valid: true}) - } + // 6. Automatically generate and sync short link target as /{location_slug}/{item_slug} + s.syncItemShortlink(createdItem.ID, lastLocID) // 7. Redirect straight to the Edit page so the user can modify any further details http.Redirect(w, r, fmt.Sprintf("/admin/items/edit/%d?toast=Asset+created+successfully!+You+can+refine+its+details+below.&toast_type=success", createdItem.ID), http.StatusSeeOther) @@ -430,13 +459,8 @@ func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { return } - // AUTOMATICALLY GENERATE A SHORT LINK (Glimmer SHA-256 collision-resistant port) - slugVal, err := slug.GenerateItemSlug(createdItem.ID, s.cfg.Slugs.Length, s.db.Conn) - if err == nil && slugVal != "" { - // Target is the internal details view of this asset - targetURL := fmt.Sprintf("/admin?view=%d", createdItem.ID) - _, _ = s.db.CreateLink(slugVal, targetURL, "admin", sql.NullInt64{Int64: createdItem.ID, Valid: true}) - } + // AUTOMATICALLY GENERATE & SYNC A SHORT LINK + s.syncItemShortlink(createdItem.ID, locID.Int64) http.Redirect(w, r, "/admin?toast=Asset+created+successfully&toast_type=success", http.StatusSeeOther) } @@ -469,7 +493,7 @@ func (s *Server) handleItemEdit(w http.ResponseWriter, r *http.Request) { CustomFieldsRaw: customFieldsRaw, FormMode: true, } - renderTemplate(w, "items.html", data) + s.render(w, r, "items.html", data) } func (s *Server) handleItemSave(w http.ResponseWriter, r *http.Request) { @@ -573,7 +597,27 @@ func (s *Server) handleItemSave(w http.ResponseWriter, r *http.Request) { return } - http.Redirect(w, r, fmt.Sprintf("/admin?view=%d&toast=Asset+updated+successfully&toast_type=success", item.ID), http.StatusSeeOther) + s.syncItemShortlink(item.ID, item.LocationID.Int64) + + var locSlug string + if item.LocationID.Valid { + loc, err := s.db.GetLocation(item.LocationID.Int64) + if err == nil { + locSlug = loc.Slug + } + } + if locSlug == "" { + locSlug = "default-room" + } + var itemSlug string + link, err := s.db.GetLinkByItemID(item.ID) + if err == nil { + itemSlug = link.Slug + } else { + itemSlug = fmt.Sprintf("%d", item.ID) + } + + http.Redirect(w, r, fmt.Sprintf("/%s/%s?toast=Asset+updated+successfully&toast_type=success", locSlug, itemSlug), http.StatusSeeOther) } func (s *Server) handleItemRemove(w http.ResponseWriter, r *http.Request) { @@ -657,7 +701,7 @@ func (s *Server) handleAdminLocations(w http.ResponseWriter, r *http.Request) { Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } - renderTemplate(w, "locations.html", data) + s.render(w, r, "locations.html", data) } func (s *Server) handleLocationCreate(w http.ResponseWriter, r *http.Request) { @@ -769,7 +813,7 @@ func (s *Server) handleAdminTags(w http.ResponseWriter, r *http.Request) { Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } - renderTemplate(w, "tags.html", data) + s.render(w, r, "tags.html", data) } func (s *Server) handleTagCreate(w http.ResponseWriter, r *http.Request) { @@ -880,7 +924,7 @@ func (s *Server) handleAdminShortener(w http.ResponseWriter, r *http.Request) { Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } - renderTemplate(w, "shortener.html", data) + s.render(w, r, "shortener.html", data) } func (s *Server) handleLinkCreate(w http.ResponseWriter, r *http.Request) { @@ -1040,7 +1084,7 @@ func (s *Server) handlePrintLabels(w http.ResponseWriter, r *http.Request) { ActiveNav: "print", Items: items, } - renderTemplate(w, "print_labels.html", data) + s.render(w, r, "print_labels.html", data) } // ========================================== @@ -1151,29 +1195,283 @@ func formatCustomFields(jsonStr string) string { } func (s *Server) resolveRoomTag(locationID int64, tagIDs []int64) []int64 { - var roomName string - err := s.db.Conn.QueryRow("SELECT name FROM locations WHERE id = ?", locationID).Scan(&roomName) - if err != nil { - roomName = "Default Room" + return tagIDs +} + +// render automatically injects IsAuthenticated based on the session token +func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, data PageData) { + cookie, err := r.Cookie("session") + data.IsAuthenticated = (err == nil && s.sessions.Valid(cookie.Value)) + if err := renderTemplate(w, name, data); err != nil { + log.Printf("Template execution error for %s: %v", name, err) + http.Error(w, "Template execution error", http.StatusInternalServerError) } - var roomTagID int64 - err = s.db.Conn.QueryRow("SELECT id FROM tags WHERE name = ?", roomName).Scan(&roomTagID) - if err != nil { - // Try falling back to Default Room tag - _ = s.db.Conn.QueryRow("SELECT id FROM tags WHERE name = 'Default Room'").Scan(&roomTagID) +} + +// syncItemShortlink automatically synchronizes the shortlink URL target as /{location_slug}/{item_slug} +func (s *Server) syncItemShortlink(itemID int64, locID int64) { + var locSlug string + loc, err := s.db.GetLocation(locID) + if err == nil { + locSlug = loc.Slug + } else { + locSlug = "default-room" } - // If we still don't have a valid tag ID, return the original tagIDs unchanged - if roomTagID == 0 { - return tagIDs + link, err := s.db.GetLinkByItemID(itemID) + if err != nil { + if err == sql.ErrNoRows { + // Generate clean, collision-resistant slug + slugVal, err := slug.GenerateItemSlug(itemID, s.cfg.Slugs.Length, s.db.Conn) + if err == nil && slugVal != "" { + newURL := fmt.Sprintf("/%s/%s", locSlug, slugVal) + _, _ = s.db.CreateLink(slugVal, newURL, "admin", sql.NullInt64{Int64: itemID, Valid: true}) + } + } + return } - // Build a deduplicated list with roomTagID first - dedupTagIDs := []int64{roomTagID} - for _, tid := range tagIDs { - if tid != roomTagID && tid != 0 { - dedupTagIDs = append(dedupTagIDs, tid) + newURL := fmt.Sprintf("/%s/%s", locSlug, link.Slug) + _ = s.db.UpdateLink(link.ID, link.Slug, newURL) +} + +// isDescendantOf recursively checks if a location is a child/descendant of another to prevent cyclic nesting loops +func (s *Server) isDescendantOf(parentID, childID int64) bool { + if parentID == childID { + return true + } + child, err := s.db.GetLocation(childID) + if err != nil || !child.ParentID.Valid { + return false + } + return s.isDescendantOf(parentID, child.ParentID.Int64) +} + +func (s *Server) handlePublicFallback(w http.ResponseWriter, r *http.Request) { + path := r.PathValue("path") + path = strings.Trim(path, "/") + if path == "" { + http.Redirect(w, r, "/admin", http.StatusSeeOther) + return + } + + parts := strings.Split(path, "/") + if len(parts) == 1 { + r.SetPathValue("location_slug", parts[0]) + s.handleFolderView(w, r) + return + } else if len(parts) == 2 { + r.SetPathValue("location_slug", parts[0]) + r.SetPathValue("item_slug", parts[1]) + s.handlePublicItemView(w, r) + return + } + + http.NotFound(w, r) +} + +func (s *Server) handleFolderView(w http.ResponseWriter, r *http.Request) { + slugVal := r.PathValue("location_slug") + if slugVal == "" { + http.NotFound(w, r) + return + } + slugVal = strings.ToLower(slugVal) + + loc, err := s.db.GetLocationBySlug(slugVal) + if err != nil { + if err == sql.ErrNoRows { + http.NotFound(w, r) + return + } + http.Error(w, "Database error", http.StatusInternalServerError) + return + } + + cookie, err := r.Cookie("session") + isAuth := (err == nil && s.sessions.Valid(cookie.Value)) + + var childLocs []db.Location + var items []db.Item + var breadcrumbs []db.Location + var showRemoved bool + var allLocations []db.Location + + if isAuth { + showRemoved = r.URL.Query().Get("show_removed") == "1" + + childLocs, err = s.db.ListChildLocations(loc.ID, showRemoved) + if err != nil { + childLocs = []db.Location{} + } + + items, err = s.db.ListItemsByLocation(loc.ID, showRemoved) + if err != nil { + items = []db.Item{} + } + + // Build breadcrumbs recursively to the root (parentID = null) + current := loc + for { + breadcrumbs = append([]db.Location{*current}, breadcrumbs...) + if !current.ParentID.Valid { + break + } + parent, err := s.db.GetLocation(current.ParentID.Int64) + if err != nil { + break + } + current = parent + } + + allLocations, _ = s.db.ListLocations(false) + } else { + // Guest user: return empty lists, hide folder structures and breadcrumbs + childLocs = []db.Location{} + items = []db.Item{} + breadcrumbs = []db.Location{} + allLocations = []db.Location{} + showRemoved = false + } + + data := PageData{ + CSRFToken: csrfToken(w, r), + ActiveNav: "locations", + CurrentLocation: loc, + ChildLocations: childLocs, + Items: items, + Breadcrumbs: breadcrumbs, + Locations: allLocations, + ShowRemoved: showRemoved, + } + + s.render(w, r, "location_folder.html", data) +} + +func (s *Server) handlePublicItemView(w http.ResponseWriter, r *http.Request) { + locationSlug := r.PathValue("location_slug") + itemSlug := r.PathValue("item_slug") + + link, err := s.db.GetLinkBySlug(itemSlug) + if err != nil { + if err == sql.ErrNoRows { + http.NotFound(w, r) + return + } + http.Error(w, "Database error", http.StatusInternalServerError) + return + } + + if !link.ItemID.Valid { + http.NotFound(w, r) + return + } + + item, err := s.db.GetItem(link.ItemID.Int64) + if err != nil { + http.NotFound(w, r) + return + } + + var correctLocationSlug string + if item.LocationID.Valid { + loc, err := s.db.GetLocation(item.LocationID.Int64) + if err == nil { + correctLocationSlug = loc.Slug } } - return dedupTagIDs + if correctLocationSlug == "" { + correctLocationSlug = "default-room" + } + + if correctLocationSlug != locationSlug { + http.Redirect(w, r, fmt.Sprintf("/%s/%s", correctLocationSlug, itemSlug), http.StatusMovedPermanently) + return + } + + // Resolve the parent location details if available for breadcrumb fallback + var currentLoc *db.Location + if item.LocationID.Valid { + currentLoc, _ = s.db.GetLocation(item.LocationID.Int64) + } + + var cfMap map[string]string + _ = json.Unmarshal([]byte(item.CustomFields), &cfMap) + + locations, _ := s.db.ListLocations(false) + tags, _ := s.db.ListTags(false) + + data := PageData{ + CSRFToken: csrfToken(w, r), + ActiveNav: "items", + Item: item, + ViewMode: true, + CustomFieldsMap: cfMap, + Locations: locations, + Tags: tags, + CurrentLocation: currentLoc, + } + + s.render(w, r, "items.html", data) } + +func (s *Server) handleItemMove(w http.ResponseWriter, r *http.Request) { + itemIDStr := r.FormValue("item_id") + locIDStr := r.FormValue("location_id") + + itemID, err1 := strconv.ParseInt(itemIDStr, 10, 64) + locID, err2 := strconv.ParseInt(locIDStr, 10, 64) + if err1 != nil || err2 != nil { + http.Error(w, "Invalid item_id or location_id", http.StatusBadRequest) + return + } + + err := s.db.MoveItemLocation(itemID, locID) + if err != nil { + http.Error(w, "Failed to move item: "+err.Error(), http.StatusInternalServerError) + return + } + + s.syncItemShortlink(itemID, locID) + + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":"success","message":"Item moved successfully"}`)) +} + +func (s *Server) handleLocationMove(w http.ResponseWriter, r *http.Request) { + locIDStr := r.FormValue("location_id") + parentIDStr := r.FormValue("parent_id") + + locID, err1 := strconv.ParseInt(locIDStr, 10, 64) + parentID, err2 := strconv.ParseInt(parentIDStr, 10, 64) + if err1 != nil { + http.Error(w, "Invalid location_id", http.StatusBadRequest) + return + } + + if err2 != nil { + parentID = 0 + } + + if locID == parentID { + http.Error(w, "A location cannot be a parent of itself", http.StatusBadRequest) + return + } + + if parentID > 0 { + if s.isDescendantOf(locID, parentID) { + http.Error(w, "Cycle detected: cannot move a location inside its own sub-folder", http.StatusBadRequest) + return + } + } + + err := s.db.MoveLocationParent(locID, parentID) + if err != nil { + http.Error(w, "Failed to move location: "+err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":"success","message":"Location moved successfully"}`)) +} + diff --git a/internal/server/server.go b/internal/server/server.go index 1e0e84b..0f94686 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -153,6 +153,14 @@ func (s *Server) Start() error { mux.HandleFunc("GET /admin/qr/{slug}", s.requireAuth(s.handleQR)) mux.HandleFunc("GET /admin/print", s.requireAuth(s.handlePrintLabels)) + // 11. Folder & Public Item Views (Wildcards) + mux.HandleFunc("GET /{path...}", s.handlePublicFallback) + + // 12. Asynchronous move endpoints + mux.HandleFunc("POST /admin/items/move", s.requireAuth(s.requireCSRF(s.handleItemMove))) + mux.HandleFunc("POST /admin/locations/move", s.requireAuth(s.requireCSRF(s.handleLocationMove))) + + // Listen and serve addr := fmt.Sprintf(":%d", s.cfg.Server.Port) srv := &http.Server{ diff --git a/internal/server/static/css/styles.css b/internal/server/static/css/styles.css index fb86b8c..a11003a 100644 --- a/internal/server/static/css/styles.css +++ b/internal/server/static/css/styles.css @@ -705,3 +705,408 @@ tr:last-child .actions-dropdown-menu { to { opacity: 1; transform: translateY(0); } } +/* ========================================================================== + Solis Public Layout, Folder Explorer & Drag & Drop Styles + ========================================================================== */ + +/* Public Layout modifications */ +.public-layout { + flex-direction: column; +} + +.public-layout .main-wrapper { + margin-left: 0; + margin-top: 0; + padding: 2.5rem 2rem; + max-width: 1200px; + width: 100%; + align-self: center; +} + +.public-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 1rem 3.5rem; + background-color: var(--color-bg-surface); + border-bottom: 1px solid var(--color-border); + position: sticky; + top: 0; + z-index: 100; + box-shadow: var(--shadow-sm); +} + +.public-brand { + display: flex; + align-items: center; + gap: 0.75rem; +} + +/* Folder browser layouts */ +.folder-view-container { + display: flex; + flex-direction: column; + gap: 2rem; +} + +.folder-header { + border-bottom: 1px solid var(--color-border); + padding-bottom: 1.5rem; +} + +.folder-breadcrumbs { + display: flex; + align-items: center; + gap: 0.5rem; + margin-bottom: 1rem; + flex-wrap: wrap; +} + +.breadcrumb-item { + display: inline-flex; + align-items: center; + gap: 0.35rem; + color: var(--color-text-muted); + text-decoration: none; + font-weight: 600; + font-size: 0.9rem; + padding: 0.25rem 0.5rem; + border-radius: var(--radius-sm); + transition: all 0.2s ease; + border: 1px solid transparent; +} + +.breadcrumb-item:hover { + color: var(--color-brand-primary); + background-color: var(--color-brand-light); +} + +.breadcrumb-item.active { + color: var(--color-text-main); + cursor: default; + background: none; + pointer-events: none; +} + +.breadcrumb-separator { + color: var(--color-text-light); + font-weight: 500; + font-size: 0.9rem; +} + +.folder-title { + font-size: 2.25rem; + font-weight: 800; + letter-spacing: -0.03em; + color: var(--color-text-main); +} + +.folder-description { + color: var(--color-text-muted); + margin-top: 0.35rem; + font-size: 1rem; + max-width: 700px; +} + +/* Drag-and-drop active visual indicators */ +.dragging { + opacity: 0.45 !important; + transform: scale(0.96); + box-shadow: 0 12px 24px -10px rgba(217, 119, 6, 0.25) !important; + border: 2px dashed var(--color-brand-primary) !important; + transition: transform 0.15s ease, opacity 0.15s ease; +} + +.dropzone { + transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1); +} + +.dropzone.drop-active { + background-color: #fffbeb !important; + border-color: var(--color-brand-accent) !important; + box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.25), var(--shadow-lg) !important; + outline: 2px dashed var(--color-brand-primary) !important; + outline-offset: -2px !important; + transform: translateY(-2px); + animation: dropPulse 1.5s infinite ease-in-out; +} + +@keyframes dropPulse { + 0% { transform: translateY(-2px); box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.25), var(--shadow-lg); } + 50% { transform: translateY(-2px); box-shadow: 0 0 0 6px rgba(245, 158, 11, 0.4), var(--shadow-lg); } + 100% { transform: translateY(-2px); box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.25), var(--shadow-lg); } +} + +/* Move Up Drop Zone card */ +.move-up-zone { + background-color: var(--color-bg-surface); + border: 2px dashed var(--color-border); + border-radius: var(--radius-md); + padding: 1.25rem; + display: flex; + align-items: center; + justify-content: center; + gap: 0.75rem; + color: var(--color-text-muted); + font-weight: 600; + font-size: 0.95rem; + cursor: pointer; + box-shadow: var(--shadow-sm); +} + +.move-up-zone svg { + transition: transform 0.2s ease; +} + +.move-up-zone:hover svg { + transform: translateY(-3px); +} + +/* Sub-folder list grid styling */ +.directory-section { + display: flex; + flex-direction: column; + gap: 1.25rem; +} + +.section-title { + font-size: 1.25rem; + font-weight: 700; + color: var(--color-text-main); + letter-spacing: -0.01em; +} + +.folders-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 1.25rem; +} + +.folder-card { + background: linear-gradient(145deg, var(--color-bg-surface), #fbfaf8); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 1.25rem; + display: flex; + justify-content: space-between; + align-items: center; + position: relative; + box-shadow: var(--shadow-sm); + transition: all 0.25s ease; +} + +.folder-card:hover { + box-shadow: var(--shadow-md); + border-color: var(--color-border-warm); + transform: translateY(-2px); +} + +.folder-card-main { + display: flex; + align-items: center; + gap: 1rem; + flex-grow: 1; +} + +.folder-icon-wrapper { + width: 44px; + height: 44px; + background: linear-gradient(135deg, #fef3c7, #fde68a); + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + color: var(--color-brand-primary); + box-shadow: 0 4px 6px -1px rgba(217, 119, 6, 0.1); +} + +.folder-icon { + width: 24px; + height: 24px; +} + +.folder-info { + display: flex; + flex-direction: column; + gap: 0.15rem; +} + +.folder-name-link { + font-weight: 600; + color: var(--color-text-main); + text-decoration: none; + font-size: 1.05rem; + transition: color 0.2s ease; +} + +.folder-name-link:hover { + color: var(--color-brand-primary); +} + +.folder-badge { + font-size: 0.75rem; + color: var(--color-text-light); + font-weight: 500; +} + +.btn-icon { + background: none; + border: none; + color: var(--color-text-light); + cursor: pointer; + padding: 0.35rem; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.btn-icon:hover { + color: var(--color-brand-primary); + background-color: var(--color-brand-light); +} + +.empty-state-card { + background-color: var(--color-bg-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 2rem; + text-align: center; + color: var(--color-text-muted); + font-size: 0.95rem; + font-weight: 500; +} + +/* Assets grid layout */ +.items-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); + gap: 1.5rem; +} + +.item-card { + background-color: var(--color-bg-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + overflow: hidden; + display: flex; + flex-direction: column; + box-shadow: var(--shadow-sm); + transition: all 0.25s ease; + position: relative; +} + +.item-card:hover { + box-shadow: var(--shadow-lg); + border-color: var(--color-border-warm); + transform: translateY(-3px); +} + +.item-card-image { + height: 180px; + background-color: var(--color-bg-base); + border-bottom: 1px solid var(--color-border); + overflow: hidden; + position: relative; + display: flex; + align-items: center; + justify-content: center; +} + +.item-card-image img { + width: 100%; + height: 100%; + object-fit: cover; + transition: transform 0.4s ease; +} + +.item-card:hover .item-card-image img { + transform: scale(1.05); +} + +.item-image-placeholder { + color: var(--color-text-light); + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; +} + +.item-image-placeholder svg { + width: 48px; + height: 48px; +} + +.item-card-body { + padding: 1.25rem; + display: flex; + flex-direction: column; + gap: 0.75rem; + flex-grow: 1; +} + +.item-card-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 0.5rem; +} + +.item-card-title { + font-weight: 700; + color: var(--color-text-main); + text-decoration: none; + font-size: 1.15rem; + transition: color 0.2s ease; + display: -webkit-box; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.item-card-title:hover { + color: var(--color-brand-primary); +} + +.item-card-meta { + font-size: 0.85rem; + color: var(--color-text-muted); + font-weight: 500; + display: flex; + gap: 0.5rem; + flex-wrap: wrap; +} + +.item-card-tags { + margin-top: auto; + display: flex; + flex-wrap: wrap; + gap: 0.35rem; +} + +.card-actions-btn { + background: rgba(255, 255, 255, 0.85); + backdrop-filter: blur(4px); + box-shadow: var(--shadow-sm); + color: var(--color-text-muted); +} + +.card-actions-btn:hover { + background: #fff; + color: var(--color-brand-primary); +} + +@media (max-width: 768px) { + .public-header { + padding: 1rem 1.5rem; + } + .folders-grid { + grid-template-columns: 1fr; + } + .items-grid { + grid-template-columns: 1fr; + } +} + diff --git a/internal/server/static/js/main.js b/internal/server/static/js/main.js index 5459ff7..b8075ae 100644 --- a/internal/server/static/js/main.js +++ b/internal/server/static/js/main.js @@ -14,6 +14,9 @@ document.addEventListener("DOMContentLoaded", () => { // 3. Room-tag locking on the item create/edit form initRoomTagLock(); + + // 4. Initialize drag and drop mechanics for directories and assets + initDragAndDrop(); }); function setupToastListeners() { @@ -123,3 +126,139 @@ document.addEventListener("click", () => { }); }); +// 5. Drag & Drop Directory Move Management +function initDragAndDrop() { + const draggables = document.querySelectorAll("[draggable='true']"); + const dropzones = document.querySelectorAll(".dropzone"); + + let draggedElement = null; + + draggables.forEach(draggable => { + draggable.addEventListener("dragstart", (e) => { + draggedElement = draggable; + draggable.classList.add("dragging"); + + const type = draggable.dataset.type; + const id = type === "location" ? draggable.dataset.locationId : draggable.dataset.itemId; + + e.dataTransfer.setData("text/plain", JSON.stringify({ id, type })); + e.dataTransfer.effectAllowed = "move"; + }); + + draggable.addEventListener("dragend", () => { + draggable.classList.remove("dragging"); + draggedElement = null; + dropzones.forEach(zone => zone.classList.remove("drop-active")); + }); + }); + + dropzones.forEach(zone => { + zone.addEventListener("dragover", (e) => { + e.preventDefault(); // Required to allow drop! + + if (!draggedElement) return; + + const draggedType = draggedElement.dataset.type; + const draggedId = draggedType === "location" ? draggedElement.dataset.locationId : draggedElement.dataset.itemId; + const zoneLocId = zone.dataset.locationId; + + // Prevent folder dropping on itself + if (draggedType === "location" && draggedId === zoneLocId) { + return; + } + + zone.classList.add("drop-active"); + }); + + zone.addEventListener("dragleave", () => { + zone.classList.remove("drop-active"); + }); + + zone.addEventListener("drop", async (e) => { + e.preventDefault(); + zone.classList.remove("drop-active"); + + try { + const rawData = e.dataTransfer.getData("text/plain"); + if (!rawData) return; + const data = JSON.parse(rawData); + const targetLocationId = zone.dataset.locationId; + + if (!data.id || !targetLocationId) return; + + const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'); + + if (data.type === "item") { + // Move item to a location + const response = await fetch("/admin/items/move", { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "X-CSRF-Token": csrfToken + }, + body: new URLSearchParams({ + "item_id": data.id, + "location_id": targetLocationId, + "csrf_token": csrfToken + }) + }); + + if (response.ok) { + showSuccessToast("Asset moved successfully!"); + setTimeout(() => window.location.reload(), 1000); + } else { + const errMsg = await response.text(); + showErrorToast(errMsg || "Failed to move asset"); + } + } else if (data.type === "location") { + // Move location inside another location + const response = await fetch("/admin/locations/move", { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "X-CSRF-Token": csrfToken + }, + body: new URLSearchParams({ + "location_id": data.id, + "parent_id": targetLocationId, + "csrf_token": csrfToken + }) + }); + + if (response.ok) { + showSuccessToast("Folder moved successfully!"); + setTimeout(() => window.location.reload(), 1000); + } else { + const errMsg = await response.text(); + showErrorToast(errMsg || "Failed to move folder"); + } + } + } catch (err) { + console.error("Error during drag-and-drop drop event:", err); + showErrorToast("An error occurred during drag-and-drop"); + } + }); + }); +} + +function showSuccessToast(message) { + showToast(message, "success"); +} + +function showErrorToast(message) { + showToast(message, "error"); +} + +function showToast(message, type) { + const container = document.getElementById("toast-container"); + if (!container) return; + + const toast = document.createElement("div"); + toast.className = `toast ${type === "success" ? "toast-success" : "toast-error"}`; + toast.innerHTML = ` +
${message}
+ + `; + container.appendChild(toast); +} + diff --git a/internal/server/templates.go b/internal/server/templates.go index c2d6e03..349cb0f 100644 --- a/internal/server/templates.go +++ b/internal/server/templates.go @@ -105,6 +105,7 @@ func initTemplates() { "tags.html", "shortener.html", "print_labels.html", + "location_folder.html", } for _, page := range layoutPages { diff --git a/internal/server/templates/base.html b/internal/server/templates/base.html index 8b5a635..3173f3c 100644 --- a/internal/server/templates/base.html +++ b/internal/server/templates/base.html @@ -16,8 +16,9 @@ -
+
+ {{if .IsAuthenticated}} + {{else}} + +
+
+ + Solis +
+ +
+ {{end}}
diff --git a/internal/server/templates/items.html b/internal/server/templates/items.html index 4338a18..dd34a2d 100644 --- a/internal/server/templates/items.html +++ b/internal/server/templates/items.html @@ -727,16 +727,22 @@

{{.Item.Name}}

- - Edit Asset - - - Back to List - + {{if .IsAuthenticated}} + + Edit Asset + + + Back to List + + {{else}} + + Back to Directory + + {{end}}
-
+
@@ -746,22 +752,27 @@
{{.Item.Status}}
+ {{if .IsAuthenticated}} Quantity: {{.Item.Quantity}} -
-
- {{range .Item.Tags}} - {{.Name}} {{end}}
+ {{if .IsAuthenticated}} +
+ {{range .Item.Tags}} + {{.Name}} + {{end}} +
+ {{end}}

Description

-

+

{{if .Item.Description}}{{.Item.Description}}{{else}}No description provided for this asset.{{end}}

+ {{if .IsAuthenticated}}
Model Number @@ -772,8 +783,10 @@ {{if .Item.SerialNumber}}{{.Item.SerialNumber}}{{else}}--{{end}}
+ {{end}}
+ {{if .IsAuthenticated}}
@@ -835,8 +848,10 @@

No custom metadata fields defined for this asset.

{{end}}
+ {{end}}
+ {{if .IsAuthenticated}}
@@ -889,9 +904,9 @@
Assigned Location - + {{if .Item.LocationName.Valid}} - {{.Item.LocationName.String}} + {{.Item.LocationName.String}} {{else}} Unassigned {{end}} @@ -899,6 +914,7 @@
+ {{end}} {{else}} @@ -943,13 +959,20 @@ {{end}} + + - {{if or .SearchQuery (or .SelectedStatus (or .SelectedLocation .ShowRemoved))}} + {{if or .SearchQuery (or .SelectedStatus (or .SelectedLocation (or .SelectedTag .ShowRemoved)))}} Reset {{end}} @@ -995,8 +1018,8 @@ {{if .LocationName.Valid}} - - {{.LocationName.String}} + + {{.LocationName.String}} {{else}} Unassigned @@ -1017,7 +1040,7 @@
{{range .Tags}} - {{.Name}} + {{.Name}} {{end}}
diff --git a/internal/server/templates/locations.html b/internal/server/templates/locations.html index ea43caa..3699c77 100644 --- a/internal/server/templates/locations.html +++ b/internal/server/templates/locations.html @@ -37,8 +37,8 @@ {{if .Locations}} {{range .Locations}} - - {{.Name}} + + {{.Name}} {{if eq .LifecycleState "archived"}} Archived {{end}} diff --git a/internal/slug/slug.go b/internal/slug/slug.go index 85a6c00..8ac99f2 100644 --- a/internal/slug/slug.go +++ b/internal/slug/slug.go @@ -10,6 +10,22 @@ import ( "strings" ) +func Slugify(name string) string { + name = strings.ToLower(name) + name = strings.ReplaceAll(name, " ", "-") + // Remove non-alphanumeric chars (except - and _) + reg := regexp.MustCompile(`[^a-z0-9_-]+`) + name = reg.ReplaceAllString(name, "") + // Collapse multiple hyphens + reg2 := regexp.MustCompile(`-+`) + name = reg2.ReplaceAllString(name, "-") + name = strings.Trim(name, "-") + if name == "" { + name = "location" + } + return name +} + const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" var reservedSlugs = map[string]bool{ diff --git a/schema.sql b/schema.sql index 8bae20e..a46b6b2 100644 --- a/schema.sql +++ b/schema.sql @@ -7,6 +7,7 @@ PRAGMA foreign_keys = ON; CREATE TABLE IF NOT EXISTS locations ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, + slug TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, image_path TEXT NOT NULL DEFAULT '', @@ -16,6 +17,7 @@ CREATE TABLE IF NOT EXISTS locations ( ); CREATE INDEX IF NOT EXISTS idx_locations_parent ON locations(parent_id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_locations_slug ON locations(slug); -- 2. Tags Table (Sleek labels for grouping items) CREATE TABLE IF NOT EXISTS tags (