The multi-tenant edition's plans (Free and Paid as decided, or a plans file) and each team's billing account, with a 14-day trial of Paid. A team's plan caps what its people and agents may change: modules outside it stay readable, a lapsed team changes nothing, and agents, Market entries, crawls and background jobs keep to it. Without a Stripe key, no billing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
320 lines
8.9 KiB
Go
320 lines
8.9 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: "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
|
|
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)
|
|
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()
|
|
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, "/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)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
}
|
|
|
|
// 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))
|
|
}
|