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>
This commit is contained in:
2026-11-20 13:17:38 -07:00
co-authored by Claude Opus 5.5
parent 13bf18facc
commit f275f039f9
24 changed files with 873 additions and 184 deletions
+312
View File
@@ -0,0 +1,312 @@
package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/utm"
)
// --- The Inbox: everything waiting for the user's approval ---
// inboxSection is one module's share of the Inbox. Later phases add their
// own (prospects to send to the CRM, SEO changes to open as pull requests).
type inboxSection struct {
Module string
Batches []*draftBatch
}
type draftBatch struct {
Batch string
InventoryName string
Kind string
CreatedAt time.Time
SourceURL string
Drafts []content.Draft
}
// inboxCount is the number shown next to Inbox in the menu.
func (s *Server) inboxCount() int {
n, err := content.CountDrafts(s.DB)
if err != nil {
s.Log.Error("counting the inbox", "err", err)
}
return n
}
// groupBatches puts drafts written together side by side, channels in
// display order, keeping the order the drafts came in.
func groupBatches(drafts []content.Draft) []*draftBatch {
var batches []*draftBatch
byID := map[string]*draftBatch{}
for _, d := range drafts {
b := byID[d.Batch]
if b == nil {
b = &draftBatch{Batch: d.Batch, InventoryName: d.InventoryName, Kind: d.Kind, CreatedAt: d.CreatedAt, SourceURL: d.SourceURL}
byID[d.Batch] = b
batches = append(batches, b)
}
b.Drafts = append(b.Drafts, d)
}
for _, b := range batches {
ordered := make([]content.Draft, 0, len(b.Drafts))
for _, c := range content.Channels {
for _, d := range b.Drafts {
if d.Channel == c.ID {
ordered = append(ordered, d)
}
}
}
b.Drafts = ordered
}
return batches
}
func (s *Server) connected() map[string]bool {
out := map[string]bool{}
for id := range s.publishers() {
out[id] = true
}
return out
}
func (s *Server) inboxPage(w http.ResponseWriter, r *http.Request) {
s.renderInbox(w, r, "")
}
func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg string) {
pending, err := content.ListDrafts(s.DB, 200, content.StatusDraft, content.StatusFailed)
if err != nil {
s.serverError(w, err)
return
}
var sections []inboxSection
if len(pending) > 0 {
sections = append(sections, inboxSection{Module: "Content", Batches: groupBatches(pending)})
}
s.render(w, r, "inbox", page{Title: "Inbox", Nav: "inbox", Error: errMsg, Data: map[string]any{
"Sections": sections,
"Connected": s.connected(),
"Tagged": s.tagger() != nil,
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
"Zone": time.Now().Format("MST"),
}})
}
// The Content module's own lists of approved and published drafts.
func (s *Server) scheduledPage(w http.ResponseWriter, r *http.Request) {
s.renderScheduled(w, r, "")
}
func (s *Server) renderScheduled(w http.ResponseWriter, r *http.Request, errMsg string) {
drafts, err := content.ListDrafts(s.DB, 500, content.StatusScheduled)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-scheduled", page{Title: "Scheduled", Nav: "content", Error: errMsg, Data: map[string]any{
"Drafts": drafts, "Connected": s.connected(), "Zone": time.Now().Format("MST"),
}})
}
func (s *Server) publishedPage(w http.ResponseWriter, r *http.Request) {
drafts, err := content.ListDrafts(s.DB, 200, content.StatusPublished)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-published", page{Title: "Published", Nav: "content", Data: map[string]any{"Drafts": drafts}})
}
// dateTimeLocal is the format of <input type="datetime-local">, read in the
// app's time zone (the computer's; see compose.yaml).
const dateTimeLocal = "2006-01-02T15:04"
func parseWhen(v string, now time.Time) (time.Time, error) {
v = strings.TrimSpace(v)
if v == "" {
return time.Time{}, errors.New("choose a date and time to publish")
}
at, err := time.ParseInLocation(dateTimeLocal, v, time.Local)
if err != nil {
return time.Time{}, fmt.Errorf("%q isn't a date and time", v)
}
// A minute's grace for a time picked as "now".
if at.Before(now.Add(-time.Minute)) {
return time.Time{}, errors.New("that time has passed: pick a later one, or publish now")
}
return at, nil
}
// draftAction saves, publishes, schedules, unschedules or discards one draft.
func (s *Server) draftAction(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 := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Where the form was: the Inbox, or the Scheduled list.
fromScheduled := r.PostForm.Get("from") == "scheduled"
back := "/inbox"
if fromScheduled {
back = "/content/scheduled"
}
fail := func(err error) {
if errors.Is(err, content.ErrNoDraft) {
http.NotFound(w, r)
return
}
if fromScheduled {
s.renderScheduled(w, r, err.Error())
} else {
s.renderInbox(w, r, err.Error())
}
}
action := r.PathValue("action")
switch action {
case "save", "publish", "schedule":
if text, sent := r.PostForm["content"]; sent {
if err := content.UpdateDraft(s.DB, id, text[0]); err != nil {
fail(err)
return
}
}
}
switch action {
case "save":
redirect(w, r, back, "saved")
case "publish":
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), id)
if err != nil {
name := "the channel"
if d != nil {
name = d.ChannelName()
}
fail(fmt.Errorf("Couldn't publish to %s: %w", name, err))
return
}
redirect(w, r, back, "published")
case "schedule":
at, err := parseWhen(r.PostForm.Get("when"), time.Now())
if err != nil {
fail(err)
return
}
d, err := content.GetDraft(s.DB, id)
if err != nil {
fail(err)
return
}
if d.TooLong() {
fail(fmt.Errorf("the %s post is %d characters; it allows %d. Shorten it before scheduling", d.ChannelName(), d.Length(), d.Limit()))
return
}
if err := content.Schedule(s.DB, id, at); err != nil {
fail(err)
return
}
redirect(w, r, back, "scheduled")
case "unschedule":
if err := content.Unschedule(s.DB, id); err != nil {
fail(err)
return
}
redirect(w, r, "/inbox", "unscheduled")
case "discard":
if err := content.DiscardDraft(s.DB, id); err != nil {
fail(err)
return
}
redirect(w, r, back, "discarded")
default:
http.NotFound(w, r)
}
}
// tagger adds UTM tags to links to the company's websites and product
// pages; nil if the profile lists none.
func (s *Server) tagger() *utm.Tagger {
p, err := profile.Load(s.DB)
if err != nil {
s.Log.Error("loading the profile for UTM tags", "err", err)
return nil
}
var sites []string
for _, w := range p.Websites {
sites = append(sites, w.URL)
}
for _, pr := range p.Products {
sites = append(sites, pr.URL)
}
t := utm.NewTagger(sites)
if !t.Any() {
return nil
}
return t
}
// --- The scheduler ---
// schedulerInterval is how often due drafts are looked for.
const schedulerInterval = 30 * time.Second
// RunScheduler publishes scheduled drafts when they're due, until ctx ends.
// The container runs all the time, so the browser needn't be open.
func (s *Server) RunScheduler(ctx context.Context) {
tick := time.NewTicker(schedulerInterval)
defer tick.Stop()
for {
s.publishDue(ctx, time.Now())
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
func (s *Server) publishDue(ctx context.Context, now time.Time) {
due, err := content.Due(s.DB, now)
if err != nil {
s.Log.Error("scheduler: listing due drafts", "err", err)
return
}
if len(due) == 0 {
return
}
pubs, tags := s.publishers(), s.tagger()
for _, d := range due {
if ctx.Err() != nil {
return
}
pctx, cancel := context.WithTimeout(ctx, 60*time.Second)
_, err := content.Publish(pctx, s.DB, pubs, tags, d.ID)
cancel()
if err != nil {
// A failed post is recorded on the draft by Publish. One refused
// before posting (not connected, too long) is still scheduled:
// send it back to the Inbox rather than retry it forever.
if ferr := content.FailScheduled(s.DB, d.ID, err.Error()); ferr != nil && !errors.Is(ferr, content.ErrNotEditable) {
s.Log.Error("scheduler: recording a failure", "draft", d.ID, "err", ferr)
}
s.Log.Warn("scheduler: publishing failed", "draft", d.ID, "channel", d.Channel, "err", err)
continue
}
s.Log.Info("scheduler: published", "draft", d.ID, "channel", d.Channel)
}
}