Files
supermarket/internal/web/inventory.go
T
davidandClaude Opus 5.5 f5d87164ac Inventory: competitor prices, as checked
Each Inventory entry can hold its plans' prices: the plan, the price,
what it's per, when it was checked and where. Comparison and alternative
pages, and new sections, state a competitor's price only as entered,
with the month it was checked; a missing one is left out and listed as a
to-do. A price checked more than six months ago is flagged on the entry
and adds a to-do to every page that names the competitor. Prices go out
and come back with the Inventory's YAML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:18:31 -07:00

299 lines
8.5 KiB
Go

package web
import (
"context"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"supermarket/examples"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/profile"
)
func (s *Server) inventoryList(w http.ResponseWriter, r *http.Request) {
rel := r.URL.Query().Get("relationship")
entries, err := inventory.List(s.DB, rel)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "inventory", page{Title: "Inventory", Nav: "inventory", Data: map[string]any{
"Entries": entries,
"Relationship": rel,
"Relationships": inventory.Relationships,
}})
}
type entryData struct {
E *inventory.Entry
Relationships []string
NoAI bool // no AI provider yet: filling in from the website can't work
DraftURL string // the address to fill in from
Filled []string // after filling in: what was filled
Suggestions []inventory.Suggestion
CanCheck bool // Reddit could be asked about the suggestions
Drafted bool
Today string // for new price rows
Blank []int // empty price rows to show
Stale []inventory.Price // prices due for another look
}
func (s *Server) entryForm(e *inventory.Entry) entryData {
d := entryData{E: e, Relationships: inventory.Relationships, NoAI: !s.aiReady(),
Today: time.Now().Format("2006-01-02"), Blank: []int{0, 1}, Stale: e.StalePrices(time.Now())}
if len(e.Websites) > 0 {
d.DraftURL = e.Websites[0]
}
return d
}
func (s *Server) inventoryEdit(w http.ResponseWriter, r *http.Request) {
e := &inventory.Entry{Relationship: inventory.Partner}
if idStr := r.PathValue("id"); idStr != "" {
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
e, err = inventory.Get(s.DB, id)
if err != nil {
s.serverError(w, err)
return
}
if e == nil {
http.NotFound(w, r)
return
}
}
title := "New entry"
if e.ID != 0 {
title = e.Name
}
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Data: s.entryForm(e)})
}
func (s *Server) inventorySave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
e := entryFromForm(r)
if err := inventory.Save(s.DB, e); err != nil {
title := e.Name
if title == "" {
title = "New entry"
}
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Error: err.Error(), Data: s.entryForm(e)})
return
}
redirect(w, r, "/inventory", "saved")
}
func entryFromForm(r *http.Request) *inventory.Entry {
f := r.PostForm
id, _ := strconv.ParseInt(f.Get("id"), 10, 64)
return &inventory.Entry{
ID: id,
Name: f.Get("name"),
Relationship: f.Get("relationship"),
Description: f.Get("description"),
Websites: profile.Lines(f.Get("websites")),
TwitterHandle: f.Get("twitter_handle"),
YouTubeChannelID: f.Get("youtube_channel_id"),
InstagramHandle: f.Get("instagram_handle"),
LinkedIn: f.Get("linkedin"),
Subreddits: profile.Lines(f.Get("subreddits")),
RSS: profile.Lines(f.Get("rss")),
Hashtags: strings.Fields(strings.ReplaceAll(f.Get("hashtags"), ",", " ")),
Keywords: profile.Lines(f.Get("keywords")),
TalkingPoints: f.Get("talking_points"),
MentionPolicy: f.Get("mention_policy"),
Prices: pricesFromForm(f),
}
}
// pricesFromForm reads the price rows (price_plan, price_amount… in step).
func pricesFromForm(f url.Values) []inventory.Price {
var out []inventory.Price
amounts := f["price_amount"]
at := func(name string, i int) string {
if v := f[name]; i < len(v) {
return v[i]
}
return ""
}
for i := range amounts {
out = append(out, inventory.Price{Plan: at("price_plan", i), Amount: amounts[i], Per: at("price_per", i),
Checked: at("price_checked", i), Source: at("price_source", i)})
}
return out
}
// inventoryFill fills the form's empty boxes from the entry's website, with
// the AI, and shows the form again, unsaved.
func (s *Server) inventoryFill(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
e := entryFromForm(r)
d := s.entryForm(e)
d.DraftURL = strings.TrimSpace(r.PostForm.Get("draft_url"))
title := e.Name
if title == "" {
title = "New entry"
}
show := func(errMsg string) {
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Error: errMsg, Data: d})
}
if d.DraftURL == "" {
show("Enter their website to fill in from.")
return
}
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
s.serverError(w, err)
return
}
client, err := ai.New(cfg, s.Secrets)
if err != nil {
show(err.Error() + ".")
return
}
ours, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
defer cancel()
check := s.subredditCheck(ctx)
d.CanCheck = check != nil
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours, check)
d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true
if err != nil {
// Links read before the model failed are kept.
show("Couldn't fill in everything: " + err.Error())
return
}
show("")
}
func (s *Server) inventoryDelete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if err := inventory.Delete(s.DB, id); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/inventory", "deleted")
}
func (s *Server) inventoryImportPage(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "import", page{Title: "Import inventory", Nav: "inventory", Data: map[string]any{
"Relationships": inventory.Relationships,
}})
}
const maxImportBytes = 4 << 20
func (s *Server) inventoryImport(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxImportBytes+64<<10)
if err := r.ParseMultipartForm(maxImportBytes); err != nil && !errors.Is(err, http.ErrNotMultipart) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
rel := r.FormValue("relationship")
overwrite := r.FormValue("overwrite") == "on"
show := func(errMsg string, res *inventory.ImportResult) {
s.render(w, r, "import", page{Title: "Import inventory", Nav: "inventory", Error: errMsg, Data: map[string]any{
"Relationships": inventory.Relationships,
"Result": res,
"YAML": r.FormValue("yaml"),
}})
}
var data []byte
switch {
case r.FormValue("example") == "federated":
data = examples.FederatedInventory
case r.MultipartForm != nil && len(r.MultipartForm.File["file"]) > 0:
f, err := r.MultipartForm.File["file"][0].Open()
if err != nil {
show(err.Error(), nil)
return
}
data, err = io.ReadAll(io.LimitReader(f, maxImportBytes))
f.Close()
if err != nil {
show(err.Error(), nil)
return
}
default:
data = []byte(r.FormValue("yaml"))
}
if len(strings.TrimSpace(string(data))) == 0 {
show("Paste a list, choose a file, or load the example.", nil)
return
}
entries, err := inventory.ParseYAML(data, rel)
if err != nil {
show(err.Error(), nil)
return
}
res := inventory.Import(s.DB, entries, overwrite)
show("", &res)
}
func (s *Server) inventoryExport(w http.ResponseWriter, r *http.Request) {
entries, err := inventory.List(s.DB, "")
if err != nil {
s.serverError(w, err)
return
}
data, err := inventory.ExportYAML(entries)
if err != nil {
s.serverError(w, err)
return
}
w.Header().Set("Content-Type", "application/yaml")
w.Header().Set("Content-Disposition", `attachment; filename="supermarket-inventory.yaml"`)
w.Write(data)
}
// subredditCheck looks subreddits up on Reddit for Fill, using the cache
// and caching what it reads (drafting for the subreddit uses it later). It's
// nil if Reddit can't be asked: no client ID and secret.
func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck {
c, err := s.redditReader(ctx)
if err != nil {
return nil
}
return func(ctx context.Context, name string) (*reddit.Subreddit, error) {
if cached, err := content.GetSubreddit(s.DB, name); err == nil && cached != nil &&
time.Since(cached.FetchedAt) < content.SubredditMaxAge {
return cached, nil
}
info, err := c.SubredditInfo(ctx, name)
if err != nil {
return nil, err
}
if err := content.SaveSubreddit(s.DB, info); err != nil {
s.Log.Error("caching subreddit", "name", name, "err", err)
}
return info, nil
}
}