Files
supermarket/internal/web/inbox.go
T
davidandClaude Opus 5.5 c8964cec12 Phase 10, part 8: the audit log, and who made what
Sign-ins and failed ones, everything admins do to users, connections,
posting accounts, each post published and email sent, pull requests and
deletions go in an audit log (schema 36), kept two years; admins read it
under Settings → Activity. Drafts, published posts and outreach emails
show who made them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:31:33 -07:00

561 lines
16 KiB
Go

package web
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/utm"
)
// --- Posts: everything waiting for the user's approval ---
// inboxSection is one module's share of Posts. 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
}
// connected says, by channel, whether the viewer has an account to post to.
func (s *Server) connected(v *viewer) map[string]bool {
out := map[string]bool{}
for ch, list := range s.usableAccounts(v) {
out[ch] = len(list) > 0
}
return out
}
// chosenAccounts is the account each draft goes out from, as things stand:
// its own, or the company's for its channel.
func (s *Server) chosenAccounts(drafts []content.Draft) map[int64]int64 {
out := map[int64]int64{}
for i := range drafts {
if a, err := s.draftAccount(&drafts[i]); err == nil && a != nil {
out[drafts[i].ID] = a.ID
}
}
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: "Posts", Nav: "content/posts", Error: errMsg, Data: map[string]any{
"Reminders": s.reminders(),
"Sections": sections,
"Reddit": s.redditViews(r.Context(), pending),
"Connected": s.connected(viewerOf(r)),
"Accounts": s.usableAccounts(viewerOf(r)),
"Chosen": s.chosenAccounts(pending),
"Tagged": s.tagger() != nil,
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
"Zone": time.Now().Format("MST"),
}})
}
// redditView is what Posts shows with a Reddit draft.
type redditView struct {
Info *reddit.Subreddit
Warnings []string
}
// redditViews works out the rules and warnings for the Reddit drafts. It
// reads the account's recent posts once (cached for a few minutes).
func (s *Server) redditViews(ctx context.Context, drafts []content.Draft) map[int64]*redditView {
views := map[int64]*redditView{}
var history []reddit.Submission
historyRead := false
tags := s.tagger()
recorded, err := content.RecordedRedditPosts(s.DB, time.Now().Add(-8*24*time.Hour))
if err != nil {
s.Log.Error("reading recorded Reddit posts", "err", err)
}
for _, d := range drafts {
if d.Channel != content.ChannelReddit {
continue
}
if !historyRead {
hctx, cancel := context.WithTimeout(ctx, 8*time.Second)
history = s.redditHistory(hctx)
cancel()
historyRead = true
}
info, _ := content.GetSubreddit(s.DB, d.Target)
check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now(),
Promo: d.Kind == content.KindProduct, Recorded: recorded}
if tags != nil {
check.Own = tags.Own
check.OwnLink = tags.Own(d.SourceURL) || tags.HasOwnLink(d.Content)
}
views[d.ID] = &redditView{Info: info, Warnings: content.RedditWarnings(check)}
}
return views
}
// refreshRules fetches a subreddit's rules again.
func (s *Server) refreshRules(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
if _, err := s.subreddit(ctx, r.PathValue("name"), true); err != nil {
s.renderInbox(w, r, "Couldn't read the subreddit's rules: "+err.Error())
return
}
redirect(w, r, "/posts", "rules-refreshed")
}
// 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/scheduled", Error: errMsg, Data: map[string]any{
"Drafts": drafts, "Connected": s.connected(viewerOf(r)), "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/published", 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: Posts, or the Scheduled list.
fromScheduled := r.PostForm.Get("from") == "scheduled"
back := "/posts"
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", "open":
if title, sent := r.PostForm["title"]; sent {
if err := content.UpdateTitle(s.DB, id, title[0]); err != nil {
fail(err)
return
}
}
if text, sent := r.PostForm["content"]; sent {
if err := content.UpdateDraft(s.DB, id, text[0]); err != nil {
fail(err)
return
}
}
if as, sent := r.PostForm["linkedin_as"]; sent {
if err := content.SetLinkedInAs(s.DB, id, as[0]); err != nil {
fail(err)
return
}
}
}
// The accounts chosen to post to: this draft goes to the first; the
// others get copies, published or scheduled with it.
var copies []int64
switch action {
case "save", "publish", "schedule":
chosen, err := s.chosenFromForm(r, id)
if err != nil {
fail(err)
return
}
if len(chosen) > 0 {
if err := content.SetAccount(s.DB, id, chosen[0]); err != nil {
fail(err)
return
}
}
if action != "save" {
if err := s.checkPostAs(viewerOf(r), id); err != nil {
fail(err)
return
}
for _, a := range chosen[min(1, len(chosen)):] {
cid, err := content.Copy(s.DB, id, a)
if err != nil {
fail(err)
return
}
copies = append(copies, cid)
}
}
}
by := int64(0)
if v := viewerOf(r); v.User != nil {
by = v.User.ID
}
switch action {
case "save":
redirect(w, r, back, "saved")
case "publish":
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
var failed []string
reddit := false
for _, did := range append([]int64{id}, copies...) {
_ = content.SetPostedBy(s.DB, did, by)
d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), did)
if err != nil {
name := "the channel"
if d != nil {
name = d.ChannelName()
}
failed = append(failed, fmt.Sprintf("Couldn't publish to %s: %v", name, err))
continue
}
reddit = reddit || d.Channel == content.ChannelReddit
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by)
s.audit(r, "published", d.PostedAs, "post "+strconv.FormatInt(did, 10)+": "+d.PostURL)
}
if reddit {
s.forgetRedditHistory()
}
if len(failed) > 0 {
fail(errors.New(strings.Join(failed, " ")))
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 problem := d.Problem(); problem != "" {
fail(fmt.Errorf("%s: fix it before scheduling", problem))
return
}
for _, did := range append([]int64{id}, copies...) {
if err := content.Schedule(s.DB, did, at); err != nil {
fail(err)
return
}
_ = content.SetPostedBy(s.DB, did, by)
}
redirect(w, r, back, "scheduled")
case "open":
// Post by hand: the edits are saved above; now off to Reddit's
// submit page, filled in, in the tab the form opened.
d, err := content.GetDraft(s.DB, id)
if err != nil {
fail(err)
return
}
info, _ := content.GetSubreddit(s.DB, d.Target)
http.Redirect(w, r, redditSubmitURL(d, s.tagger(), info), http.StatusSeeOther)
case "posted":
postURL := strings.TrimSpace(r.PostForm.Get("post_url"))
if postURL != "" {
if u, err := url.Parse(postURL); err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
fail(errors.New("that isn't a link to a post: copy the address from your browser, or leave it empty"))
return
}
}
if err := content.MarkPosted(s.DB, id, postURL); err != nil {
fail(err)
return
}
s.forgetRedditHistory()
redirect(w, r, back, "posted")
case "unschedule":
if err := content.Unschedule(s.DB, id); err != nil {
fail(err)
return
}
redirect(w, r, "/posts", "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.jobDo(ctx, "scheduler", func(ctx context.Context) {
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
}
var err error
if d.PostedBy != 0 {
err = s.checkPostAs(s.viewerFor(d.PostedBy), d.ID)
}
if err == nil {
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 Posts 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)
if pd, err := content.GetDraft(s.DB, d.ID); err == nil {
s.auditFor(d.PostedBy, "published", pd.PostedAs, "scheduled post "+strconv.FormatInt(d.ID, 10)+": "+pd.PostURL)
}
}
}
// maxSubmitURL is about as long as a link to Reddit's submit page can be
// and still open; past it, the text is left for the user to paste.
const maxSubmitURL = 7500
// redditSubmitURL is Reddit's submit page for the draft's subreddit, filled
// in: a text post with the source link at the end, or a link post where the
// subreddit only takes links. It uses old.reddit.com, whose submit page
// reliably takes the title and text from the address.
func redditSubmitURL(d *content.Draft, tags *utm.Tagger, info *reddit.Subreddit) string {
text, src := content.Manual(d, tags)
base := "https://old.reddit.com/submit"
if sub := reddit.CleanName(d.Target); sub != "" {
base = "https://old.reddit.com/r/" + url.PathEscape(sub) + "/submit"
}
q := url.Values{"title": {d.Title}}
if info != nil && !info.AllowsText() && src != "" {
q.Set("url", src)
return base + "?" + q.Encode()
}
if src != "" && !strings.Contains(text, src) {
text += "\n\nSource: " + src
}
q.Set("selftext", "true")
q.Set("text", text)
if u := base + "?" + q.Encode(); len(u) <= maxSubmitURL {
return u
}
q.Del("text")
return base + "?" + q.Encode()
}
// chosenFromForm reads the accounts chosen on a draft's form (accounts=<id>,
// several): each must be one the viewer may post to, for the draft's
// channel.
func (s *Server) chosenFromForm(r *http.Request, id int64) ([]int64, error) {
raw, sent := r.PostForm["accounts"]
if !sent {
return nil, nil
}
d, err := content.GetDraft(s.DB, id)
if err != nil {
return nil, err
}
usable := map[int64]bool{}
for _, a := range s.usableAccounts(viewerOf(r))[d.Channel] {
usable[a.ID] = true
}
var out []int64
seen := map[int64]bool{}
for _, v := range raw {
a, err := strconv.ParseInt(v, 10, 64)
if err != nil || !usable[a] {
return nil, errors.New("you can't post to one of the accounts chosen: choose among those listed")
}
if !seen[a] {
seen[a] = true
out = append(out, a)
}
}
return out, nil
}
// checkPostAs says why a viewer may not post a draft from its account, or
// nil if they may.
func (s *Server) checkPostAs(v *viewer, id int64) error {
d, err := content.GetDraft(s.DB, id)
if err != nil {
return err
}
a, err := s.draftAccount(d)
if err != nil || a == nil {
return err // Publish says it isn't connected
}
if !s.mayPostAs(v, a) {
return fmt.Errorf("you may not post as %s: choose another account, or ask an admin", a.Label())
}
return nil
}