Files
supermarket/internal/web/inventory.go
T
davidandClaude Opus 5.5 5451fe6d63 Reddit: posted by hand, with the rules pasted
Reddit's API isn't open to apps like this one, so Supermarket no longer
signs in to Reddit, publishes or schedules there, or reads subreddits and
the account's posts. The internal/api/reddit client, Reddit's OAuth, its
keys and its Social accounts card are gone.

Supermarket still writes the post. Each Reddit draft in Posts has a box
for its subreddit's rules, with a link to them on Reddit: pasted once,
they're kept (subreddits.data, as pasted_rules) and given to the model
for later drafts. Open in Reddit saves the edits and opens the submit
page filled in; Copy title and Copy text (with the tagged source link)
cover a box that comes up empty; Mark as posted records it. Warnings come
from the pasted rules and the posts marked as posted. Fill's subreddit
suggestions are kept unchecked, and say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:48:54 -07:00

291 lines
7.9 KiB
Go

package web
import (
"context"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"supermarket/examples"
"supermarket/internal/ai"
"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: "Market", 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
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)
err := s.marketRoom(e)
if err == nil {
err = inventory.Save(s.DB, e)
}
if 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, "/market", "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()
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours)
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, "/market", "deleted")
}
func (s *Server) inventoryImportPage(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "import", page{Title: "Import into the Market", 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 into the Market", 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-market.yaml"`)
w.Write(data)
}
// marketRoom says why a new entry can't be added (the plan's limit), or nil.
func (s *Server) marketRoom(e *inventory.Entry) error {
if e.ID != 0 {
return nil
}
list, err := inventory.List(s.DB, "")
if err != nil {
return err
}
for _, x := range list {
if strings.EqualFold(x.Name, strings.TrimSpace(e.Name)) {
return nil // the same name: Save says so
}
}
return s.limitSources(len(list))
}