Files
go-redis-inventory/pkg/inventory/badge.go
T
2026-07-21 16:49:40 +02:00

52 lines
1.5 KiB
Go

package inventory
import (
"context"
"fmt"
"net/http"
)
// StockReader abstracts the inventory getter for badge rendering.
type StockReader interface {
GetInventory(ctx context.Context, sku SKU, locationID LocationID) (int64, error)
}
// BadgeHandler returns an http.HandlerFunc that renders an HTML stock badge fragment.
func BadgeHandler(reader StockReader) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
sku := r.URL.Query().Get("sku")
if sku == "" {
http.Error(w, "missing sku parameter", http.StatusBadRequest)
return
}
locationID := LocationID(r.URL.Query().Get("location_id"))
if locationID == "" {
locationID = "default"
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "private, max-age=5")
qty, err := reader.GetInventory(r.Context(), SKU(sku), locationID)
if err != nil {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<span class="stock-badge stock-unknown" data-sku="` + sku + `">Availability unavailable</span>`))
return
}
var htmlSnippet string
switch {
case qty > 10:
htmlSnippet = fmt.Sprintf(`<span class="stock-badge stock-in-stock" data-sku="%s">✓ In stock</span>`, sku)
case qty > 0:
htmlSnippet = fmt.Sprintf(`<span class="stock-badge stock-low-stock" data-sku="%s">⚡ Only %d left!</span>`, sku, qty)
default:
htmlSnippet = fmt.Sprintf(`<span class="stock-badge stock-out-of-stock" data-sku="%s">✕ Out of stock</span>`, sku)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(htmlSnippet))
}
}