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:
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user