Files
supermarket/internal/web/content.go
T
davidandClaude Opus 5.5 f275f039f9 Phase 1, part 2: Inbox, scheduled publishing and UTM tags
- Inbox: a top-level page, with a count in the menu, for everything
  waiting for approval; Content's drafts are reviewed there. /drafts
  redirects to it.
- Scheduling: publish a draft now or at a time (migration 3 adds
  publish_at). A scheduler in the app publishes due drafts every 30
  seconds. Posts more than 12 hours overdue, or refused before posting,
  go back to the Inbox with the reason. Content gets Scheduled and
  Published tabs.
- UTM tags on links to the company's own websites and product pages,
  added when publishing; drafts stay untagged.
- The container runs in the computer's time zone, so times are shown
  and read correctly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:17:38 -07:00

270 lines
6.6 KiB
Go

package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/ai"
"supermarket/internal/content"
"supermarket/internal/fetcher"
"supermarket/internal/inventory"
"supermarket/internal/profile"
)
// maxPerItem caps "one post per item", which makes one AI call per item.
const maxPerItem = 10
// --- Sources: entries and their fetched items ---
type contentRow struct {
Entry inventory.Entry
Sources []string
Waiting int
LastChecked time.Time
}
func (s *Server) contentIndex(w http.ResponseWriter, r *http.Request) {
entries, err := inventory.List(s.DB, "")
if err != nil {
s.serverError(w, err)
return
}
counts, err := content.Counts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
rows := make([]contentRow, 0, len(entries))
for _, e := range entries {
last, _ := content.LastChecked(s.DB, e.Name)
rows = append(rows, contentRow{Entry: e, Sources: fetcher.Sources(&e),
Waiting: counts[strings.ToLower(e.Name)], LastChecked: last})
}
s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{"Rows": rows}})
}
type channelChoice struct {
content.Channel
Connected bool
}
type entryPage struct {
Entry *inventory.Entry
Sources []string
Items []content.Item
ShowDismissed bool
LastChecked time.Time
Since time.Time
Channels []channelChoice
ProfileSet bool
// After a fetch
Fetched bool
NewItems int
Errors []string
Skipped []string
}
func (s *Server) loadEntry(w http.ResponseWriter, r *http.Request) *inventory.Entry {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return nil
}
e, err := inventory.Get(s.DB, id)
if err != nil {
s.serverError(w, err)
return nil
}
if e == nil {
http.NotFound(w, r)
}
return e
}
func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, error) {
items, err := content.ListItems(s.DB, e.Name, showDismissed, 200)
if err != nil {
return nil, err
}
last, err := content.LastChecked(s.DB, e.Name)
if err != nil {
return nil, err
}
since, _ := content.Since(s.DB, e.Name, time.Now())
p, err := profile.Load(s.DB)
if err != nil {
return nil, err
}
pubs := s.publishers()
var chans []channelChoice
for _, c := range content.Channels {
chans = append(chans, channelChoice{c, pubs[c.ID] != nil})
}
return &entryPage{Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil
}
func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) {
e := s.loadEntry(w, r)
if e == nil {
return
}
d, err := s.entryData(e, r.URL.Query().Get("dismissed") == "1")
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Data: d})
}
func (s *Server) contentFetch(w http.ResponseWriter, r *http.Request) {
e := s.loadEntry(w, r)
if e == nil {
return
}
now := time.Now()
since, err := content.Since(s.DB, e.Name, now)
if err != nil {
s.serverError(w, err)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second)
defer cancel()
res := s.fetcher().Fetch(ctx, e, since)
n, err := content.SaveItems(s.DB, res.Items)
if err != nil {
s.serverError(w, err)
return
}
// Only move the start of the next fetch on if every source answered, so
// a failed source is read from the same point next time.
if len(res.Errors) == 0 {
if err := content.SetLastChecked(s.DB, e.Name, now); err != nil {
s.serverError(w, err)
return
}
}
d, err := s.entryData(e, false)
if err != nil {
s.serverError(w, err)
return
}
d.Fetched, d.NewItems, d.Errors, d.Skipped = true, n, res.Errors, res.Skipped
s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Data: d})
}
// contentItems handles the item list's buttons: dismiss, restore, write.
func (s *Server) contentItems(w http.ResponseWriter, r *http.Request) {
e := s.loadEntry(w, r)
if e == nil {
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ids := r.PostForm["item"]
back := fmt.Sprintf("/content/%d", e.ID)
showErr := func(msg string) {
d, err := s.entryData(e, r.PostForm.Get("dismissed") == "1")
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Error: msg, Data: d})
}
if len(ids) == 0 {
showErr("Select at least one item first.")
return
}
switch r.PostForm.Get("action") {
case "dismiss":
if err := content.Dismiss(s.DB, ids); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, back, "dismissed")
case "restore":
if err := content.Restore(s.DB, ids); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, back+"?dismissed=1", "restored")
case "write":
if err := s.writeDrafts(r, e, ids); err != nil {
showErr(err.Error())
return
}
redirect(w, r, "/inbox", "drafted")
default:
http.Error(w, "unknown action", http.StatusBadRequest)
}
}
func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string) error {
channels := r.PostForm["channel"]
if len(channels) == 0 {
return errors.New("choose at least one channel to write for")
}
perItem := r.PostForm.Get("mode") == "each"
if perItem && len(ids) > maxPerItem {
return fmt.Errorf("one post per item works on up to %d items at a time; you selected %d", maxPerItem, len(ids))
}
p, err := profile.Load(s.DB)
if err != nil {
return err
}
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
return err
}
client, err := ai.New(cfg, s.Secrets)
if err != nil {
return err
}
items, err := content.GetItems(s.DB, ids)
if err != nil {
return err
}
groups := [][]content.Item{items}
if perItem {
groups = groups[:0]
for _, it := range items {
groups = append(groups, []content.Item{it})
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
// Keep channels in display order whatever order the form sent.
var ordered []string
for _, c := range content.Channels {
for _, ch := range channels {
if ch == c.ID {
ordered = append(ordered, c.ID)
break
}
}
}
written := 0
for _, g := range groups {
drafts, err := content.Generate(ctx, client, content.Request{Profile: p, Entry: e, Items: g, Channels: ordered})
if err != nil {
if written > 0 {
return fmt.Errorf("wrote %d set(s) of drafts, then: %w", written, err)
}
return err
}
if _, err := content.CreateDrafts(s.DB, drafts); err != nil {
return err
}
written++
}
return nil
}