diff --git a/PLAN.md b/PLAN.md index 625ce50..b5415b0 100644 --- a/PLAN.md +++ b/PLAN.md @@ -330,7 +330,7 @@ mcphub failed. ### Phase 1: Content (today's pipeline, generalized) + Reddit -**Status (2026-11-20): part 1 of 4 built on `phase0-foundation`.** Phase 1 is +**Status (2026-11-20): parts 1 and 2 of 4 built on `phase0-foundation`.** Phase 1 is built in four parts, each committed on its own: (1) the pipeline, items 1–2 below, for X and LinkedIn; (2) the approval inbox, schedule and UTM tags, item 5; (3) Reddit, item 4; (4) promoting our own products, the rest of @@ -347,6 +347,22 @@ item 3. Part 1: quotes. An X draft over the limit gets one request to shorten it. - Publishing claims the draft first (`publishing`), so it can't post twice; a draft left `publishing` by a restart is marked failed for review. + +Part 2: +- **Inbox** (top-level menu, with a count): everything waiting for + approval, one section per module; Content's drafts for now. Phase 2's + prospects and Phase 3's SEO changes add sections. +- **Scheduling**: a draft is published now or scheduled (`scheduled`, + `publish_at`, migration 3). A scheduler in the app checks every 30 + seconds. A post more than 12 hours overdue (the computer was off) goes + back to the Inbox rather than out stale, and so does one refused before + posting (signed out, too long). Content has Scheduled and Published tabs. +- **UTM tags** only on links to the company's websites and product URLs + (from the profile), added at publishing; drafts are stored untagged. + `utm_source` = channel, `utm_medium` = social, `utm_campaign` = kind of + post, `utm_content` = entry slug and draft ID. +- The container now runs in the computer's time zone (`SUPERMARKET_TZ` in + compose.env, from /etc/localtime), so times show and parse correctly. 1. Port fetch → browse → select → generate → approve → publish into the web UI, keeping the dismiss feature, tracking of what was posted where, partial posting, and X length handling. diff --git a/README.md b/README.md index 27fa332..0d04394 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Everything starts from your **company profile** (what you sell, to whom, in what | Metrics | Pipeline influence, CAC, CLV and NRR, from Stripe, EspoCRM and Plausible | Phase 4 | | Sites | Builds pages and sites from a component library and publishes them through Gitea | Phase 5 | -This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has the first part of the Content module (Phase 1): fetching, writing drafts, and publishing to X and LinkedIn. See [PLAN.md](PLAN.md) for the whole plan. +This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has most of the Content module (Phase 1): fetching, writing drafts, an Inbox for approval, scheduled publishing to X and LinkedIn, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan. ## Install @@ -96,7 +96,10 @@ To check the connection, open **Core & Hermes** in Supermarket and ask Hermes th 2. Add partners and competitors to the **Inventory**, with the places to watch: an X handle, hashtags, a YouTube channel, RSS feeds. 3. Under **Content**, open an entry and press **Fetch new**. Supermarket reads every source that has credentials, starting where the last fetch ended (or a week back). 4. Select items, choose the channels, and press **Write drafts**: one post from all of them, or one per item. Each channel gets its own draft. -5. On **Drafts**, edit and publish each one. The source link is added when publishing (on X it counts toward the 280 characters, and the counter includes it). A failed draft keeps its error and can be published again; the other channel's draft is unaffected. +5. In the **Inbox**, edit each draft, then **Publish now** or **Schedule** it. The source link is added when publishing (on X it counts toward the 280 characters, and the counter includes it). A failed draft comes back to the Inbox with its error; the other channel's draft is unaffected. +6. Scheduled posts are listed under **Content → Scheduled**, and go out on time while the container runs (it starts with your computer). One more than 12 hours late, because the computer was off, goes back to the Inbox instead of going out stale. + +Links to your own websites and product pages (from the profile) get UTM tags when published: `utm_source` is the channel, `utm_medium` is `social`, `utm_campaign` is the kind of post (partner, competitor, watch) and `utm_content` is the entry and draft. Links elsewhere are left as they are. Times are shown and read in your computer's time zone. Reading X needs a bearer token from an X API plan with read access; YouTube needs a free API key; RSS needs nothing. Posting needs the sign-ins below. @@ -133,7 +136,8 @@ SUPERMARKET_DATA=/tmp/cm SUPERMARKET_ADDR=127.0.0.1:8470 go run ./cmd/supermarke | `internal/ai` | AI providers: Anthropic (official Go SDK) and OpenAI-compatible servers | | `internal/mcpserver`, `internal/bridge` | The `/mcp` endpoint and Hermes' check-ins | | `internal/legacy` | One-time import from the old terminal app | -| `internal/content` | The Content module: fetched items, per-channel drafts, prompts, publishing | +| `internal/content` | The Content module: fetched items, per-channel drafts, prompts, scheduling, publishing | +| `internal/utm` | UTM tags for links to the company's own sites | | `internal/api`, `internal/fetcher` | X, LinkedIn, YouTube and RSS clients, and fetching for an inventory entry | | `hermes/setup.sh` | Connects Hermes | diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 871ac55..af2d81f 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -145,6 +145,7 @@ func run(log *slog.Logger) error { errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err) } }() + go srv.RunScheduler(ctx) go func() { log.Info("Supermarket is running", "version", version, "listen", addr, "open", publicURL) errCh <- httpServer.ListenAndServe() diff --git a/compose.yaml b/compose.yaml index fa3b4cf..475348f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,6 +21,8 @@ services: SUPERMARKET_PUBLIC_URL: http://localhost:8470 # Where the data folder (and the MCP socket Hermes uses) is on the host SUPERMARKET_HOST_DATA: ${SUPERMARKET_DATA:?} + # Your time zone, so times and schedules are shown and read in it + TZ: ${SUPERMARKET_TZ:-UTC} volumes: - ${SUPERMARKET_DATA:?}:/data # LLM servers on this computer are at host.docker.internal. diff --git a/internal/content/content_test.go b/internal/content/content_test.go index 6717fd9..0874e17 100644 --- a/internal/content/content_test.go +++ b/internal/content/content_test.go @@ -3,6 +3,7 @@ package content import ( "context" "errors" + "fmt" "path/filepath" "strings" "testing" @@ -13,6 +14,7 @@ import ( "supermarket/internal/inventory" "supermarket/internal/models" "supermarket/internal/profile" + "supermarket/internal/utm" ) func openDB(t *testing.T) *db.DB { @@ -123,13 +125,13 @@ func TestDraftsAndPublish(t *testing.T) { ctx := context.Background() // LinkedIn isn't connected: refused, and nothing changes. pub := &fakePub{} - if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") { + if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") { t.Errorf("publishing without a connection: %v", err) } // A failure is recorded; the draft can be fixed and published again. pub.err = errors.New("HTTP 503") - if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, x.ID); err == nil { + if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID); err == nil { t.Fatal("expected the failure") } got, _ := GetDraft(d, x.ID) @@ -140,7 +142,7 @@ func TestDraftsAndPublish(t *testing.T) { t.Fatal(err) } pub.err = nil - got, err = Publish(ctx, d, Publishers{ChannelX: pub}, x.ID) + got, err = Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID) if err != nil || got.Status != StatusPublished || got.PostURL == "" || got.Error != "" { t.Fatalf("publish: %+v, %v", got, err) } @@ -148,7 +150,7 @@ func TestDraftsAndPublish(t *testing.T) { t.Errorf("published %q", last) } // Published once: a second click doesn't post again, and it can't be edited. - if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, x.ID); !errors.Is(err, ErrBusy) { + if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID); !errors.Is(err, ErrBusy) { t.Errorf("second publish: %v", err) } if err := UpdateDraft(d, x.ID, "again"); !errors.Is(err, ErrNotEditable) { @@ -161,7 +163,7 @@ func TestDraftsAndPublish(t *testing.T) { // Too long for X: refused before calling X. _, _ = CreateDrafts(d, []Draft{{Channel: ChannelX, Content: strings.Repeat("a", 270), SourceURL: "https://example.com"}}) long, _ := ListDrafts(d, 1, StatusDraft) - if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") { + if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") { t.Errorf("over-long post: %v", err) } @@ -256,3 +258,76 @@ func TestGenerate(t *testing.T) { t.Error("expected an error without a profile") } } + +func TestScheduleAndDue(t *testing.T) { + d := openDB(t) + _, _ = CreateDrafts(d, []Draft{ + {InventoryName: "Jitsi Meet", Kind: "partner", Channel: ChannelLinkedIn, Content: "See https://acme.example/blog.", SourceURL: "https://acme.example/news"}, + }) + _, _ = CreateDrafts(d, []Draft{{InventoryName: "Old", Kind: "watch", Channel: ChannelX, Content: "Stale"}}) + all, _ := ListDrafts(d, 10, StatusDraft) + var soon, stale Draft + for _, dr := range all { + if dr.InventoryName == "Old" { + stale = dr + } else { + soon = dr + } + } + now := time.Now().UTC().Truncate(time.Second) + if err := Schedule(d, soon.ID, now.Add(time.Hour)); err != nil { + t.Fatal(err) + } + if err := Schedule(d, stale.ID, now.Add(-13*time.Hour)); err != nil { + t.Fatal(err) + } + if err := UpdateDraft(d, soon.ID, "edit"); !errors.Is(err, ErrNotEditable) { + t.Errorf("a scheduled draft must be unscheduled before editing: %v", err) + } + if err := Schedule(d, soon.ID, now.AddDate(2, 0, 0)); err == nil { + t.Error("scheduling twice or two years out should fail") + } + if n(CountDrafts(d)) != 0 { + t.Errorf("scheduled drafts still counted for review") + } + + // Not due yet; the stale one goes back to the Inbox with a note. + due, err := Due(d, now) + if err != nil || len(due) != 0 { + t.Fatalf("due now = %+v, %v", due, err) + } + if got, _ := GetDraft(d, stale.ID); got.Status != StatusFailed || !strings.Contains(got.Error, "wasn't running") { + t.Errorf("stale draft: %+v", got) + } + due, _ = Due(d, now.Add(2*time.Hour)) + if len(due) != 1 || due[0].ID != soon.ID || !due[0].PublishAt.Equal(now.Add(time.Hour)) { + t.Fatalf("due later = %+v", due) + } + + // Publishing tags only the company's links, and stores the draft untagged. + pub := &fakePub{} + tags := utm.NewTagger([]string{"acme.example"}) + got, err := Publish(context.Background(), d, Publishers{ChannelLinkedIn: pub}, tags, soon.ID) + if err != nil || got.Status != StatusPublished { + t.Fatalf("publish scheduled: %+v, %v", got, err) + } + q := fmt.Sprintf("utm_campaign=partner&utm_content=jitsi-meet-%d&utm_medium=social&utm_source=linkedin", soon.ID) + want := "See https://acme.example/blog?" + q + ".|https://acme.example/news?" + q + if pub.calls[0] != want { + t.Errorf("published\n%s\nwant\n%s", pub.calls[0], want) + } + if got.Content != "See https://acme.example/blog." { + t.Errorf("stored content changed: %q", got.Content) + } + + // Unschedule sends it back for editing. + _, _ = CreateDrafts(d, []Draft{{Channel: ChannelX, Content: "Later"}}) + later, _ := ListDrafts(d, 1, StatusDraft) + _ = Schedule(d, later[0].ID, now.Add(time.Hour)) + if err := Unschedule(d, later[0].ID); err != nil { + t.Fatal(err) + } + if got, _ := GetDraft(d, later[0].ID); got.Status != StatusDraft || !got.PublishAt.IsZero() { + t.Errorf("unscheduled: %+v", got) + } +} diff --git a/internal/content/drafts.go b/internal/content/drafts.go index 950d17d..959f083 100644 --- a/internal/content/drafts.go +++ b/internal/content/drafts.go @@ -46,7 +46,8 @@ func ChannelByID(id string) (Channel, bool) { // Draft statuses. const ( - StatusDraft = "draft" + StatusDraft = "draft" // waiting for review, in the Inbox + StatusScheduled = "scheduled" // approved, goes out at PublishAt StatusPublishing = "publishing" // claimed by a publish in progress StatusPublished = "published" StatusFailed = "failed" @@ -69,6 +70,7 @@ type Draft struct { CreatedAt time.Time UpdatedAt time.Time PublishedAt time.Time + PublishAt time.Time // when a scheduled draft goes out } // Length is the draft's length as its channel counts it, including the @@ -155,20 +157,21 @@ func nonNil(s []string) []string { } const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error, - post_url, created_at, updated_at, COALESCE(published_at, '')` + post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, '')` func scanDrafts(rows *sql.Rows) ([]Draft, error) { defer rows.Close() var out []Draft for rows.Next() { var dr Draft - var ids, created, updated, published string + var ids, created, updated, published, publishAt string if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content, - &dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published); err != nil { + &dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt); err != nil { return nil, err } _ = json.Unmarshal([]byte(ids), &dr.ItemIDs) dr.CreatedAt, dr.UpdatedAt, dr.PublishedAt = parseTime(created), parseTime(updated), parseTime(published) + dr.PublishAt = parseTime(publishAt) out = append(out, dr) } return out, rows.Err() @@ -187,6 +190,8 @@ func ListDrafts(d *db.DB, limit int, statuses ...string) ([]Draft, error) { order := "created_at DESC, id DESC" if len(statuses) == 1 && statuses[0] == StatusPublished { order = "published_at DESC, id DESC" + } else if len(statuses) == 1 && statuses[0] == StatusScheduled { + order = "publish_at, id" } rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status IN (?`+ strings.Repeat(", ?", len(statuses)-1)+`) ORDER BY `+order+` LIMIT ?`, args...) @@ -266,3 +271,52 @@ func CountDrafts(d *db.DB) (int, error) { err := d.QueryRow(`SELECT count(*) FROM drafts WHERE status IN (?, ?)`, StatusDraft, StatusFailed).Scan(&n) return n, err } + +// Schedule approves a draft to go out at at. It must be one that can still +// be published, and at most a year ahead. +func Schedule(d *db.DB, id int64, at time.Time) error { + if at.After(time.Now().AddDate(1, 0, 0)) { + return errors.New("that's more than a year away") + } + res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = ?, error = '', updated_at = ? + WHERE id = ? AND status IN (?, ?)`, + StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed) + return oneRow(res, err) +} + +// Unschedule sends a scheduled draft back to the Inbox, to edit or drop. +func Unschedule(d *db.DB, id int64) error { + res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = NULL, updated_at = ? WHERE id = ? AND status = ?`, + StatusDraft, formatTime(time.Now()), id, StatusScheduled) + return oneRow(res, err) +} + +// MaxLate is how late a scheduled post may still go out, if the app was +// stopped when it was due. Later than that, news is stale: it goes back to +// the Inbox instead. +const MaxLate = 12 * time.Hour + +// Due returns the scheduled drafts whose time has come, oldest first. Ones +// more than MaxLate overdue are sent back to the Inbox with a note. +func Due(d *db.DB, now time.Time) ([]Draft, error) { + if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? + WHERE status = ? AND publish_at < ?`, + StatusFailed, "Not published: Supermarket wasn't running when this was due. Publish or reschedule it.", + formatTime(now), StatusScheduled, formatTime(now.Add(-MaxLate))); err != nil { + return nil, err + } + rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status = ? AND publish_at <= ? + ORDER BY publish_at, id`, StatusScheduled, formatTime(now)) + if err != nil { + return nil, err + } + return scanDrafts(rows) +} + +// FailScheduled sends a scheduled draft that couldn't go out (its channel +// was signed out, say) back to the Inbox with the reason. +func FailScheduled(d *db.DB, id int64, reason string) error { + res, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ? AND status = ?`, + StatusFailed, reason, formatTime(time.Now()), id, StatusScheduled) + return oneRow(res, err) +} diff --git a/internal/content/publish.go b/internal/content/publish.go index c07f4c1..00c60bd 100644 --- a/internal/content/publish.go +++ b/internal/content/publish.go @@ -7,6 +7,7 @@ import ( "time" "supermarket/internal/db" + "supermarket/internal/utm" ) // Publisher posts to one channel and returns the post's URL. @@ -23,12 +24,15 @@ var ErrBusy = errors.New("this draft is already being published, or was publishe // Publish posts one draft. It claims the draft first, so a second click or a // second tab can't post it twice. A failure is recorded on the draft, which // can then be edited and published again. -func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft, error) { +// +// Links to the company's own sites get UTM tags (tags may be nil); the draft +// itself is kept without them. +func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, id int64) (*Draft, error) { dr, err := GetDraft(d, id) if err != nil { return nil, err } - if !dr.Editable() { + if !dr.Editable() && dr.Status != StatusScheduled { return dr, ErrBusy } pub := pubs[dr.Channel] @@ -44,8 +48,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft, dr.Length(), withLink, dr.ChannelName(), dr.Limit()) } - res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', updated_at = ? WHERE id = ? AND status IN (?, ?)`, - StatusPublishing, formatTime(time.Now()), id, StatusDraft, StatusFailed) + res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`, + StatusPublishing, formatTime(time.Now()), id, StatusDraft, StatusFailed, StatusScheduled) if err := oneRow(res, err); err != nil { if errors.Is(err, ErrNotEditable) { return dr, ErrBusy @@ -53,7 +57,12 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft, return dr, err } - postURL, pubErr := pub.Publish(ctx, dr.Content, dr.SourceURL) + text, src := dr.Content, dr.SourceURL + if tags != nil { + p := dr.UTM() + text, src = tags.Text(text, p), tags.URL(src, p) + } + postURL, pubErr := pub.Publish(ctx, text, src) now := formatTime(time.Now()) if pubErr != nil { if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`, @@ -70,3 +79,13 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft, } return GetDraft(d, id) } + +// UTM is the tags for the draft's links: the channel, the kind of post, +// and which entry and draft it was. +func (d *Draft) UTM() utm.Params { + content := fmt.Sprintf("draft-%d", d.ID) + if slug := utm.Slug(d.InventoryName); slug != "" { + content = slug + "-" + fmt.Sprint(d.ID) + } + return utm.Params{Source: d.Channel, Medium: "social", Campaign: d.Kind, Content: content} +} diff --git a/internal/db/db.go b/internal/db/db.go index 1d23cef..04f1603 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -112,6 +112,12 @@ FROM posts p, (SELECT 'x' AS channel UNION ALL SELECT 'linkedin') c WHERE NOT EXISTS (SELECT 1 FROM json_each(p.posted_to) WHERE value = c.channel) ORDER BY p.generated_at, c.channel; DROP TABLE posts; +`, + // 3: scheduling. An approved draft is "scheduled" with the time it goes + // out; "publish now" is a schedule for the present. + ` +ALTER TABLE drafts ADD COLUMN publish_at TEXT; +CREATE INDEX drafts_due ON drafts (status, publish_at); `, } diff --git a/internal/utm/utm.go b/internal/utm/utm.go new file mode 100644 index 0000000..9277252 --- /dev/null +++ b/internal/utm/utm.go @@ -0,0 +1,126 @@ +// Package utm adds UTM tags to links that point at the company's own sites, +// so its analytics (Plausible) can tell which posts brought visitors. Links +// elsewhere are left alone: no one else's analytics will read the tags. +package utm + +import ( + "net/url" + "regexp" + "strings" +) + +// Params are the tags for one post. +type Params struct { + Source string // the channel: x, linkedin, reddit + Medium string // "social" + Campaign string // the kind of post: partner, competitor, watch, product + Content string // which post: entry and draft +} + +// Tagger knows which hosts are the company's. +type Tagger struct { + hosts []string +} + +// NewTagger takes the company's site and product URLs (or bare hosts). +func NewTagger(sites []string) *Tagger { + t := &Tagger{} + seen := map[string]bool{} + for _, s := range sites { + h := host(s) + if h != "" && !seen[h] { + seen[h] = true + t.hosts = append(t.hosts, h) + } + } + return t +} + +func host(s string) string { + s = strings.TrimSpace(s) + if s == "" { + return "" + } + if !strings.Contains(s, "://") { + s = "https://" + s + } + u, err := url.Parse(s) + if err != nil { + return "" + } + return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") +} + +// Own reports whether rawURL is on one of the company's hosts or their +// subdomains. +func (t *Tagger) Own(rawURL string) bool { + h := host(rawURL) + if h == "" || !strings.Contains(rawURL, "://") { + return false + } + for _, own := range t.hosts { + if h == own || strings.HasSuffix(h, "."+own) { + return true + } + } + return false +} + +// URL tags rawURL if it's the company's. Tags already in the link win. +func (t *Tagger) URL(rawURL string, p Params) string { + if t == nil || !t.Own(rawURL) { + return rawURL + } + u, err := url.Parse(rawURL) + if err != nil { + return rawURL + } + q := u.Query() + for k, v := range map[string]string{ + "utm_source": p.Source, "utm_medium": p.Medium, "utm_campaign": p.Campaign, "utm_content": p.Content, + } { + if v != "" && q.Get(k) == "" { + q.Set(k, v) + } + } + u.RawQuery = q.Encode() + return u.String() +} + +// links finds http(s) URLs in text. Trailing punctuation that usually ends +// a sentence isn't part of the link. +var links = regexp.MustCompile(`https?://[^\s<>"]+`) + +// Text tags the company's links inside a post. +func (t *Tagger) Text(text string, p Params) string { + if t == nil || len(t.hosts) == 0 { + return text + } + return links.ReplaceAllStringFunc(text, func(m string) string { + trail := "" + for len(m) > 0 && strings.ContainsRune(".,;:!?)]}'", rune(m[len(m)-1])) { + trail = m[len(m)-1:] + trail + m = m[:len(m)-1] + } + return t.URL(m, p) + trail + }) +} + +// Slug turns a name into a lowercase tag value: "Jitsi Meet" → "jitsi-meet". +func Slug(s string) string { + var b strings.Builder + dash := false + for _, r := range strings.ToLower(s) { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') { + b.WriteRune(r) + dash = false + } else if b.Len() > 0 && !dash { + b.WriteByte('-') + dash = true + } + } + return strings.TrimSuffix(b.String(), "-") +} + +// Any reports whether the tagger knows any of the company's hosts. +func (t *Tagger) Any() bool { return t != nil && len(t.hosts) > 0 } diff --git a/internal/utm/utm_test.go b/internal/utm/utm_test.go new file mode 100644 index 0000000..bcfef88 --- /dev/null +++ b/internal/utm/utm_test.go @@ -0,0 +1,42 @@ +package utm + +import "testing" + +func TestTagger(t *testing.T) { + tg := NewTagger([]string{"https://www.acme.example/", "acme.dev", "", "https://acme.example/pricing"}) + p := Params{Source: "x", Medium: "social", Campaign: "partner", Content: "jitsi-12"} + + for in, want := range map[string]string{ + "https://acme.example/blog/post": "https://acme.example/blog/post?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x", + "https://docs.acme.dev/x?a=1": "https://docs.acme.dev/x?a=1&utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x", + "https://www.acme.example/?utm_source=newsletter#top": "https://www.acme.example/?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=newsletter#top", + "https://jitsi.org/news": "https://jitsi.org/news", + "https://notacme.example/": "https://notacme.example/", + "https://x.com/acme/status/1": "https://x.com/acme/status/1", + "": "", + } { + if got := tg.URL(in, p); got != want { + t.Errorf("URL(%q) = %q, want %q", in, got, want) + } + } + + text := "Read it (https://acme.example/a). Or https://jitsi.org/b, or https://acme.dev!" + want := "Read it (https://acme.example/a?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x). " + + "Or https://jitsi.org/b, or https://acme.dev?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x!" + if got := tg.Text(text, p); got != want { + t.Errorf("Text =\n%s\nwant\n%s", got, want) + } + + var none *Tagger + if none.URL("https://acme.example", p) != "https://acme.example" || NewTagger(nil).Text(text, p) != text { + t.Error("a tagger without sites must change nothing") + } +} + +func TestSlug(t *testing.T) { + for in, want := range map[string]string{"Jitsi Meet": "jitsi-meet", " Acme, Inc. ": "acme-inc", "Ünïcode 2": "n-code-2", "": ""} { + if got := Slug(in); got != want { + t.Errorf("Slug(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/web/content.go b/internal/web/content.go index f0c1b16..82d532b 100644 --- a/internal/web/content.go +++ b/internal/web/content.go @@ -45,10 +45,7 @@ func (s *Server) contentIndex(w http.ResponseWriter, r *http.Request) { rows = append(rows, contentRow{Entry: e, Sources: fetcher.Sources(&e), Waiting: counts[strings.ToLower(e.Name)], LastChecked: last}) } - drafts, _ := content.CountDrafts(s.DB) - s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{ - "Rows": rows, "Drafts": drafts, - }}) + s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{"Rows": rows}}) } type channelChoice struct { @@ -65,7 +62,6 @@ type entryPage struct { Since time.Time Channels []channelChoice ProfileSet bool - Drafts int // After a fetch Fetched bool NewItems int @@ -109,9 +105,8 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, for _, c := range content.Channels { chans = append(chans, channelChoice{c, pubs[c.ID] != nil}) } - drafts, _ := content.CountDrafts(s.DB) return &entryPage{Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed, - LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet(), Drafts: drafts}, nil + LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil } func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) { @@ -206,7 +201,7 @@ func (s *Server) contentItems(w http.ResponseWriter, r *http.Request) { showErr(err.Error()) return } - redirect(w, r, "/drafts", "drafted") + redirect(w, r, "/inbox", "drafted") default: http.Error(w, "unknown action", http.StatusBadRequest) } @@ -272,124 +267,3 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string) } return nil } - -// --- Drafts --- - -type draftBatch struct { - Batch string - InventoryName string - Kind string - CreatedAt time.Time - SourceURL string - Drafts []content.Draft -} - -func (s *Server) draftsPage(w http.ResponseWriter, r *http.Request) { - s.renderDrafts(w, r, "") -} - -func (s *Server) renderDrafts(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 batches []*draftBatch - byID := map[string]*draftBatch{} - for _, d := range pending { - 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 { - // X first, then LinkedIn, whatever order they were stored in. - 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 - } - published, err := content.ListDrafts(s.DB, 20, content.StatusPublished) - if err != nil { - s.serverError(w, err) - return - } - pubs := s.publishers() - connected := map[string]bool{} - for id := range pubs { - connected[id] = true - } - s.render(w, r, "drafts", page{Title: "Drafts", Nav: "content", Error: errMsg, Data: map[string]any{ - "Batches": batches, "Published": published, "Connected": connected, - }}) -} - -func (s *Server) draftID(w http.ResponseWriter, r *http.Request) (int64, bool) { - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { - http.NotFound(w, r) - return 0, false - } - return id, true -} - -// draftAction saves, publishes or discards one draft. -func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) { - id, ok := s.draftID(w, r) - if !ok { - return - } - if err := r.ParseForm(); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - fail := func(err error) { - if errors.Is(err, content.ErrNoDraft) { - http.NotFound(w, r) - return - } - s.renderDrafts(w, r, err.Error()) - } - action := r.PathValue("action") - if action == "save" || action == "publish" { - 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, "/drafts", "saved") - case "publish": - ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) - defer cancel() - d, err := content.Publish(ctx, s.DB, s.publishers(), 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, "/drafts", "published") - case "discard": - if err := content.DiscardDraft(s.DB, id); err != nil { - fail(err) - return - } - redirect(w, r, "/drafts", "discarded") - default: - http.NotFound(w, r) - } -} diff --git a/internal/web/content_test.go b/internal/web/content_test.go index 84e2304..b030a7e 100644 --- a/internal/web/content_test.go +++ b/internal/web/content_test.go @@ -1,6 +1,7 @@ package web import ( + "context" "net/http" "net/url" "strconv" @@ -89,11 +90,15 @@ func TestDraftsPage(t *testing.T) { ids[d.Channel] = strconv.FormatInt(d.ID, 10) } - rec := do(h, http.MethodGet, "/drafts", nil, nil) + if rec := do(h, http.MethodGet, "/drafts?msg=drafted", nil, nil); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/inbox?msg=drafted" { + t.Errorf("old drafts page: %d %s", rec.Code, rec.Header().Get("Location")) + } + rec := do(h, http.MethodGet, "/inbox", nil, nil) body := rec.Body.String() if rec.Code != 200 || strings.Index(body, "X text") > strings.Index(body, "LinkedIn text") || - !strings.Contains(body, "31 / 280 including the link") || !strings.Contains(body, `data-reserve="25"`) { - t.Errorf("drafts page (X should come first):\n%s", body) + !strings.Contains(body, "31 / 280 including the link") || !strings.Contains(body, `data-reserve="25"`) || + !strings.Contains(body, `class="count-badge">2<`) { + t.Errorf("inbox (X should come first, menu count 2):\n%s", body) } // Save an edit. @@ -123,6 +128,71 @@ func TestDraftsPage(t *testing.T) { } } +func TestScheduleFromInbox(t *testing.T) { + s, h := newTestServer(t, nil) + if _, err := content.CreateDrafts(s.DB, []content.Draft{{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelX, Content: "Soon"}}); err != nil { + t.Fatal(err) + } + drafts, _ := content.ListDrafts(s.DB, 1, content.StatusDraft) + id := strconv.FormatInt(drafts[0].ID, 10) + + // A past time, or none, is refused. + past := time.Now().Add(-time.Hour).Format(dateTimeLocal) + if rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"when": {past}}); !strings.Contains(rec.Body.String(), "that time has passed") { + t.Errorf("past time: %s", rec.Body.String()) + } + if rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"when": {""}}); !strings.Contains(rec.Body.String(), "choose a date") { + t.Errorf("no time: %s", rec.Body.String()) + } + + when := time.Now().Add(2 * time.Hour).Truncate(time.Minute) + rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"content": {"Soon, edited"}, "when": {when.Format(dateTimeLocal)}}) + if rec.Code != http.StatusSeeOther { + t.Fatalf("schedule: %d %s", rec.Code, rec.Body.String()) + } + d, _ := content.GetDraft(s.DB, mustID(id)) + if d.Status != content.StatusScheduled || !d.PublishAt.Equal(when) || d.Content != "Soon, edited" { + t.Errorf("scheduled draft: %+v (want %v)", d, when) + } + body := do(h, http.MethodGet, "/content/scheduled", nil, nil).Body.String() + if !strings.Contains(body, "Soon, edited") || !strings.Contains(body, when.Format("15:04")) || !strings.Contains(body, "not connected") { + t.Errorf("scheduled page:\n%s", body) + } + if !strings.Contains(do(h, http.MethodGet, "/inbox", nil, nil).Body.String(), "Nothing waiting") { + t.Error("a scheduled draft is still in the Inbox") + } + + // When it's due and X isn't connected, it goes back to the Inbox with + // the reason instead of being retried for ever. + s.publishDue(context.Background(), when.Add(time.Minute)) + d, _ = content.GetDraft(s.DB, mustID(id)) + if d.Status != content.StatusFailed || !strings.Contains(d.Error, "isn't connected") { + t.Errorf("after the scheduler: %+v", d) + } + + // Unschedule from the Scheduled page. + _ = content.Schedule(s.DB, mustID(id), when) + if rec := postForm(h, "/drafts/"+id+"/unschedule", url.Values{"from": {"scheduled"}}); rec.Code != http.StatusSeeOther { + t.Fatalf("unschedule: %d", rec.Code) + } + if d, _ := content.GetDraft(s.DB, mustID(id)); d.Status != content.StatusDraft { + t.Errorf("unscheduled: %+v", d) + } +} + +func TestTaggerFromProfile(t *testing.T) { + s, _ := newTestServer(t, nil) + if s.tagger() != nil { + t.Error("no sites in the profile: no tagger") + } + _ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "x", + Websites: []profile.Website{{URL: "https://acme.example"}}, Products: []profile.Product{{Name: "P", URL: "https://app.acme.dev/p"}}}) + tg := s.tagger() + if tg == nil || !tg.Own("https://acme.example/blog") || !tg.Own("https://app.acme.dev/") || tg.Own("https://jitsi.org") { + t.Errorf("tagger: %+v", tg) + } +} + func mustID(s string) int64 { n, _ := strconv.ParseInt(s, 10, 64) return n diff --git a/internal/web/inbox.go b/internal/web/inbox.go new file mode 100644 index 0000000..c247085 --- /dev/null +++ b/internal/web/inbox.go @@ -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 , 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) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index ab7f880..9cfe038 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -95,7 +95,12 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("GET /content/{id}", s.contentEntry) mux.HandleFunc("POST /content/{id}/fetch", s.contentFetch) mux.HandleFunc("POST /content/{id}/items", s.contentItems) - mux.HandleFunc("GET /drafts", s.draftsPage) + mux.HandleFunc("GET /content/scheduled", s.scheduledPage) + mux.HandleFunc("GET /content/published", s.publishedPage) + mux.HandleFunc("GET /inbox", s.inboxPage) + mux.HandleFunc("GET /drafts", func(w http.ResponseWriter, r *http.Request) { + redirect(w, r, "/inbox", r.URL.Query().Get("msg")) + }) mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction) mux.HandleFunc("GET /core", s.corePage) @@ -201,6 +206,7 @@ type page struct { Flash string Error string Data any + Inbox int // drafts waiting for review, shown in the menu } // render writes a full page, or only its "content" block for htmx requests @@ -212,6 +218,7 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p return } p.Version = s.Version + p.Inbox = s.inboxCount() if p.Flash == "" { p.Flash = flashes[r.URL.Query().Get("msg")] } @@ -247,6 +254,8 @@ var flashes = map[string]string{ "drafted": "Drafts written. Review them below.", "published": "Published.", "discarded": "Discarded.", + "scheduled": "Scheduled.", + "unscheduled": "Back in the Inbox: edit it, then publish or schedule it again.", } func redirect(w http.ResponseWriter, r *http.Request, path, msg string) { diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 38ecba0..1418650 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -89,7 +89,8 @@ func TestEveryPageRenders(t *testing.T) { for _, path := range []string{"/", "/?msg=saved", "/profile", "/inventory", "/inventory?relationship=partner", "/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export", "/settings/ai", "/settings/credentials", "/core", "/static/app.css", "/static/htmx.min.js", "/healthz", - "/content", "/content/1", "/content/1?dismissed=1", "/drafts", "/drafts?msg=drafted"} { + "/content", "/content/1", "/content/1?dismissed=1", "/inbox", "/inbox?msg=drafted", + "/content/scheduled", "/content/published"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String()) diff --git a/internal/web/static/app.css b/internal/web/static/app.css index df84cb4..d5cb97c 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -139,3 +139,10 @@ button.pill:hover { background: #e0f2f7; } .count { margin: 0.3rem 0 0; font-size: 0.85rem; color: var(--muted); text-align: right; } .count.over { color: var(--bad); font-weight: 600; } button.small { padding: 0.3rem 0.8rem; font-size: 0.85rem; } +.count-badge { display: inline-block; min-width: 1.3rem; padding: 0 0.35rem; margin-left: 0.2rem; border-radius: 999px; background: var(--magenta); color: #fff; font-size: 0.75rem; font-weight: 700; text-align: center; line-height: 1.3rem; } +.schedule { display: flex; gap: 0.5rem; align-items: flex-end; flex-wrap: wrap; margin-bottom: 0.5rem; } +.schedule label { margin: 0; flex: 1; min-width: 12rem; } +.row-actions { white-space: nowrap; } +.row-actions form { display: inline-block; margin: 0 0.25rem 0.25rem 0; } +.post-text { overflow-wrap: anywhere; } +.small { font-size: 0.85rem; } diff --git a/internal/web/templates/content-entry.html b/internal/web/templates/content-entry.html index d0a3de7..1d0ee94 100644 --- a/internal/web/templates/content-entry.html +++ b/internal/web/templates/content-entry.html @@ -1,7 +1,8 @@ {{define "content"}}{{with .Data}}
The last 200 posts Supermarket published.
+ +{{if .Drafts}} +| When | Channel | Entry | Post |
|---|---|---|---|
| {{.PublishedAt.Local.Format "2 Jan 2006 15:04"}} | +{{.ChannelName}} | +{{.InventoryName}} | +{{if .PostURL}}{{truncate 200 .Content}}{{else}}{{truncate 200 .Content}}{{end}} | +
Nothing published yet.
Approved posts, in the order they go out ({{.Zone}}). Supermarket publishes them on time as long as it's running; one more than 12 hours late goes back to the Inbox instead.
+ +{{if .Drafts}} +| When | Channel | Entry | Post | |
|---|---|---|---|---|
| {{.PublishAt.Local.Format "Mon 2 Jan 15:04"}} | +{{.ChannelName}}{{if not (index $conn .Channel)}} not connected{{end}} |
+ {{.InventoryName}} | +{{truncate 200 .Content}} | ++ + + | +
Nothing scheduled. Schedule drafts from the Inbox.
Pick an inventory entry to fetch its latest news, choose what to write about, and get a draft for each channel to review on the Drafts page.
+Pick an inventory entry to fetch its latest news, choose what to write about, and get a draft for each channel to review in the Inbox.
{{if .Rows}}| When | Channel | Entry | Post |
|---|---|---|---|
| {{ago .PublishedAt}} | -{{.ChannelName}} | -{{.InventoryName}} | -{{if .PostURL}}{{truncate 80 .Content}}{{else}}{{truncate 80 .Content}}{{end}} | -