commit 3d7c232b949e2e77535abd43c2cfbfabe7cc44ea Author: Lucio Chen Date: Thu May 21 02:11:11 2026 -0700 Initial working version diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..abf8360 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +# Binaries +*.exe +*.exe~ +*.dll +*.so +*.dylib +bin/ + +# Application Data (Database and Uploads) +data/ +*.db +*.sqlite +*.sqlite3 + +# OS specific +.DS_Store +Thumbs.db + +# Config files (if you want to ignore actual config but keep example) +config.toml diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000..e4d97cd --- /dev/null +++ b/Caddyfile @@ -0,0 +1,22 @@ +# Solis Reverse Proxy Configuration for Caddy +# Replace solis.local or :80 with your domain name + +:80 { + # Compress responses with gzip or zstd + encode zstd gzip + + # Set up reverse proxy to the Solis application + reverse_proxy http://localhost:8889 { + # Standard headers for secure reverse proxy + header_up Host {host} + header_up X-Real-IP {remote_host} + header_up X-Forwarded-For {remote_host} + header_up X-Forwarded-Proto {scheme} + } + + # Enable logging for access and errors + log { + output file /var/log/caddy/solis_access.log + format json + } +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..2f579d8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,63 @@ +# ========================================== +# Build Stage +# ========================================== +FROM --platform=$BUILDPLATFORM golang:1.22-alpine AS builder + +WORKDIR /build + +# Install git and ca-certificates (needed for downloading modules and SSL) +RUN apk add --no-cache git ca-certificates + +# Copy go.mod and go.sum and download dependencies +COPY go.mod go.sum ./ +RUN go mod download + +# Copy the rest of the source code +COPY . . + +# Compile static binary optimized for Raspberry Pi Zero (ARMv6, no CGO) +# - ldflags "-s -w" removes symbol tables and debugging info, reducing binary size +ARG TARGETOS=linux +ARG TARGETARCH=arm +ARG TARGETVARIANT=v6 + +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} GOARM=6 \ + go build -ldflags="-s -w" -o solis main.go + +# ========================================== +# Final Stage +# ========================================== +FROM alpine:latest + +# Install basic certificates and tools +RUN apk add --no-cache ca-certificates tzdata + +WORKDIR /app + +# Create a non-root user for security +RUN addgroup -S solis && adduser -S solis -G solis + +# Create data directory and change ownership +RUN mkdir -p /app/data && chown -R solis:solis /app/data + +# Copy the compiled binary from the builder +COPY --from=builder /build/solis /app/solis + +# Copy example config (and default config) +COPY config.toml.example /app/config.toml.example +COPY config.toml.example /app/config.toml + +# Set permissions for the non-root user +RUN chown -R solis:solis /app + +# Switch to the non-root user +USER solis + +# Persist DB and uploads in a mounted volume +VOLUME ["/app/data"] + +# Expose the default premium port +EXPOSE 8889 + +# Run the lightweight binary +ENTRYPOINT ["/app/solis", "--config", "/app/config.toml"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..c8c47cb --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# Solis + +Solis is a lightweight, efficient, and reliable home asset tracking server designed specifically for minimal hardware like the Raspberry Pi Zero (ARMv6, 512MB RAM). + +## Features + +- **Hierarchical Asset Tracking:** Keep track of your home equipment, tools, and inventory. +- **Location & Tag Management:** Group assets by physical rooms or logical categories. +- **Shortlink Generation:** Automatically generates collision-resistant shortlinks (e.g. `s/item1`) for quick QR code access. +- **Photo & Receipt Uploads:** Store and securely serve important asset documentation. +- **Offline-First UI:** Self-contained static assets, no external CDNs required. +- **CGO-Free SQLite:** Cross-compiles beautifully to ARMv6 architectures without painful C/C++ toolchains. + +## Building + +Because Solis uses `modernc.org/sqlite`, it can be cross-compiled cleanly with CGO disabled: + +```bash +# Build for Windows (or local testing) +$env:CGO_ENABLED="0"; go build -o solis.exe main.go + +# Cross-compile for Raspberry Pi Zero (ARMv6) +$env:GOOS="linux"; $env:GOARCH="arm"; $env:GOARM="6"; $env:CGO_ENABLED="0"; go build -o solis main.go +``` + +## Running + +1. Copy `config.toml.example` to `config.toml`. +2. Edit `config.toml` to customize the server port, admin credentials, and data directory. +3. Start the server: + ```bash + ./solis.exe + ``` +4. Access the web interface at `http://localhost:8889` (or your configured port). Default login is `admin` / `admin`. + +## Project Structure + +- `main.go` - Application entry point +- `internal/db/` - SQLite schema, queries, and migrations +- `internal/server/` - Web server, HTMX templates, and routing +- `internal/slug/` - URL shortener hashing algorithm +- `config.toml` - Core application configuration +- `data/` - (Ignored by git) Default location for the SQLite database and file uploads diff --git a/config.toml.example b/config.toml.example new file mode 100644 index 0000000..c253949 --- /dev/null +++ b/config.toml.example @@ -0,0 +1,24 @@ +# Solis Configuration Template + +[server] +port = 8889 +base_url = "http://localhost:8889" +read_timeout = "5s" +write_timeout = "10s" + +[admin] +username = "admin" +# Default password: "admin" — CHANGE THIS IN PRODUCTION! +# Generate a new bcrypt hash using: ./solis --hash-password "your-password" +password_hash = "$2a$10$WXBoF7ZB7fIRl5smdGH9seqlNbXWiCS7ZbGNk0ONb9xjS8499gBpu" +session_hours = 24 + +[database] +path = "./data/solis.db" + +[slugs] +length = 4 + +[upload] +dir = "./data/uploads" +max_size_mb = 10 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ccbab57 --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module Solis + +go 1.26.1 + +require ( + github.com/BurntSushi/toml v1.6.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect + golang.org/x/crypto v0.51.0 // indirect + golang.org/x/sys v0.44.0 // indirect + modernc.org/libc v1.72.3 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect + modernc.org/sqlite v1.50.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c83b59f --- /dev/null +++ b/go.sum @@ -0,0 +1,27 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= +golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= +golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ= +golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU= +modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w= +modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..ba9fdb9 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,99 @@ +package config + +import ( + "fmt" + "os" + "time" + + "github.com/BurntSushi/toml" +) + +type Config struct { + Server ServerConfig `toml:"server"` + Admin AdminConfig `toml:"admin"` + Database DatabaseConfig `toml:"database"` + Slugs SlugConfig `toml:"slugs"` + Upload UploadConfig `toml:"upload"` +} + +type ServerConfig struct { + Port int `toml:"port"` + BaseURL string `toml:"base_url"` + ReadTimeout string `toml:"read_timeout"` + WriteTimeout string `toml:"write_timeout"` +} + +type AdminConfig struct { + Username string `toml:"username"` + PasswordHash string `toml:"password_hash"` + SessionHours int `toml:"session_hours"` +} + +type DatabaseConfig struct { + Path string `toml:"path"` +} + +type SlugConfig struct { + Length int `toml:"length"` +} + +type UploadConfig struct { + Dir string `toml:"dir"` + MaxSize int64 `toml:"max_size_mb"` +} + +func (c *ServerConfig) ReadTimeoutDuration() time.Duration { + d, err := time.ParseDuration(c.ReadTimeout) + if err != nil { + return 5 * time.Second + } + return d +} + +func (c *ServerConfig) WriteTimeoutDuration() time.Duration { + d, err := time.ParseDuration(c.WriteTimeout) + if err != nil { + return 10 * time.Second + } + return d +} + +func Load(path string) (*Config, error) { + cfg := &Config{ + Server: ServerConfig{ + Port: 8889, + BaseURL: "http://localhost:8889", + ReadTimeout: "5s", + WriteTimeout: "10s", + }, + Admin: AdminConfig{ + Username: "admin", + SessionHours: 24, + }, + Database: DatabaseConfig{ + Path: "./data/solis.db", + }, + Slugs: SlugConfig{ + Length: 4, // 4 characters gives plenty of short URL combinations (1.6M+) for home inventories + }, + Upload: UploadConfig{ + Dir: "./data/uploads", + MaxSize: 10, // 10MB is plenty for home receipts and item photos + }, + } + + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("reading config: %w", err) + } + + if err := toml.Unmarshal(data, cfg); err != nil { + return nil, fmt.Errorf("parsing config: %w", err) + } + + if cfg.Admin.PasswordHash == "" { + return nil, fmt.Errorf("admin.password_hash is required in config") + } + + return cfg, nil +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..5e80ae8 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,77 @@ +package db + +import ( + "database/sql" + _ "embed" + "fmt" + "os" + "path/filepath" + + _ "modernc.org/sqlite" +) + +//go:embed schema.sql +var schemaSQL string + +type DB struct { + Conn *sql.DB +} + +func Open(path string) (*DB, error) { + // Ensure parent directory exists + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, fmt.Errorf("creating db directory: %w", err) + } + + // Open CGO-free SQLite connection with high-concurrency WAL mode and busy timeout + conn, err := sql.Open("sqlite", path+"?_journal_mode=WAL&_busy_timeout=5000&_fk=true") + if err != nil { + return nil, fmt.Errorf("opening database: %w", err) + } + + // SQLite operates best in Go with max open connections limited to 1, avoiding concurrent write lockouts + conn.SetMaxOpenConns(1) + + if err := migrate(conn); err != nil { + conn.Close() + return nil, err + } + + return &DB{Conn: conn}, nil +} + +func migrate(conn *sql.DB) error { + // Execute schema migrations + _, err := conn.Exec(schemaSQL) + if err != nil { + return fmt.Errorf("running schema migrations: %w", err) + } + + // Check if locations count is 0 + var count int + err = conn.QueryRow("SELECT COUNT(*) FROM locations").Scan(&count) + if err != nil { + return fmt.Errorf("checking locations count: %w", err) + } + + 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')") + if err != nil { + return fmt.Errorf("inserting default room: %w", err) + } + + // Create the corresponding tag for Default Room + _, err = conn.Exec("INSERT INTO tags (name, color, description) VALUES ('Default Room', '#f59e0b', 'Default tag for items in Default Room')") + if err != nil { + return fmt.Errorf("inserting default room tag: %w", err) + } + } + + return nil +} + +func (d *DB) Close() error { + return d.Conn.Close() +} diff --git a/internal/db/items.go b/internal/db/items.go new file mode 100644 index 0000000..ace98d3 --- /dev/null +++ b/internal/db/items.go @@ -0,0 +1,365 @@ +package db + +import ( + "database/sql" + "fmt" + "time" +) + +type Item struct { + ID int64 + Name string + Description string + Quantity int + ModelNumber string + SerialNumber string + Status string // 'In Use', 'In Storage', 'Borrowed', 'Lost', 'Disposed' + LocationID sql.NullInt64 + LocationName sql.NullString + PurchasePrice sql.NullFloat64 + PurchaseDate sql.NullString // ISO8601 YYYY-MM-DD + WarrantyMonths sql.NullInt64 + Supplier string + CustomFields string // JSON text + ImagePath string + ReceiptPath string + CreatedAt time.Time + UpdatedAt time.Time + Tags []Tag // Loaded on demand + ShortSlug string // Generated or loaded short URL slug +} + +func (d *DB) CreateItem(item *Item, tagIDs []int64) (*Item, error) { + // Wrap in a SQLite transaction for safe consistency + tx, err := d.Conn.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + + res, err := tx.Exec(` + INSERT INTO items ( + name, description, quantity, model_number, serial_number, status, + location_id, purchase_price, purchase_date, warranty_months, supplier, + custom_fields, image_path, receipt_path + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + item.Name, item.Description, item.Quantity, item.ModelNumber, item.SerialNumber, item.Status, + item.LocationID, item.PurchasePrice, item.PurchaseDate, item.WarrantyMonths, item.Supplier, + item.CustomFields, item.ImagePath, item.ReceiptPath, + ) + if err != nil { + return nil, err + } + + itemID, err := res.LastInsertId() + if err != nil { + return nil, err + } + item.ID = itemID + + // Insert tag associations + if len(tagIDs) > 0 { + stmt, err := tx.Prepare("INSERT INTO item_tags (item_id, tag_id) VALUES (?, ?)") + if err != nil { + return nil, err + } + defer stmt.Close() + + for _, tagID := range tagIDs { + _, err = stmt.Exec(item.ID, tagID) + if err != nil { + return nil, err + } + } + } + + if err := tx.Commit(); err != nil { + return nil, err + } + + return item, nil +} + +func (d *DB) GetItem(id int64) (*Item, error) { + row := d.Conn.QueryRow(` + 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 + 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.id = ?`, + id, + ) + + item, err := scanItem(row) + if err != nil { + return nil, err + } + + // Load tags for this item + tags, err := d.getItemTags(item.ID) + if err != nil { + return nil, err + } + item.Tags = d.arrangeTags(item.LocationName.String, tags) + + return item, nil +} + +func (d *DB) UpdateItem(item *Item, tagIDs []int64) error { + tx, err := d.Conn.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + _, err = tx.Exec(` + UPDATE items SET + name = ?, description = ?, quantity = ?, model_number = ?, serial_number = ?, status = ?, + location_id = ?, purchase_price = ?, purchase_date = ?, warranty_months = ?, supplier = ?, + custom_fields = ?, image_path = ?, receipt_path = ?, updated_at = datetime('now') + WHERE id = ?`, + item.Name, item.Description, item.Quantity, item.ModelNumber, item.SerialNumber, item.Status, + item.LocationID, item.PurchasePrice, item.PurchaseDate, item.WarrantyMonths, item.Supplier, + item.CustomFields, item.ImagePath, item.ReceiptPath, item.ID, + ) + if err != nil { + return err + } + + // Rebuild tag associations + _, err = tx.Exec("DELETE FROM item_tags WHERE item_id = ?", item.ID) + if err != nil { + return err + } + + if len(tagIDs) > 0 { + stmt, err := tx.Prepare("INSERT INTO item_tags (item_id, tag_id) VALUES (?, ?)") + if err != nil { + return err + } + defer stmt.Close() + + for _, tagID := range tagIDs { + _, err = stmt.Exec(item.ID, tagID) + if err != nil { + return err + } + } + } + + return tx.Commit() +} + +func (d *DB) DeleteItem(id int64) error { + // Schema cascading rules handle tag mappings and short links automatically + _, err := d.Conn.Exec("DELETE FROM items WHERE id = ?", id) + return err +} + +func (d *DB) ListItems() ([]Item, error) { + rows, err := d.Conn.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 + 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 err != nil { + return nil, err + } + defer rows.Close() + + 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, + ) + 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) + } + + 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 { + locName := "" + if item.LocationName.Valid { + locName = item.LocationName.String + } + if tags, exists := tagMap[item.ID]; exists { + items[idx].Tags = d.arrangeTags(locName, tags) + } else { + items[idx].Tags = d.arrangeTags(locName, []Tag{}) + } + } + + return items, nil +} + +func (d *DB) getItemTags(itemID int64) ([]Tag, error) { + rows, err := d.Conn.Query(` + SELECT t.id, t.name, t.color, t.description + FROM item_tags it + JOIN tags t ON it.tag_id = t.id + WHERE it.item_id = ?`, + itemID, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + var tags []Tag + for rows.Next() { + var t Tag + if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.Description); err != nil { + return nil, err + } + tags = append(tags, t) + } + return tags, rows.Err() +} + +func (d *DB) getBulkItemTags(itemIDs []int64) (map[int64][]Tag, error) { + tagMap := make(map[int64][]Tag) + if len(itemIDs) == 0 { + return tagMap, nil + } + + // Dynamic IN clause building for pure SQL safely (itemIDs are system-generated int64 values) + inClause := "" + for i, id := range itemIDs { + if i > 0 { + inClause += "," + } + inClause += fmt.Sprintf("%d", id) + } + + query := fmt.Sprintf(` + SELECT it.item_id, t.id, t.name, t.color, t.description + FROM item_tags it + JOIN tags t ON it.tag_id = t.id + WHERE it.item_id IN (%s)`, inClause) + + rows, err := d.Conn.Query(query) + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + var itemID int64 + var t Tag + if err := rows.Scan(&itemID, &t.ID, &t.Name, &t.Color, &t.Description); err != nil { + return nil, err + } + tagMap[itemID] = append(tagMap[itemID], t) + } + + return tagMap, rows.Err() +} + +func scanItem(row interface { + Scan(dest ...any) error +}) (*Item, error) { + 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 := 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, + ) + 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) + + return &i, nil +} + +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...) +} diff --git a/internal/db/links.go b/internal/db/links.go new file mode 100644 index 0000000..dab76fa --- /dev/null +++ b/internal/db/links.go @@ -0,0 +1,102 @@ +package db + +import ( + "database/sql" + "time" +) + +type Link struct { + ID int64 + Slug string + URL string + ItemID sql.NullInt64 + CreatedBy string + Clicks int64 + CreatedAt time.Time +} + +func (d *DB) CreateLink(slug, url, createdBy string, itemID sql.NullInt64) (*Link, error) { + res, err := d.Conn.Exec( + "INSERT INTO links (slug, url, created_by, item_id) VALUES (?, ?, ?, ?)", + slug, url, createdBy, itemID, + ) + if err != nil { + return nil, err + } + id, _ := res.LastInsertId() + return &Link{ + ID: id, + Slug: slug, + URL: url, + ItemID: itemID, + CreatedBy: createdBy, + CreatedAt: time.Now(), + }, nil +} + +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) + 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) + return scanLink(row) +} + +func (d *DB) IncrementLinkClicks(slug string) error { + _, err := d.Conn.Exec("UPDATE links SET clicks = clicks + 1 WHERE slug = ?", slug) + 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") + if err != nil { + return nil, err + } + defer rows.Close() + + var links []Link + for rows.Next() { + 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 { + return nil, err + } + l.ItemID = itemID + l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts) + links = append(links, l) + } + return links, rows.Err() +} + +func (d *DB) DeleteLink(id int64) error { + _, err := d.Conn.Exec("DELETE FROM links WHERE id = ?", id) + return err +} + +func (d *DB) UpdateLink(id int64, slug, url string) error { + _, err := d.Conn.Exec("UPDATE links SET slug = ?, url = ? WHERE id = ?", slug, url, id) + return err +} + +func (d *DB) SlugExists(slug string) (bool, error) { + var count int + err := d.Conn.QueryRow("SELECT COUNT(*) FROM links WHERE slug = ?", slug).Scan(&count) + return count > 0, err +} + +func scanLink(row interface { + Scan(dest ...any) error +}) (*Link, error) { + 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 { + return nil, err + } + l.ItemID = itemID + l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts) + return &l, nil +} diff --git a/internal/db/locations.go b/internal/db/locations.go new file mode 100644 index 0000000..c54140d --- /dev/null +++ b/internal/db/locations.go @@ -0,0 +1,222 @@ +package db + +import ( + "database/sql" + "fmt" + "time" +) + +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 +} + +func (d *DB) CreateLocation(name, description string, parentID sql.NullInt64, imagePath string) (*Location, error) { + tx, err := d.Conn.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + + res, err := tx.Exec( + "INSERT INTO locations (name, description, parent_id, image_path) VALUES (?, ?, ?, ?)", + name, 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 + } + + return &Location{ + ID: id, + Name: name, + Description: description, + ParentID: parentID, + ImagePath: imagePath, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }, nil +} + +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 + FROM locations l + LEFT JOIN locations p ON l.parent_id = p.id + WHERE l.id = ?`, + id, + ) + 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") + } + + tx, err := d.Conn.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + var oldName string + err = tx.QueryRow("SELECT name FROM locations WHERE id = ?", id).Scan(&oldName) + if err != nil { + return err + } + + _, err = tx.Exec( + "UPDATE locations SET name = ?, description = ?, parent_id = ?, image_path = ?, updated_at = datetime('now') WHERE id = ?", + name, 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() +} + +func (d *DB) DeleteLocation(id int64) error { + if id == 1 { + return fmt.Errorf("cannot delete the Default Room") + } + + tx, err := d.Conn.Begin() + if err != nil { + return err + } + 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 { + return err + } + + // Delete the location + _, err = tx.Exec("DELETE FROM locations WHERE id = ?", id) + if err != nil { + return err + } + + 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 + FROM locations l + LEFT JOIN locations p ON l.parent_id = p.id + ORDER BY l.name ASC`, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + var locations []Location + for rows.Next() { + var l Location + 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 { + return nil, err + } + l.ParentID = parentID + l.ParentName = parentName + 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, rows.Err() +} + +func scanLocation(row interface { + Scan(dest ...any) error +}) (*Location, error) { + var l Location + 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 { + return nil, err + } + l.ParentID = parentID + l.ParentName = parentName + l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) + l.UpdatedAt, _ = time.Parse("2006-01-02 15:04:05", updated) + return &l, nil +} diff --git a/internal/db/schema.sql b/internal/db/schema.sql new file mode 100644 index 0000000..dded98d --- /dev/null +++ b/internal/db/schema.sql @@ -0,0 +1,68 @@ +-- SQLite Database Schema for Solis +-- Enables high-fidelity asset tracking and custom URL shortening + +-- 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')) +); + +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')) +); + +-- 3. Items Table (Asset entries with purchase records and JSON custom fields) +CREATE TABLE IF NOT EXISTS items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + quantity INTEGER NOT NULL DEFAULT 1, + model_number TEXT NOT NULL DEFAULT '', + serial_number TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'In Use', -- 'In Use', 'In Storage', 'Borrowed', 'Lost', 'Disposed' + location_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, + purchase_price REAL, -- Double/Real for financial values + purchase_date TEXT, -- ISO8601 date string (YYYY-MM-DD) + warranty_months INTEGER, + supplier TEXT NOT NULL DEFAULT '', + 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 '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS idx_items_location ON items(location_id); + +-- 4. Item Tags Junction Table (Many-to-Many relationship) +CREATE TABLE IF NOT EXISTS item_tags ( + item_id INTEGER NOT NULL REFERENCES items(id) ON DELETE CASCADE, + tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE, + PRIMARY KEY (item_id, tag_id) +); + +-- 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')) +); + +CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug); +CREATE INDEX IF NOT EXISTS idx_links_item ON links(item_id); diff --git a/internal/db/tags.go b/internal/db/tags.go new file mode 100644 index 0000000..5026ce8 --- /dev/null +++ b/internal/db/tags.go @@ -0,0 +1,107 @@ +package db + +import ( + "fmt" + "time" +) + +type Tag struct { + ID int64 + Name string + Color string // Hex representation, e.g. "#3b82f6" + Description string + CreatedAt time.Time +} + +func (d *DB) CreateTag(name, color, description string) (*Tag, error) { + if color == "" { + color = "#e2e8f0" // default soft light gray + } + res, err := d.Conn.Exec( + "INSERT INTO tags (name, color, description) VALUES (?, ?, ?)", + name, color, description, + ) + if err != nil { + return nil, err + } + id, _ := res.LastInsertId() + return &Tag{ + ID: id, + Name: name, + Color: color, + Description: description, + CreatedAt: time.Now(), + }, nil +} + +func (d *DB) GetTag(id int64) (*Tag, error) { + row := d.Conn.QueryRow("SELECT id, name, color, description, 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) + return scanTag(row) +} + +func (d *DB) UpdateTag(id int64, name, color, description string) error { + if color == "" { + color = "#e2e8f0" + } + + var oldName string + err := d.Conn.QueryRow("SELECT name FROM tags WHERE id = ?", id).Scan(&oldName) + if err == nil && oldName == "Default Room" && name != "Default Room" { + return fmt.Errorf("cannot rename the Default Room tag") + } + + _, err = d.Conn.Exec( + "UPDATE tags SET name = ?, color = ?, description = ? WHERE id = ?", + name, color, description, id, + ) + return err +} + +func (d *DB) DeleteTag(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 delete the Default Room tag") + } + + // Foreign key constraints on item_tags handle cascade delete + _, err = d.Conn.Exec("DELETE FROM tags WHERE id = ?", id) + 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") + if err != nil { + return nil, err + } + defer rows.Close() + + var tags []Tag + for rows.Next() { + var t Tag + var created string + if err := rows.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &created); err != nil { + return nil, err + } + t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) + tags = append(tags, t) + } + return tags, rows.Err() +} + +func scanTag(row interface { + Scan(dest ...any) error +}) (*Tag, error) { + var t Tag + var created string + if err := row.Scan(&t.ID, &t.Name, &t.Color, &t.Description, &created); err != nil { + return nil, err + } + t.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", created) + return &t, nil +} diff --git a/internal/server/handlers.go b/internal/server/handlers.go new file mode 100644 index 0000000..240941b --- /dev/null +++ b/internal/server/handlers.go @@ -0,0 +1,929 @@ +package server + +import ( + "database/sql" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "Solis/internal/db" + "Solis/internal/slug" + + "github.com/google/uuid" + "golang.org/x/crypto/bcrypt" +) + +// Global View Data context +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 +} + +// ========================================== +// 1. PUBLIC SHORT URL REDIRECT HANDLER +// ========================================== + +func (s *Server) handleShortRedirect(w http.ResponseWriter, r *http.Request) { + slugVal := r.PathValue("slug") + if slugVal == "" { + http.NotFound(w, r) + return + } + + // Fetch redirect target by slug + link, err := s.db.GetLinkBySlug(slugVal) + if err != nil { + if err == sql.ErrNoRows { + http.NotFound(w, r) + return + } + http.Error(w, "Database error", http.StatusInternalServerError) + return + } + + // Increment analytics click counter + _ = s.db.IncrementLinkClicks(link.Slug) + + // Perform redirect + http.Redirect(w, r, link.URL, http.StatusMovedPermanently) +} + +// ========================================== +// 2. AUTHENTICATION & LOGIN HANDLERS +// ========================================== + +func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) { + // If already authenticated, redirect to Admin dashboard + if cookie, err := r.Cookie("session"); err == nil && s.sessions.Valid(cookie.Value) { + http.Redirect(w, r, "/admin", http.StatusSeeOther) + return + } + + data := PageData{ + CSRFToken: csrfToken(w, r), + } + renderTemplate(w, "login.html", data) +} + +func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { + ip := clientIP(r) + if !s.limiter.Allow(ip) { + data := PageData{ + CSRFToken: csrfToken(w, r), + Error: "Too many login attempts. Please wait.", + } + w.WriteHeader(http.StatusTooManyRequests) + renderTemplate(w, "login.html", data) + return + } + + // Validate CSRF + if !verifyCSRF(r) { + http.Error(w, "Invalid CSRF token", http.StatusForbidden) + return + } + + username := r.FormValue("username") + password := r.FormValue("password") + + // Verify Admin Credentials using Bcrypt + if username == s.cfg.Admin.Username && bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)) == nil { + token, err := s.sessions.Create() + if err != nil { + http.Error(w, "Session creation failed", http.StatusInternalServerError) + return + } + + // Set highly secure session cookie + http.SetCookie(w, &http.Cookie{ + Name: "session", + Value: token, + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + MaxAge: int(time.Duration(s.cfg.Admin.SessionHours) * time.Hour / time.Second), + }) + + http.Redirect(w, r, "/admin", http.StatusSeeOther) + return + } + + data := PageData{ + CSRFToken: csrfToken(w, r), + Error: "Invalid username or password.", + } + renderTemplate(w, "login.html", data) +} + +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("session") + if err == nil { + s.sessions.Delete(cookie.Value) + } + + // Expire session cookie + http.SetCookie(w, &http.Cookie{ + Name: "session", + Value: "", + Path: "/", + HttpOnly: true, + MaxAge: -1, + }) + + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) +} + +// ========================================== +// 3. ASSET INVENTORY ITEMS CRUD HANDLERS +// ========================================== + +func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) { + csrf := csrfToken(w, r) + locations, _ := s.db.ListLocations() + tags, _ := s.db.ListTags() + + // 1. DETAIL VIEW MODE + 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) + + data := PageData{ + CSRFToken: csrf, + ActiveNav: "items", + Item: item, + ViewMode: true, + CustomFieldsMap: cfMap, + Locations: locations, + Tags: tags, + Toast: r.URL.Query().Get("toast"), + ToastType: r.URL.Query().Get("toast_type"), + } + renderTemplate(w, "items.html", data) + return + } + } + } + + // 2. LIST ALL ITEMS MODE (With filter / search criteria) + searchQuery := r.URL.Query().Get("search") + statusQuery := r.URL.Query().Get("status") + locationQuery := r.URL.Query().Get("location") + + allItems, err := s.db.ListItems() + if err != nil { + http.Error(w, "Failed to load assets", http.StatusInternalServerError) + return + } + + // Apply filtering in memory (simple and extremely fast on SQLite dataset) + var filteredItems []db.Item + var locFilterID int64 + if locationQuery != "" { + locFilterID, _ = strconv.ParseInt(locationQuery, 10, 64) + } + + for _, item := range allItems { + matchesSearch := searchQuery == "" || + strings.Contains(strings.ToLower(item.Name), strings.ToLower(searchQuery)) || + strings.Contains(strings.ToLower(item.ModelNumber), strings.ToLower(searchQuery)) || + strings.Contains(strings.ToLower(item.SerialNumber), strings.ToLower(searchQuery)) + + matchesStatus := statusQuery == "" || item.Status == statusQuery + + matchesLocation := locationQuery == "" || (item.LocationID.Valid && item.LocationID.Int64 == locFilterID) + + if matchesSearch && matchesStatus && matchesLocation { + filteredItems = append(filteredItems, item) + } + } + + data := PageData{ + CSRFToken: csrf, + ActiveNav: "items", + Items: filteredItems, + Locations: locations, + Tags: tags, + SearchQuery: searchQuery, + SelectedStatus: statusQuery, + SelectedLocation: locFilterID, + Toast: r.URL.Query().Get("toast"), + ToastType: r.URL.Query().Get("toast_type"), + } + + renderTemplate(w, "items.html", data) +} + +func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) { + locations, _ := s.db.ListLocations() + tags, _ := s.db.ListTags() + + data := PageData{ + CSRFToken: csrfToken(w, r), + ActiveNav: "items", + Locations: locations, + Tags: tags, + FormMode: true, + } + renderTemplate(w, "items.html", data) +} + +func (s *Server) handleItemCreate(w http.ResponseWriter, r *http.Request) { + // Limit file uploads to prevent resource exhaustion attacks + r.Body = http.MaxBytesReader(w, r.Body, s.cfg.Upload.MaxSize*1024*1024) + if err := r.ParseMultipartForm(s.cfg.Upload.MaxSize * 1024 * 1024); err != nil { + http.Error(w, "Upload exceeds maximum limit", http.StatusBadRequest) + return + } + + name := r.FormValue("name") + qty, _ := strconv.Atoi(r.FormValue("quantity")) + desc := r.FormValue("description") + model := r.FormValue("model_number") + serial := r.FormValue("serial_number") + status := r.FormValue("status") + supplier := r.FormValue("supplier") + + var locID sql.NullInt64 + if locVal := r.FormValue("location_id"); locVal != "" { + id, _ := strconv.ParseInt(locVal, 10, 64) + locID = sql.NullInt64{Int64: id, Valid: true} + } else { + locID = sql.NullInt64{Int64: 1, Valid: true} + } + + var price sql.NullFloat64 + if priceVal := r.FormValue("purchase_price"); priceVal != "" { + p, _ := strconv.ParseFloat(priceVal, 64) + price = sql.NullFloat64{Float64: p, Valid: true} + } + + var date sql.NullString + if dateVal := r.FormValue("purchase_date"); dateVal != "" { + date = sql.NullString{String: dateVal, Valid: true} + } + + var warranty sql.NullInt64 + if warrVal := r.FormValue("warranty_months"); warrVal != "" { + w, _ := strconv.ParseInt(warrVal, 10, 64) + warranty = sql.NullInt64{Int64: w, Valid: true} + } + + // Parse tags checkboxes + var tagIDs []int64 + for _, idStr := range r.MultipartForm.Value["tag_ids"] { + id, _ := strconv.ParseInt(idStr, 10, 64) + tagIDs = append(tagIDs, id) + } + + // Resolve the room tag, prepend it, and deduplicate + tagIDs = s.resolveRoomTag(locID.Int64, tagIDs) + + // Handle secure file uploads (photo and receipt) + imagePath, _ := s.saveUploadedFile(r, "image", true) + receiptPath, _ := s.saveUploadedFile(r, "receipt", false) + + // Format custom fields input to SQLite JSON string + customFieldsJSON := parseCustomFields(r.FormValue("custom_fields")) + + item := &db.Item{ + Name: name, + Description: desc, + Quantity: qty, + ModelNumber: model, + SerialNumber: serial, + Status: status, + LocationID: locID, + PurchasePrice: price, + PurchaseDate: date, + WarrantyMonths: warranty, + Supplier: supplier, + CustomFields: customFieldsJSON, + ImagePath: imagePath, + ReceiptPath: receiptPath, + } + + // Insert item into database + createdItem, err := s.db.CreateItem(item, tagIDs) + if err != nil { + log.Printf("Error creating item: %v", err) + http.Error(w, "Failed to create item", http.StatusInternalServerError) + 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}) + } + + http.Redirect(w, r, "/admin?toast=Asset+created+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleItemEdit(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + item, err := s.db.GetItem(id) + if err != nil { + http.NotFound(w, r) + return + } + + locations, _ := s.db.ListLocations() + tags, _ := s.db.ListTags() + + // Translate custom JSON string back to raw lines for edit comfort + customFieldsRaw := formatCustomFields(item.CustomFields) + + data := PageData{ + CSRFToken: csrfToken(w, r), + ActiveNav: "items", + Locations: locations, + Tags: tags, + EditingItem: item, + CustomFieldsRaw: customFieldsRaw, + FormMode: true, + } + renderTemplate(w, "items.html", data) +} + +func (s *Server) handleItemSave(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + item, err := s.db.GetItem(id) + if err != nil { + http.NotFound(w, r) + return + } + + r.Body = http.MaxBytesReader(w, r.Body, s.cfg.Upload.MaxSize*1024*1024) + if err := r.ParseMultipartForm(s.cfg.Upload.MaxSize * 1024 * 1024); err != nil { + http.Error(w, "Upload size exceeded", http.StatusBadRequest) + return + } + + name := r.FormValue("name") + qty, _ := strconv.Atoi(r.FormValue("quantity")) + desc := r.FormValue("description") + model := r.FormValue("model_number") + serial := r.FormValue("serial_number") + status := r.FormValue("status") + supplier := r.FormValue("supplier") + + var locID sql.NullInt64 + if locVal := r.FormValue("location_id"); locVal != "" { + lid, _ := strconv.ParseInt(locVal, 10, 64) + locID = sql.NullInt64{Int64: lid, Valid: true} + } else { + locID = sql.NullInt64{Int64: 1, Valid: true} + } + + var price sql.NullFloat64 + if priceVal := r.FormValue("purchase_price"); priceVal != "" { + p, _ := strconv.ParseFloat(priceVal, 64) + price = sql.NullFloat64{Float64: p, Valid: true} + } + + var date sql.NullString + if dateVal := r.FormValue("purchase_date"); dateVal != "" { + date = sql.NullString{String: dateVal, Valid: true} + } + + var warranty sql.NullInt64 + if warrVal := r.FormValue("warranty_months"); warrVal != "" { + w, _ := strconv.ParseInt(warrVal, 10, 64) + warranty = sql.NullInt64{Int64: w, Valid: true} + } + + // Parse tags checkboxes + var tagIDs []int64 + for _, idStr := range r.MultipartForm.Value["tag_ids"] { + tid, _ := strconv.ParseInt(idStr, 10, 64) + tagIDs = append(tagIDs, tid) + } + + // Resolve the room tag, prepend it, and deduplicate + tagIDs = s.resolveRoomTag(locID.Int64, tagIDs) + + // Securely upload new files and purge old replaced files + newImage, hasNewImg := s.saveUploadedFile(r, "image", true) + if hasNewImg && item.ImagePath != "" { + _ = os.Remove(filepath.Join(s.cfg.Upload.Dir, item.ImagePath)) + } + if hasNewImg { + item.ImagePath = newImage + } + + newReceipt, hasNewRec := s.saveUploadedFile(r, "receipt", false) + if hasNewRec && item.ReceiptPath != "" { + _ = os.Remove(filepath.Join(s.cfg.Upload.Dir, item.ReceiptPath)) + } + if hasNewRec { + item.ReceiptPath = newReceipt + } + + customFieldsJSON := parseCustomFields(r.FormValue("custom_fields")) + + // Update record + item.Name = name + item.Description = desc + item.Quantity = qty + item.ModelNumber = model + item.SerialNumber = serial + item.Status = status + item.LocationID = locID + item.PurchasePrice = price + item.PurchaseDate = date + item.WarrantyMonths = warranty + item.Supplier = supplier + item.CustomFields = customFieldsJSON + + err = s.db.UpdateItem(item, tagIDs) + if err != nil { + http.Error(w, "Failed to update item", http.StatusInternalServerError) + return + } + + 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) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + // Load item details first to delete uploaded file media from disk + item, err := s.db.GetItem(id) + if err == nil { + if item.ImagePath != "" { + _ = os.Remove(filepath.Join(s.cfg.Upload.Dir, item.ImagePath)) + } + if item.ReceiptPath != "" { + _ = os.Remove(filepath.Join(s.cfg.Upload.Dir, item.ReceiptPath)) + } + } + + _ = s.db.DeleteItem(id) + http.Redirect(w, r, "/admin?toast=Asset+deleted+successfully&toast_type=success", http.StatusSeeOther) +} + +// ========================================== +// 4. LOCATIONS MANAGEMENT HANDLERS +// ========================================== + +func (s *Server) handleAdminLocations(w http.ResponseWriter, r *http.Request) { + csrf := csrfToken(w, r) + locations, _ := s.db.ListLocations() + + var editLoc *db.Location + if editIDStr := r.URL.Query().Get("edit"); editIDStr != "" { + id, err := strconv.ParseInt(editIDStr, 10, 64) + if err == nil { + editLoc, _ = s.db.GetLocation(id) + } + } + + data := PageData{ + CSRFToken: csrf, + ActiveNav: "locations", + Locations: locations, + EditingLocation: editLoc, + Toast: r.URL.Query().Get("toast"), + ToastType: r.URL.Query().Get("toast_type"), + } + renderTemplate(w, "locations.html", data) +} + +func (s *Server) handleLocationCreate(w http.ResponseWriter, r *http.Request) { + name := r.FormValue("name") + desc := r.FormValue("description") + + var parentID sql.NullInt64 + if parentVal := r.FormValue("parent_id"); parentVal != "" { + id, _ := strconv.ParseInt(parentVal, 10, 64) + parentID = sql.NullInt64{Int64: id, Valid: true} + } + + _, err := s.db.CreateLocation(name, desc, parentID, "") + if err != nil { + http.Error(w, "Failed to create location", http.StatusInternalServerError) + return + } + + http.Redirect(w, r, "/admin/locations?toast=Location+created+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLocationEdit(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + name := r.FormValue("name") + desc := r.FormValue("description") + + var parentID sql.NullInt64 + if parentVal := r.FormValue("parent_id"); parentVal != "" { + pid, _ := strconv.ParseInt(parentVal, 10, 64) + parentID = sql.NullInt64{Int64: pid, Valid: true} + } + + _ = s.db.UpdateLocation(id, name, desc, parentID, "") + 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) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.DeleteLocation(id) + http.Redirect(w, r, "/admin/locations?toast=Location+deleted+successfully&toast_type=success", http.StatusSeeOther) +} + +// ========================================== +// 5. TAGS MANAGEMENT HANDLERS +// ========================================== + +func (s *Server) handleAdminTags(w http.ResponseWriter, r *http.Request) { + csrf := csrfToken(w, r) + tags, _ := s.db.ListTags() + + var editTag *db.Tag + if editIDStr := r.URL.Query().Get("edit"); editIDStr != "" { + id, err := strconv.ParseInt(editIDStr, 10, 64) + if err == nil { + editTag, _ = s.db.GetTag(id) + } + } + + data := PageData{ + CSRFToken: csrf, + ActiveNav: "tags", + Tags: tags, + EditingTag: editTag, + Toast: r.URL.Query().Get("toast"), + ToastType: r.URL.Query().Get("toast_type"), + } + renderTemplate(w, "tags.html", data) +} + +func (s *Server) handleTagCreate(w http.ResponseWriter, r *http.Request) { + name := r.FormValue("name") + color := r.FormValue("color") + desc := r.FormValue("description") + + _, err := s.db.CreateTag(name, color, desc) + if err != nil { + http.Error(w, "Failed to create tag", http.StatusInternalServerError) + return + } + + http.Redirect(w, r, "/admin/tags?toast=Tag+created+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleTagEdit(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + name := r.FormValue("name") + color := r.FormValue("color") + desc := r.FormValue("description") + + _ = s.db.UpdateTag(id, name, color, desc) + 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) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.DeleteTag(id) + http.Redirect(w, r, "/admin/tags?toast=Tag+deleted+successfully&toast_type=success", http.StatusSeeOther) +} + +// ========================================== +// 6. SHORTENER / LINK REDIRECT HANDLERS +// ========================================== + +func (s *Server) handleAdminShortener(w http.ResponseWriter, r *http.Request) { + csrf := csrfToken(w, r) + links, _ := s.db.ListLinks() + + 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) + 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 { + l.ItemID = itemID + l.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", ts) + editLink = &l + } + } + } + + data := PageData{ + CSRFToken: csrf, + ActiveNav: "shortener", + Links: links, + EditingLink: editLink, + Toast: r.URL.Query().Get("toast"), + ToastType: r.URL.Query().Get("toast_type"), + } + renderTemplate(w, "shortener.html", data) +} + +func (s *Server) handleLinkCreate(w http.ResponseWriter, r *http.Request) { + slugVal := strings.TrimSpace(r.FormValue("slug")) + urlVal := strings.TrimSpace(r.FormValue("url")) + + if urlVal == "" { + http.Redirect(w, r, "/admin/shortener?toast=Destination+URL+is+required&toast_type=error", http.StatusSeeOther) + return + } + + // Auto generate slug if left blank + if slugVal == "" { + for i := 0; i < 10; i++ { + temp := slug.Generate(s.cfg.Slugs.Length) + exists, _ := s.db.SlugExists(temp) + if !exists { + slugVal = temp + break + } + } + } + + // Validate slug syntax using glimmer validator + if err := slug.Validate(slugVal); err != nil { + http.Redirect(w, r, fmt.Sprintf("/admin/shortener?toast=%s&toast_type=error", err.Error()), http.StatusSeeOther) + return + } + + // Validate duplicate slug + exists, _ := s.db.SlugExists(slugVal) + if exists { + http.Redirect(w, r, "/admin/shortener?toast=Short+slug+already+exists&toast_type=error", http.StatusSeeOther) + return + } + + _, err := s.db.CreateLink(slugVal, urlVal, "admin", sql.NullInt64{Valid: false}) + if err != nil { + http.Error(w, "Failed to create short link", http.StatusInternalServerError) + return + } + + http.Redirect(w, r, "/admin/shortener?toast=Custom+shortlink+added+successfully&toast_type=success", http.StatusSeeOther) +} + +func (s *Server) handleLinkSave(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + slugVal := strings.TrimSpace(r.FormValue("slug")) + urlVal := strings.TrimSpace(r.FormValue("url")) + + // Validate slug + if err := slug.Validate(slugVal); err != nil { + http.Redirect(w, r, fmt.Sprintf("/admin/shortener?toast=%s&toast_type=error", err.Error()), http.StatusSeeOther) + return + } + + // Check if this slug is taken by ANOTHER link ID + var existingID int64 + err = s.db.Conn.QueryRow("SELECT id FROM links WHERE slug = ? AND id != ?", slugVal, id).Scan(&existingID) + if err == nil { + http.Redirect(w, r, "/admin/shortener?toast=Short+slug+already+taken&toast_type=error", http.StatusSeeOther) + return + } + + _ = s.db.UpdateLink(id, slugVal, urlVal) + 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) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + + _ = s.db.DeleteLink(id) + http.Redirect(w, r, "/admin/shortener?toast=Shortlink+deleted+successfully&toast_type=success", http.StatusSeeOther) +} + +// ========================================== +// 7. LABELS & PRINT ENGINE HANDLER +// ========================================== + +func (s *Server) handlePrintLabels(w http.ResponseWriter, r *http.Request) { + csrf := csrfToken(w, r) + items, err := s.db.ListItems() + if err != nil { + http.Error(w, "Failed to load labels", http.StatusInternalServerError) + return + } + + data := PageData{ + CSRFToken: csrf, + ActiveNav: "print", + Items: items, + } + renderTemplate(w, "print_labels.html", data) +} + +// ========================================== +// 8. SECURITY PRIVATE MEDIA UPLOAD HELPERS +// ========================================== + +func (s *Server) saveUploadedFile(r *http.Request, fieldName string, isImage bool) (string, bool) { + file, header, err := r.FormFile(fieldName) + if err != nil { + return "", false // No file uploaded or empty + } + defer file.Close() + + // Sniff MIME type using standard 512-byte detection + buffer := make([]byte, 512) + n, _ := file.Read(buffer) + mimeType := http.DetectContentType(buffer[:n]) + file.Seek(0, io.SeekStart) + + // Validate content types + if isImage { + switch mimeType { + case "image/jpeg", "image/png", "image/webp": + // Allow + default: + log.Printf("Rejected image upload. Invalid MIME type: %s", mimeType) + return "", false + } + } else { + switch mimeType { + case "image/jpeg", "image/png", "image/webp", "application/pdf": + // Allow + default: + log.Printf("Rejected receipt document. Invalid MIME type: %s", mimeType) + return "", false + } + } + + // Generate safe, randomized filename (UUID) keeping original extension + ext := strings.ToLower(filepath.Ext(header.Filename)) + if ext == "" { + // Fallback clean extensions + if mimeType == "application/pdf" { + ext = ".pdf" + } else if mimeType == "image/png" { + ext = ".png" + } else { + ext = ".jpg" + } + } + + uniqueFilename := fmt.Sprintf("%s%s", uuid.New().String(), ext) + outPath := filepath.Join(s.cfg.Upload.Dir, uniqueFilename) + + outFile, err := os.Create(outPath) + if err != nil { + log.Printf("Error creating upload output file: %v", err) + return "", false + } + defer outFile.Close() + + _, err = io.Copy(outFile, file) + if err != nil { + log.Printf("Error writing file contents: %v", err) + return "", false + } + + return uniqueFilename, true +} + +// Custom Fields Textarea parser: translates key: value lines to SQLite JSON +func parseCustomFields(raw string) string { + lines := strings.Split(raw, "\n") + m := make(map[string]string) + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + parts := strings.SplitN(line, ":", 2) + if len(parts) == 2 { + key := strings.TrimSpace(parts[0]) + val := strings.TrimSpace(parts[1]) + if key != "" && val != "" { + m[key] = val + } + } + } + + b, _ := json.Marshal(m) + return string(b) +} + +// Translates SQLite JSON string back to Key: Value lines for easy text form editing +func formatCustomFields(jsonStr string) string { + if jsonStr == "" || jsonStr == "{}" { + return "" + } + var m map[string]string + if err := json.Unmarshal([]byte(jsonStr), &m); err != nil { + return "" + } + var sb strings.Builder + for k, v := range m { + sb.WriteString(fmt.Sprintf("%s: %s\n", k, v)) + } + return sb.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" + } + 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) + } + + // If we still don't have a valid tag ID, return the original tagIDs unchanged + if roomTagID == 0 { + return tagIDs + } + + // Build a deduplicated list with roomTagID first + dedupTagIDs := []int64{roomTagID} + for _, tid := range tagIDs { + if tid != roomTagID && tid != 0 { + dedupTagIDs = append(dedupTagIDs, tid) + } + } + return dedupTagIDs +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go new file mode 100644 index 0000000..6be9081 --- /dev/null +++ b/internal/server/middleware.go @@ -0,0 +1,189 @@ +package server + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "net" + "net/http" + "strings" + "sync" + "time" +) + +type sessionStore struct { + mu sync.RWMutex + sessions map[string]time.Time + ttl time.Duration +} + +func newSessionStore(ttl time.Duration) *sessionStore { + s := &sessionStore{ + sessions: make(map[string]time.Time), + ttl: ttl, + } + go s.cleanup() + return s +} + +func (s *sessionStore) cleanup() { + ticker := time.NewTicker(time.Hour) + defer ticker.Stop() + for range ticker.C { + s.mu.Lock() + now := time.Now() + for token, expiry := range s.sessions { + if now.After(expiry) { + delete(s.sessions, token) + } + } + s.mu.Unlock() + } +} + +func (s *sessionStore) Create() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + token := hex.EncodeToString(b) + s.mu.Lock() + s.sessions[token] = time.Now().Add(s.ttl) + s.mu.Unlock() + return token, nil +} + +func (s *sessionStore) Valid(token string) bool { + s.mu.RLock() + expiry, ok := s.sessions[token] + s.mu.RUnlock() + if !ok { + return false + } + if time.Now().After(expiry) { + s.mu.Lock() + delete(s.sessions, token) + s.mu.Unlock() + return false + } + return true +} + +func (s *sessionStore) Delete(token string) { + s.mu.Lock() + delete(s.sessions, token) + s.mu.Unlock() +} + +func (srv *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("session") + if err != nil || !srv.sessions.Valid(cookie.Value) { + // Check if it's an HTMX request. If so, trigger a client-side redirect + if r.Header.Get("HX-Request") == "true" { + w.Header().Set("HX-Redirect", "/admin/login") + w.WriteHeader(http.StatusUnauthorized) + return + } + http.Redirect(w, r, "/admin/login", http.StatusSeeOther) + return + } + next(w, r) + } +} + +// csrfToken returns the CSRF token for this session, creating one if needed. +// Uses a lax cookie, embedded in HTMX meta templates and form files. +func csrfToken(w http.ResponseWriter, r *http.Request) string { + if c, err := r.Cookie("csrf"); err == nil && len(c.Value) == 64 { + return c.Value + } + b := make([]byte, 32) + rand.Read(b) + token := hex.EncodeToString(b) + http.SetCookie(w, &http.Cookie{ + Name: "csrf", + Value: token, + Path: "/", + SameSite: http.SameSiteLaxMode, + MaxAge: 86400, + }) + return token +} + +func verifyCSRF(r *http.Request) bool { + cookie, err := r.Cookie("csrf") + if err != nil { + return false + } + + // 1. Verify via form value + formToken := r.FormValue("csrf_token") + if subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(formToken)) == 1 { + return true + } + + // 2. Verify via standard headers (useful for HTMX / AJAX calls) + headerToken := r.Header.Get("X-CSRF-Token") + if headerToken == "" { + headerToken = r.Header.Get("HX-CSRF-Token") + } + return subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(headerToken)) == 1 +} + +func (srv *Server) requireCSRF(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !verifyCSRF(r) { + http.Error(w, "Invalid CSRF token", http.StatusForbidden) + return + } + next(w, r) + } +} + +// rateLimiter tracks the last request time per IP. +type rateLimiter struct { + mu sync.Mutex + clients map[string]time.Time + window time.Duration +} + +func newRateLimiter(window time.Duration) *rateLimiter { + return &rateLimiter{ + clients: make(map[string]time.Time), + window: window, + } +} + +func (rl *rateLimiter) Allow(ip string) bool { + rl.mu.Lock() + defer rl.mu.Unlock() + now := time.Now() + if last, ok := rl.clients[ip]; ok && now.Sub(last) < rl.window { + return false + } + rl.clients[ip] = now + // Lazy cleanup: purge stale entries when map grows large + if len(rl.clients) > 1000 { + for k, v := range rl.clients { + if now.Sub(v) > rl.window*10 { + delete(rl.clients, k) + } + } + } + return true +} + +func clientIP(r *http.Request) string { + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + if i := strings.Index(xff, ","); i > 0 { + return strings.TrimSpace(xff[:i]) + } + return strings.TrimSpace(xff) + } + if xri := r.Header.Get("X-Real-Ip"); xri != "" { + return strings.TrimSpace(xri) + } + host, _, _ := net.SplitHostPort(r.RemoteAddr) + return host +} diff --git a/internal/server/qr.go b/internal/server/qr.go new file mode 100644 index 0000000..08e5bb6 --- /dev/null +++ b/internal/server/qr.go @@ -0,0 +1,48 @@ +package server + +import ( + "fmt" + "net/http" + + "github.com/skip2/go-qrcode" +) + +// GenerateQRCodePNG encodes a given string (e.g. short link URL) into a 256x256 PNG image +func GenerateQRCodePNG(data string) ([]byte, error) { + png, err := qrcode.Encode(data, qrcode.Medium, 256) + if err != nil { + return nil, fmt.Errorf("encoding qr code: %w", err) + } + return png, nil +} + +// HandleQR serves a PNG image containing a QR code for a given short slug +func (s *Server) handleQR(w http.ResponseWriter, r *http.Request) { + slug := r.PathValue("slug") + if slug == "" { + http.Error(w, "Missing slug", http.StatusBadRequest) + return + } + + // Double check if slug exists in database + exists, err := s.db.SlugExists(slug) + if err != nil || !exists { + http.Error(w, "Slug not found", http.StatusNotFound) + return + } + + // Build the absolute short URL + shortURL := fmt.Sprintf("%s/s/%s", s.cfg.Server.BaseURL, slug) + + // Generate QR code PNG + pngData, err := GenerateQRCodePNG(shortURL) + if err != nil { + http.Error(w, "Failed to generate QR code", http.StatusInternalServerError) + return + } + + // Write PNG to response + w.Header().Set("Content-Type", "image/png") + w.Header().Set("Cache-Control", "public, max-age=86400") // Cache for 24h as QR codes are static + w.Write(pngData) +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..0560ac9 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,180 @@ +package server + +import ( + "fmt" + "io" + "io/fs" + "log" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "Solis/internal/config" + "Solis/internal/db" +) + +type Server struct { + cfg *config.Config + db *db.DB + sessions *sessionStore + limiter *rateLimiter +} + +func New(cfg *config.Config, database *db.DB) *Server { + ttl := time.Duration(cfg.Admin.SessionHours) * time.Hour + return &Server{ + cfg: cfg, + db: database, + sessions: newSessionStore(ttl), + limiter: newRateLimiter(2 * time.Second), // 2 seconds between login attempts + } +} + +func securityHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") + + // Offline-first CSP: Only allows local static resources and fonts from Google Fonts + w.Header().Set("Content-Security-Policy", + "default-src 'self'; "+ + "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "+ + "font-src 'self' https://fonts.gstatic.com; "+ + "img-src 'self' data:; "+ + "connect-src 'self';") + + next.ServeHTTP(w, r) + }) +} + +// lowercasePath normalises URL paths to lowercase so that short links are case-insensitive. +// Admin, uploads, and static routes are excluded to preserve asset names. +func lowercasePath(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + lower := strings.ToLower(r.URL.Path) + if lower != r.URL.Path && + !strings.HasPrefix(r.URL.Path, "/static/") && + !strings.HasPrefix(lower, "/admin") && + !strings.HasPrefix(r.URL.Path, "/uploads/") { + r.URL.Path = lower + http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently) + return + } + next.ServeHTTP(w, r) + }) +} + +func (s *Server) Start() error { + initTemplates() + + // Ensure upload directory exists + if err := os.MkdirAll(s.cfg.Upload.Dir, 0755); err != nil { + return fmt.Errorf("creating upload directory: %w", err) + } + + mux := http.NewServeMux() + + // 1. Embedded static files + staticSub, _ := fs.Sub(staticFS, "static") + mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub)))) + + // 2. Safe Uploads Serving + mux.HandleFunc("GET /uploads/", s.handleServeUploads) + + // 3. Root redirect to Admin panel + mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/admin", http.StatusSeeOther) + }) + + // 4. Short Slug Redirect Handler + mux.HandleFunc("GET /s/{slug}", s.handleShortRedirect) + + // 5. Authentication handlers + mux.HandleFunc("GET /admin/login", s.handleLoginPage) + mux.HandleFunc("POST /admin/login", s.handleLogin) + mux.HandleFunc("POST /admin/logout", s.requireAuth(s.requireCSRF(s.handleLogout))) + + // 6. Admin items management (HTMX & standard CRUD) + mux.HandleFunc("GET /admin", s.requireAuth(s.handleAdminItems)) + mux.HandleFunc("GET /admin/items/new", s.requireAuth(s.handleItemNew)) + 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))) + + // 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))) + + // 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))) + + // 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))) + + // 10. QR & Labels + mux.HandleFunc("GET /admin/qr/{slug}", s.requireAuth(s.handleQR)) + mux.HandleFunc("GET /admin/print", s.requireAuth(s.handlePrintLabels)) + + // Listen and serve + addr := fmt.Sprintf(":%d", s.cfg.Server.Port) + srv := &http.Server{ + Addr: addr, + Handler: lowercasePath(securityHeaders(mux)), + ReadTimeout: s.cfg.Server.ReadTimeoutDuration(), + WriteTimeout: s.cfg.Server.WriteTimeoutDuration(), + } + + log.Printf("Solis running on http://localhost:%d (Base URL: %s)", s.cfg.Server.Port, s.cfg.Server.BaseURL) + return srv.ListenAndServe() +} + +// handleServeUploads serving local photos/receipts safely +func (s *Server) handleServeUploads(w http.ResponseWriter, r *http.Request) { + // Extract clean filename to prevent directory traversal + filename := filepath.Base(r.URL.Path) + filePath := filepath.Join(s.cfg.Upload.Dir, filename) + + // Validate path is strictly inside s.cfg.Upload.Dir + if !strings.HasPrefix(filepath.Clean(filePath), filepath.Clean(s.cfg.Upload.Dir)) { + http.Error(w, "Access Denied", http.StatusForbidden) + return + } + + file, err := os.Open(filePath) + if err != nil { + http.Error(w, "File not found", http.StatusNotFound) + return + } + defer file.Close() + + // Sniff MIME type to prevent same-origin executable execution (e.g. SVG/HTML uploads running JS) + buffer := make([]byte, 512) + n, _ := file.Read(buffer) + mimeType := http.DetectContentType(buffer[:n]) + file.Seek(0, io.SeekStart) + + // Direct rendering is allowed for safe image MIME types only + switch mimeType { + case "image/jpeg", "image/png", "image/gif", "image/webp": + w.Header().Set("Content-Type", mimeType) + w.Header().Set("Cache-Control", "public, max-age=31536000") // Cache heavily + default: + // Force download/attachment for all other mime types (e.g. PDF/TXT receipts or arbitrary files) + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename)) + } + + io.Copy(w, file) +} diff --git a/internal/server/static/css/styles.css b/internal/server/static/css/styles.css new file mode 100644 index 0000000..b437507 --- /dev/null +++ b/internal/server/static/css/styles.css @@ -0,0 +1,589 @@ +/* Solis CSS Design System + Theme: Sunlight & Clarity (Amber, Gold, Cream, Slate) */ + +@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap'); + +:root { + --font-sans: 'Outfit', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + + /* Warm sunlight colors */ + --color-bg-base: #fafaf9; /* Stone 50 - creamy clean background */ + --color-bg-surface: #ffffff; /* Pure white cards */ + --color-bg-warm: #fef3c7; /* Amber 100 - warm highlights */ + + --color-text-main: #1c1917; /* Stone 900 - extreme readability */ + --color-text-muted: #6b6661; /* Stone 500 */ + --color-text-light: #a8a29e; /* Stone 400 */ + + --color-brand-primary: #d97706; /* Amber 600 - solar branding */ + --color-brand-hover: #b45309; /* Amber 700 */ + --color-brand-light: #fef3c7; /* Amber 100 */ + --color-brand-accent: #f59e0b; /* Gold 500 */ + + --color-border: #e7e5e4; /* Stone 200 - subtle separations */ + --color-border-warm: #fcd34d; /* Amber 300 - highlight borders */ + + /* Status codes */ + --color-status-in-use: #d1fae5; + --color-status-in-use-txt: #065f46; + --color-status-storage: #dbeafe; + --color-status-storage-txt: #1e40af; + --color-status-borrowed: #fef3c7; + --color-status-borrowed-txt: #92400e; + --color-status-lost: #fee2e2; + --color-status-lost-txt: #991b1b; + --color-status-disposed: #f3f4f6; + --color-status-disposed-txt: #374151; + + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px -1px rgba(217, 119, 6, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03); + --shadow-lg: 0 10px 15px -3px rgba(217, 119, 6, 0.08), 0 4px 6px -2px rgba(0, 0, 0, 0.03); + + --radius-sm: 6px; + --radius-md: 12px; + --radius-lg: 18px; +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + font-family: var(--font-sans); + background-color: var(--color-bg-base); + color: var(--color-text-main); + line-height: 1.5; + -webkit-font-smoothing: antialiased; +} + +/* Global Grid Layout */ +.app-container { + display: flex; + min-height: 100vh; +} + +/* Premium Sidebar Navigation */ +.sidebar { + width: 260px; + background-color: var(--color-bg-surface); + border-right: 1px solid var(--color-border); + padding: 2rem 1.5rem; + display: flex; + flex-direction: column; + position: fixed; + height: 100vh; + z-index: 100; +} + +.brand { + display: flex; + align-items: center; + gap: 0.75rem; + margin-bottom: 3rem; +} + +.brand-logo { + width: 38px; + height: 38px; + background: linear-gradient(135deg, var(--color-brand-accent), var(--color-brand-primary)); + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + color: white; + font-weight: 700; + font-size: 1.25rem; + box-shadow: 0 4px 10px rgba(217, 119, 6, 0.25); +} + +.brand-name { + font-size: 1.35rem; + font-weight: 700; + letter-spacing: -0.02em; + background: linear-gradient(to right, var(--color-brand-primary), var(--color-text-main)); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; +} + +.nav-list { + list-style: none; + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.nav-link { + display: flex; + align-items: center; + gap: 0.75rem; + padding: 0.75rem 1rem; + color: var(--color-text-muted); + text-decoration: none; + font-weight: 500; + border-radius: var(--radius-sm); + transition: all 0.2s ease; +} + +.nav-link:hover { + color: var(--color-brand-primary); + background-color: #fefaf0; +} + +.nav-item.active .nav-link { + color: var(--color-brand-primary); + background-color: var(--color-brand-light); + font-weight: 600; + box-shadow: inset 3px 0 0 var(--color-brand-primary); +} + +.nav-link svg { + width: 20px; + height: 20px; + transition: transform 0.2s ease; +} + +.nav-link:hover svg { + transform: translateX(2px); +} + +.sidebar-footer { + margin-top: auto; + border-top: 1px solid var(--color-border); + padding-top: 1.5rem; +} + +/* Main Content Area */ +.main-wrapper { + margin-left: 260px; + flex-grow: 1; + padding: 2.5rem 3.5rem; + max-width: 1400px; +} + +.page-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 2.5rem; +} + +.page-title h1 { + font-size: 2rem; + font-weight: 700; + letter-spacing: -0.02em; +} + +.page-title p { + color: var(--color-text-muted); + font-size: 0.95rem; + margin-top: 0.25rem; +} + +/* Buttons */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + padding: 0.625rem 1.25rem; + font-size: 0.95rem; + font-weight: 600; + border-radius: var(--radius-sm); + border: 1px solid transparent; + cursor: pointer; + transition: all 0.2s ease; + text-decoration: none; +} + +.btn-primary { + background-color: var(--color-brand-primary); + color: white; + box-shadow: 0 2px 4px rgba(217, 119, 6, 0.15); +} + +.btn-primary:hover { + background-color: var(--color-brand-hover); + box-shadow: 0 4px 8px rgba(217, 119, 6, 0.25); +} + +.btn-secondary { + background-color: var(--color-bg-surface); + border-color: var(--color-border); + color: var(--color-text-main); +} + +.btn-secondary:hover { + background-color: var(--color-bg-base); + border-color: var(--color-text-light); +} + +.btn-danger { + background-color: #fee2e2; + border-color: #fca5a5; + color: #b91c1c; +} + +.btn-danger:hover { + background-color: #fecaca; + color: #991b1b; +} + +/* Beautiful Premium Cards */ +.card { + background-color: var(--color-bg-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + box-shadow: var(--shadow-md); + padding: 1.75rem; + margin-bottom: 2rem; + transition: box-shadow 0.3s ease, border-color 0.3s ease; +} + +.card:hover { + box-shadow: var(--shadow-lg); + border-color: var(--color-border-warm); +} + +/* Search bar & filter cards */ +.filter-bar { + display: flex; + gap: 1rem; + margin-bottom: 2rem; + align-items: center; + background-color: var(--color-bg-surface); + border: 1px solid var(--color-border); + padding: 0.75rem 1.25rem; + border-radius: var(--radius-sm); + box-shadow: var(--shadow-sm); +} + +.search-input-wrapper { + flex-grow: 1; + position: relative; +} + +.search-input-wrapper svg { + position: absolute; + left: 0.75rem; + top: 50%; + transform: translateY(-50%); + color: var(--color-text-light); + width: 18px; + height: 18px; +} + +.form-control { + width: 100%; + padding: 0.625rem 1rem; + font-size: 0.95rem; + border-radius: var(--radius-sm); + border: 1px solid var(--color-border); + background-color: var(--color-bg-surface); + color: var(--color-text-main); + transition: all 0.2s ease; +} + +.form-control:focus { + outline: none; + border-color: var(--color-brand-primary); + box-shadow: 0 0 0 3px rgba(217, 119, 6, 0.15); +} + +.search-input-wrapper .form-control { + padding-left: 2.5rem; +} + +/* Items Tables and Layouts */ +.data-table-wrapper { + overflow-x: auto; +} + +.data-table { + width: 100%; + border-collapse: collapse; + text-align: left; +} + +.data-table th { + padding: 1rem; + font-weight: 600; + color: var(--color-text-muted); + border-bottom: 2px solid var(--color-border); + font-size: 0.9rem; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.data-table td { + padding: 1.25rem 1rem; + border-bottom: 1px solid var(--color-border); + vertical-align: middle; +} + +.data-table tr:last-child td { + border-bottom: none; +} + +.data-table tr:hover td { + background-color: #fffbeb; /* Solar hover highlight */ +} + +/* Custom pills and tags */ +.status-pill { + display: inline-flex; + padding: 0.25rem 0.75rem; + font-size: 0.8rem; + font-weight: 600; + border-radius: 9999px; + text-transform: uppercase; +} + +.status-pill.in-use { background-color: var(--color-status-in-use); color: var(--color-status-in-use-txt); } +.status-pill.in-storage { background-color: var(--color-status-storage); color: var(--color-status-storage-txt); } +.status-pill.borrowed { background-color: var(--color-status-borrowed); color: var(--color-status-borrowed-txt); } +.status-pill.lost { background-color: var(--color-status-lost); color: var(--color-status-lost-txt); } +.status-pill.disposed { background-color: var(--color-status-disposed); color: var(--color-status-disposed-txt); } + +.tag-pill { + display: inline-flex; + padding: 0.15rem 0.5rem; + font-size: 0.75rem; + font-weight: 600; + border-radius: 4px; + border: 1px solid rgba(0, 0, 0, 0.05); +} + +.tag-list { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; +} + +/* Asset Detail Grid */ +.detail-grid { + display: grid; + grid-template-columns: 2fr 1fr; + gap: 2rem; +} + +.detail-main { + display: flex; + flex-direction: column; + gap: 2rem; +} + +.item-visuals { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1.5rem; +} + +.visual-box { + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + overflow: hidden; + aspect-ratio: 4/3; + display: flex; + align-items: center; + justify-content: center; + background-color: var(--color-bg-base); + position: relative; +} + +.visual-box img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.visual-placeholder { + color: var(--color-text-light); + display: flex; + flex-direction: column; + align-items: center; + gap: 0.5rem; +} + +/* Sidebar QR Codes and metadata */ +.detail-sidebar { + display: flex; + flex-direction: column; + gap: 2rem; +} + +.qr-card { + text-align: center; + display: flex; + flex-direction: column; + align-items: center; + gap: 1rem; +} + +.qr-image { + width: 180px; + height: 180px; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + padding: 0.5rem; + background-color: white; + box-shadow: var(--shadow-sm); +} + +/* Toast System */ +#toast-container { + position: fixed; + bottom: 2rem; + right: 2rem; + display: flex; + flex-direction: column; + gap: 0.75rem; + z-index: 1000; +} + +.toast { + display: flex; + align-items: center; + gap: 1rem; + padding: 1rem 1.25rem; + background-color: var(--color-bg-surface); + border-left: 4px solid var(--color-brand-primary); + border-top: 1px solid var(--color-border); + border-right: 1px solid var(--color-border); + border-bottom: 1px solid var(--color-border); + box-shadow: var(--shadow-lg); + border-radius: var(--radius-sm); + animation: slideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1); + min-width: 300px; + max-width: 450px; +} + +.toast.toast-success { border-left-color: #10b981; } +.toast.toast-error { border-left-color: #ef4444; } + +.toast-message { + font-size: 0.9rem; + font-weight: 500; + flex-grow: 1; +} + +.toast-close { + background: none; + border: none; + color: var(--color-text-light); + cursor: pointer; +} + +@keyframes slideIn { + from { + opacity: 0; + transform: translateY(1rem); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +/* Login Page Styling */ +.login-container { + display: flex; + align-items: center; + justify-content: center; + min-height: 100vh; + background-color: var(--color-bg-base); +} + +.login-card { + width: 100%; + max-width: 420px; + padding: 2.5rem; + background-color: var(--color-bg-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-lg); +} + +.login-header { + text-align: center; + margin-bottom: 2rem; +} + +.login-header .brand { + justify-content: center; + margin-bottom: 1rem; +} + +/* Form Group Utilities */ +.form-group { + margin-bottom: 1.25rem; +} + +.form-label { + display: block; + margin-bottom: 0.5rem; + font-weight: 600; + font-size: 0.9rem; + color: var(--color-text-muted); +} + +/* PRINT SUB-SYSTEM: Sticker Sheets */ +@media print { + body { + background-color: white; + color: black; + } + + .sidebar, .main-wrapper > .page-header, .filter-bar, .btn, #toast-container { + display: none !important; + } + + .main-wrapper { + margin-left: 0 !important; + padding: 0 !important; + max-width: 100% !important; + } + + /* Print Label grid settings */ + .print-grid { + display: grid !important; + grid-template-columns: repeat(4, 1fr) !important; + gap: 15px !important; + padding: 10px !important; + } + + .print-label-item { + border: 1px solid #000 !important; + border-radius: 4px !important; + padding: 8px !important; + text-align: center !important; + display: flex !important; + flex-direction: column !important; + align-items: center !important; + justify-content: space-between !important; + aspect-ratio: 1/1 !important; + page-break-inside: avoid !important; + } + + .print-label-name { + font-size: 10pt !important; + font-weight: bold !important; + margin-bottom: 4px !important; + white-space: nowrap !important; + overflow: hidden !important; + text-overflow: ellipsis !important; + width: 100% !important; + } + + .print-label-qr { + width: 1.8in !important; + height: 1.8in !important; + } + + .print-label-slug { + font-size: 8pt !important; + font-family: monospace !important; + margin-top: 4px !important; + } +} diff --git a/internal/server/static/js/htmx.min.js b/internal/server/static/js/htmx.min.js new file mode 100644 index 0000000..47eb70f --- /dev/null +++ b/internal/server/static/js/htmx.min.js @@ -0,0 +1 @@ +(function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else if(typeof module==="object"&&module.exports){module.exports=t()}else{e.htmx=e.htmx||t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var Q={onLoad:F,process:zt,on:de,off:ge,trigger:ce,ajax:Nr,find:C,findAll:f,closest:v,values:function(e,t){var r=dr(e,t||"post");return r.values},remove:_,addClass:z,removeClass:n,toggleClass:$,takeClass:W,defineExtension:Ur,removeExtension:Br,logAll:V,logNone:j,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get"],selfRequestsOnly:false,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null},parseInterval:d,_:t,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){var t=new WebSocket(e,[]);t.binaryType=Q.config.wsBinaryType;return t},version:"1.9.10"};var r={addTriggerHandler:Lt,bodyContains:se,canAccessLocalStorage:U,findThisElement:xe,filterValues:yr,hasAttribute:o,getAttributeValue:te,getClosestAttributeValue:ne,getClosestMatch:c,getExpressionVars:Hr,getHeaders:xr,getInputValues:dr,getInternalData:ae,getSwapSpecification:wr,getTriggerSpecs:it,getTarget:ye,makeFragment:l,mergeObjects:le,makeSettleInfo:T,oobSwap:Ee,querySelectorExt:ue,selectAndSwap:je,settleImmediately:nr,shouldCancel:ut,triggerEvent:ce,triggerErrorEvent:fe,withExtensions:R};var w=["get","post","put","delete","patch"];var i=w.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");var S=e("head"),q=e("title"),H=e("svg",true);function e(e,t=false){return new RegExp(`<${e}(\\s[^>]*>|>)([\\s\\S]*?)<\\/${e}>`,t?"gim":"im")}function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e.getAttribute&&e.getAttribute(t)}function o(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){return e.parentElement}function re(){return document}function c(e,t){while(e&&!t(e)){e=u(e)}return e?e:null}function L(e,t,r){var n=te(t,r);var i=te(t,"hx-disinherit");if(e!==t&&i&&(i==="*"||i.split(" ").indexOf(r)>=0)){return"unset"}else{return n}}function ne(t,r){var n=null;c(t,function(e){return n=L(t,e,r)});if(n!=="unset"){return n}}function h(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function A(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function a(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=re().createDocumentFragment()}return i}function N(e){return/",0);return i.querySelector("template").content}switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return a(""+n+"
",1);case"col":return a(""+n+"
",2);case"tr":return a(""+n+"
",2);case"td":case"th":return a(""+n+"
",3);case"script":case"style":return a("
"+n+"
",1);default:return a(n,0)}}function ie(e){if(e){e()}}function I(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return I(e,"Function")}function P(e){return I(e,"Object")}function ae(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function M(e){var t=[];if(e){for(var r=0;r=0}function se(e){if(e.getRootNode&&e.getRootNode()instanceof window.ShadowRoot){return re().body.contains(e.getRootNode().host)}else{return re().body.contains(e)}}function D(e){return e.trim().split(/\s+/)}function le(e,t){for(var r in t){if(t.hasOwnProperty(r)){e[r]=t[r]}}return e}function E(e){try{return JSON.parse(e)}catch(e){b(e);return null}}function U(){var e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function B(t){try{var e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function t(e){return Tr(re().body,function(){return eval(e)})}function F(t){var e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,r){if(console){console.log(t,e,r)}}}function j(){Q.logger=null}function C(e,t){if(t){return e.querySelector(t)}else{return C(re(),e)}}function f(e,t){if(t){return e.querySelectorAll(t)}else{return f(re(),e)}}function _(e,t){e=g(e);if(t){setTimeout(function(){_(e);e=null},t)}else{e.parentElement.removeChild(e)}}function z(e,t,r){e=g(e);if(r){setTimeout(function(){z(e,t);e=null},r)}else{e.classList&&e.classList.add(t)}}function n(e,t,r){e=g(e);if(r){setTimeout(function(){n(e,t);e=null},r)}else{if(e.classList){e.classList.remove(t);if(e.classList.length===0){e.removeAttribute("class")}}}}function $(e,t){e=g(e);e.classList.toggle(t)}function W(e,t){e=g(e);oe(e.parentElement.children,function(e){n(e,t)});z(e,t)}function v(e,t){e=g(e);if(e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&u(e));return null}}function s(e,t){return e.substring(0,t.length)===t}function G(e,t){return e.substring(e.length-t.length)===t}function J(e){var t=e.trim();if(s(t,"<")&&G(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function Z(e,t){if(t.indexOf("closest ")===0){return[v(e,J(t.substr(8)))]}else if(t.indexOf("find ")===0){return[C(e,J(t.substr(5)))]}else if(t==="next"){return[e.nextElementSibling]}else if(t.indexOf("next ")===0){return[K(e,J(t.substr(5)))]}else if(t==="previous"){return[e.previousElementSibling]}else if(t.indexOf("previous ")===0){return[Y(e,J(t.substr(9)))]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else if(t==="body"){return[document.body]}else{return re().querySelectorAll(J(t))}}var K=function(e,t){var r=re().querySelectorAll(t);for(var n=0;n=0;n--){var i=r[n];if(i.compareDocumentPosition(e)===Node.DOCUMENT_POSITION_FOLLOWING){return i}}};function ue(e,t){if(t){return Z(e,t)[0]}else{return Z(re().body,e)[0]}}function g(e){if(I(e,"String")){return C(e)}else{return e}}function ve(e,t,r){if(k(t)){return{target:re().body,event:e,listener:t}}else{return{target:g(e),event:t,listener:r}}}function de(t,r,n){jr(function(){var e=ve(t,r,n);e.target.addEventListener(e.event,e.listener)});var e=k(r);return e?r:n}function ge(t,r,n){jr(function(){var e=ve(t,r,n);e.target.removeEventListener(e.event,e.listener)});return k(r)?r:n}var me=re().createElement("output");function pe(e,t){var r=ne(e,t);if(r){if(r==="this"){return[xe(e,t)]}else{var n=Z(e,r);if(n.length===0){b('The selector "'+r+'" on '+t+" returned no matches!");return[me]}else{return n}}}}function xe(e,t){return c(e,function(e){return te(e,t)!=null})}function ye(e){var t=ne(e,"hx-target");if(t){if(t==="this"){return xe(e,"hx-target")}else{return ue(e,t)}}else{var r=ae(e);if(r.boosted){return re().body}else{return e}}}function be(e){var t=Q.config.attributesToSettle;for(var r=0;r0){o=e.substr(0,e.indexOf(":"));t=e.substr(e.indexOf(":")+1,e.length)}else{o=e}var r=re().querySelectorAll(t);if(r){oe(r,function(e){var t;var r=i.cloneNode(true);t=re().createDocumentFragment();t.appendChild(r);if(!Se(o,e)){t=r}var n={shouldSwap:true,target:e,fragment:t};if(!ce(e,"htmx:oobBeforeSwap",n))return;e=n.target;if(n["shouldSwap"]){Fe(o,e,e,t,a)}oe(a.elts,function(e){ce(e,"htmx:oobAfterSwap",n)})});i.parentNode.removeChild(i)}else{i.parentNode.removeChild(i);fe(re().body,"htmx:oobErrorNoTarget",{content:i})}return e}function Ce(e,t,r){var n=ne(e,"hx-select-oob");if(n){var i=n.split(",");for(var a=0;a0){var r=t.replace("'","\\'");var n=e.tagName.replace(":","\\:");var i=o.querySelector(n+"[id='"+r+"']");if(i&&i!==o){var a=e.cloneNode();we(e,i);s.tasks.push(function(){we(e,a)})}}})}function Oe(e){return function(){n(e,Q.config.addedClass);zt(e);Nt(e);qe(e);ce(e,"htmx:load")}}function qe(e){var t="[autofocus]";var r=h(e,t)?e:e.querySelector(t);if(r!=null){r.focus()}}function m(e,t,r,n){Te(e,r,n);while(r.childNodes.length>0){var i=r.firstChild;z(i,Q.config.addedClass);e.insertBefore(i,t);if(i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE){n.tasks.push(Oe(i))}}}function He(e,t){var r=0;while(r-1){var t=e.replace(H,"");var r=t.match(q);if(r){return r[2]}}}function je(e,t,r,n,i,a){i.title=Ve(n);var o=l(n);if(o){Ce(r,o,i);o=Be(r,o,a);Re(o);return Fe(e,r,t,o,i)}}function _e(e,t,r){var n=e.getResponseHeader(t);if(n.indexOf("{")===0){var i=E(n);for(var a in i){if(i.hasOwnProperty(a)){var o=i[a];if(!P(o)){o={value:o}}ce(r,a,o)}}}else{var s=n.split(",");for(var l=0;l0){var o=t[0];if(o==="]"){n--;if(n===0){if(a===null){i=i+"true"}t.shift();i+=")})";try{var s=Tr(e,function(){return Function(i)()},function(){return true});s.source=i;return s}catch(e){fe(re().body,"htmx:syntax:error",{error:e,source:i});return null}}}else if(o==="["){n++}if(Qe(o,a,r)){i+="(("+r+"."+o+") ? ("+r+"."+o+") : (window."+o+"))"}else{i=i+o}a=t.shift()}}}function y(e,t){var r="";while(e.length>0&&!t.test(e[0])){r+=e.shift()}return r}function tt(e){var t;if(e.length>0&&Ze.test(e[0])){e.shift();t=y(e,Ke).trim();e.shift()}else{t=y(e,x)}return t}var rt="input, textarea, select";function nt(e,t,r){var n=[];var i=Ye(t);do{y(i,Je);var a=i.length;var o=y(i,/[,\[\s]/);if(o!==""){if(o==="every"){var s={trigger:"every"};y(i,Je);s.pollInterval=d(y(i,/[,\[\s]/));y(i,Je);var l=et(e,i,"event");if(l){s.eventFilter=l}n.push(s)}else if(o.indexOf("sse:")===0){n.push({trigger:"sse",sseEvent:o.substr(4)})}else{var u={trigger:o};var l=et(e,i,"event");if(l){u.eventFilter=l}while(i.length>0&&i[0]!==","){y(i,Je);var f=i.shift();if(f==="changed"){u.changed=true}else if(f==="once"){u.once=true}else if(f==="consume"){u.consume=true}else if(f==="delay"&&i[0]===":"){i.shift();u.delay=d(y(i,x))}else if(f==="from"&&i[0]===":"){i.shift();if(Ze.test(i[0])){var c=tt(i)}else{var c=y(i,x);if(c==="closest"||c==="find"||c==="next"||c==="previous"){i.shift();var h=tt(i);if(h.length>0){c+=" "+h}}}u.from=c}else if(f==="target"&&i[0]===":"){i.shift();u.target=tt(i)}else if(f==="throttle"&&i[0]===":"){i.shift();u.throttle=d(y(i,x))}else if(f==="queue"&&i[0]===":"){i.shift();u.queue=y(i,x)}else if(f==="root"&&i[0]===":"){i.shift();u[f]=tt(i)}else if(f==="threshold"&&i[0]===":"){i.shift();u[f]=y(i,x)}else{fe(e,"htmx:syntax:error",{token:i.shift()})}}n.push(u)}}if(i.length===a){fe(e,"htmx:syntax:error",{token:i.shift()})}y(i,Je)}while(i[0]===","&&i.shift());if(r){r[t]=n}return n}function it(e){var t=te(e,"hx-trigger");var r=[];if(t){var n=Q.config.triggerSpecsCache;r=n&&n[t]||nt(e,t,n)}if(r.length>0){return r}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,rt)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function at(e){ae(e).cancelled=true}function ot(e,t,r){var n=ae(e);n.timeout=setTimeout(function(){if(se(e)&&n.cancelled!==true){if(!ct(r,e,Wt("hx:poll:trigger",{triggerSpec:r,target:e}))){t(e)}ot(e,t,r)}},r.pollInterval)}function st(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function lt(t,r,e){if(t.tagName==="A"&&st(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"){r.boosted=true;var n,i;if(t.tagName==="A"){n="get";i=ee(t,"href")}else{var a=ee(t,"method");n=a?a.toLowerCase():"get";if(n==="get"){}i=ee(t,"action")}e.forEach(function(e){ht(t,function(e,t){if(v(e,Q.config.disableSelector)){p(e);return}he(n,i,e,t)},r,e,true)})}}function ut(e,t){if(e.type==="submit"||e.type==="click"){if(t.tagName==="FORM"){return true}if(h(t,'input[type="submit"], button')&&v(t,"form")!==null){return true}if(t.tagName==="A"&&t.href&&(t.getAttribute("href")==="#"||t.getAttribute("href").indexOf("#")!==0)){return true}}return false}function ft(e,t){return ae(e).boosted&&e.tagName==="A"&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function ct(e,t,r){var n=e.eventFilter;if(n){try{return n.call(t,r)!==true}catch(e){fe(re().body,"htmx:eventFilter:error",{error:e,source:n.source});return true}}return false}function ht(a,o,e,s,l){var u=ae(a);var t;if(s.from){t=Z(a,s.from)}else{t=[a]}if(s.changed){t.forEach(function(e){var t=ae(e);t.lastValue=e.value})}oe(t,function(n){var i=function(e){if(!se(a)){n.removeEventListener(s.trigger,i);return}if(ft(a,e)){return}if(l||ut(e,a)){e.preventDefault()}if(ct(s,a,e)){return}var t=ae(e);t.triggerSpec=s;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(a)<0){t.handledFor.push(a);if(s.consume){e.stopPropagation()}if(s.target&&e.target){if(!h(e.target,s.target)){return}}if(s.once){if(u.triggeredOnce){return}else{u.triggeredOnce=true}}if(s.changed){var r=ae(n);if(r.lastValue===n.value){return}r.lastValue=n.value}if(u.delayed){clearTimeout(u.delayed)}if(u.throttle){return}if(s.throttle>0){if(!u.throttle){o(a,e);u.throttle=setTimeout(function(){u.throttle=null},s.throttle)}}else if(s.delay>0){u.delayed=setTimeout(function(){o(a,e)},s.delay)}else{ce(a,"htmx:trigger");o(a,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:s.trigger,listener:i,on:n});n.addEventListener(s.trigger,i)})}var vt=false;var dt=null;function gt(){if(!dt){dt=function(){vt=true};window.addEventListener("scroll",dt);setInterval(function(){if(vt){vt=false;oe(re().querySelectorAll("[hx-trigger='revealed'],[data-hx-trigger='revealed']"),function(e){mt(e)})}},200)}}function mt(t){if(!o(t,"data-hx-revealed")&&X(t)){t.setAttribute("data-hx-revealed","true");var e=ae(t);if(e.initHash){ce(t,"revealed")}else{t.addEventListener("htmx:afterProcessNode",function(e){ce(t,"revealed")},{once:true})}}}function pt(e,t,r){var n=D(r);for(var i=0;i=0){var t=wt(n);setTimeout(function(){xt(s,r,n+1)},t)}};t.onopen=function(e){n=0};ae(s).webSocket=t;t.addEventListener("message",function(e){if(yt(s)){return}var t=e.data;R(s,function(e){t=e.transformResponse(t,null,s)});var r=T(s);var n=l(t);var i=M(n.children);for(var a=0;a0){ce(u,"htmx:validation:halted",i);return}t.send(JSON.stringify(l));if(ut(e,u)){e.preventDefault()}})}else{fe(u,"htmx:noWebSocketSourceError")}}function wt(e){var t=Q.config.wsReconnectDelay;if(typeof t==="function"){return t(e)}if(t==="full-jitter"){var r=Math.min(e,6);var n=1e3*Math.pow(2,r);return n*Math.random()}b('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"')}function St(e,t,r){var n=D(r);for(var i=0;i0){setTimeout(i,n)}else{i()}}function Ht(t,i,e){var a=false;oe(w,function(r){if(o(t,"hx-"+r)){var n=te(t,"hx-"+r);a=true;i.path=n;i.verb=r;e.forEach(function(e){Lt(t,e,i,function(e,t){if(v(e,Q.config.disableSelector)){p(e);return}he(r,n,e,t)})})}});return a}function Lt(n,e,t,r){if(e.sseEvent){Rt(n,r,e.sseEvent)}else if(e.trigger==="revealed"){gt();ht(n,r,t,e);mt(n)}else if(e.trigger==="intersect"){var i={};if(e.root){i.root=ue(n,e.root)}if(e.threshold){i.threshold=parseFloat(e.threshold)}var a=new IntersectionObserver(function(e){for(var t=0;t0){t.polling=true;ot(n,r,e)}else{ht(n,r,t,e)}}function At(e){if(Q.config.allowScriptTags&&(e.type==="text/javascript"||e.type==="module"||e.type==="")){var t=re().createElement("script");oe(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}var r=e.parentElement;try{r.insertBefore(t,e)}catch(e){b(e)}finally{if(e.parentElement){e.parentElement.removeChild(e)}}}}function Nt(e){if(h(e,"script")){At(e)}oe(f(e,"script"),function(e){At(e)})}function It(e){var t=e.attributes;for(var r=0;r0){var o=n.shift();var s=o.match(/^\s*([a-zA-Z:\-\.]+:)(.*)/);if(a===0&&s){o.split(":");i=s[1].slice(0,-1);r[i]=s[2]}else{r[i]+=o}a+=Bt(o)}for(var l in r){Ft(e,l,r[l])}}}function jt(e){Ae(e);for(var t=0;tQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(re().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Yt(e){if(!U()){return null}e=B(e);var t=E(localStorage.getItem("htmx-history-cache"))||[];for(var r=0;r=200&&this.status<400){ce(re().body,"htmx:historyCacheMissLoad",o);var e=l(this.response);e=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;var t=Zt();var r=T(t);var n=Ve(this.response);if(n){var i=C("title");if(i){i.innerHTML=n}else{window.document.title=n}}Ue(t,e,r);nr(r.tasks);Jt=a;ce(re().body,"htmx:historyRestore",{path:a,cacheMiss:true,serverResponse:this.response})}else{fe(re().body,"htmx:historyCacheMissLoadError",o)}};e.send()}function ar(e){er();e=e||location.pathname+location.search;var t=Yt(e);if(t){var r=l(t.content);var n=Zt();var i=T(n);Ue(n,r,i);nr(i.tasks);document.title=t.title;setTimeout(function(){window.scrollTo(0,t.scroll)},0);Jt=e;ce(re().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{ir(e)}}}function or(e){var t=pe(e,"hx-indicator");if(t==null){t=[e]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.classList["add"].call(e.classList,Q.config.requestClass)});return t}function sr(e){var t=pe(e,"hx-disabled-elt");if(t==null){t=[]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","")});return t}function lr(e,t){oe(e,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.classList["remove"].call(e.classList,Q.config.requestClass)}});oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.removeAttribute("disabled")}})}function ur(e,t){for(var r=0;r=0}function wr(e,t){var r=t?t:ne(e,"hx-swap");var n={swapStyle:ae(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ae(e).boosted&&!br(e)){n["show"]="top"}if(r){var i=D(r);if(i.length>0){for(var a=0;a0?l.join(":"):null;n["scroll"]=u;n["scrollTarget"]=f}else if(o.indexOf("show:")===0){var c=o.substr(5);var l=c.split(":");var h=l.pop();var f=l.length>0?l.join(":"):null;n["show"]=h;n["showTarget"]=f}else if(o.indexOf("focus-scroll:")===0){var v=o.substr("focus-scroll:".length);n["focusScroll"]=v=="true"}else if(a==0){n["swapStyle"]=o}else{b("Unknown modifier in hx-swap: "+o)}}}}return n}function Sr(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function Er(t,r,n){var i=null;R(r,function(e){if(i==null){i=e.encodeParameters(t,n,r)}});if(i!=null){return i}else{if(Sr(r)){return pr(n)}else{return mr(n)}}}function T(e){return{tasks:[],elts:[e]}}function Cr(e,t){var r=e[0];var n=e[e.length-1];if(t.scroll){var i=null;if(t.scrollTarget){i=ue(r,t.scrollTarget)}if(t.scroll==="top"&&(r||i)){i=i||r;i.scrollTop=0}if(t.scroll==="bottom"&&(n||i)){i=i||n;i.scrollTop=i.scrollHeight}}if(t.show){var i=null;if(t.showTarget){var a=t.showTarget;if(t.showTarget==="window"){a="body"}i=ue(r,a)}if(t.show==="top"&&(r||i)){i=i||r;i.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(n||i)){i=i||n;i.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Rr(e,t,r,n){if(n==null){n={}}if(e==null){return n}var i=te(e,t);if(i){var a=i.trim();var o=r;if(a==="unset"){return null}if(a.indexOf("javascript:")===0){a=a.substr(11);o=true}else if(a.indexOf("js:")===0){a=a.substr(3);o=true}if(a.indexOf("{")!==0){a="{"+a+"}"}var s;if(o){s=Tr(e,function(){return Function("return ("+a+")")()},{})}else{s=E(a)}for(var l in s){if(s.hasOwnProperty(l)){if(n[l]==null){n[l]=s[l]}}}}return Rr(u(e),t,r,n)}function Tr(e,t,r){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return r}}function Or(e,t){return Rr(e,"hx-vars",true,t)}function qr(e,t){return Rr(e,"hx-vals",false,t)}function Hr(e){return le(Or(e),qr(e))}function Lr(t,r,n){if(n!==null){try{t.setRequestHeader(r,n)}catch(e){t.setRequestHeader(r,encodeURIComponent(n));t.setRequestHeader(r+"-URI-AutoEncoded","true")}}}function Ar(t){if(t.responseURL&&typeof URL!=="undefined"){try{var e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(re().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function O(e,t){return t.test(e.getAllResponseHeaders())}function Nr(e,t,r){e=e.toLowerCase();if(r){if(r instanceof Element||I(r,"String")){return he(e,t,null,null,{targetOverride:g(r),returnPromise:true})}else{return he(e,t,g(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:g(r.target),swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return he(e,t,null,null,{returnPromise:true})}}function Ir(e){var t=[];while(e){t.push(e);e=e.parentElement}return t}function kr(e,t,r){var n;var i;if(typeof URL==="function"){i=new URL(t,document.location.href);var a=document.location.origin;n=a===i.origin}else{i=t;n=s(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!n){return false}}return ce(e,"htmx:validateUrl",le({url:i,sameHost:n},r))}function he(t,r,n,i,a,e){var o=null;var s=null;a=a!=null?a:{};if(a.returnPromise&&typeof Promise!=="undefined"){var l=new Promise(function(e,t){o=e;s=t})}if(n==null){n=re().body}var M=a.handler||Mr;var X=a.select||null;if(!se(n)){ie(o);return l}var u=a.targetOverride||ye(n);if(u==null||u==me){fe(n,"htmx:targetError",{target:te(n,"hx-target")});ie(s);return l}var f=ae(n);var c=f.lastButtonClicked;if(c){var h=ee(c,"formaction");if(h!=null){r=h}var v=ee(c,"formmethod");if(v!=null){if(v.toLowerCase()!=="dialog"){t=v}}}var d=ne(n,"hx-confirm");if(e===undefined){var D=function(e){return he(t,r,n,i,a,!!e)};var U={target:u,elt:n,path:r,verb:t,triggeringEvent:i,etc:a,issueRequest:D,question:d};if(ce(n,"htmx:confirm",U)===false){ie(o);return l}}var g=n;var m=ne(n,"hx-sync");var p=null;var x=false;if(m){var B=m.split(":");var F=B[0].trim();if(F==="this"){g=xe(n,"hx-sync")}else{g=ue(n,F)}m=(B[1]||"drop").trim();f=ae(g);if(m==="drop"&&f.xhr&&f.abortable!==true){ie(o);return l}else if(m==="abort"){if(f.xhr){ie(o);return l}else{x=true}}else if(m==="replace"){ce(g,"htmx:abort")}else if(m.indexOf("queue")===0){var V=m.split(" ");p=(V[1]||"last").trim()}}if(f.xhr){if(f.abortable){ce(g,"htmx:abort")}else{if(p==null){if(i){var y=ae(i);if(y&&y.triggerSpec&&y.triggerSpec.queue){p=y.triggerSpec.queue}}if(p==null){p="last"}}if(f.queuedRequests==null){f.queuedRequests=[]}if(p==="first"&&f.queuedRequests.length===0){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(p==="all"){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(p==="last"){f.queuedRequests=[];f.queuedRequests.push(function(){he(t,r,n,i,a)})}ie(o);return l}}var b=new XMLHttpRequest;f.xhr=b;f.abortable=x;var w=function(){f.xhr=null;f.abortable=false;if(f.queuedRequests!=null&&f.queuedRequests.length>0){var e=f.queuedRequests.shift();e()}};var j=ne(n,"hx-prompt");if(j){var S=prompt(j);if(S===null||!ce(n,"htmx:prompt",{prompt:S,target:u})){ie(o);w();return l}}if(d&&!e){if(!confirm(d)){ie(o);w();return l}}var E=xr(n,u,S);if(t!=="get"&&!Sr(n)){E["Content-Type"]="application/x-www-form-urlencoded"}if(a.headers){E=le(E,a.headers)}var _=dr(n,t);var C=_.errors;var R=_.values;if(a.values){R=le(R,a.values)}var z=Hr(n);var $=le(R,z);var T=yr($,n);if(Q.config.getCacheBusterParam&&t==="get"){T["org.htmx.cache-buster"]=ee(u,"id")||"true"}if(r==null||r===""){r=re().location.href}var O=Rr(n,"hx-request");var W=ae(n).boosted;var q=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;var H={boosted:W,useUrlParams:q,parameters:T,unfilteredParameters:$,headers:E,target:u,verb:t,errors:C,withCredentials:a.credentials||O.credentials||Q.config.withCredentials,timeout:a.timeout||O.timeout||Q.config.timeout,path:r,triggeringEvent:i};if(!ce(n,"htmx:configRequest",H)){ie(o);w();return l}r=H.path;t=H.verb;E=H.headers;T=H.parameters;C=H.errors;q=H.useUrlParams;if(C&&C.length>0){ce(n,"htmx:validation:halted",H);ie(o);w();return l}var G=r.split("#");var J=G[0];var L=G[1];var A=r;if(q){A=J;var Z=Object.keys(T).length!==0;if(Z){if(A.indexOf("?")<0){A+="?"}else{A+="&"}A+=mr(T);if(L){A+="#"+L}}}if(!kr(n,A,H)){fe(n,"htmx:invalidPath",H);ie(s);return l}b.open(t.toUpperCase(),A,true);b.overrideMimeType("text/html");b.withCredentials=H.withCredentials;b.timeout=H.timeout;if(O.noHeaders){}else{for(var N in E){if(E.hasOwnProperty(N)){var K=E[N];Lr(b,N,K)}}}var I={xhr:b,target:u,requestConfig:H,etc:a,boosted:W,select:X,pathInfo:{requestPath:r,finalRequestPath:A,anchor:L}};b.onload=function(){try{var e=Ir(n);I.pathInfo.responsePath=Ar(b);M(n,I);lr(k,P);ce(n,"htmx:afterRequest",I);ce(n,"htmx:afterOnLoad",I);if(!se(n)){var t=null;while(e.length>0&&t==null){var r=e.shift();if(se(r)){t=r}}if(t){ce(t,"htmx:afterRequest",I);ce(t,"htmx:afterOnLoad",I)}}ie(o);w()}catch(e){fe(n,"htmx:onLoadError",le({error:e},I));throw e}};b.onerror=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendError",I);ie(s);w()};b.onabort=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendAbort",I);ie(s);w()};b.ontimeout=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:timeout",I);ie(s);w()};if(!ce(n,"htmx:beforeRequest",I)){ie(o);w();return l}var k=or(n);var P=sr(n);oe(["loadstart","loadend","progress","abort"],function(t){oe([b,b.upload],function(e){e.addEventListener(t,function(e){ce(n,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ce(n,"htmx:beforeSend",I);var Y=q?null:Er(b,n,T);b.send(Y);return l}function Pr(e,t){var r=t.xhr;var n=null;var i=null;if(O(r,/HX-Push:/i)){n=r.getResponseHeader("HX-Push");i="push"}else if(O(r,/HX-Push-Url:/i)){n=r.getResponseHeader("HX-Push-Url");i="push"}else if(O(r,/HX-Replace-Url:/i)){n=r.getResponseHeader("HX-Replace-Url");i="replace"}if(n){if(n==="false"){return{}}else{return{type:i,path:n}}}var a=t.pathInfo.finalRequestPath;var o=t.pathInfo.responsePath;var s=ne(e,"hx-push-url");var l=ne(e,"hx-replace-url");var u=ae(e).boosted;var f=null;var c=null;if(s){f="push";c=s}else if(l){f="replace";c=l}else if(u){f="push";c=o||a}if(c){if(c==="false"){return{}}if(c==="true"){c=o||a}if(t.pathInfo.anchor&&c.indexOf("#")===-1){c=c+"#"+t.pathInfo.anchor}return{type:f,path:c}}else{return{}}}function Mr(l,u){var f=u.xhr;var c=u.target;var e=u.etc;var t=u.requestConfig;var h=u.select;if(!ce(l,"htmx:beforeOnLoad",u))return;if(O(f,/HX-Trigger:/i)){_e(f,"HX-Trigger",l)}if(O(f,/HX-Location:/i)){er();var r=f.getResponseHeader("HX-Location");var v;if(r.indexOf("{")===0){v=E(r);r=v["path"];delete v["path"]}Nr("GET",r,v).then(function(){tr(r)});return}var n=O(f,/HX-Refresh:/i)&&"true"===f.getResponseHeader("HX-Refresh");if(O(f,/HX-Redirect:/i)){location.href=f.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){location.reload();return}if(O(f,/HX-Retarget:/i)){if(f.getResponseHeader("HX-Retarget")==="this"){u.target=l}else{u.target=ue(l,f.getResponseHeader("HX-Retarget"))}}var d=Pr(l,u);var i=f.status>=200&&f.status<400&&f.status!==204;var g=f.response;var a=f.status>=400;var m=Q.config.ignoreTitle;var o=le({shouldSwap:i,serverResponse:g,isError:a,ignoreTitle:m},u);if(!ce(c,"htmx:beforeSwap",o))return;c=o.target;g=o.serverResponse;a=o.isError;m=o.ignoreTitle;u.target=c;u.failed=a;u.successful=!a;if(o.shouldSwap){if(f.status===286){at(l)}R(l,function(e){g=e.transformResponse(g,f,l)});if(d.type){er()}var s=e.swapOverride;if(O(f,/HX-Reswap:/i)){s=f.getResponseHeader("HX-Reswap")}var v=wr(l,s);if(v.hasOwnProperty("ignoreTitle")){m=v.ignoreTitle}c.classList.add(Q.config.swappingClass);var p=null;var x=null;var y=function(){try{var e=document.activeElement;var t={};try{t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null}}catch(e){}var r;if(h){r=h}if(O(f,/HX-Reselect:/i)){r=f.getResponseHeader("HX-Reselect")}if(d.type){ce(re().body,"htmx:beforeHistoryUpdate",le({history:d},u));if(d.type==="push"){tr(d.path);ce(re().body,"htmx:pushedIntoHistory",{path:d.path})}else{rr(d.path);ce(re().body,"htmx:replacedInHistory",{path:d.path})}}var n=T(c);je(v.swapStyle,c,l,g,n,r);if(t.elt&&!se(t.elt)&&ee(t.elt,"id")){var i=document.getElementById(ee(t.elt,"id"));var a={preventScroll:v.focusScroll!==undefined?!v.focusScroll:!Q.config.defaultFocusScroll};if(i){if(t.start&&i.setSelectionRange){try{i.setSelectionRange(t.start,t.end)}catch(e){}}i.focus(a)}}c.classList.remove(Q.config.swappingClass);oe(n.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}ce(e,"htmx:afterSwap",u)});if(O(f,/HX-Trigger-After-Swap:/i)){var o=l;if(!se(l)){o=re().body}_e(f,"HX-Trigger-After-Swap",o)}var s=function(){oe(n.tasks,function(e){e.call()});oe(n.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}ce(e,"htmx:afterSettle",u)});if(u.pathInfo.anchor){var e=re().getElementById(u.pathInfo.anchor);if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}if(n.title&&!m){var t=C("title");if(t){t.innerHTML=n.title}else{window.document.title=n.title}}Cr(n.elts,v);if(O(f,/HX-Trigger-After-Settle:/i)){var r=l;if(!se(l)){r=re().body}_e(f,"HX-Trigger-After-Settle",r)}ie(p)};if(v.settleDelay>0){setTimeout(s,v.settleDelay)}else{s()}}catch(e){fe(l,"htmx:swapError",u);ie(x);throw e}};var b=Q.config.globalViewTransitions;if(v.hasOwnProperty("transition")){b=v.transition}if(b&&ce(l,"htmx:beforeTransition",u)&&typeof Promise!=="undefined"&&document.startViewTransition){var w=new Promise(function(e,t){p=e;x=t});var S=y;y=function(){document.startViewTransition(function(){S();return w})}}if(v.swapDelay>0){setTimeout(y,v.swapDelay)}else{y()}}if(a){fe(l,"htmx:responseError",le({error:"Response Status Error Code "+f.status+" from "+u.pathInfo.requestPath},u))}}var Xr={};function Dr(){return{init:function(e){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,r){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,r,n){return false},encodeParameters:function(e,t,r){return null}}}function Ur(e,t){if(t.init){t.init(r)}Xr[e]=le(Dr(),t)}function Br(e){delete Xr[e]}function Fr(e,r,n){if(e==undefined){return r}if(r==undefined){r=[]}if(n==undefined){n=[]}var t=te(e,"hx-ext");if(t){oe(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){n.push(e.slice(7));return}if(n.indexOf(e)<0){var t=Xr[e];if(t&&r.indexOf(t)<0){r.push(t)}}})}return Fr(u(e),r,n)}var Vr=false;re().addEventListener("DOMContentLoaded",function(){Vr=true});function jr(e){if(Vr||re().readyState==="complete"){e()}else{re().addEventListener("DOMContentLoaded",e)}}function _r(){if(Q.config.includeIndicatorStyles!==false){re().head.insertAdjacentHTML("beforeend","")}}function zr(){var e=re().querySelector('meta[name="htmx-config"]');if(e){return E(e.content)}else{return null}}function $r(){var e=zr();if(e){Q.config=le(Q.config,e)}}jr(function(){$r();_r();var e=re().body;zt(e);var t=re().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){var t=e.target;var r=ae(t);if(r&&r.xhr){r.xhr.abort()}});const r=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){ar();oe(t,function(e){ce(e,"htmx:restored",{document:re(),triggerEvent:ce})})}else{if(r){r(e)}}};setTimeout(function(){ce(e,"htmx:load",{});e=null},0)});return Q}()}); \ No newline at end of file diff --git a/internal/server/static/js/main.js b/internal/server/static/js/main.js new file mode 100644 index 0000000..4620a31 --- /dev/null +++ b/internal/server/static/js/main.js @@ -0,0 +1,98 @@ +// Solis Client-side Interactions + +document.addEventListener("DOMContentLoaded", () => { + // 1. Automatically configure HTMX requests to include CSRF token + document.addEventListener("htmx:configRequest", (evt) => { + const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'); + if (csrfToken) { + evt.detail.headers['X-CSRF-Token'] = csrfToken; + } + }); + + // 2. Setup dynamic toast auto-dismissals + setupToastListeners(); + + // 3. Room-tag locking on the item create/edit form + initRoomTagLock(); +}); + +function setupToastListeners() { + const observer = new MutationObserver((mutations) => { + mutations.forEach((mutation) => { + mutation.addedNodes.forEach((node) => { + if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('toast')) { + autoDismissToast(node); + } + }); + }); + }); + + const toastContainer = document.getElementById('toast-container'); + if (toastContainer) { + observer.observe(toastContainer, { childList: true }); + // Dismiss any initial toasts + toastContainer.querySelectorAll('.toast').forEach(autoDismissToast); + } +} + +function autoDismissToast(toast) { + // Fade out and remove after 4 seconds + setTimeout(() => { + toast.style.opacity = '0'; + toast.style.transform = 'translateY(1rem)'; + toast.style.transition = 'opacity 0.5s ease, transform 0.5s ease'; + setTimeout(() => { + toast.remove(); + }, 500); + }, 4000); +} + +function dismissToast(button) { + const toast = button.closest('.toast'); + if (toast) { + toast.style.opacity = '0'; + toast.style.transform = 'translateY(1rem)'; + toast.style.transition = 'opacity 0.3s ease, transform 0.3s ease'; + setTimeout(() => { + toast.remove(); + }, 300); + } +} + +function initRoomTagLock() { + const locationSelect = document.getElementById("location_id"); + if (!locationSelect) return; + + // Track the checkbox that is currently locked as the room tag + let lockedCheckbox = null; + + function updateRoomTag() { + const selectedOption = locationSelect.options[locationSelect.selectedIndex]; + if (!selectedOption) return; + const activeRoomName = selectedOption.text.trim(); + + // Unlock the previously locked checkbox before locking the new one + if (lockedCheckbox) { + lockedCheckbox.disabled = false; + // Only uncheck it if it was previously auto-checked (i.e., it IS a room tag). + // We leave non-room tags that the user manually checked alone. + lockedCheckbox.checked = false; + lockedCheckbox = null; + } + + // Find and lock the checkbox matching the new active room name + const checkboxes = document.querySelectorAll('input[name="tag_ids"]'); + checkboxes.forEach(cb => { + const tagName = cb.getAttribute('data-tag-name'); + if (tagName === activeRoomName) { + cb.checked = true; + cb.disabled = true; + lockedCheckbox = cb; + } + }); + } + + locationSelect.addEventListener("change", updateRoomTag); + // Run immediately on page load to lock the default/current room tag + updateRoomTag(); +} diff --git a/internal/server/templates.go b/internal/server/templates.go new file mode 100644 index 0000000..c67fadb --- /dev/null +++ b/internal/server/templates.go @@ -0,0 +1,130 @@ +package server + +import ( + "database/sql" + "embed" + "fmt" + "html/template" + "io" + "time" + + "Solis/internal/db" +) + +//go:embed all:templates +var templateFS embed.FS + +//go:embed all:static +var staticFS embed.FS + +var templates *template.Template + +var templateMap map[string]*template.Template + +var templateFuncs = template.FuncMap{ + "formatPrice": func(p any) string { + switch v := p.(type) { + case float64: + return fmt.Sprintf("$%.2f", v) + case sql.NullFloat64: + if v.Valid { + return fmt.Sprintf("$%.2f", v.Float64) + } + } + return "" + }, + "formatDate": func(d any) string { + if d == nil { + return "" + } + switch v := d.(type) { + case string: + if v == "" { + return "" + } + t, err := time.Parse("2006-01-02 15:04:05", v) + if err == nil { + return t.Format("Jan 02, 2006") + } + t, err = time.Parse("2006-01-02", v) + if err == nil { + return t.Format("Jan 02, 2006") + } + return v + case time.Time: + if v.IsZero() { + return "" + } + return v.Format("Jan 02, 2006") + case sql.NullString: + if v.Valid && v.String != "" { + t, err := time.Parse("2006-01-02", v.String) + if err == nil { + return t.Format("Jan 02, 2006") + } + return v.String + } + } + return "" + }, + "dict": func(values ...interface{}) (map[string]interface{}, error) { + if len(values)%2 != 0 { + return nil, fmt.Errorf("invalid dict call") + } + dict := make(map[string]interface{}, len(values)/2) + for i := 0; i < len(values); i += 2 { + key, ok := values[i].(string) + if !ok { + return nil, fmt.Errorf("dict keys must be strings") + } + dict[key] = values[i+1] + } + return dict, nil + }, + "hasTag": func(itemTags []db.Tag, tagID int64) bool { + for _, t := range itemTags { + if t.ID == tagID { + return true + } + } + return false + }, +} + +func initTemplates() { + templateMap = make(map[string]*template.Template) + + // Pages that use the base layout — each gets its own template set + // so their {{define "content"}} blocks don't collide. + layoutPages := []string{ + "items.html", + "locations.html", + "tags.html", + "shortener.html", + "print_labels.html", + } + + for _, page := range layoutPages { + t := template.Must( + template.New("").Funcs(templateFuncs).ParseFS(templateFS, "templates/base.html", "templates/"+page), + ) + templateMap[page] = t + } + + // Standalone pages (no base layout wrapper) + templateMap["login.html"] = template.Must( + template.New("").Funcs(templateFuncs).ParseFS(templateFS, "templates/login.html"), + ) +} + +func renderTemplate(w io.Writer, name string, data any) error { + t, ok := templateMap[name] + if !ok { + return fmt.Errorf("template %q not found", name) + } + // Standalone pages render by their own name; layout pages render via base.html + if name == "login.html" { + return t.ExecuteTemplate(w, name, data) + } + return t.ExecuteTemplate(w, "base.html", data) +} diff --git a/internal/server/templates/base.html b/internal/server/templates/base.html new file mode 100644 index 0000000..3e70b73 --- /dev/null +++ b/internal/server/templates/base.html @@ -0,0 +1,104 @@ + + + + + + {{block "title" .}}Solis | Home Assets{{end}} + + + + + + + + + + + + +
+ + + + +
+ {{template "content" .}} +
+
+ + +
+ {{if .Toast}} +
+
{{.Toast}}
+ +
+ {{end}} +
+ + diff --git a/internal/server/templates/items.html b/internal/server/templates/items.html new file mode 100644 index 0000000..7c2ed8b --- /dev/null +++ b/internal/server/templates/items.html @@ -0,0 +1,469 @@ +{{define "title"}}Solis | Assets{{end}} + +{{define "content"}} + +{{if .FormMode}} + + + +
+
+ + +

Basic Information

+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ +
+ {{range .Tags}} + + {{end}} +
+
+
+ +

Purchase & Warranty

+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +

Documentation & Visuals

+ +
+
+ + + {{if .EditingItem}}{{if .EditingItem.ImagePath}} + Active Image: {{.EditingItem.ImagePath}} + {{end}}{{end}} +
+
+ + + {{if .EditingItem}}{{if .EditingItem.ReceiptPath}} + Active Receipt: {{.EditingItem.ReceiptPath}} + {{end}}{{end}} +
+
+ +

Custom Fields

+

Enter custom parameters one per line as Key: Value (e.g. Battery: 18v Lithium). These will be parsed into indexed SQLite JSON dynamically.

+ +
+ + +
+ + +
+
+ +{{else if .ViewMode}} + + + +
+ +
+ +
+
+
+
+ {{.Item.Status}} +
+ + Quantity: {{.Item.Quantity}} + +
+
+ {{range .Item.Tags}} + {{.Name}} + {{end}} +
+
+ +

Description

+

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

+ +
+
+ Model Number + {{if .Item.ModelNumber}}{{.Item.ModelNumber}}{{else}}--{{end}} +
+
+ Serial Number + {{if .Item.SerialNumber}}{{.Item.SerialNumber}}{{else}}--{{end}} +
+
+
+ + +
+
+

Asset Photo

+
+ {{if .Item.ImagePath}} + Asset Photo + {{else}} +
+ + + + No Photo Attached +
+ {{end}} +
+
+ +
+

Receipt / Invoice

+
+ {{if .Item.ReceiptPath}} + + Receipt + + {{else}} +
+ + + + No Receipt Document +
+ {{end}} +
+
+
+ + +
+

Custom Asset Metadata

+ {{if .CustomFieldsMap}} +
+ + + {{range $key, $value := .CustomFieldsMap}} + + + + + {{end}} + +
{{$key}}{{$value}}
+
+ {{else}} +

No custom metadata fields defined for this asset.

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

Asset Label QR Code

+ {{if .Item.ShortSlug}} + QR Code + + s/{{.Item.ShortSlug}} + + + Download Label Image + + {{else}} + No short URL associated. + {{end}} +
+ + +
+

Purchase Context

+ +
+ Purchase Price + + {{if .Item.PurchasePrice.Valid}}{{formatPrice .Item.PurchasePrice}}{{else}}--{{end}} + +
+ +
+ Supplier / Dealer + + {{if .Item.Supplier}}{{.Item.Supplier}}{{else}}--{{end}} + +
+ +
+ Purchase Date + + {{if .Item.PurchaseDate.Valid}}{{formatDate .Item.PurchaseDate}}{{else}}--{{end}} + +
+ +
+ Warranty Period + + {{if .Item.WarrantyMonths.Valid}}{{.Item.WarrantyMonths.Int64}} Months{{else}}--{{end}} + +
+ +
+ Assigned Location + + {{if .Item.LocationName.Valid}} + {{.Item.LocationName.String}} + {{else}} + Unassigned + {{end}} + +
+
+
+
+ +{{else}} + + + + +
+
+ + + + +
+ + + + + + + {{if or .SearchQuery (or .SelectedStatus .SelectedLocation)}} + Reset + {{end}} +
+ + +
+
+ + + + + + + + + + + + + + {{if .Items}} + {{range .Items}} + + + + + + + + + + {{end}} + {{else}} + + + + {{end}} + +
QR LabelNameLocationStatusQuantityTagsActions
+ {{if .ShortSlug}} + + QR Label + + {{else}} + -- + {{end}} + +
+ + {{.Name}} + + {{if .ModelNumber}} + Model: {{.ModelNumber}} + {{end}} +
+
+ {{if .LocationName.Valid}} + + {{.LocationName.String}} + + {{else}} + Unassigned + {{end}} + + + {{.Status}} + + + {{.Quantity}} + +
+ {{range .Tags}} + {{.Name}} + {{end}} +
+
+
+ + Details + + + Edit + +
+ + +
+
+
+
+ + + +
+

No assets found

+

Try refining your filters or click "Add Asset" to start tracking equipment.

+
+
+
+
+
+{{end}} + +{{end}} diff --git a/internal/server/templates/locations.html b/internal/server/templates/locations.html new file mode 100644 index 0000000..f570e23 --- /dev/null +++ b/internal/server/templates/locations.html @@ -0,0 +1,141 @@ +{{define "title"}}Solis | Locations{{end}} + +{{define "content"}} + + +
+ +
+
+
+ + + + + + + + + + + {{if .Locations}} + {{range .Locations}} + + + + + + + {{end}} + {{else}} + + + + {{end}} + +
NameParent PathDescriptionActions
{{.Name}} + {{if .ParentName.Valid}} + + {{.ParentName.String}} → + + {{else}} + Root + {{end}} + {{.Description}} +
+ + + Edit + + {{if ne .ID 1}} +
+ + +
+ {{else}} + Locked + {{end}} +
+
+ No locations defined yet. Add one on the right to get started! +
+
+
+
+ + +
+
+ {{if .EditingLocation}} +

Edit Location

+
+ + +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + Cancel +
+
+ {{else}} +

Create Location

+
+ + +
+ + +
+ +
+ + +
+ +
+ + +
+ + +
+ {{end}} +
+
+
+{{end}} diff --git a/internal/server/templates/login.html b/internal/server/templates/login.html new file mode 100644 index 0000000..9749f5a --- /dev/null +++ b/internal/server/templates/login.html @@ -0,0 +1,45 @@ + + + + + + Solis | Sign In + + + + + + diff --git a/internal/server/templates/print_labels.html b/internal/server/templates/print_labels.html new file mode 100644 index 0000000..287c3e7 --- /dev/null +++ b/internal/server/templates/print_labels.html @@ -0,0 +1,51 @@ +{{define "title"}}Solis | Print Labels{{end}} + +{{define "content"}} + + +
+

Printing Guidelines

+
    +
  • Set your margins to None or Minimum in the browser print dialogue.
  • +
  • Enable Background graphics to preserve borders and alignments.
  • +
  • Check the layout preview page size (standard Letter/A4) to ensure grid alignment on your sticker paper.
  • +
+
+ + + +{{end}} diff --git a/internal/server/templates/shortener.html b/internal/server/templates/shortener.html new file mode 100644 index 0000000..94db17e --- /dev/null +++ b/internal/server/templates/shortener.html @@ -0,0 +1,143 @@ +{{define "title"}}Solis | URL Shortener{{end}} + +{{define "content"}} + + +
+ +
+
+
+ + + + + + + + + + + + {{if .Links}} + {{range .Links}} + + + + + + + + {{end}} + {{else}} + + + + {{end}} + +
SlugTarget URLLink TypeClicksActions
+ + +
+ {{.URL}} +
+
+ {{if .ItemID.Valid}} + + Asset #{{.ItemID.Int64}} Link + + {{else}} + + Manual Redirect + + {{end}} + + {{.Clicks}} + + {{if .ItemID.Valid}} + + Managed by Asset + {{else}} +
+ + Edit + +
+ + +
+
+ {{end}} +
+ No short links recorded. Create a custom redirect on the right! +
+
+
+
+ + +
+
+ {{if .EditingLink}} +

Edit Redirect

+
+ + +
+ + +
+ +
+ + +
+ +
+ + Cancel +
+
+ {{else}} +

Create Redirect

+
+ + +
+ +
+ + +
+ Leave blank to generate a random 4-character slug. +
+ +
+ + +
+ + +
+ {{end}} +
+
+
+{{end}} diff --git a/internal/server/templates/tags.html b/internal/server/templates/tags.html new file mode 100644 index 0000000..de8352b --- /dev/null +++ b/internal/server/templates/tags.html @@ -0,0 +1,132 @@ +{{define "title"}}Solis | Tags{{end}} + +{{define "content"}} + + +
+ +
+
+
+ + + + + + + + + + + {{if .Tags}} + {{range .Tags}} + + + + + + + {{end}} + {{else}} + + + + {{end}} + +
TagColor HexDescriptionActions
+ + {{.Name}} + + + + {{.Color}} + + {{.Description}} +
+ + Edit + + {{if ne .Name "Default Room"}} +
+ + +
+ {{else}} + Locked + {{end}} +
+
+ No tags defined yet. Add one on the right to get started! +
+
+
+
+ + +
+
+ {{if .EditingTag}} +

Edit Tag

+
+ + +
+ + +
+ +
+ +
+ + +
+
+ +
+ + +
+ +
+ + Cancel +
+
+ {{else}} +

Create Tag

+
+ + +
+ + +
+ +
+ +
+ + +
+
+ +
+ + +
+ + +
+ {{end}} +
+
+
+{{end}} diff --git a/internal/slug/slug.go b/internal/slug/slug.go new file mode 100644 index 0000000..85a6c00 --- /dev/null +++ b/internal/slug/slug.go @@ -0,0 +1,89 @@ +package slug + +import ( + "crypto/sha256" + "database/sql" + "encoding/hex" + "fmt" + "math/rand/v2" + "regexp" + "strings" +) + +const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" + +var reservedSlugs = map[string]bool{ + "admin": true, + "static": true, + "api": true, + "health": true, + "items": true, + "locations": true, + "tags": true, + "s": true, + "uploads": true, + "login": true, + "logout": true, +} + +var validSlugRe = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) + +func Generate(length int) string { + b := make([]byte, length) + for i := range b { + b[i] = alphabet[rand.IntN(len(alphabet))] + } + return string(b) +} + +func Validate(slug string) error { + if len(slug) == 0 { + return fmt.Errorf("slug cannot be empty") + } + if len(slug) > 64 { + return fmt.Errorf("slug too long (max 64 characters)") + } + if !validSlugRe.MatchString(slug) { + return fmt.Errorf("slug can only contain letters, numbers, hyphens, and underscores") + } + if reservedSlugs[strings.ToLower(slug)] { + return fmt.Errorf("slug %q is reserved", slug) + } + return nil +} + +func GenerateItemSlug(itemID int64, length int, dbConn *sql.DB) (string, error) { + if length <= 0 { + length = 8 + } + + baseInput := fmt.Sprintf("item%d", itemID) + for { + h := sha256.New() + h.Write([]byte(baseInput)) + hashBytes := h.Sum(nil) + hashHex := hex.EncodeToString(hashBytes) + + slugStr := hashHex + if length < len(hashHex) { + slugStr = hashHex[:length] + } + + if reservedSlugs[strings.ToLower(slugStr)] { + baseInput = fmt.Sprintf("item%d-%d", itemID, rand.IntN(900000)+100000) + continue + } + + var exists int + err := dbConn.QueryRow("SELECT COUNT(*) FROM links WHERE slug = ?", slugStr).Scan(&exists) + if err != nil { + return "", err + } + + if exists == 0 { + return slugStr, nil + } + + baseInput = fmt.Sprintf("item%d-%d", itemID, rand.IntN(900000)+100000) + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..3a6d21f --- /dev/null +++ b/main.go @@ -0,0 +1,77 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + + "golang.org/x/crypto/bcrypt" + + "Solis/internal/config" + "Solis/internal/db" + "Solis/internal/server" +) + +func main() { + configPath := flag.String("config", "config.toml", "Path to config file") + hashPassword := flag.String("hash-password", "", "Generate a bcrypt hash of the given password and exit") + flag.StringVar(configPath, "c", "config.toml", "Path to config file (shorthand)") + flag.Parse() + + // If the user requested to hash a password, hash it and print the result + if *hashPassword != "" { + hash, err := bcrypt.GenerateFromPassword([]byte(*hashPassword), bcrypt.DefaultCost) + if err != nil { + log.Fatalf("Error hashing password: %v", err) + } + fmt.Printf("Bcrypt hash for password %q:\n%s\n", *hashPassword, string(hash)) + os.Exit(0) + } + + // Out-of-the-box ease: check if config file exists, if not, attempt to copy it from config.toml.example + if _, err := os.Stat(*configPath); os.IsNotExist(err) { + if *configPath == "config.toml" { + if _, errExample := os.Stat("config.toml.example"); errExample == nil { + log.Println("config.toml not found, copying from config.toml.example...") + input, errRead := os.ReadFile("config.toml.example") + if errRead == nil { + errWrite := os.WriteFile("config.toml", input, 0644) + if errWrite != nil { + log.Printf("Warning: failed to create config.toml from example: %v", errWrite) + } + } + } + } + } + + // Load configuration + log.Printf("Loading configuration from %s...", *configPath) + cfg, err := config.Load(*configPath) + if err != nil { + log.Fatalf("Error loading config: %v\n\nIf the config file does not exist, make sure to create config.toml (you can use config.toml.example as a template).", err) + } + + // Initialize the CGO-free database + log.Printf("Initializing database at %s...", cfg.Database.Path) + database, err := db.Open(cfg.Database.Path) + if err != nil { + log.Fatalf("Failed to initialize database: %v", err) + } + defer func() { + if err := database.Close(); err != nil { + log.Printf("Error closing database: %v", err) + } + }() + + // Ensure upload directory exists before starting server + if err := os.MkdirAll(cfg.Upload.Dir, 0755); err != nil { + log.Fatalf("Failed to create upload directory: %v", err) + } + + // Initialize and start the premium Solis server + srv := server.New(cfg, database) + if err := srv.Start(); err != nil { + log.Fatalf("Server stopped with error: %v", err) + } +} diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..b402705 --- /dev/null +++ b/schema.sql @@ -0,0 +1,70 @@ +-- SQLite Database Schema for Solis +-- Enables high-fidelity asset tracking and custom URL shortening + +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')) +); + +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')) +); + +-- 3. Items Table (Asset entries with purchase records and JSON custom fields) +CREATE TABLE IF NOT EXISTS items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + quantity INTEGER NOT NULL DEFAULT 1, + model_number TEXT NOT NULL DEFAULT '', + serial_number TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'In Use', -- 'In Use', 'In Storage', 'Borrowed', 'Lost', 'Disposed' + location_id INTEGER REFERENCES locations(id) ON DELETE SET NULL, + purchase_price REAL, -- Double/Real for financial values + purchase_date TEXT, -- ISO8601 date string (YYYY-MM-DD) + warranty_months INTEGER, + supplier TEXT NOT NULL DEFAULT '', + 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 '', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS idx_items_location ON items(location_id); + +-- 4. Item Tags Junction Table (Many-to-Many relationship) +CREATE TABLE IF NOT EXISTS item_tags ( + item_id INTEGER NOT NULL REFERENCES items(id) ON DELETE CASCADE, + tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE, + PRIMARY KEY (item_id, tag_id) +); + +-- 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')) +); + +CREATE INDEX IF NOT EXISTS idx_links_slug ON links(slug); +CREATE INDEX IF NOT EXISTS idx_links_item ON links(item_id);