From 960c375557a6f4803bef8a88f5082eb7b277232d Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Thu, 21 May 2026 18:31:24 -0700 Subject: [PATCH] Implement non-destructive Remove & Archive lifecycle system across assets, locations, tags, and shortlinks --- internal/db/db.go | 31 ++ internal/db/items.go | 37 +- internal/db/links.go | 48 +- internal/db/locations.go | 60 +- internal/db/schema.sql | 42 +- internal/db/tags.go | 54 +- internal/server/handlers.go | 227 +++++++- internal/server/server.go | 25 +- internal/server/static/css/styles.css | 103 ++++ internal/server/static/js/main.js | 27 + internal/server/templates/base.html | 37 ++ internal/server/templates/items.html | 86 ++- internal/server/templates/locations.html | 80 ++- internal/server/templates/shortener.html | 91 +++- internal/server/templates/tags.html | 73 ++- schema.sql | 42 +- scratch/render_diagnostic.go | 97 ++++ scratch/render_test.go | 97 ++++ scratch/rendered.html | 663 +++++++++++++++++++++++ scratch/test_parse.go | 16 + 20 files changed, 1751 insertions(+), 185 deletions(-) create mode 100644 scratch/render_diagnostic.go create mode 100644 scratch/render_test.go create mode 100644 scratch/rendered.html create mode 100644 scratch/test_parse.go diff --git a/internal/db/db.go b/internal/db/db.go index 5e80ae8..7d88199 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -48,6 +48,37 @@ func migrate(conn *sql.DB) error { return fmt.Errorf("running schema migrations: %w", err) } + // Ensure lifecycle_state column exists in items, locations, tags, links (for existing databases) + for _, tableName := range []string{"items", "locations", "tags", "links"} { + rows, err := conn.Query(fmt.Sprintf("PRAGMA table_info(%s)", tableName)) + if err != nil { + return fmt.Errorf("pragma table_info for %s: %w", tableName, err) + } + + hasLifecycleState := 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 %s: %w", tableName, err) + } + if name == "lifecycle_state" { + hasLifecycleState = true + } + } + rows.Close() + + if !hasLifecycleState { + alterQuery := fmt.Sprintf("ALTER TABLE %s ADD COLUMN lifecycle_state TEXT NOT NULL DEFAULT 'active'", tableName) + if _, err := conn.Exec(alterQuery); err != nil { + return fmt.Errorf("adding lifecycle_state column to %s: %w", tableName, err) + } + } + } + // Check if locations count is 0 var count int err = conn.QueryRow("SELECT COUNT(*) FROM locations").Scan(&count) diff --git a/internal/db/items.go b/internal/db/items.go index a076cdf..ae36512 100644 --- a/internal/db/items.go +++ b/internal/db/items.go @@ -23,6 +23,7 @@ type Item struct { CustomFields string // JSON text ImagePath string ReceiptPath string + LifecycleState string // 'active', 'archived', 'removed' CreatedAt time.Time UpdatedAt time.Time Tags []Tag // Loaded on demand @@ -86,7 +87,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 + COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state FROM items i LEFT JOIN locations l ON i.location_id = l.id LEFT JOIN links lk ON lk.item_id = i.id @@ -160,18 +161,38 @@ func (d *DB) DeleteItem(id int64) error { return err } -func (d *DB) ListItems() ([]Item, error) { - rows, err := d.Conn.Query(` +func (d *DB) SoftRemoveItem(id int64) error { + _, err := d.Conn.Exec("UPDATE items SET lifecycle_state = 'removed', updated_at = datetime('now') WHERE id = ?", id) + return err +} + +func (d *DB) ArchiveItem(id int64) error { + _, err := d.Conn.Exec("UPDATE items SET lifecycle_state = 'archived', updated_at = datetime('now') WHERE id = ?", id) + return err +} + +func (d *DB) RestoreItem(id int64) error { + _, err := d.Conn.Exec("UPDATE items SET lifecycle_state = 'active', updated_at = datetime('now') WHERE id = ?", id) + return err +} + +func (d *DB) ListItems(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 + COALESCE(lk.slug, '') AS short_slug, i.lifecycle_state FROM items i LEFT JOIN locations l ON i.location_id = l.id LEFT JOIN links lk ON lk.item_id = i.id - ORDER BY i.id DESC`, - ) + ` + if !showRemoved { + query += " WHERE 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) if err != nil { return nil, err } @@ -191,7 +212,7 @@ func (d *DB) ListItems() ([]Item, error) { 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.ReceiptPath, &created, &updated, &i.ShortSlug, &i.LifecycleState, ) if err != nil { return nil, err @@ -312,7 +333,7 @@ func scanItem(row interface { 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.ReceiptPath, &created, &updated, &i.ShortSlug, &i.LifecycleState, ) if err != nil { return nil, err diff --git a/internal/db/links.go b/internal/db/links.go index dab76fa..3f6a5af 100644 --- a/internal/db/links.go +++ b/internal/db/links.go @@ -6,13 +6,14 @@ import ( ) type Link struct { - ID int64 - Slug string - URL string - ItemID sql.NullInt64 - CreatedBy string - Clicks int64 - CreatedAt time.Time + ID int64 + Slug string + URL string + ItemID sql.NullInt64 + CreatedBy string + Clicks int64 + LifecycleState string // 'active', 'archived', 'removed' + CreatedAt time.Time } func (d *DB) CreateLink(slug, url, createdBy string, itemID sql.NullInt64) (*Link, error) { @@ -35,12 +36,12 @@ func (d *DB) CreateLink(slug, url, createdBy string, itemID sql.NullInt64) (*Lin } func (d *DB) GetLinkBySlug(slug string) (*Link, error) { - row := d.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links WHERE slug = ?", slug) + row := d.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, lifecycle_state, created_at FROM links WHERE slug = ?", slug) return scanLink(row) } func (d *DB) GetLinkByItemID(itemID int64) (*Link, error) { - row := d.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links WHERE item_id = ?", itemID) + row := d.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, lifecycle_state, created_at FROM links WHERE item_id = ?", itemID) return scanLink(row) } @@ -49,8 +50,29 @@ func (d *DB) IncrementLinkClicks(slug string) error { return err } -func (d *DB) ListLinks() ([]Link, error) { - rows, err := d.Conn.Query("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links ORDER BY id DESC") +func (d *DB) SoftRemoveLink(id int64) error { + _, err := d.Conn.Exec("UPDATE links SET lifecycle_state = 'removed' WHERE id = ?", id) + return err +} + +func (d *DB) ArchiveLink(id int64) error { + _, err := d.Conn.Exec("UPDATE links SET lifecycle_state = 'archived' WHERE id = ?", id) + return err +} + +func (d *DB) RestoreLink(id int64) error { + _, err := d.Conn.Exec("UPDATE links SET lifecycle_state = 'active' WHERE id = ?", id) + return err +} + +func (d *DB) ListLinks(showRemoved bool) ([]Link, error) { + query := "SELECT id, slug, url, item_id, created_by, clicks, lifecycle_state, created_at FROM links" + if !showRemoved { + query += " WHERE lifecycle_state != 'removed'" + } + query += " ORDER BY CASE lifecycle_state WHEN 'archived' THEN 1 WHEN 'removed' THEN 2 ELSE 0 END, id DESC" + + rows, err := d.Conn.Query(query) if err != nil { return nil, err } @@ -61,7 +83,7 @@ func (d *DB) ListLinks() ([]Link, error) { var l Link var itemID sql.NullInt64 var ts string - if err := rows.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &ts); err != nil { + if err := rows.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &l.LifecycleState, &ts); err != nil { return nil, err } l.ItemID = itemID @@ -93,7 +115,7 @@ func scanLink(row interface { var l Link var itemID sql.NullInt64 var ts string - if err := row.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &ts); err != nil { + if err := row.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &l.LifecycleState, &ts); err != nil { return nil, err } l.ItemID = itemID diff --git a/internal/db/locations.go b/internal/db/locations.go index c54140d..a99a62e 100644 --- a/internal/db/locations.go +++ b/internal/db/locations.go @@ -7,14 +7,15 @@ import ( ) type Location struct { - ID int64 - Name string - Description string - ParentID sql.NullInt64 - ParentName sql.NullString // Resolved parent location name - ImagePath string - CreatedAt time.Time - UpdatedAt time.Time + ID int64 + Name string + Description string + ParentID sql.NullInt64 + ParentName sql.NullString // Resolved parent location name + ImagePath string + LifecycleState string // 'active', 'archived', 'removed' + CreatedAt time.Time + UpdatedAt time.Time } func (d *DB) CreateLocation(name, description string, parentID sql.NullInt64, imagePath string) (*Location, error) { @@ -63,7 +64,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.created_at, l.updated_at + 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 FROM locations l LEFT JOIN locations p ON l.parent_id = p.id WHERE l.id = ?`, @@ -174,13 +175,38 @@ func (d *DB) DeleteLocation(id int64) error { return tx.Commit() } -func (d *DB) ListLocations() ([]Location, error) { - rows, err := d.Conn.Query(` - SELECT l.id, l.name, l.description, l.parent_id, p.name AS parent_name, l.image_path, l.created_at, l.updated_at +func (d *DB) SoftRemoveLocation(id int64) error { + if id == 1 { + return fmt.Errorf("cannot remove the Default Room") + } + _, err := d.Conn.Exec("UPDATE locations SET lifecycle_state = 'removed', updated_at = datetime('now') WHERE id = ?", id) + return err +} + +func (d *DB) ArchiveLocation(id int64) error { + if id == 1 { + return fmt.Errorf("cannot archive the Default Room") + } + _, err := d.Conn.Exec("UPDATE locations SET lifecycle_state = 'archived', updated_at = datetime('now') WHERE id = ?", id) + return err +} + +func (d *DB) RestoreLocation(id int64) error { + _, err := d.Conn.Exec("UPDATE locations SET lifecycle_state = 'active', updated_at = datetime('now') WHERE id = ?", id) + return err +} + +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 FROM locations l - LEFT JOIN locations p ON l.parent_id = p.id - ORDER BY l.name ASC`, - ) + LEFT JOIN locations p ON l.parent_id = p.id` + if !showRemoved { + query += " WHERE 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) if err != nil { return nil, err } @@ -192,7 +218,7 @@ func (d *DB) ListLocations() ([]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, &created, &updated); err != nil { + if err := rows.Scan(&l.ID, &l.Name, &l.Description, &parentID, &parentName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { return nil, err } l.ParentID = parentID @@ -211,7 +237,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, &created, &updated); err != nil { + if err := row.Scan(&l.ID, &l.Name, &l.Description, &parentID, &parentName, &l.ImagePath, &l.LifecycleState, &created, &updated); err != nil { return nil, err } l.ParentID = parentID diff --git a/internal/db/schema.sql b/internal/db/schema.sql index dded98d..c70146e 100644 --- a/internal/db/schema.sql +++ b/internal/db/schema.sql @@ -3,24 +3,26 @@ -- 1. Locations Table (Supports hierarchical locations via parent_id) CREATE TABLE IF NOT EXISTS locations ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - description TEXT NOT NULL DEFAULT '', - parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, - image_path TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')) + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, + image_path TEXT NOT NULL DEFAULT '', + lifecycle_state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE INDEX IF NOT EXISTS idx_locations_parent ON locations(parent_id); -- 2. Tags Table (Sleek labels for grouping items) CREATE TABLE IF NOT EXISTS tags ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL UNIQUE, - color TEXT NOT NULL DEFAULT '#e2e8f0', -- Hex code for pill color - description TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL DEFAULT (datetime('now')) + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + color TEXT NOT NULL DEFAULT '#e2e8f0', -- Hex code for pill color + description TEXT NOT NULL DEFAULT '', + lifecycle_state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (datetime('now')) ); -- 3. Items Table (Asset entries with purchase records and JSON custom fields) @@ -40,6 +42,7 @@ CREATE TABLE IF NOT EXISTS items ( custom_fields TEXT NOT NULL DEFAULT '{}', -- JSON text field containing arbitrary key-value custom metadata image_path TEXT NOT NULL DEFAULT '', receipt_path TEXT NOT NULL DEFAULT '', + lifecycle_state TEXT NOT NULL DEFAULT 'active', created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); @@ -55,13 +58,14 @@ CREATE TABLE IF NOT EXISTS item_tags ( -- 5. Links Table (Ported and enhanced from Glimmer) CREATE TABLE IF NOT EXISTS links ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - slug TEXT NOT NULL UNIQUE, - url TEXT NOT NULL, -- Redirect target (internal, e.g., '/items/12', or external) - item_id INTEGER REFERENCES items(id) ON DELETE CASCADE, -- Nullable; links specific assets to short URLs - created_by TEXT NOT NULL DEFAULT 'admin', - clicks INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL DEFAULT (datetime('now')) + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + url TEXT NOT NULL, -- Redirect target (internal, e.g., '/items/12', or external) + item_id INTEGER REFERENCES items(id) ON DELETE CASCADE, -- Nullable; links specific assets to short URLs + created_by TEXT NOT NULL DEFAULT 'admin', + clicks INTEGER NOT NULL DEFAULT 0, + lifecycle_state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug); diff --git a/internal/db/tags.go b/internal/db/tags.go index 5026ce8..ddb5cf5 100644 --- a/internal/db/tags.go +++ b/internal/db/tags.go @@ -6,11 +6,12 @@ import ( ) type Tag struct { - ID int64 - Name string - Color string // Hex representation, e.g. "#3b82f6" - Description string - CreatedAt time.Time + ID int64 + Name string + Color string // Hex representation, e.g. "#3b82f6" + Description string + LifecycleState string // 'active', 'archived', 'removed' + CreatedAt time.Time } func (d *DB) CreateTag(name, color, description string) (*Tag, error) { @@ -35,12 +36,12 @@ func (d *DB) CreateTag(name, color, description string) (*Tag, error) { } func (d *DB) GetTag(id int64) (*Tag, error) { - row := d.Conn.QueryRow("SELECT id, name, color, description, created_at FROM tags WHERE id = ?", id) + row := d.Conn.QueryRow("SELECT id, name, color, description, lifecycle_state, created_at FROM tags WHERE id = ?", id) return scanTag(row) } func (d *DB) GetTagByName(name string) (*Tag, error) { - row := d.Conn.QueryRow("SELECT id, name, color, description, created_at FROM tags WHERE name = ?", name) + row := d.Conn.QueryRow("SELECT id, name, color, description, lifecycle_state, created_at FROM tags WHERE name = ?", name) return scanTag(row) } @@ -74,8 +75,39 @@ func (d *DB) DeleteTag(id int64) error { return err } -func (d *DB) ListTags() ([]Tag, error) { - rows, err := d.Conn.Query("SELECT id, name, color, description, created_at FROM tags ORDER BY name ASC") +func (d *DB) SoftRemoveTag(id int64) error { + var name string + err := d.Conn.QueryRow("SELECT name FROM tags WHERE id = ?", id).Scan(&name) + if err == nil && name == "Default Room" { + return fmt.Errorf("cannot remove the Default Room tag") + } + _, err = d.Conn.Exec("UPDATE tags SET lifecycle_state = 'removed' WHERE id = ?", id) + return err +} + +func (d *DB) ArchiveTag(id int64) error { + var name string + err := d.Conn.QueryRow("SELECT name FROM tags WHERE id = ?", id).Scan(&name) + if err == nil && name == "Default Room" { + return fmt.Errorf("cannot archive the Default Room tag") + } + _, err = d.Conn.Exec("UPDATE tags SET lifecycle_state = 'archived' WHERE id = ?", id) + return err +} + +func (d *DB) RestoreTag(id int64) error { + _, err := d.Conn.Exec("UPDATE tags SET lifecycle_state = 'active' WHERE id = ?", id) + return err +} + +func (d *DB) ListTags(showRemoved bool) ([]Tag, error) { + query := "SELECT id, name, color, description, lifecycle_state, created_at FROM tags" + if !showRemoved { + query += " WHERE lifecycle_state != 'removed'" + } + query += " ORDER BY CASE lifecycle_state WHEN 'archived' THEN 1 WHEN 'removed' THEN 2 ELSE 0 END, name ASC" + + rows, err := d.Conn.Query(query) if err != nil { return nil, err } @@ -85,7 +117,7 @@ func (d *DB) ListTags() ([]Tag, error) { for rows.Next() { var t Tag var created string - if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &created); err != nil { + if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &t.LifecycleState, &created); err != nil { return nil, err } t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) @@ -99,7 +131,7 @@ func scanTag(row interface { }) (*Tag, error) { var t Tag var created string - if err := row.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &created); err != nil { + if err := row.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &t.LifecycleState, &created); err != nil { return nil, err } t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 2c27233..4ffff5d 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -9,6 +9,7 @@ import ( "net/http" "os" "path/filepath" + "regexp" "strconv" "strings" "time" @@ -44,6 +45,8 @@ type PageData struct { SelectedStatus string SelectedLocation int64 CatalogJSON string + SlugLength int + ShowRemoved bool } // ========================================== @@ -167,8 +170,9 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { csrf := csrfToken(w, r) - locations, _ := s.db.ListLocations() - tags, _ := s.db.ListTags() + showRemoved := r.URL.Query().Get("show_removed") == "1" + locations, _ := s.db.ListLocations(showRemoved) + tags, _ := s.db.ListTags(showRemoved) // 1. DETAIL VIEW MODE if viewIDStr := r.URL.Query().Get("view"); viewIDStr != "" { @@ -188,6 +192,7 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { CustomFieldsMap: cfMap, Locations: locations, Tags: tags, + ShowRemoved: showRemoved, Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } @@ -202,7 +207,7 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { statusQuery := r.URL.Query().Get("status") locationQuery := r.URL.Query().Get("location") - allItems, err := s.db.ListItems() + allItems, err := s.db.ListItems(showRemoved) if err != nil { http.Error(w, "Failed to load assets", http.StatusInternalServerError) return @@ -239,6 +244,7 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { SearchQuery: searchQuery, SelectedStatus: statusQuery, SelectedLocation: locFilterID, + ShowRemoved: showRemoved, Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } @@ -247,8 +253,8 @@ func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { } func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) { - locations, _ := s.db.ListLocations() - tags, _ := s.db.ListTags() + locations, _ := s.db.ListLocations(false) + tags, _ := s.db.ListTags(false) catalogJSON, err := json.Marshal(s.catalog) if err != nil { @@ -448,8 +454,8 @@ func (s *Server) handleItemEdit(w http.ResponseWriter, r *http.Request) { return } - locations, _ := s.db.ListLocations() - tags, _ := s.db.ListTags() + locations, _ := s.db.ListLocations(false) + tags, _ := s.db.ListTags(false) // Translate custom JSON string back to raw lines for edit comfort customFieldsRaw := formatCustomFields(item.CustomFields) @@ -570,7 +576,40 @@ func (s *Server) handleItemSave(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, fmt.Sprintf("/admin?view=%d&toast=Asset+updated+successfully&toast_type=success", item.ID), http.StatusSeeOther) } -func (s *Server) handleItemDelete(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleItemRemove(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.SoftRemoveItem(id) + http.Redirect(w, r, "/admin?toast=Asset+moved+to+soon-to-be-deleted+queue&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleItemArchive(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.ArchiveItem(id) + http.Redirect(w, r, "/admin?toast=Asset+archived+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleItemRestore(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.RestoreItem(id) + http.Redirect(w, r, "/admin?show_removed=1&toast=Asset+restored+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleItemPermanentDelete(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) @@ -589,7 +628,7 @@ func (s *Server) handleItemDelete(w http.ResponseWriter, r *http.Request) { } _ = s.db.DeleteItem(id) - http.Redirect(w, r, "/admin?toast=Asset+deleted+successfully&toast_type=success", http.StatusSeeOther) + http.Redirect(w, r, "/admin?show_removed=1&toast=Asset+deleted+forever+successfully&toast_type=success", http.StatusSeeOther) } // ========================================== @@ -598,7 +637,8 @@ func (s *Server) handleItemDelete(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAdminLocations(w http.ResponseWriter, r *http.Request) { csrf := csrfToken(w, r) - locations, _ := s.db.ListLocations() + showRemoved := r.URL.Query().Get("show_removed") == "1" + locations, _ := s.db.ListLocations(showRemoved) var editLoc *db.Location if editIDStr := r.URL.Query().Get("edit"); editIDStr != "" { @@ -613,6 +653,7 @@ func (s *Server) handleAdminLocations(w http.ResponseWriter, r *http.Request) { ActiveNav: "locations", Locations: locations, EditingLocation: editLoc, + ShowRemoved: showRemoved, Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } @@ -658,7 +699,40 @@ func (s *Server) handleLocationEdit(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/admin/locations?toast=Location+updated+successfully&toast_type=success", http.StatusSeeOther) } -func (s *Server) handleLocationDelete(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleLocationRemove(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.SoftRemoveLocation(id) + http.Redirect(w, r, "/admin/locations?toast=Location+moved+to+soon-to-be-deleted+queue&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLocationArchive(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.ArchiveLocation(id) + http.Redirect(w, r, "/admin/locations?toast=Location+archived+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLocationRestore(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.RestoreLocation(id) + http.Redirect(w, r, "/admin/locations?show_removed=1&toast=Location+restored+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLocationPermanentDelete(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) @@ -666,7 +740,7 @@ func (s *Server) handleLocationDelete(w http.ResponseWriter, r *http.Request) { } _ = s.db.DeleteLocation(id) - http.Redirect(w, r, "/admin/locations?toast=Location+deleted+successfully&toast_type=success", http.StatusSeeOther) + http.Redirect(w, r, "/admin/locations?show_removed=1&toast=Location+deleted+forever+successfully&toast_type=success", http.StatusSeeOther) } // ========================================== @@ -675,7 +749,8 @@ func (s *Server) handleLocationDelete(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAdminTags(w http.ResponseWriter, r *http.Request) { csrf := csrfToken(w, r) - tags, _ := s.db.ListTags() + showRemoved := r.URL.Query().Get("show_removed") == "1" + tags, _ := s.db.ListTags(showRemoved) var editTag *db.Tag if editIDStr := r.URL.Query().Get("edit"); editIDStr != "" { @@ -686,12 +761,13 @@ func (s *Server) handleAdminTags(w http.ResponseWriter, r *http.Request) { } data := PageData{ - CSRFToken: csrf, - ActiveNav: "tags", - Tags: tags, - EditingTag: editTag, - Toast: r.URL.Query().Get("toast"), - ToastType: r.URL.Query().Get("toast_type"), + CSRFToken: csrf, + ActiveNav: "tags", + Tags: tags, + EditingTag: editTag, + ShowRemoved: showRemoved, + Toast: r.URL.Query().Get("toast"), + ToastType: r.URL.Query().Get("toast_type"), } renderTemplate(w, "tags.html", data) } @@ -725,7 +801,40 @@ func (s *Server) handleTagEdit(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/admin/tags?toast=Tag+updated+successfully&toast_type=success", http.StatusSeeOther) } -func (s *Server) handleTagDelete(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleTagRemove(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.SoftRemoveTag(id) + http.Redirect(w, r, "/admin/tags?toast=Tag+moved+to+soon-to-be-deleted+queue&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleTagArchive(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.ArchiveTag(id) + http.Redirect(w, r, "/admin/tags?toast=Tag+archived+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleTagRestore(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.RestoreTag(id) + http.Redirect(w, r, "/admin/tags?show_removed=1&toast=Tag+restored+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleTagPermanentDelete(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) @@ -733,7 +842,7 @@ func (s *Server) handleTagDelete(w http.ResponseWriter, r *http.Request) { } _ = s.db.DeleteTag(id) - http.Redirect(w, r, "/admin/tags?toast=Tag+deleted+successfully&toast_type=success", http.StatusSeeOther) + http.Redirect(w, r, "/admin/tags?show_removed=1&toast=Tag+deleted+forever+successfully&toast_type=success", http.StatusSeeOther) } // ========================================== @@ -742,20 +851,18 @@ func (s *Server) handleTagDelete(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAdminShortener(w http.ResponseWriter, r *http.Request) { csrf := csrfToken(w, r) - links, _ := s.db.ListLinks() + showRemoved := r.URL.Query().Get("show_removed") == "1" + links, _ := s.db.ListLinks(showRemoved) var editLink *db.Link if editIDStr := r.URL.Query().Get("edit"); editIDStr != "" { id, err := strconv.ParseInt(editIDStr, 10, 64) if err == nil { - editLink, _ = s.db.GetLinkBySlug(editIDStr) // Note: ListLinks uses ID, so let's match by ID instead of slug in the select queries if possible. Wait! - // Actually let's query by id using db.Conn directly or adding a GetLinkByID function. - // Let's query by ID in database: - row := s.db.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, created_at FROM links WHERE id = ?", id) + row := s.db.Conn.QueryRow("SELECT id, slug, url, item_id, created_by, clicks, lifecycle_state, created_at FROM links WHERE id = ?", id) var l db.Link var itemID sql.NullInt64 var ts string - if row.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &ts) == nil { + if row.Scan(&l.ID, &l.Slug, &l.URL, &itemID, &l.CreatedBy, &l.Clicks, &l.LifecycleState, &ts) == nil { l.ItemID = itemID l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts) editLink = &l @@ -768,6 +875,8 @@ func (s *Server) handleAdminShortener(w http.ResponseWriter, r *http.Request) { ActiveNav: "shortener", Links: links, EditingLink: editLink, + SlugLength: s.cfg.Slugs.Length, + ShowRemoved: showRemoved, Toast: r.URL.Query().Get("toast"), ToastType: r.URL.Query().Get("toast_type"), } @@ -845,7 +954,40 @@ func (s *Server) handleLinkSave(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/admin/shortener?toast=Shortlink+updated+successfully&toast_type=success", http.StatusSeeOther) } -func (s *Server) handleLinkDelete(w http.ResponseWriter, r *http.Request) { +func (s *Server) handleLinkRemove(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.SoftRemoveLink(id) + http.Redirect(w, r, "/admin/shortener?toast=Shortlink+moved+to+soon-to-be-deleted+queue&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLinkArchive(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.ArchiveLink(id) + http.Redirect(w, r, "/admin/shortener?toast=Shortlink+archived+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLinkRestore(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.RestoreLink(id) + http.Redirect(w, r, "/admin/shortener?show_removed=1&toast=Shortlink+restored+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLinkPermanentDelete(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) @@ -853,7 +995,32 @@ func (s *Server) handleLinkDelete(w http.ResponseWriter, r *http.Request) { } _ = s.db.DeleteLink(id) - http.Redirect(w, r, "/admin/shortener?toast=Shortlink+deleted+successfully&toast_type=success", http.StatusSeeOther) + http.Redirect(w, r, "/admin/shortener?show_removed=1&toast=Shortlink+deleted+forever+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleSlugLengthUpdate(w http.ResponseWriter, r *http.Request) { + lengthStr := strings.TrimSpace(r.FormValue("slug_length")) + length, err := strconv.Atoi(lengthStr) + if err != nil || length < 3 || length > 16 { + http.Redirect(w, r, "/admin/shortener?toast=Slug+length+must+be+between+3+and+16&toast_type=error", http.StatusSeeOther) + return + } + + // Update in-memory config + s.cfg.Slugs.Length = length + + // Persist to config.toml + configPath := "config.toml" + data, err := os.ReadFile(configPath) + if err == nil { + content := string(data) + // Replace the length line in the [slugs] section + re := regexp.MustCompile(`(?m)^(\s*length\s*=\s*)\d+`) + content = re.ReplaceAllString(content, "${1}"+strconv.Itoa(length)) + _ = os.WriteFile(configPath, []byte(content), 0644) + } + + http.Redirect(w, r, "/admin/shortener?toast=Slug+length+updated+to+"+strconv.Itoa(length)+"+characters&toast_type=success", http.StatusSeeOther) } // ========================================== @@ -862,7 +1029,7 @@ func (s *Server) handleLinkDelete(w http.ResponseWriter, r *http.Request) { func (s *Server) handlePrintLabels(w http.ResponseWriter, r *http.Request) { csrf := csrfToken(w, r) - items, err := s.db.ListItems() + items, err := s.db.ListItems(false) if err != nil { http.Error(w, "Failed to load labels", http.StatusInternalServerError) return diff --git a/internal/server/server.go b/internal/server/server.go index 4c5ab20..1e0e84b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -112,25 +112,42 @@ func (s *Server) Start() error { mux.HandleFunc("POST /admin/items/new", s.requireAuth(s.requireCSRF(s.handleItemCreate))) mux.HandleFunc("GET /admin/items/edit/{id}", s.requireAuth(s.handleItemEdit)) mux.HandleFunc("POST /admin/items/edit/{id}", s.requireAuth(s.requireCSRF(s.handleItemSave))) - mux.HandleFunc("POST /admin/items/delete/{id}", s.requireAuth(s.requireCSRF(s.handleItemDelete))) + mux.HandleFunc("POST /admin/items/delete/{id}", s.requireAuth(s.requireCSRF(s.handleItemRemove))) + mux.HandleFunc("POST /admin/items/remove/{id}", s.requireAuth(s.requireCSRF(s.handleItemRemove))) + mux.HandleFunc("POST /admin/items/archive/{id}", s.requireAuth(s.requireCSRF(s.handleItemArchive))) + mux.HandleFunc("POST /admin/items/restore/{id}", s.requireAuth(s.requireCSRF(s.handleItemRestore))) + mux.HandleFunc("POST /admin/items/permanent-delete/{id}", s.requireAuth(s.requireCSRF(s.handleItemPermanentDelete))) // 7. Admin locations management mux.HandleFunc("GET /admin/locations", s.requireAuth(s.handleAdminLocations)) mux.HandleFunc("POST /admin/locations/new", s.requireAuth(s.requireCSRF(s.handleLocationCreate))) mux.HandleFunc("POST /admin/locations/edit/{id}", s.requireAuth(s.requireCSRF(s.handleLocationEdit))) - mux.HandleFunc("POST /admin/locations/delete/{id}", s.requireAuth(s.requireCSRF(s.handleLocationDelete))) + mux.HandleFunc("POST /admin/locations/delete/{id}", s.requireAuth(s.requireCSRF(s.handleLocationRemove))) + mux.HandleFunc("POST /admin/locations/remove/{id}", s.requireAuth(s.requireCSRF(s.handleLocationRemove))) + mux.HandleFunc("POST /admin/locations/archive/{id}", s.requireAuth(s.requireCSRF(s.handleLocationArchive))) + mux.HandleFunc("POST /admin/locations/restore/{id}", s.requireAuth(s.requireCSRF(s.handleLocationRestore))) + mux.HandleFunc("POST /admin/locations/permanent-delete/{id}", s.requireAuth(s.requireCSRF(s.handleLocationPermanentDelete))) // 8. Admin tags management mux.HandleFunc("GET /admin/tags", s.requireAuth(s.handleAdminTags)) mux.HandleFunc("POST /admin/tags/new", s.requireAuth(s.requireCSRF(s.handleTagCreate))) mux.HandleFunc("POST /admin/tags/edit/{id}", s.requireAuth(s.requireCSRF(s.handleTagEdit))) - mux.HandleFunc("POST /admin/tags/delete/{id}", s.requireAuth(s.requireCSRF(s.handleTagDelete))) + mux.HandleFunc("POST /admin/tags/delete/{id}", s.requireAuth(s.requireCSRF(s.handleTagRemove))) + mux.HandleFunc("POST /admin/tags/remove/{id}", s.requireAuth(s.requireCSRF(s.handleTagRemove))) + mux.HandleFunc("POST /admin/tags/archive/{id}", s.requireAuth(s.requireCSRF(s.handleTagArchive))) + mux.HandleFunc("POST /admin/tags/restore/{id}", s.requireAuth(s.requireCSRF(s.handleTagRestore))) + mux.HandleFunc("POST /admin/tags/permanent-delete/{id}", s.requireAuth(s.requireCSRF(s.handleTagPermanentDelete))) // 9. Admin custom shortlinks manager mux.HandleFunc("GET /admin/shortener", s.requireAuth(s.handleAdminShortener)) mux.HandleFunc("POST /admin/shortener/new", s.requireAuth(s.requireCSRF(s.handleLinkCreate))) mux.HandleFunc("POST /admin/shortener/edit/{id}", s.requireAuth(s.requireCSRF(s.handleLinkSave))) - mux.HandleFunc("POST /admin/shortener/delete/{id}", s.requireAuth(s.requireCSRF(s.handleLinkDelete))) + mux.HandleFunc("POST /admin/shortener/delete/{id}", s.requireAuth(s.requireCSRF(s.handleLinkRemove))) + mux.HandleFunc("POST /admin/shortener/remove/{id}", s.requireAuth(s.requireCSRF(s.handleLinkRemove))) + mux.HandleFunc("POST /admin/shortener/archive/{id}", s.requireAuth(s.requireCSRF(s.handleLinkArchive))) + mux.HandleFunc("POST /admin/shortener/restore/{id}", s.requireAuth(s.requireCSRF(s.handleLinkRestore))) + mux.HandleFunc("POST /admin/shortener/permanent-delete/{id}", s.requireAuth(s.requireCSRF(s.handleLinkPermanentDelete))) + mux.HandleFunc("POST /admin/shortener/slug-length", s.requireAuth(s.requireCSRF(s.handleSlugLengthUpdate))) // 10. QR & Labels mux.HandleFunc("GET /admin/qr/{slug}", s.requireAuth(s.handleQR)) diff --git a/internal/server/static/css/styles.css b/internal/server/static/css/styles.css index b437507..f3246b8 100644 --- a/internal/server/static/css/styles.css +++ b/internal/server/static/css/styles.css @@ -587,3 +587,106 @@ body { margin-top: 4px !important; } } + +/* ========================================================================== + Solis Lifecycle Styles (Archive, Soft-Remove & Premium Dropdowns) + ========================================================================== */ + +/* Actions Dropdown Container */ +.actions-dropdown { + position: relative; + display: inline-block; + text-align: left; +} + +/* Actions Menu Popup */ +.actions-dropdown-menu { + position: absolute; + right: 0; + top: 100%; + margin-top: 0.35rem; + background-color: var(--color-bg-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); + z-index: 999; + min-width: 160px; + display: none; + flex-direction: column; + padding: 0.35rem 0; + animation: dropdownFadeIn 0.15s cubic-bezier(0.16, 1, 0.3, 1); +} + +@keyframes dropdownFadeIn { + from { opacity: 0; transform: translateY(-4px); } + to { opacity: 1; transform: translateY(0); } +} + +/* Toggle Menu Display */ +.actions-dropdown.show .actions-dropdown-menu { + display: flex; +} + +/* Menu Items (Forms & Buttons) */ +.actions-dropdown-item { + background: none; + border: none; + width: 100%; + text-align: left; + padding: 0.6rem 1rem; + font-size: 0.85rem; + font-weight: 500; + color: var(--color-text-main); + cursor: pointer; + display: flex; + align-items: center; + gap: 0.5rem; + transition: background-color 0.15s ease, color 0.15s ease; + text-decoration: none; + font-family: var(--font-sans); +} + +.actions-dropdown-item:hover { + background-color: var(--color-bg-base); + color: var(--color-brand-primary); +} + +/* Muted / Red text variations for drop options */ +.actions-dropdown-item.text-danger { + color: #b91c1c; +} +.actions-dropdown-item.text-danger:hover { + background-color: #fee2e2; + color: #991b1b; +} + +.actions-dropdown-item.text-warning { + color: #b45309; +} +.actions-dropdown-item.text-warning:hover { + background-color: #fef3c7; + color: #92400e; +} + +/* Visual States for Soft Removed Elements */ +tr.lifecycle-removed { + opacity: 0.65; + background-color: var(--color-bg-base) !important; +} + +tr.lifecycle-removed td:not(.actions-cell) { + text-decoration: line-through; + color: var(--color-text-light); +} + +/* Visual States for Archived Elements */ +tr.lifecycle-archived { + background-color: #fcfbfb; +} + +.status-pill.archived { + background-color: var(--color-bg-base); + color: var(--color-text-muted); + border: 1px solid var(--color-border); +} + diff --git a/internal/server/static/js/main.js b/internal/server/static/js/main.js index 4620a31..5459ff7 100644 --- a/internal/server/static/js/main.js +++ b/internal/server/static/js/main.js @@ -96,3 +96,30 @@ function initRoomTagLock() { // Run immediately on page load to lock the default/current room tag updateRoomTag(); } + +// 4. Dropdown Action Menu Manager +function toggleActionsDropdown(btn, event) { + if (event) { + event.stopPropagation(); + event.preventDefault(); + } + const container = btn.parentElement; + const isShown = container.classList.contains("show"); + + // Close any other open dropdowns first + document.querySelectorAll(".actions-dropdown").forEach(d => { + d.classList.remove("show"); + }); + + if (!isShown) { + container.classList.add("show"); + } +} + +// Close dropdowns on outside click +document.addEventListener("click", () => { + document.querySelectorAll(".actions-dropdown").forEach(d => { + d.classList.remove("show"); + }); +}); + diff --git a/internal/server/templates/base.html b/internal/server/templates/base.html index 3e70b73..8b5a635 100644 --- a/internal/server/templates/base.html +++ b/internal/server/templates/base.html @@ -100,5 +100,42 @@ {{end}} + + + + + diff --git a/internal/server/templates/items.html b/internal/server/templates/items.html index 5f868dd..4338a18 100644 --- a/internal/server/templates/items.html +++ b/internal/server/templates/items.html @@ -943,12 +943,18 @@ {{end}} + + - {{if or .SearchQuery (or .SelectedStatus .SelectedLocation)}} + {{if or .SearchQuery (or .SelectedStatus (or .SelectedLocation .ShowRemoved))}} Reset {{end}} +
@@ -967,11 +973,11 @@ {{if .Items}} {{range .Items}} - + {{if .ShortSlug}} - - QR Label + + QR Label {{else}} -- @@ -997,9 +1003,13 @@ {{end}} - - {{.Status}} - + {{if eq .LifecycleState "archived"}} + Archived + {{else}} + + {{.Status}} + + {{end}} {{.Quantity}} @@ -1011,20 +1021,56 @@ {{end}}
- +
- - Details - - - Edit - -
- - -
+ {{if eq .LifecycleState "removed"}} + +
+ + +
+
+ + +
+ {{else}} + + + Details + + + {{if ne .LifecycleState "archived"}} + + Edit + + {{end}} + +
+ +
+
+ + +
+ {{if ne .LifecycleState "archived"}} +
+ + +
+ {{end}} +
+
+ {{end}}
diff --git a/internal/server/templates/locations.html b/internal/server/templates/locations.html index f570e23..ea43caa 100644 --- a/internal/server/templates/locations.html +++ b/internal/server/templates/locations.html @@ -8,6 +8,17 @@
+
+ {{if .EditingLocation}} + + {{end}} + +
+ +
@@ -25,8 +36,13 @@ {{if .Locations}} {{range .Locations}} - - {{.Name}} + + + {{.Name}} + {{if eq .LifecycleState "archived"}} + Archived + {{end}} + {{if .ParentName.Valid}} @@ -37,21 +53,53 @@ {{end}} {{.Description}} - -
- - - Edit - - {{if ne .ID 1}} -
- - -
- {{else}} + +
+ {{if eq .ID 1}} Locked + {{else if eq .LifecycleState "removed"}} + +
+ + +
+
+ + +
+ {{else}} + + {{if ne .LifecycleState "archived"}} + + Edit + + {{end}} + +
+ +
+
+ + +
+ {{if ne .LifecycleState "archived"}} +
+ + +
+ {{end}} +
+
{{end}}
diff --git a/internal/server/templates/shortener.html b/internal/server/templates/shortener.html index 94db17e..443b940 100644 --- a/internal/server/templates/shortener.html +++ b/internal/server/templates/shortener.html @@ -7,6 +7,15 @@

Manage custom manual redirects (e.g. warranties, external manuals) or review auto-generated asset short URLs.

+
+ {{if .EditingLink}} + + {{end}} + +
@@ -26,14 +35,19 @@ {{if .Links}} {{range .Links}} - +
- - /s/{{.Slug}} - +
+ + /s/{{.Slug}} + + {{if eq .LifecycleState "archived"}} + Archived + {{end}} +
- + View QR Code
@@ -57,21 +71,56 @@ {{.Clicks}} - + {{if .ItemID.Valid}} Managed by Asset - {{else}} -
- - Edit - -
+ {{else if eq .LifecycleState "removed"}} + +
+ - +
+ + +
+
+ {{else}} + +
+ {{if ne .LifecycleState "archived"}} + + Edit + + {{end}} + +
+ +
+
+ + +
+ {{if ne .LifecycleState "archived"}} +
+ + +
+ {{end}} +
+
{{end}} @@ -138,6 +187,20 @@ {{end}}
+ + +
+

URL Slug Length

+

Controls the character length of auto-generated short URL slugs. Shorter slugs make smaller QR codes. Changes apply to newly created assets only.

+
+ +
+ + characters + +
+
+
{{end}} diff --git a/internal/server/templates/tags.html b/internal/server/templates/tags.html index de8352b..adad20e 100644 --- a/internal/server/templates/tags.html +++ b/internal/server/templates/tags.html @@ -7,6 +7,15 @@

Label and categorize assets to easily group similar items together (e.g. Tools, Electronics, Fragile)

+
+ {{if .EditingTag}} + + {{end}} + +
@@ -25,11 +34,14 @@ {{if .Tags}} {{range .Tags}} - + {{.Name}} + {{if eq .LifecycleState "archived"}} + Archived + {{end}} @@ -37,20 +49,53 @@ {{.Description}} - -
- - Edit - - {{if ne .Name "Default Room"}} -
- - -
- {{else}} + +
+ {{if eq .Name "Default Room"}} Locked + {{else if eq .LifecycleState "removed"}} + +
+ + +
+
+ + +
+ {{else}} + + {{if ne .LifecycleState "archived"}} + + Edit + + {{end}} + +
+ +
+
+ + +
+ {{if ne .LifecycleState "archived"}} +
+ + +
+ {{end}} +
+
{{end}}
diff --git a/schema.sql b/schema.sql index b402705..8bae20e 100644 --- a/schema.sql +++ b/schema.sql @@ -5,24 +5,26 @@ PRAGMA foreign_keys = ON; -- 1. Locations Table (Supports hierarchical locations via parent_id) CREATE TABLE IF NOT EXISTS locations ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - description TEXT NOT NULL DEFAULT '', - parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, - image_path TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')) + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + parent_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, + image_path TEXT NOT NULL DEFAULT '', + lifecycle_state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE INDEX IF NOT EXISTS idx_locations_parent ON locations(parent_id); -- 2. Tags Table (Sleek labels for grouping items) CREATE TABLE IF NOT EXISTS tags ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL UNIQUE, - color TEXT NOT NULL DEFAULT '#e2e8f0', -- Hex code for pill color - description TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL DEFAULT (datetime('now')) + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE, + color TEXT NOT NULL DEFAULT '#e2e8f0', -- Hex code for pill color + description TEXT NOT NULL DEFAULT '', + lifecycle_state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (datetime('now')) ); -- 3. Items Table (Asset entries with purchase records and JSON custom fields) @@ -42,6 +44,7 @@ CREATE TABLE IF NOT EXISTS items ( custom_fields TEXT NOT NULL DEFAULT '{}', -- JSON text field containing arbitrary key-value custom metadata image_path TEXT NOT NULL DEFAULT '', receipt_path TEXT NOT NULL DEFAULT '', + lifecycle_state TEXT NOT NULL DEFAULT 'active', created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) ); @@ -57,13 +60,14 @@ CREATE TABLE IF NOT EXISTS item_tags ( -- 5. Links Table (Ported and enhanced from Glimmer) CREATE TABLE IF NOT EXISTS links ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - slug TEXT NOT NULL UNIQUE, - url TEXT NOT NULL, -- Redirect target (internal, e.g., '/items/12', or external) - item_id INTEGER REFERENCES items(id) ON DELETE CASCADE, -- Nullable; links specific assets to short URLs - created_by TEXT NOT NULL DEFAULT 'admin', - clicks INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL DEFAULT (datetime('now')) + id INTEGER PRIMARY KEY AUTOINCREMENT, + slug TEXT NOT NULL UNIQUE, + url TEXT NOT NULL, -- Redirect target (internal, e.g., '/items/12', or external) + item_id INTEGER REFERENCES items(id) ON DELETE CASCADE, -- Nullable; links specific assets to short URLs + created_by TEXT NOT NULL DEFAULT 'admin', + clicks INTEGER NOT NULL DEFAULT 0, + lifecycle_state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug); diff --git a/scratch/render_diagnostic.go b/scratch/render_diagnostic.go new file mode 100644 index 0000000..f728e08 --- /dev/null +++ b/scratch/render_diagnostic.go @@ -0,0 +1,97 @@ +package main + +import ( + "encoding/json" + "fmt" + "html/template" + "os" + + "Solis/internal/config" + "Solis/internal/db" +) + +func main() { + // 1. Load catalog + cat, err := config.LoadCatalog("../catalog.json") + if err != nil { + fmt.Printf("Error loading catalog: %v\n", err) + return + } + catalogJSON, _ := json.Marshal(cat) + + // 2. Define PageData struct matching internal/server/handlers.go + type PageData struct { + CSRFToken string + ActiveNav string + Toast string + ToastType string + Error string + Items []db.Item + Item *db.Item + Locations []db.Location + Tags []db.Tag + Links []db.Link + EditingLocation *db.Location + EditingTag *db.Tag + EditingLink *db.Link + EditingItem *db.Item + FormMode bool + ViewMode bool + CustomFieldsRaw string + CustomFieldsMap map[string]string + SearchQuery string + SelectedStatus string + SelectedLocation int64 + CatalogJSON string + } + + data := PageData{ + FormMode: true, + CatalogJSON: string(catalogJSON), + } + + // 3. Define the template functions matching internal/server/templates.go + templateFuncs := template.FuncMap{ + "safeJS": func(s string) template.JS { + return template.JS(s) + }, + "formatPrice": func(p any) string { + return "" + }, + "formatDate": func(d any) string { + return "" + }, + "dict": func(values ...interface{}) (map[string]interface{}, error) { + return nil, nil + }, + "hasTag": func(itemTags []db.Tag, tagID int64) bool { + return false + }, + } + + // 4. Parse templates + t, err := template.New("base.html").Funcs(templateFuncs).ParseFiles( + "../internal/server/templates/base.html", + "../internal/server/templates/items.html", + ) + if err != nil { + fmt.Printf("Error parsing templates: %v\n", err) + return + } + + // 5. Render template + out, err := os.Create("rendered.html") + if err != nil { + fmt.Printf("Error creating output file: %v\n", err) + return + } + defer out.Close() + + err = t.Execute(out, data) + if err != nil { + fmt.Printf("Error executing template: %v\n", err) + return + } + + fmt.Println("Render completed successfully!") +} diff --git a/scratch/render_test.go b/scratch/render_test.go new file mode 100644 index 0000000..f728e08 --- /dev/null +++ b/scratch/render_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "encoding/json" + "fmt" + "html/template" + "os" + + "Solis/internal/config" + "Solis/internal/db" +) + +func main() { + // 1. Load catalog + cat, err := config.LoadCatalog("../catalog.json") + if err != nil { + fmt.Printf("Error loading catalog: %v\n", err) + return + } + catalogJSON, _ := json.Marshal(cat) + + // 2. Define PageData struct matching internal/server/handlers.go + type PageData struct { + CSRFToken string + ActiveNav string + Toast string + ToastType string + Error string + Items []db.Item + Item *db.Item + Locations []db.Location + Tags []db.Tag + Links []db.Link + EditingLocation *db.Location + EditingTag *db.Tag + EditingLink *db.Link + EditingItem *db.Item + FormMode bool + ViewMode bool + CustomFieldsRaw string + CustomFieldsMap map[string]string + SearchQuery string + SelectedStatus string + SelectedLocation int64 + CatalogJSON string + } + + data := PageData{ + FormMode: true, + CatalogJSON: string(catalogJSON), + } + + // 3. Define the template functions matching internal/server/templates.go + templateFuncs := template.FuncMap{ + "safeJS": func(s string) template.JS { + return template.JS(s) + }, + "formatPrice": func(p any) string { + return "" + }, + "formatDate": func(d any) string { + return "" + }, + "dict": func(values ...interface{}) (map[string]interface{}, error) { + return nil, nil + }, + "hasTag": func(itemTags []db.Tag, tagID int64) bool { + return false + }, + } + + // 4. Parse templates + t, err := template.New("base.html").Funcs(templateFuncs).ParseFiles( + "../internal/server/templates/base.html", + "../internal/server/templates/items.html", + ) + if err != nil { + fmt.Printf("Error parsing templates: %v\n", err) + return + } + + // 5. Render template + out, err := os.Create("rendered.html") + if err != nil { + fmt.Printf("Error creating output file: %v\n", err) + return + } + defer out.Close() + + err = t.Execute(out, data) + if err != nil { + fmt.Printf("Error executing template: %v\n", err) + return + } + + fmt.Println("Render completed successfully!") +} diff --git a/scratch/rendered.html b/scratch/rendered.html new file mode 100644 index 0000000..c0372e1 --- /dev/null +++ b/scratch/rendered.html @@ -0,0 +1,663 @@ + + + + + + Solis | Assets + + + + + + + + + + + + +
+ + + + +
+ + + + + + + + +
+
+ 1 + Category +
+
+
+ 2 + Item +
+
+
+ 3 + Brand +
+
+ + +
+ +
+ + + + + +
+ + + + + +
+

Which category of item do you want to add?

+
+ +
+
+ + +
+

What kind of item is it?

+
+ +
+
+ + +
+

What brand is the item?

+
+ +
+
+
+ + + + + + + + + +
+
+ + +
+ +
+ + diff --git a/scratch/test_parse.go b/scratch/test_parse.go new file mode 100644 index 0000000..0a1efa9 --- /dev/null +++ b/scratch/test_parse.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "log" + + "Solis/internal/config" +) + +func main() { + cat, err := config.LoadCatalog("../catalog.json") + if err != nil { + log.Fatalf("Error: %v", err) + } + fmt.Printf("Loaded %d categories\n", len(cat)) +}