Files
supermarket/internal/content/items.go
T
davidandClaude Opus 5.5 13bf18facc Phase 1, part 1: fetch, write and publish posts from the web app
Brings back posting, which Phase 0 removed with the terminal interface.

- Content page: per inventory entry, fetch its X account, X hashtag
  search, YouTube channel and RSS/Atom feeds (new), then select, dismiss
  or restore the fetched items, which are kept in the database.
- Writing: one AI call returns a draft per channel (X and LinkedIn),
  prompted from the company profile, the entry's relationship, talking
  points and mention policy, and each channel's rules. Fetched text is
  quoted as untrusted. An over-long X draft gets one request to shorten.
- Drafts page: edit with a live length counter that counts like X, then
  publish each draft on its own. A draft is claimed before posting so it
  can't go out twice; failures are kept on the draft for a retry; X
  tokens are refreshed and saved.
- Migration 2 adds content_items and drafts, and turns queued posts into
  drafts for the platforms they hadn't reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:58:24 -07:00

195 lines
5.4 KiB
Go

// Package content is the Content module: fetched items, per-channel drafts
// written from them, and publishing those drafts.
package content
import (
"database/sql"
"errors"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/models"
)
// DefaultLookback is how far back the first fetch for an entry goes.
const DefaultLookback = 7 * 24 * time.Hour
// Item is a stored content item.
type Item struct {
models.ContentItem
FetchedAt time.Time
Used bool // a draft was written from it
Dismissed bool
}
const timeFormat = time.RFC3339
func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) }
func parseTime(s string) time.Time {
t, _ := time.Parse(timeFormat, s)
return t
}
// SaveItems stores fetched items, keeping ones already stored as they are.
// It returns how many were new.
func SaveItems(d *db.DB, items []models.ContentItem) (int, error) {
tx, err := d.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
n := 0
for _, it := range items {
res, err := tx.Exec(`INSERT OR IGNORE INTO content_items
(id, inventory_name, source, author, author_handle, title, body, url, published_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
it.ID, it.AppName, string(it.Source), it.Author, it.AuthorHandle, it.Title, it.Body, it.URL,
formatTime(it.PublishedAt))
if err != nil {
return 0, err
}
if k, _ := res.RowsAffected(); k > 0 {
n++
}
}
return n, tx.Commit()
}
const itemColumns = `c.id, c.inventory_name, c.source, c.author, c.author_handle, c.title, c.body, c.url,
c.published_at, c.fetched_at, c.used_at IS NOT NULL, d.item_id IS NOT NULL`
const itemFrom = ` FROM content_items c LEFT JOIN dismissed d ON d.item_id = c.id`
func scanItems(rows *sql.Rows) ([]Item, error) {
defer rows.Close()
var out []Item
for rows.Next() {
var it Item
var source, published, fetched string
if err := rows.Scan(&it.ID, &it.AppName, &source, &it.Author, &it.AuthorHandle, &it.Title, &it.Body,
&it.URL, &published, &fetched, &it.Used, &it.Dismissed); err != nil {
return nil, err
}
it.Source = models.ContentSource(source)
it.PublishedAt = parseTime(published)
it.FetchedAt = parseTime(fetched)
out = append(out, it)
}
return out, rows.Err()
}
// ListItems returns an entry's items, newest first. Dismissed items are left
// out unless dismissed is true, and then only they are returned.
func ListItems(d *db.DB, entryName string, dismissed bool, limit int) ([]Item, error) {
cond := "d.item_id IS NULL"
if dismissed {
cond = "d.item_id IS NOT NULL"
}
rows, err := d.Query(`SELECT `+itemColumns+itemFrom+`
WHERE c.inventory_name = ? AND `+cond+`
ORDER BY c.published_at DESC LIMIT ?`, entryName, limit)
if err != nil {
return nil, err
}
return scanItems(rows)
}
// GetItems returns the items with these IDs, in the order given; unknown
// IDs are skipped.
func GetItems(d *db.DB, ids []string) ([]Item, error) {
var out []Item
for _, id := range ids {
rows, err := d.Query(`SELECT `+itemColumns+itemFrom+` WHERE c.id = ?`, id)
if err != nil {
return nil, err
}
items, err := scanItems(rows)
if err != nil {
return nil, err
}
out = append(out, items...)
}
return out, nil
}
// Counts is how many items an entry has waiting (not used, not dismissed).
func Counts(d *db.DB) (map[string]int, error) {
rows, err := d.Query(`SELECT c.inventory_name, count(*)` + itemFrom + `
WHERE d.item_id IS NULL AND c.used_at IS NULL GROUP BY c.inventory_name COLLATE NOCASE`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]int{}
for rows.Next() {
var name string
var n int
if err := rows.Scan(&name, &n); err != nil {
return nil, err
}
out[strings.ToLower(name)] = n
}
return out, rows.Err()
}
// Dismiss hides items from the list for good (until restored).
func Dismiss(d *db.DB, ids []string) error {
for _, id := range ids {
if _, err := d.Exec(`INSERT OR IGNORE INTO dismissed (item_id) VALUES (?)`, id); err != nil {
return err
}
}
return nil
}
// Restore brings dismissed items back.
func Restore(d *db.DB, ids []string) error {
for _, id := range ids {
if _, err := d.Exec(`DELETE FROM dismissed WHERE item_id = ?`, id); err != nil {
return err
}
}
return nil
}
func markUsed(tx *sql.Tx, ids []string) error {
for _, id := range ids {
if _, err := tx.Exec(`UPDATE content_items SET used_at = ? WHERE id = ? AND used_at IS NULL`,
formatTime(time.Now()), id); err != nil {
return err
}
}
return nil
}
// LastChecked is when the entry was last fetched, or zero.
func LastChecked(d *db.DB, entryName string) (time.Time, error) {
var s string
err := d.QueryRow(`SELECT last_checked FROM fetch_state WHERE key = ?`, entryName).Scan(&s)
if errors.Is(err, sql.ErrNoRows) {
return time.Time{}, nil
}
if err != nil {
return time.Time{}, err
}
return parseTime(s), nil
}
// Since is where the next fetch for the entry starts.
func Since(d *db.DB, entryName string, now time.Time) (time.Time, error) {
last, err := LastChecked(d, entryName)
if err != nil || last.IsZero() || now.Sub(last) > 30*24*time.Hour {
return now.Add(-DefaultLookback), err
}
return last, nil
}
// SetLastChecked records a fetch.
func SetLastChecked(d *db.DB, entryName string, at time.Time) error {
_, err := d.Exec(`INSERT INTO fetch_state (key, last_checked) VALUES (?, ?)
ON CONFLICT (key) DO UPDATE SET last_checked = excluded.last_checked`, entryName, formatTime(at))
return err
}