Initial working version

This commit is contained in:
lucio committed 2026-05-21 02:11:11 -07:00
commit 3d7c232b94
32 files changed
+4743

No files matched your search

+20
View File
@@ -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
+22
View File
@@ -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
}
}
+63
View File
@@ -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"]
+43
View File
@@ -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
+24
View File
@@ -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
+19
View File
@@ -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
)
+27
View File
@@ -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=
+99
View File
@@ -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
}
+77
View File
@@ -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()
}
+365
View File
@@ -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...)
}
+102
View File
@@ -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
}
+222
View File
@@ -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
}
+68
View File
@@ -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);
+107
View File
@@ -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
}
+929
View File
@@ -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
}
+189
View File
@@ -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
}
+48
View File
@@ -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)
}
+180
View File
@@ -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)
}
+589
View File
@@ -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;
}
}
+1
View File
@@ -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/<body/.test(e)}function l(e){var t=!N(e);var r=A(e);var n=e;if(r==="head"){n=n.replace(S,"")}if(Q.config.useTemplateFragments&&t){var i=a("<body><template>"+n+"</template></body>",0);return i.querySelector("template").content}switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return a("<table>"+n+"</table>",1);case"col":return a("<table><colgroup>"+n+"</colgroup></table>",2);case"tr":return a("<table><tbody>"+n+"</tbody></table>",2);case"td":case"th":return a("<table><tbody><tr>"+n+"</tr></tbody></table>",3);case"script":case"style":return a("<div>"+n+"</div>",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<e.length;r++){t.push(e[r])}}return t}function oe(e,t){if(e){for(var r=0;r<e.length;r++){t(e[r])}}}function X(e){var t=e.getBoundingClientRect();var r=t.top;var n=t.bottom;return r<window.innerHeight&&n>=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 Line truncated
+98
View File
@@ -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();
}
+130
View File
@@ -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)
}
+104
View File
@@ -0,0 +1,104 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{block "title" .}}Solis | Home Assets{{end}}</title>
<!-- Dynamic CSRF Metadata for HTMX requests -->
<meta name="csrf-token" content="{{.CSRFToken}}">
<!-- Styles & Fonts -->
<link rel="stylesheet" href="/static/css/styles.css">
<!-- Self-contained scripts serving fully offline -->
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/main.js"></script>
</head>
<body>
<div class="app-container">
<!-- Sidebar Navigation -->
<aside class="sidebar">
<div class="brand">
<div class="brand-logo">S</div>
<span class="brand-name">Solis</span>
</div>
<nav class="sidebar-nav">
<ul class="nav-list">
<li class="nav-item {{if eq .ActiveNav "items"}}active{{end}}">
<a href="/admin" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
</svg>
Assets
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "locations"}}active{{end}}">
<a href="/admin/locations" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25s-7.5-4.108-7.5-11.25g3 3 0 1115 0z" />
</svg>
Locations
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "tags"}}active{{end}}">
<a href="/admin/tags" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M9.568 3H5.25A2.25 2.25 0 003 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581a1.125 1.125 0 001.591 0l4.318-4.318a1.125 1.125 0 000-1.591l-9.581-9.581A2.25 2.25 0 009.568 3z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6z" />
</svg>
Tags
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "shortener"}}active{{end}}">
<a href="/admin/shortener" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244" />
</svg>
Shortlinks
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "print"}}active{{end}}">
<a href="/admin/print" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0110.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0a2.25 2.25 0 01-2.247 2.118H8.587A2.25 2.25 0 016.34 18m11.32 0h.008v.008h-.008V18zm-12 0h.008v.008H5.66V18zm0-11.25h12.75c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125H5.66c-.621 0-1.125-.504-1.125-1.125v-1.5c0-.621.504-1.125 1.125-1.125z" />
</svg>
Print Labels
</a>
</li>
</ul>
</nav>
<!-- Sidebar Footer -->
<div class="sidebar-footer">
<form action="/admin/logout" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-secondary" style="width: 100%;">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px;margin-right:4px;">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75" />
</svg>
Sign Out
</button>
</form>
</div>
</aside>
<!-- Main Content View Wrapper -->
<main class="main-wrapper">
{{template "content" .}}
</main>
</div>
<!-- Dynamic Slide-in Alert Toasts -->
<div id="toast-container">
{{if .Toast}}
<div class="toast {{if eq .ToastType "success"}}toast-success{{else}}toast-error{{end}}">
<div class="toast-message">{{.Toast}}</div>
<button class="toast-close" onclick="dismissToast(this)">&times;</button>
</div>
{{end}}
</div>
</body>
</html>
+469
View File
@@ -0,0 +1,469 @@
{{define "title"}}Solis | Assets{{end}}
{{define "content"}}
{{if .FormMode}}
<!-- ================== ASSET EDIT / CREATE FORM ================== -->
<div class="page-header">
<div class="page-title">
<h1>{{if .EditingItem}}Edit Asset: {{.EditingItem.Name}}{{else}}Add New Asset{{end}}</h1>
<p>Define inventory items, upload documentation, and generate automated QR codes.</p>
</div>
<div>
<a href="/admin" class="btn btn-secondary">Cancel</a>
</div>
</div>
<div class="card">
<form action="{{if .EditingItem}}/admin/items/edit/{{.EditingItem.ID}}{{else}}/admin/items/new{{end}}" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<h3 style="font-weight: 700; margin-bottom: 1.5rem; color: var(--color-brand-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Basic Information</h3>
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem;">
<div class="form-group">
<label for="name" class="form-label">Asset Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="e.g. Cordless Hammer Drill" value="{{if .EditingItem}}{{.EditingItem.Name}}{{end}}" required>
</div>
<div class="form-group">
<label for="quantity" class="form-label">Quantity</label>
<input type="number" id="quantity" name="quantity" class="form-control" min="1" value="{{if .EditingItem}}{{.EditingItem.Quantity}}{{else}}1{{end}}" required>
</div>
</div>
<div class="form-group">
<label for="description" class="form-label">Description</label>
<textarea id="description" name="description" class="form-control" rows="3" placeholder="e.g. Brushless motor hammer drill, includes two 18V Li-ion batteries">{{if .EditingItem}}{{.EditingItem.Description}}{{end}}</textarea>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1.5rem;">
<div class="form-group">
<label for="model_number" class="form-label">Model Number</label>
<input type="text" id="model_number" name="model_number" class="form-control" placeholder="e.g. DCD796" value="{{if .EditingItem}}{{.EditingItem.ModelNumber}}{{end}}">
</div>
<div class="form-group">
<label for="serial_number" class="form-label">Serial Number</label>
<input type="text" id="serial_number" name="serial_number" class="form-control" placeholder="e.g. 2018-W42-9988" value="{{if .EditingItem}}{{.EditingItem.SerialNumber}}{{end}}">
</div>
<div class="form-group">
<label for="status" class="form-label">Status</label>
<select id="status" name="status" class="form-control">
<option value="In Use" {{if .EditingItem}}{{if eq .EditingItem.Status "In Use"}}selected{{end}}{{end}}>In Use</option>
<option value="In Storage" {{if .EditingItem}}{{if eq .EditingItem.Status "In Storage"}}selected{{end}}{{end}}>In Storage</option>
<option value="Borrowed" {{if .EditingItem}}{{if eq .EditingItem.Status "Borrowed"}}selected{{end}}{{end}}>Borrowed</option>
<option value="Lost" {{if .EditingItem}}{{if eq .EditingItem.Status "Lost"}}selected{{end}}{{end}}>Lost</option>
<option value="Disposed" {{if .EditingItem}}{{if eq .EditingItem.Status "Disposed"}}selected{{end}}{{end}}>Disposed</option>
</select>
</div>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem;">
<div class="form-group">
<label for="location_id" class="form-label">Location</label>
<select id="location_id" name="location_id" class="form-control" required>
{{range .Locations}}
<option value="{{.ID}}" {{if $.EditingItem}}{{if $.EditingItem.LocationID.Valid}}{{if eq .ID $.EditingItem.LocationID.Int64}}selected{{end}}{{end}}{{else}}{{if eq .ID 1}}selected{{end}}{{end}}>
{{.Name}}
</option>
{{end}}
</select>
</div>
<div class="form-group">
<label class="form-label">Tags / Categories</label>
<div style="display: flex; flex-wrap: wrap; gap: 0.75rem; border: 1px solid var(--color-border); padding: 0.625rem; border-radius: var(--radius-sm); background-color: var(--color-bg-base); max-height: 110px; overflow-y: auto;">
{{range .Tags}}
<label style="display: inline-flex; align-items: center; gap: 0.35rem; font-size: 0.85rem; font-weight: 500; cursor: pointer;">
<input type="checkbox" name="tag_ids" value="{{.ID}}" data-tag-name="{{.Name}}" {{if $.EditingItem}}{{if hasTag $.EditingItem.Tags .ID}}checked{{end}}{{end}}>
<span class="tag-pill" style="background-color: {{.Color}};">{{.Name}}</span>
</label>
{{end}}
</div>
</div>
</div>
<h3 style="font-weight: 700; margin-bottom: 1.5rem; color: var(--color-brand-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem; margin-top: 2rem;">Purchase & Warranty</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 1.5rem;">
<div class="form-group">
<label for="purchase_price" class="form-label">Purchase Price ($)</label>
<input type="number" id="purchase_price" name="purchase_price" class="form-control" step="0.01" min="0" placeholder="e.g. 149.99" value="{{if .EditingItem}}{{if .EditingItem.PurchasePrice.Valid}}{{.EditingItem.PurchasePrice.Float64}}{{end}}{{end}}">
</div>
<div class="form-group">
<label for="purchase_date" class="form-label">Purchase Date</label>
<input type="date" id="purchase_date" name="purchase_date" class="form-control" value="{{if .EditingItem}}{{if .EditingItem.PurchaseDate.Valid}}{{.EditingItem.PurchaseDate.String}}{{end}}{{end}}">
</div>
<div class="form-group">
<label for="warranty_months" class="form-label">Warranty (Months)</label>
<input type="number" id="warranty_months" name="warranty_months" class="form-control" min="0" placeholder="e.g. 24" value="{{if .EditingItem}}{{if .EditingItem.WarrantyMonths.Valid}}{{.EditingItem.WarrantyMonths.Int64}}{{end}}{{end}}">
</div>
<div class="form-group">
<label for="supplier" class="form-label">Supplier / Store</label>
<input type="text" id="supplier" name="supplier" class="form-control" placeholder="e.g. Home Depot" value="{{if .EditingItem}}{{.EditingItem.Supplier}}{{end}}">
</div>
</div>
<h3 style="font-weight: 700; margin-bottom: 1.5rem; color: var(--color-brand-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem; margin-top: 2rem;">Documentation & Visuals</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
<div class="form-group">
<label for="image" class="form-label">Item Photo</label>
<input type="file" id="image" name="image" class="form-control" accept="image/*">
{{if .EditingItem}}{{if .EditingItem.ImagePath}}
<span style="font-size: 0.8rem; color: var(--color-brand-primary); margin-top: 0.25rem; display: block;">Active Image: {{.EditingItem.ImagePath}}</span>
{{end}}{{end}}
</div>
<div class="form-group">
<label for="receipt" class="form-label">Receipt / Invoice Document</label>
<input type="file" id="receipt" name="receipt" class="form-control" accept="image/*,application/pdf">
{{if .EditingItem}}{{if .EditingItem.ReceiptPath}}
<span style="font-size: 0.8rem; color: var(--color-brand-primary); margin-top: 0.25rem; display: block;">Active Receipt: {{.EditingItem.ReceiptPath}}</span>
{{end}}{{end}}
</div>
</div>
<h3 style="font-weight: 700; margin-bottom: 0.5rem; color: var(--color-brand-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem; margin-top: 2rem;">Custom Fields</h3>
<p style="font-size: 0.8rem; color: var(--color-text-muted); margin-bottom: 1rem;">Enter custom parameters one per line as <code>Key: Value</code> (e.g. <code>Battery: 18v Lithium</code>). These will be parsed into indexed SQLite JSON dynamically.</p>
<div class="form-group" style="margin-bottom: 2.5rem;">
<label for="custom_fields" class="form-label">Custom Fields Editor</label>
<textarea id="custom_fields" name="custom_fields" class="form-control" rows="4" placeholder="Battery: 18v&#10;MotorType: Brushless">{{.CustomFieldsRaw}}</textarea>
</div>
<button type="submit" class="btn btn-primary" style="padding: 0.75rem 2rem; font-size: 1rem;">
{{if .EditingItem}}Save Changes{{else}}Create Asset{{end}}
</button>
</form>
</div>
{{else if .ViewMode}}
<!-- ================== ASSET VIEW DETAILS MODE ================== -->
<div class="page-header">
<div class="page-title">
<span style="color: var(--color-text-light); font-size: 0.85rem; font-weight: 600; text-transform: uppercase;">Asset Details</span>
<h1 style="margin-top: 0.15rem;">{{.Item.Name}}</h1>
</div>
<div style="display: flex; gap: 0.5rem;">
<a href="/admin/items/edit/{{.Item.ID}}" class="btn btn-primary">
Edit Asset
</a>
<a href="/admin" class="btn btn-secondary">
Back to List
</a>
</div>
</div>
<div class="detail-grid">
<!-- Detail Main Section -->
<div class="detail-main">
<!-- Basic info card -->
<div class="card">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 1.5rem;">
<div>
<div class="status-pill {{if eq .Item.Status "In Use"}}in-use{{else if eq .Item.Status "In Storage"}}in-storage{{else if eq .Item.Status "Borrowed"}}borrowed{{else if eq .Item.Status "Lost"}}lost{{else}}disposed{{end}}">
{{.Item.Status}}
</div>
<span style="margin-left: 0.5rem; font-size: 0.9rem; color: var(--color-text-muted); font-weight: 500;">
Quantity: <strong>{{.Item.Quantity}}</strong>
</span>
</div>
<div class="tag-list">
{{range .Item.Tags}}
<span class="tag-pill" style="background-color: {{.Color}};">{{.Name}}</span>
{{end}}
</div>
</div>
<h3 style="font-weight: 700; font-size: 1.15rem; margin-bottom: 0.75rem;">Description</h3>
<p style="color: var(--color-text-muted); margin-bottom: 1.75rem;">
{{if .Item.Description}}{{.Item.Description}}{{else}}<em>No description provided for this asset.</em>{{end}}
</p>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; border-top: 1px solid var(--color-border); padding-top: 1.5rem;">
<div>
<span style="font-size: 0.85rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Model Number</span>
<span style="font-weight: 500; font-size: 1.05rem;">{{if .Item.ModelNumber}}{{.Item.ModelNumber}}{{else}}--{{end}}</span>
</div>
<div>
<span style="font-size: 0.85rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Serial Number</span>
<span style="font-weight: 500; font-size: 1.05rem; font-family: monospace;">{{if .Item.SerialNumber}}{{.Item.SerialNumber}}{{else}}--{{end}}</span>
</div>
</div>
</div>
<!-- Image Visuals and Receipts -->
<div class="item-visuals">
<div class="card" style="padding: 1rem; display: flex; flex-direction: column; gap: 0.75rem;">
<h4 style="font-weight: 600; font-size: 0.95rem; color: var(--color-text-muted); border-bottom:1px solid var(--color-border); padding-bottom:0.25rem;">Asset Photo</h4>
<div class="visual-box">
{{if .Item.ImagePath}}
<img src="/uploads/{{.Item.ImagePath}}" alt="Asset Photo">
{{else}}
<div class="visual-placeholder">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 48px; height: 48px;">
<path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V6.75zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" />
</svg>
<span>No Photo Attached</span>
</div>
{{end}}
</div>
</div>
<div class="card" style="padding: 1rem; display: flex; flex-direction: column; gap: 0.75rem;">
<h4 style="font-weight: 600; font-size: 0.95rem; color: var(--color-text-muted); border-bottom:1px solid var(--color-border); padding-bottom:0.25rem;">Receipt / Invoice</h4>
<div class="visual-box">
{{if .Item.ReceiptPath}}
<!-- receipts could be PDFs or images. Since we force downloads for PDFs, let's see. If it's pdf we show pdf icon, otherwise image -->
<img src="/uploads/{{.Item.ReceiptPath}}" alt="Receipt">
<div style="position: absolute; bottom: 0.5rem; right: 0.5rem;">
<a href="/uploads/{{.Item.ReceiptPath}}" target="_blank" class="btn btn-secondary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem; background: white;">
Open Document
</a>
</div>
{{else}}
<div class="visual-placeholder">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 48px; height: 48px;">
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
</svg>
<span>No Receipt Document</span>
</div>
{{end}}
</div>
</div>
</div>
<!-- Custom fields card -->
<div class="card">
<h3 style="font-weight: 700; font-size: 1.15rem; margin-bottom: 1.25rem; color: var(--color-brand-primary); border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem;">Custom Asset Metadata</h3>
{{if .CustomFieldsMap}}
<div class="data-table-wrapper">
<table class="data-table">
<tbody>
{{range $key, $value := .CustomFieldsMap}}
<tr>
<td style="font-weight: 600; width: 200px; color: var(--color-text-muted); padding: 0.75rem 0.5rem;">{{$key}}</td>
<td style="font-family: monospace; font-size: 0.95rem; padding: 0.75rem 0.5rem;">{{$value}}</td>
</tr>
{{end}}
</tbody>
</table>
</div>
{{else}}
<p style="color: var(--color-text-light); font-size: 0.95rem; font-style: italic;">No custom metadata fields defined for this asset.</p>
{{end}}
</div>
</div>
<!-- Detail Sidebar Section -->
<div class="detail-sidebar">
<!-- QR code card -->
<div class="card qr-card">
<h4 style="font-weight: 700; color: var(--color-text-muted); font-size: 1.05rem;">Asset Label QR Code</h4>
{{if .Item.ShortSlug}}
<img class="qr-image" src="/admin/qr/{{.Item.ShortSlug}}" alt="QR Code">
<code style="font-family: monospace; background-color: var(--color-bg-base); padding: 0.35rem 0.75rem; border-radius: 4px; border: 1px solid var(--color-border); font-weight: 600; font-size: 0.95rem;">
s/{{.Item.ShortSlug}}
</code>
<a href="/admin/qr/{{.Item.ShortSlug}}" download="{{.Item.Name}}_QR.png" class="btn btn-secondary" style="width: 100%; font-size: 0.85rem;">
Download Label Image
</a>
{{else}}
<span style="color: var(--color-text-light); font-size: 0.85rem;">No short URL associated.</span>
{{end}}
</div>
<!-- Purchase particulars card -->
<div class="card" style="display: flex; flex-direction: column; gap: 1.25rem;">
<h4 style="font-weight: 700; color: var(--color-text-muted); font-size: 1.05rem; border-bottom: 1px solid var(--color-border); padding-bottom: 0.5rem; margin-bottom: 0.25rem;">Purchase Context</h4>
<div>
<span style="font-size: 0.75rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Purchase Price</span>
<span style="font-weight: 700; font-size: 1.35rem; color: var(--color-brand-primary);">
{{if .Item.PurchasePrice.Valid}}{{formatPrice .Item.PurchasePrice}}{{else}}--{{end}}
</span>
</div>
<div>
<span style="font-size: 0.75rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Supplier / Dealer</span>
<span style="font-weight: 600; font-size: 1rem;">
{{if .Item.Supplier}}{{.Item.Supplier}}{{else}}--{{end}}
</span>
</div>
<div>
<span style="font-size: 0.75rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Purchase Date</span>
<span style="font-weight: 600; font-size: 1rem;">
{{if .Item.PurchaseDate.Valid}}{{formatDate .Item.PurchaseDate}}{{else}}--{{end}}
</span>
</div>
<div>
<span style="font-size: 0.75rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Warranty Period</span>
<span style="font-weight: 600; font-size: 1rem;">
{{if .Item.WarrantyMonths.Valid}}{{.Item.WarrantyMonths.Int64}} Months{{else}}--{{end}}
</span>
</div>
<div>
<span style="font-size: 0.75rem; color: var(--color-text-light); text-transform: uppercase; font-weight: 600; display: block;">Assigned Location</span>
<span style="font-weight: 600; font-size: 1rem; color: var(--color-brand-primary);">
{{if .Item.LocationName.Valid}}
{{.Item.LocationName.String}}
{{else}}
<span style="color: var(--color-text-light); font-style: italic; font-weight: 500;">Unassigned</span>
{{end}}
</span>
</div>
</div>
</div>
</div>
{{else}}
<!-- ================== DEFAULT: MAIN INVENTORY LIST ================== -->
<div class="page-header">
<div class="page-title">
<h1>Asset Inventory</h1>
<p>Track, manage, and label your home equipment and tools.</p>
</div>
<div>
<a href="/admin/items/new" class="btn btn-primary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2.5" stroke="currentColor" style="width: 18px; height: 18px;">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
</svg>
Add Asset
</a>
</div>
</div>
<!-- Search & Filters -->
<form action="/admin" method="GET" class="filter-bar">
<div class="search-input-wrapper">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.604 10.604z" />
</svg>
<input type="text" name="search" class="form-control" placeholder="Search by asset name, model, serial number..." value="{{.SearchQuery}}">
</div>
<select name="status" class="form-control" style="width: 180px;" onchange="this.form.submit()">
<option value="">-- All Statuses --</option>
<option value="In Use" {{if eq .SelectedStatus "In Use"}}selected{{end}}>In Use</option>
<option value="In Storage" {{if eq .SelectedStatus "In Storage"}}selected{{end}}>In Storage</option>
<option value="Borrowed" {{if eq .SelectedStatus "Borrowed"}}selected{{end}}>Borrowed</option>
<option value="Lost" {{if eq .SelectedStatus "Lost"}}selected{{end}}>Lost</option>
<option value="Disposed" {{if eq .SelectedStatus "Disposed"}}selected{{end}}>Disposed</option>
</select>
<select name="location" class="form-control" style="width: 200px;" onchange="this.form.submit()">
<option value="">-- All Locations --</option>
{{range .Locations}}
<option value="{{.ID}}" {{if eq $.SelectedLocation .ID}}selected{{end}}>{{.Name}}</option>
{{end}}
</select>
<button type="submit" class="btn btn-secondary">Filter</button>
{{if or .SearchQuery (or .SelectedStatus .SelectedLocation)}}
<a href="/admin" class="btn btn-secondary" style="padding: 0.625rem;">Reset</a>
{{end}}
</form>
<!-- Assets Inventory Table -->
<div class="card" style="padding: 0;">
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th style="width: 80px;">QR Label</th>
<th>Name</th>
<th>Location</th>
<th>Status</th>
<th>Quantity</th>
<th>Tags</th>
<th style="width: 140px; text-align: right;">Actions</th>
</tr>
</thead>
<tbody>
{{if .Items}}
{{range .Items}}
<tr>
<td style="text-align: center; vertical-align: middle;">
{{if .ShortSlug}}
<a href="/admin/qr/{{.ShortSlug}}" target="_blank">
<img src="/admin/qr/{{.ShortSlug}}" alt="QR Label" style="width: 42px; height: 42px; border: 1px solid var(--color-border); padding: 1px; border-radius: 4px; background: white;">
</a>
{{else}}
<span style="color: var(--color-text-light); font-size: 0.75rem;">--</span>
{{end}}
</td>
<td>
<div style="display: flex; flex-direction: column;">
<a href="/admin?view={{.ID}}" style="font-weight: 700; color: var(--color-text-main); text-decoration: none; font-size: 1.05rem;">
{{.Name}}
</a>
{{if .ModelNumber}}
<span style="color: var(--color-text-muted); font-size: 0.8rem; font-family: monospace;">Model: {{.ModelNumber}}</span>
{{end}}
</div>
</td>
<td>
{{if .LocationName.Valid}}
<span style="color: var(--color-brand-primary); font-weight: 500; font-size: 0.95rem;">
{{.LocationName.String}}
</span>
{{else}}
<span style="color: var(--color-text-light); font-style: italic; font-size: 0.9rem;">Unassigned</span>
{{end}}
</td>
<td>
<span class="status-pill {{if eq .Status "In Use"}}in-use{{else if eq .Status "In Storage"}}in-storage{{else if eq .Status "Borrowed"}}borrowed{{else if eq .Status "Lost"}}lost{{else}}disposed{{end}}">
{{.Status}}
</span>
</td>
<td style="font-weight: 600; font-size: 0.95rem; color: var(--color-text-muted); text-align: center;">
{{.Quantity}}
</td>
<td>
<div class="tag-list">
{{range .Tags}}
<span class="tag-pill" style="background-color: {{.Color}};">{{.Name}}</span>
{{end}}
</div>
</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.5rem; align-items: center;">
<a href="/admin?view={{.ID}}" class="btn btn-secondary" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Details
</a>
<a href="/admin/items/edit/{{.ID}}" class="btn btn-secondary" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Edit
</a>
<form action="/admin/items/delete/{{.ID}}" method="POST" onsubmit="return confirm('Are you sure you want to delete this asset? This cannot be undone.')" style="margin: 0;">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Delete
</button>
</form>
</div>
</td>
</tr>
{{end}}
{{else}}
<tr>
<td colspan="7" style="text-align: center; color: var(--color-text-light); padding: 5rem 1rem;">
<div style="display: flex; flex-direction: column; align-items: center; gap: 1rem;">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1" stroke="currentColor" style="width: 64px; height: 64px; color: var(--color-text-light);">
<path stroke-linecap="round" stroke-linejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
</svg>
<div>
<h3 style="font-weight:600; color:var(--color-text-muted);">No assets found</h3>
<p style="font-size:0.9rem; margin-top:0.25rem;">Try refining your filters or click "Add Asset" to start tracking equipment.</p>
</div>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
</div>
</div>
{{end}}
{{end}}
+141
View File
@@ -0,0 +1,141 @@
{{define "title"}}Solis | Locations{{end}}
{{define "content"}}
<div class="page-header">
<div class="page-title">
<h1>Locations</h1>
<p>Define physical areas and hierarchical storage places (e.g., House > Kitchen > Drawer A)</p>
</div>
</div>
<div class="detail-grid">
<!-- Left Column: Locations List -->
<div class="detail-main">
<div class="card" style="padding: 0;">
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th>Name</th>
<th>Parent Path</th>
<th>Description</th>
<th style="width: 120px; text-align: right;">Actions</th>
</tr>
</thead>
<tbody>
{{if .Locations}}
{{range .Locations}}
<tr>
<td style="font-weight: 600; color: var(--color-brand-primary);">{{.Name}}</td>
<td>
{{if .ParentName.Valid}}
<span style="color: var(--color-text-muted); font-size: 0.9rem;">
{{.ParentName.String}} &rarr;
</span>
{{else}}
<span style="color: var(--color-text-light); font-size: 0.85rem;">Root</span>
{{end}}
</td>
<td style="color: var(--color-text-muted); font-size: 0.9rem;">{{.Description}}</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.5rem;">
<!-- Edit Location triggers loading edit state in the right-side form -->
<a href="/admin/locations?edit={{.ID}}" class="btn btn-secondary" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Edit
</a>
{{if ne .ID 1}}
<form action="/admin/locations/delete/{{.ID}}" method="POST" onsubmit="return confirm('Are you sure you want to delete this location? Sub-locations and assets will be detached.')" style="margin: 0;">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Delete
</button>
</form>
{{else}}
<span style="color: var(--color-text-light); font-size: 0.8rem; font-style: italic; padding: 0.35rem 0.65rem;">Locked</span>
{{end}}
</div>
</td>
</tr>
{{end}}
{{else}}
<tr>
<td colspan="4" style="text-align: center; color: var(--color-text-light); padding: 3rem 1rem;">
No locations defined yet. Add one on the right to get started!
</td>
</tr>
{{end}}
</tbody>
</table>
</div>
</div>
</div>
<!-- Right Column: Add/Edit Form -->
<div class="detail-sidebar">
<div class="card">
{{if .EditingLocation}}
<h3 style="font-weight: 700; margin-bottom: 1.25rem;">Edit Location</h3>
<form action="/admin/locations/edit/{{.EditingLocation.ID}}" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div class="form-group">
<label for="name" class="form-label">Location Name</label>
<input type="text" id="name" name="name" class="form-control" value="{{.EditingLocation.Name}}" {{if eq .EditingLocation.ID 1}}readonly style="background-color: var(--color-bg-base); cursor: not-allowed;"{{end}} required>
</div>
<div class="form-group">
<label for="parent_id" class="form-label">Parent Location (Optional)</label>
<select id="parent_id" name="parent_id" class="form-control">
<option value="">-- None (Root Location) --</option>
{{range $.Locations}}
{{if ne .ID $.EditingLocation.ID}}
<option value="{{.ID}}" {{if $.EditingLocation.ParentID.Valid}}{{if eq .ID $.EditingLocation.ParentID.Int64}}selected{{end}}{{end}}>
{{.Name}}
</option>
{{end}}
{{end}}
</select>
</div>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="description" class="form-label">Description</label>
<textarea id="description" name="description" class="form-control" rows="3" placeholder="e.g. Red plastic storage box on shelf 2">{{.EditingLocation.Description}}</textarea>
</div>
<div style="display: flex; gap: 0.5rem;">
<button type="submit" class="btn btn-primary" style="flex-grow: 1;">Save Changes</button>
<a href="/admin/locations" class="btn btn-secondary">Cancel</a>
</div>
</form>
{{else}}
<h3 style="font-weight: 700; margin-bottom: 1.25rem;">Create Location</h3>
<form action="/admin/locations/new" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div class="form-group">
<label for="name" class="form-label">Location Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="e.g. Living Room, Drawer B" required>
</div>
<div class="form-group">
<label for="parent_id" class="form-label">Parent Location (Optional)</label>
<select id="parent_id" name="parent_id" class="form-control">
<option value="">-- None (Root Location) --</option>
{{range .Locations}}
<option value="{{.ID}}">{{.Name}}</option>
{{end}}
</select>
</div>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="description" class="form-label">Description</label>
<textarea id="description" name="description" class="form-control" rows="3" placeholder="e.g. First floor living room cupboard"></textarea>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%;">Add Location</button>
</form>
{{end}}
</div>
</div>
</div>
{{end}}
+45
View File
@@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Solis | Sign In</title>
<link rel="stylesheet" href="/static/css/styles.css">
</head>
<body class="login-container">
<div class="login-card">
<div class="login-header">
<div class="brand">
<div class="brand-logo">S</div>
<span class="brand-name">Solis</span>
</div>
<h2 style="font-weight:700;font-size:1.5rem;letter-spacing:-0.01em;">Sign in to your assets</h2>
<p style="color:var(--color-text-muted);font-size:0.9rem;margin-top:0.25rem;">Enter your administrator credentials below</p>
</div>
{{if .Error}}
<div style="background-color:#fee2e2; border:1px solid #fca5a5; color:#b91c1c; padding:0.75rem 1rem; border-radius:6px; font-size:0.9rem; margin-bottom:1.5rem; font-weight:500; text-align:center;">
{{.Error}}
</div>
{{end}}
<form action="/admin/login" method="POST">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<div class="form-group">
<label for="username" class="form-label">Username</label>
<input type="text" id="username" name="username" class="form-control" placeholder="e.g. admin" required autofocus>
</div>
<div class="form-group" style="margin-bottom: 2rem;">
<label for="password" class="form-label">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="••••••••" required>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%; padding: 0.75rem 1.25rem; font-size: 1rem;">
Sign In
</button>
</form>
</div>
</body>
</html>
@@ -0,0 +1,51 @@
{{define "title"}}Solis | Print Labels{{end}}
{{define "content"}}
<div class="page-header">
<div class="page-title">
<h1>Printable QR Labels</h1>
<p>Generate high-fidelity label sheets for your inventory. Press <kbd style="font-family: monospace; background:#e7e5e4; padding:0.1rem 0.3rem; border-radius:3px; font-weight:600;">Ctrl + P</kbd> (or <kbd style="font-family: monospace; background:#e7e5e4; padding:0.1rem 0.3rem; border-radius:3px; font-weight:600;">Cmd + P</kbd>) to print sticker sheets. Standard print stylesheets are auto-applied.</p>
</div>
<div style="display: flex; gap: 0.5rem;">
<button onclick="window.print()" class="btn btn-primary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:18px;height:18px;">
<path stroke-linecap="round" stroke-linejoin="round" d="M6.72 13.829c-.24.03-.48.062-.72.096m.72-.096a42.415 42.415 0 0110.56 0m-10.56 0L6.34 18m10.94-4.171c.24.03.48.062.72.096m-.72-.096L17.66 18m0 0a2.25 2.25 0 01-2.247 2.118H8.587A2.25 2.25 0 016.34 18m11.32 0h.008v.008h-.008V18zm-12 0h.008v.008h-.008V18zm0-11.25h12.75c.621 0 1.125.504 1.125 1.125v1.5c0 .621-.504 1.125-1.125 1.125H5.66c-.621 0-1.125-.504-1.125-1.125v-1.5c0-.621.504-1.125 1.125-1.125z" />
</svg>
Print Sheet
</button>
<a href="/admin" class="btn btn-secondary">Back to Assets</a>
</div>
</div>
<div class="card" style="margin-bottom: 2rem;">
<h3 style="font-weight: 700; margin-bottom: 0.5rem; color: var(--color-brand-primary);">Printing Guidelines</h3>
<ul style="margin-left: 1.5rem; color: var(--color-text-muted); font-size: 0.95rem; display: flex; flex-direction: column; gap: 0.25rem;">
<li>Set your margins to <strong>None</strong> or <strong>Minimum</strong> in the browser print dialogue.</li>
<li>Enable <strong>Background graphics</strong> to preserve borders and alignments.</li>
<li>Check the layout preview page size (standard Letter/A4) to ensure grid alignment on your sticker paper.</li>
</ul>
</div>
<!-- Dynamic Printable Grid -->
<div class="print-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; padding: 10px; background-color: white; border: 1px solid var(--color-border); border-radius: var(--radius-md);">
{{if .Items}}
{{range .Items}}
{{if .ShortSlug}}
<div class="print-label-item" style="border: 1px dashed var(--color-border); border-radius: var(--radius-sm); padding: 1rem; text-align: center; background-color: white; display: flex; flex-direction: column; align-items: center; justify-content: space-between; aspect-ratio: 1/1;">
<div class="print-label-name" style="font-weight: 700; font-size: 0.95rem; color: var(--color-text-main); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 100%;" title="{{.Name}}">
{{.Name}}
</div>
<img class="print-label-qr" src="/admin/qr/{{.ShortSlug}}" alt="QR Code" style="width: 110px; height: 110px; margin: 0.5rem 0; border: 1px solid var(--color-border); padding: 2px;">
<div class="print-label-slug" style="font-family: monospace; font-size: 0.8rem; color: var(--color-text-muted); font-weight: 600;">
s/{{.ShortSlug}}
</div>
</div>
{{end}}
{{end}}
{{else}}
<div style="grid-column: 1/-1; text-align: center; color: var(--color-text-light); padding: 4rem 1rem;">
No items with active short links found. Create an asset to generate labels!
</div>
{{end}}
</div>
{{end}}
+143
View File
@@ -0,0 +1,143 @@
{{define "title"}}Solis | URL Shortener{{end}}
{{define "content"}}
<div class="page-header">
<div class="page-title">
<h1>URL Shortener</h1>
<p>Manage custom manual redirects (e.g. warranties, external manuals) or review auto-generated asset short URLs.</p>
</div>
</div>
<div class="detail-grid">
<!-- Left Column: Links List -->
<div class="detail-main">
<div class="card" style="padding: 0;">
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th>Slug</th>
<th>Target URL</th>
<th>Link Type</th>
<th style="width: 80px; text-align: center;">Clicks</th>
<th style="width: 120px; text-align: right;">Actions</th>
</tr>
</thead>
<tbody>
{{if .Links}}
{{range .Links}}
<tr>
<td>
<div style="display: flex; flex-direction: column; gap: 0.15rem;">
<a href="/s/{{.Slug}}" target="_blank" style="font-weight: 700; color: var(--color-brand-primary); text-decoration: none;">
/s/{{.Slug}}
</a>
<!-- QR code link quick view in printer sheet -->
<a href="/admin/qr/{{.Slug}}" target="_blank" style="font-size: 0.75rem; color: var(--color-text-light); text-decoration: underline;">
View QR Code
</a>
</div>
</td>
<td>
<div style="max-width: 250px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: monospace; font-size: 0.85rem;" title="{{.URL}}">
{{.URL}}
</div>
</td>
<td>
{{if .ItemID.Valid}}
<span style="font-size: 0.8rem; font-weight: 600; color:#065f46; background-color:#d1fae5; padding: 0.2rem 0.5rem; border-radius: 4px;">
Asset #{{.ItemID.Int64}} Link
</span>
{{else}}
<span style="font-size: 0.8rem; font-weight: 600; color:#1e40af; background-color:#dbeafe; padding: 0.2rem 0.5rem; border-radius: 4px;">
Manual Redirect
</span>
{{end}}
</td>
<td style="text-align: center; font-weight: 600; font-size: 0.95rem; color: var(--color-text-muted);">
{{.Clicks}}
</td>
<td style="text-align: right;">
{{if .ItemID.Valid}}
<!-- Asset link modifications are handled through items CRUD -->
<span style="color: var(--color-text-light); font-size: 0.85rem; font-style: italic;">Managed by Asset</span>
{{else}}
<div style="display: inline-flex; gap: 0.5rem;">
<a href="/admin/shortener?edit={{.ID}}" class="btn btn-secondary" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Edit
</a>
<form action="/admin/shortener/delete/{{.ID}}" method="POST" onsubmit="return confirm('Are you sure you want to delete this custom redirect?')" style="margin: 0;">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Delete
</button>
</form>
</div>
{{end}}
</td>
</tr>
{{end}}
{{else}}
<tr>
<td colspan="5" style="text-align: center; color: var(--color-text-light); padding: 3rem 1rem;">
No short links recorded. Create a custom redirect on the right!
</td>
</tr>
{{end}}
</tbody>
</table>
</div>
</div>
</div>
<!-- Right Column: Add/Edit Form -->
<div class="detail-sidebar">
<div class="card">
{{if .EditingLink}}
<h3 style="font-weight: 700; margin-bottom: 1.25rem;">Edit Redirect</h3>
<form action="/admin/shortener/edit/{{.EditingLink.ID}}" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div class="form-group">
<label for="slug" class="form-label">Short Slug</label>
<input type="text" id="slug" name="slug" class="form-control" value="{{.EditingLink.Slug}}" required>
</div>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="url" class="form-label">Target Destination URL</label>
<input type="url" id="url" name="url" class="form-control" value="{{.EditingLink.URL}}" placeholder="e.g. https://brand.com/manual.pdf" required>
</div>
<div style="display: flex; gap: 0.5rem;">
<button type="submit" class="btn btn-primary" style="flex-grow: 1;">Save Changes</button>
<a href="/admin/shortener" class="btn btn-secondary">Cancel</a>
</div>
</form>
{{else}}
<h3 style="font-weight: 700; margin-bottom: 1.25rem;">Create Redirect</h3>
<form action="/admin/shortener/new" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div class="form-group">
<label for="slug" class="form-label">Custom Slug (Optional)</label>
<div style="display: flex; gap: 0.5rem;">
<input type="text" id="slug" name="slug" class="form-control" placeholder="e.g. warranty1" style="flex-grow:1;">
<button type="button" class="btn btn-secondary" style="padding: 0 0.75rem;" onclick="document.getElementById('slug').value = Math.random().toString(36).substring(2, 6)">
Auto
</button>
</div>
<span style="font-size: 0.75rem; color: var(--color-text-light); margin-top: 0.25rem; display: block;">Leave blank to generate a random 4-character slug.</span>
</div>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="url" class="form-label">Destination URL</label>
<input type="url" id="url" name="url" class="form-control" placeholder="e.g. https://support.brand.com/warranty" required>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%;">Add Redirect</button>
</form>
{{end}}
</div>
</div>
</div>
{{end}}
+132
View File
@@ -0,0 +1,132 @@
{{define "title"}}Solis | Tags{{end}}
{{define "content"}}
<div class="page-header">
<div class="page-title">
<h1>Tags</h1>
<p>Label and categorize assets to easily group similar items together (e.g. Tools, Electronics, Fragile)</p>
</div>
</div>
<div class="detail-grid">
<!-- Left Column: Tags List -->
<div class="detail-main">
<div class="card" style="padding: 0;">
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th style="width: 150px;">Tag</th>
<th>Color Hex</th>
<th>Description</th>
<th style="width: 120px; text-align: right;">Actions</th>
</tr>
</thead>
<tbody>
{{if .Tags}}
{{range .Tags}}
<tr>
<td>
<span class="tag-pill" style="background-color: {{.Color}}; color: #1c1917; padding: 0.35rem 0.75rem; font-size: 0.85rem;">
{{.Name}}
</span>
</td>
<td>
<code style="font-family: monospace; font-size: 0.9rem; background-color: var(--color-bg-base); padding: 0.15rem 0.35rem; border-radius: 4px; border: 1px solid var(--color-border);">
{{.Color}}
</code>
</td>
<td style="color: var(--color-text-muted); font-size: 0.9rem;">{{.Description}}</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.5rem;">
<a href="/admin/tags?edit={{.ID}}" class="btn btn-secondary" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Edit
</a>
{{if ne .Name "Default Room"}}
<form action="/admin/tags/delete/{{.ID}}" method="POST" onsubmit="return confirm('Are you sure you want to delete this tag? All associated items will lose this tag reference.')" style="margin: 0;">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger" style="padding: 0.35rem 0.65rem; font-size: 0.8rem;">
Delete
</button>
</form>
{{else}}
<span style="color: var(--color-text-light); font-size: 0.8rem; font-style: italic; padding: 0.35rem 0.65rem;">Locked</span>
{{end}}
</div>
</td>
</tr>
{{end}}
{{else}}
<tr>
<td colspan="4" style="text-align: center; color: var(--color-text-light); padding: 3rem 1rem;">
No tags defined yet. Add one on the right to get started!
</td>
</tr>
{{end}}
</tbody>
</table>
</div>
</div>
</div>
<!-- Right Column: Add/Edit Form -->
<div class="detail-sidebar">
<div class="card">
{{if .EditingTag}}
<h3 style="font-weight: 700; margin-bottom: 1.25rem;">Edit Tag</h3>
<form action="/admin/tags/edit/{{.EditingTag.ID}}" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div class="form-group">
<label for="name" class="form-label">Tag Name</label>
<input type="text" id="name" name="name" class="form-control" value="{{.EditingTag.Name}}" {{if eq .EditingTag.Name "Default Room"}}readonly style="background-color: var(--color-bg-base); cursor: not-allowed;"{{end}} required>
</div>
<div class="form-group">
<label for="color" class="form-label">Tag Color</label>
<div style="display: flex; gap: 0.5rem; align-items: center;">
<input type="color" id="color-picker" class="form-control" style="width: 50px; height: 38px; padding: 2px; cursor: pointer;" value="{{.EditingTag.Color}}" oninput="document.getElementById('color').value = this.value">
<input type="text" id="color" name="color" class="form-control" style="flex-grow:1;" value="{{.EditingTag.Color}}" required placeholder="e.g. #3b82f6" oninput="document.getElementById('color-picker').value = this.value">
</div>
</div>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="description" class="form-label">Description</label>
<textarea id="description" name="description" class="form-control" rows="3" placeholder="e.g. Kitchen appliances and tools">{{.EditingTag.Description}}</textarea>
</div>
<div style="display: flex; gap: 0.5rem;">
<button type="submit" class="btn btn-primary" style="flex-grow: 1;">Save Changes</button>
<a href="/admin/tags" class="btn btn-secondary">Cancel</a>
</div>
</form>
{{else}}
<h3 style="font-weight: 700; margin-bottom: 1.25rem;">Create Tag</h3>
<form action="/admin/tags/new" method="POST">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<div class="form-group">
<label for="name" class="form-label">Tag Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="e.g. Tools, Kitchen" required>
</div>
<div class="form-group">
<label for="color" class="form-label">Tag Color</label>
<div style="display: flex; gap: 0.5rem; align-items: center;">
<input type="color" id="color-picker" class="form-control" style="width: 50px; height: 38px; padding: 2px; cursor: pointer;" value="#e2e8f0" oninput="document.getElementById('color').value = this.value">
<input type="text" id="color" name="color" class="form-control" style="flex-grow:1;" value="#e2e8f0" required placeholder="e.g. #3b82f6" oninput="document.getElementById('color-picker').value = this.value">
</div>
</div>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="description" class="form-label">Description</label>
<textarea id="description" name="description" class="form-control" rows="3" placeholder="e.g. All electronic appliances"></textarea>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%;">Add Tag</button>
</form>
{{end}}
</div>
</div>
</div>
{{end}}
+89
View File
@@ -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)
}
}
+77
View File
@@ -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)
}
}
+70
View File
@@ -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);