diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 87064f7..7a89c99 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -98,6 +98,9 @@ func run(log *slog.Logger) error { }); n > 0 { log.Info("backups: moved old copies into the backups folder", "count", n) } + if n := backup.RemoveOrphans(backup.Dir(dataDir)); n > 0 { + log.Info("backups: removed -wal and -shm files of deleted backups", "count", n) + } db.BeforeMigrate = func(d *sql.DB, from, to int) error { b, err := backup.Make(d, backup.Dir(dataDir), backup.Migration, fmt.Sprintf("before-schema-%d", to), time.Now()) if err == nil { diff --git a/go.mod b/go.mod index 2700825..dca98c9 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/emersion/go-message v0.18.2 github.com/modelcontextprotocol/go-sdk v1.8.0 golang.org/x/net v0.63.0 + golang.org/x/text v0.44.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.62.0 ) @@ -42,7 +43,6 @@ require ( golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect - golang.org/x/text v0.44.0 // indirect golang.org/x/time v0.15.0 // indirect modernc.org/libc v1.80.1 // indirect modernc.org/mathutil v1.7.1 // indirect diff --git a/internal/api/rss/rss.go b/internal/api/rss/rss.go index 796fceb..296e9ed 100644 --- a/internal/api/rss/rss.go +++ b/internal/api/rss/rss.go @@ -174,14 +174,23 @@ func itemID(key string) string { } var ( + // Elements whose text isn't text: a post's own scripts and styles. + code = regexp.MustCompile(`(?is)<(script|style|noscript|template)\b[^>]*>.*?`) tags = regexp.MustCompile(`(?s)<[^>]*>`) spaces = regexp.MustCompile(`\s+`) ) -// clean turns feed HTML into plain text of at most n characters. +// clean turns feed HTML into plain text of at most n characters. Some +// feeds escape their HTML once more, so it's stripped again after +// unescaping. func clean(s string, n int) string { - s = tags.ReplaceAllString(s, " ") - s = html.UnescapeString(s) + strip := func(s string) string { return tags.ReplaceAllString(code.ReplaceAllString(s, " "), " ") } + s = strip(s) + if u := html.UnescapeString(s); u != s && strings.Contains(u, "<") { + s = html.UnescapeString(strip(u)) + } else { + s = u + } s = strings.TrimSpace(spaces.ReplaceAllString(s, " ")) if r := []rune(s); len(r) > n { s = string(r[:n-1]) + "…" diff --git a/internal/api/rss/rss_test.go b/internal/api/rss/rss_test.go index fc11de5..d7d318b 100644 --- a/internal/api/rss/rss_test.go +++ b/internal/api/rss/rss_test.go @@ -57,3 +57,14 @@ func TestParseRejectsHTML(t *testing.T) { t.Fatal("expected an error for an HTML page") } } + +func TestCleanDropsScripts(t *testing.T) { + in := `

Table

+

How to set up & share

` + if got := clean(in, 500); got != "Table How to set up & share" { + t.Errorf("clean = %q", got) + } + if got := clean(`<p>Hi</p><script>var a = 1;</script> there`, 500); got != "Hi there" { + t.Errorf("escaped: %q", got) + } +} diff --git a/internal/backup/backup.go b/internal/backup/backup.go index b0215c4..12f4be2 100644 --- a/internal/backup/backup.go +++ b/internal/backup/backup.go @@ -135,9 +135,11 @@ func (b *Backup) read() { b.Schema = v } -// open opens a database file read-only, without touching it. +// open opens a database file read-only, without touching it. A backup is +// never written to, so it's opened as immutable: SQLite then leaves no -shm +// or -wal file next to it, even for a copy in WAL mode. func open(path string) (*sql.DB, error) { - d, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)") + d, err := sql.Open("sqlite", "file:"+path+"?mode=ro&immutable=1&_pragma=busy_timeout(5000)") if err != nil { return nil, err } @@ -154,11 +156,17 @@ func SchemaOf(path string) (int, error) { defer d.Close() var v int if err := d.QueryRow(`PRAGMA user_version`).Scan(&v); err != nil { - return 0, fmt.Errorf("not a database Supermarket can read: %w", err) + return 0, ErrNotDatabase } return v, nil } +// What Check says about a file that isn't a backup. +var ( + ErrNotDatabase = errors.New("it isn't a database file") + ErrNotSupermarket = errors.New("it's a database, but not a Supermarket one") +) + // Check checks a database file: SQLite's integrity check, and that it's a // Supermarket database (it has the settings table). func Check(path string) error { @@ -169,14 +177,14 @@ func Check(path string) error { defer d.Close() var res string if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&res); err != nil { - return fmt.Errorf("not a database Supermarket can read: %w", err) + return ErrNotDatabase } if res != "ok" { return fmt.Errorf("the database is damaged: %s", res) } var n int if err := d.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'settings'`).Scan(&n); err != nil || n == 0 { - return errors.New("that isn't a Supermarket database") + return ErrNotSupermarket } return nil } @@ -223,13 +231,37 @@ func Find(dir, name string) (*Backup, error) { return nil, os.ErrNotExist } -// Delete deletes a backup. +// Delete deletes a backup, with any -wal and -shm files left next to it. func Delete(dir, name string) error { b, err := Find(dir, name) if err != nil { return err } - return os.Remove(b.Path) + if err := os.Remove(b.Path); err != nil { + return err + } + removeSidecars(b.Path) + return nil +} + +func removeSidecars(path string) { + os.Remove(path + "-wal") + os.Remove(path + "-shm") +} + +// RemoveOrphans deletes -wal and -shm files whose backup is gone. Older +// versions left them when a backup was deleted. It returns how many. +func RemoveOrphans(dir string) int { + n := 0 + for _, suffix := range []string{"-wal", "-shm"} { + matches, _ := filepath.Glob(filepath.Join(dir, "app-*.db"+suffix)) + for _, m := range matches { + if _, err := os.Stat(strings.TrimSuffix(m, suffix)); errors.Is(err, os.ErrNotExist) && os.Remove(m) == nil { + n++ + } + } + } + return n } // Keep says which daily backups to keep: the newest 7, then the newest of @@ -274,9 +306,11 @@ func Prune(dir string) (int, error) { if err := os.Remove(b.Path); err != nil { return n, err } + removeSidecars(b.Path) n++ } } + RemoveOrphans(dir) return n, nil } diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go index 15c7749..0cdb0a2 100644 --- a/internal/backup/backup_test.go +++ b/internal/backup/backup_test.go @@ -90,7 +90,7 @@ func TestCheckNotSupermarket(t *testing.T) { d, _ := sql.Open("sqlite", "file:"+path) d.Exec(`CREATE TABLE x (y)`) d.Close() - if err := Check(path); err == nil || !strings.Contains(err.Error(), "isn't a Supermarket database") { + if err := Check(path); err == nil || !strings.Contains(err.Error(), "not a Supermarket one") { t.Errorf("check: %v", err) } } @@ -190,3 +190,37 @@ func TestAdoptLegacy(t *testing.T) { t.Errorf("second run moved %d", n) } } + +func TestDeleteLeavesNoSidecars(t *testing.T) { + dir := t.TempDir() + name := "app-20261121-124721-legacy-phase2.db" + src := filepath.Join(t.TempDir(), "src.db") + d, err := sql.Open("sqlite", "file:"+src) + if err != nil { + t.Fatal(err) + } + d.Exec(`PRAGMA journal_mode = WAL`) + d.Exec(`CREATE TABLE settings (key TEXT, value TEXT)`) + d.Close() + raw, _ := os.ReadFile(src) + os.WriteFile(filepath.Join(dir, name), raw, 0o600) + if _, err := List(dir); err != nil { // reads each backup's schema + t.Fatal(err) + } + for _, suffix := range []string{"-wal", "-shm"} { + if _, err := os.Stat(filepath.Join(dir, name+suffix)); err == nil { + t.Errorf("listing made %s", suffix) + } + } + os.WriteFile(filepath.Join(dir, name+"-shm"), []byte("x"), 0o600) + if err := Delete(dir, name); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(dir, "app-20261120-125700-legacy-phase1.db-wal"), nil, 0o600) + if n := RemoveOrphans(dir); n != 1 { + t.Errorf("orphans removed: %d", n) + } + if left, _ := filepath.Glob(filepath.Join(dir, "*")); len(left) != 0 { + t.Errorf("left: %v", left) + } +} diff --git a/internal/backup/restore_test.go b/internal/backup/restore_test.go index 48423a9..6775941 100644 --- a/internal/backup/restore_test.go +++ b/internal/backup/restore_test.go @@ -38,7 +38,7 @@ func TestStageAndApply(t *testing.T) { nd.Close() junk := filepath.Join(t.TempDir(), "junk.db") os.WriteFile(junk, []byte("junk"), 0o600) - for src, want := range map[string]string{newer: "newer Supermarket", junk: "not a database", "/nope.db": "no such file"} { + for src, want := range map[string]string{newer: "newer Supermarket", junk: "isn't a database", "/nope.db": "no such file"} { if _, err := Stage(cur, data, src, 24, now); err == nil || !strings.Contains(err.Error(), want) { t.Errorf("%s: %v", src, err) } diff --git a/internal/metrics/spend.go b/internal/metrics/spend.go index a8ca8f6..34373cf 100644 --- a/internal/metrics/spend.go +++ b/internal/metrics/spend.go @@ -97,13 +97,17 @@ func SpendLog(d *db.DB, limit int) ([]Spend, error) { return out, rows.Err() } -// ParseAmount reads "1,250.50", "$80" or "80" as cents. +// ParseAmount reads "1,250.50", "$80" or "80" as cents. Spend is never +// below zero. func ParseAmount(s string) (int64, error) { s = strings.NewReplacer("$", "", ",", "", " ", "").Replace(strings.TrimSpace(s)) f, err := strconv.ParseFloat(s, 64) if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { return 0, fmt.Errorf("%q isn't an amount", s) } + if f < 0 { + return 0, fmt.Errorf("%q is below zero: log what was spent, as a positive amount", s) + } return int64(math.Round(f * 100)), nil } diff --git a/internal/metrics/spend_test.go b/internal/metrics/spend_test.go index af3b831..7e0b863 100644 --- a/internal/metrics/spend_test.go +++ b/internal/metrics/spend_test.go @@ -17,6 +17,9 @@ func TestSpendLog(t *testing.T) { t.Errorf("accepted %+v", bad) } } + if _, err := ParseAmount("-5"); err == nil { + t.Error("accepted a negative amount") + } if c, err := ParseAmount("$1,250.50"); err != nil || c != 125050 { t.Errorf("amount: %d %v", c, err) } diff --git a/internal/prospects/prospects.go b/internal/prospects/prospects.go index 108ed3c..215f138 100644 --- a/internal/prospects/prospects.go +++ b/internal/prospects/prospects.go @@ -998,3 +998,79 @@ func Search(d *db.DB, words []string, limit int) ([]Company, []Contact, error) { contacts, err := scanContacts(rows) return companies, contacts, err } + +// Delete forgets a company (with its people) or a person added by mistake: +// their steps in the funnel and Hunter.io searches go too, and a CRM action +// that hasn't been done yet is taken back. A record Hermes already added to +// EspoCRM stays there. +func Delete(d *db.DB, kind string, id int64) error { + tbl, err := table(kind) + if err != nil { + return err + } + tx, err := d.Begin() + if err != nil { + return err + } + defer tx.Rollback() + var exists int + if err := tx.QueryRow(`SELECT count(*) FROM `+tbl+` WHERE id = ?`, id).Scan(&exists); err != nil { + return err + } + if exists == 0 { + return ErrNotFound + } + contacts := []int64{} + if kind == "contact" { + contacts = append(contacts, id) + } else { + rows, err := tx.Query(`SELECT id FROM prospect_contacts WHERE company_id = ?`, id) + if err != nil { + return err + } + for rows.Next() { + var c int64 + if err := rows.Scan(&c); err != nil { + rows.Close() + return err + } + contacts = append(contacts, c) + } + rows.Close() + } + subjects := []any{} + if kind == "company" { + subjects = append(subjects, "company:"+strconv.FormatInt(id, 10)) + } + for _, c := range contacts { + subjects = append(subjects, "contact:"+strconv.FormatInt(c, 10)) + } + origins := make([]any, len(subjects)) + for i, s := range subjects { + origins[i] = "prospect-" + s.(string) + } + in := "(?" + strings.Repeat(", ?", len(subjects)-1) + ")" + for _, q := range []struct { + sql string + args []any + }{ + {`DELETE FROM funnel_events WHERE subject IN ` + in, subjects}, + {`DELETE FROM enrich_runs WHERE subject IN ` + in, subjects}, + {`UPDATE crm_actions SET status = 'cancelled' WHERE status IN ('pending', 'failed') AND origin IN ` + in, origins}, + } { + if _, err := tx.Exec(q.sql, q.args...); err != nil { + return err + } + } + for _, c := range contacts { + if _, err := tx.Exec(`DELETE FROM prospect_contacts WHERE id = ?`, c); err != nil { + return err + } + } + if kind == "company" { + if _, err := tx.Exec(`DELETE FROM prospect_companies WHERE id = ?`, id); err != nil { + return err + } + } + return tx.Commit() +} diff --git a/internal/prospects/prospects_test.go b/internal/prospects/prospects_test.go index cb0cfc2..f51b5b6 100644 --- a/internal/prospects/prospects_test.go +++ b/internal/prospects/prospects_test.go @@ -248,3 +248,41 @@ func TestAddWithoutEmails(t *testing.T) { t.Error("a namesake without a company was merged") } } + +func TestDelete(t *testing.T) { + d := openDB(t) + now := time.Now() + co, _, err := AddCompany(d, Company{Name: "Oops", Website: "https://oops.example", Source: SourceManual}, now) + if err != nil { + t.Fatal(err) + } + p1, _, _ := AddContact(d, Contact{CompanyID: co, FirstName: "Ann", LastName: "Oops", Email: "ann@oops.example", Source: SourceManual}, now) + p2, _, _ := AddContact(d, Contact{CompanyID: co, FirstName: "Solo", Email: "solo@oops.example", Source: SourceManual}, now) + if _, err := AcceptContact(d, p2, now); err != nil { + t.Fatal(err) + } + d.Exec(`INSERT INTO funnel_events (stage, channel, subject, source, at) VALUES ('paid', 'email', ?, 'manual', ?)`, "contact:"+strconv.FormatInt(p1, 10), now.Format(time.RFC3339)) + if err := Delete(d, "contact", p1); err != nil { + t.Fatal(err) + } + var n int + d.QueryRow(`SELECT count(*) FROM funnel_events WHERE subject = ?`, "contact:"+strconv.FormatInt(p1, 10)).Scan(&n) + if n != 0 { + t.Errorf("funnel events left: %d", n) + } + if err := Delete(d, "company", co); err != nil { + t.Fatal(err) + } + d.QueryRow(`SELECT (SELECT count(*) FROM prospect_companies) + (SELECT count(*) FROM prospect_contacts)`).Scan(&n) + if n != 0 { + t.Errorf("prospects left: %d", n) + } + var status string + d.QueryRow(`SELECT status FROM crm_actions WHERE origin = ?`, "prospect-contact:"+strconv.FormatInt(p2, 10)).Scan(&status) + if status != "cancelled" { + t.Errorf("the queued Lead is %q", status) + } + if err := Delete(d, "company", co); !errors.Is(err, ErrNotFound) { + t.Errorf("deleting again: %v", err) + } +} diff --git a/internal/seo/audit.go b/internal/seo/audit.go index 6d6b813..665c446 100644 --- a/internal/seo/audit.go +++ b/internal/seo/audit.go @@ -226,7 +226,7 @@ func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property strin traffic := map[string]Numbers{} if property != "" { if from, to, ok := period(d, property, RanksDays); ok { - if rows, err := pageNumbers(d, property, from, to); err == nil { + if rows, err := pageNumbers(d, NewScope(property, siteURL), from, to); err == nil { for _, p := range rows { traffic[normalize(p.Page)] = p.Numbers } diff --git a/internal/seo/briefs.go b/internal/seo/briefs.go index 522623e..801940b 100644 --- a/internal/seo/briefs.go +++ b/internal/seo/briefs.go @@ -19,6 +19,7 @@ import ( "supermarket/internal/db" "supermarket/internal/hugorepo" "supermarket/internal/profile" + "supermarket/internal/slug" ) // Brief statuses. @@ -308,11 +309,7 @@ Answer with JSON only, in this shape: return b, nil } -var nonSlug = regexp.MustCompile(`[^a-z0-9]+`) - -func slugify(s string) string { - return strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(s), "-"), "-") -} +func slugify(s string) string { return slug.Make(s) } // EditBrief saves the user's changes to a brief and their answers. func EditBrief(d *db.DB, id int64, plan Plan, answers []string, pagePath string) error { diff --git a/internal/seo/changes.go b/internal/seo/changes.go index 20d6934..6a5d6ec 100644 --- a/internal/seo/changes.go +++ b/internal/seo/changes.go @@ -248,7 +248,7 @@ func Candidates(d *db.DB, site, property string, now time.Time) ([]Candidate, er out = append(out, c) } if property != "" { - if r, err := WhatRanks(d, property); err == nil && r != nil { + if r, err := WhatRanks(d, NewScope(property, site)); err == nil && r != nil { for _, p := range r.Push { add(Candidate{Page: p.Page, Why: p.Why, Title: true, Desc: true, Traffic: p.Numbers}) } diff --git a/internal/seo/changes_test.go b/internal/seo/changes_test.go index 4cd880a..72c32d8 100644 --- a/internal/seo/changes_test.go +++ b/internal/seo/changes_test.go @@ -116,7 +116,7 @@ func TestChangeLifecycle(t *testing.T) { if _, err := pr.SuggestChanges(ctx, d, site, prop, time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)); err == nil { t.Error("proposed again for the same page") } - if r, _ := Weekly(d, prop, time.Now()); r == nil || len(r.Waiting) != 1 || !strings.Contains(r.Waiting[0].Why, "New title: “Pricing and plans") { + if r, _ := Weekly(d, Scope{Property: prop}, time.Now()); r == nil || len(r.Waiting) != 1 || !strings.Contains(r.Waiting[0].Why, "New title: “Pricing and plans") { t.Errorf("report's waiting list: %+v", r) } if err := EditChange(d, c.ID, "Pricing and plans from $5 · Site", c.NewDescription); err != nil { diff --git a/internal/seo/check.go b/internal/seo/check.go index 7ed047f..794caf3 100644 --- a/internal/seo/check.go +++ b/internal/seo/check.go @@ -88,11 +88,20 @@ func weeks(d *db.DB, site string) (from, to, prevFrom, prevTo string, ok bool) { return t.AddDate(0, 0, -6).Format(dayFormat), to, t.AddDate(0, 0, -13).Format(dayFormat), t.AddDate(0, 0, -7).Format(dayFormat), true } -func siteNumbers(d *db.DB, site, from, to string) (Numbers, error) { +// siteNumbers are the scope's totals. A whole property has its own daily +// totals; a website within one is the sum of its pages. +func siteNumbers(d *db.DB, sc Scope, from, to string) (Numbers, error) { var n Numbers var ps float64 - err := d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0) - FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, site, from, to).Scan(&n.Clicks, &n.Impressions, &ps) + var err error + if len(sc.Hosts) == 0 { + err = d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0) + FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, sc.Property, from, to).Scan(&n.Clicks, &n.Impressions, &ps) + } else { + cond, args := sc.where() + err = d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0) + FROM gsc_page_days WHERE `+cond+` AND date BETWEEN ? AND ?`, append(args, from, to)...).Scan(&n.Clicks, &n.Impressions, &ps) + } n.Position = position(ps, n.Impressions) return n, err } @@ -118,22 +127,23 @@ func grouped(d *db.DB, query string, args ...any) (map[string]Numbers, error) { return out, rows.Err() } -func pagesIn(d *db.DB, site, from, to string) (map[string]Numbers, error) { +func pagesIn(d *db.DB, sc Scope, from, to string) (map[string]Numbers, error) { + cond, args := sc.where() return grouped(d, `SELECT page, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_page_days - WHERE site = ? AND date BETWEEN ? AND ? GROUP BY page`, site, from, to) + WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY page`, append(args, from, to)...) } -func queriesIn(d *db.DB, site, from, to string) (map[string]Numbers, error) { +func queriesIn(d *db.DB, sc Scope, from, to string) (map[string]Numbers, error) { + cond, args := sc.where() return grouped(d, `SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days - WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query`, site, from, to) + WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query`, append(args, from, to)...) } -func pageQueriesIn(d *db.DB, site, page, from, to string) (map[string]Numbers, error) { +func pageQueriesIn(d *db.DB, sc Scope, page, from, to string) (map[string]Numbers, error) { return grouped(d, `SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days - WHERE site = ? AND page = ? AND date BETWEEN ? AND ? GROUP BY query`, site, page, from, to) + WHERE site = ? AND page = ? AND date BETWEEN ? AND ? GROUP BY query`, sc.Property, page, from, to) } -// real decides whether a change passes the thresholds. func (s Settings) real(before, after Numbers) bool { if abs(after.Clicks-before.Clicks) > s.MinClicks { return true @@ -165,17 +175,17 @@ func abs(n int) int { // MorningCheck compares the last 7 days of final data with the 7 before, // by page and by query, and keeps only real moves. It returns nil if there // isn't two weeks of data yet. -func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) { - from, to, pfrom, pto, ok := weeks(d, site) +func MorningCheck(d *db.DB, sc Scope, set Settings) (*Check, error) { + from, to, pfrom, pto, ok := weeks(d, sc.Property) if !ok { return nil, nil } - c := &Check{Site: site, From: from, To: to, PrevFrom: pfrom, PrevTo: pto, Settings: set} + c := &Check{Site: sc.Property, From: from, To: to, PrevFrom: pfrom, PrevTo: pto, Settings: set} var err error - if c.After, err = siteNumbers(d, site, from, to); err != nil { + if c.After, err = siteNumbers(d, sc, from, to); err != nil { return nil, err } - if c.Before, err = siteNumbers(d, site, pfrom, pto); err != nil { + if c.Before, err = siteNumbers(d, sc, pfrom, pto); err != nil { return nil, err } for _, kind := range []string{"page", "query"} { @@ -183,11 +193,11 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) { if kind == "query" { load = queriesIn } - after, err := load(d, site, from, to) + after, err := load(d, sc, from, to) if err != nil { return nil, err } - before, err := load(d, site, pfrom, pto) + before, err := load(d, sc, pfrom, pto) if err != nil { return nil, err } @@ -219,7 +229,7 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) { m.Why = append(m.Why, "No row the week before: new in Search Console this week.") } if kind == "page" && hasA && hasB { - if err := explainPage(d, site, &m, from, to, pfrom, pto, set); err != nil { + if err := explainPage(d, sc, &m, from, to, pfrom, pto, set); err != nil { return nil, err } } @@ -255,12 +265,12 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) { // explainPage says what the page's queries show about its move: which // query's clicks changed most, and whether a position change is real or // comes from Google showing it for a different mix of searches. -func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, set Settings) error { - after, err := pageQueriesIn(d, site, m.Key, from, to) +func explainPage(d *db.DB, sc Scope, m *Move, from, to, pfrom, pto string, set Settings) error { + after, err := pageQueriesIn(d, sc, m.Key, from, to) if err != nil { return err } - before, err := pageQueriesIn(d, site, m.Key, pfrom, pto) + before, err := pageQueriesIn(d, sc, m.Key, pfrom, pto) if err != nil { return err } @@ -302,13 +312,13 @@ func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, se if w > 0 { like := moved / w if math.Abs(like) < math.Abs(m.PosDelta())/2 { - m.Why = append(m.Why, fmt.Sprintf("Like for like it moved %+.1f positions, on the searches it had both weeks. The average moved because Google showed it for a different mix of searches.", like)) + m.Why = append(m.Why, fmt.Sprintf("Like for like it moved %s, on the searches it had both weeks. The average moved because Google showed it for a different mix of searches.", places(like))) if shift != "" { m.Why = append(m.Why, fmt.Sprintf("Biggest change: “%s”, %s.", shift, change(before[shift], after[shift]))) } return nil } - m.Why = append(m.Why, fmt.Sprintf("On the searches it had both weeks it moved %+.1f positions: a real move.", like)) + m.Why = append(m.Why, fmt.Sprintf("On the searches it had both weeks it moved %s: its rankings changed, not just the mix of searches.", places(like))) return nil } if shift != "" { @@ -317,6 +327,19 @@ func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, se return nil } +// places says a change in average position in words: a lower position +// number is higher up the results. +func places(delta float64) string { + switch { + case math.Abs(delta) < 0.05: + return "less than 0.1 places" + case delta < 0: + return fmt.Sprintf("%.1f places up", -delta) + default: + return fmt.Sprintf("%.1f places down", delta) + } +} + func union(a, b map[string]Numbers) map[string]bool { out := map[string]bool{} for k := range a { diff --git a/internal/seo/check_test.go b/internal/seo/check_test.go index a62ce54..9bdd309 100644 --- a/internal/seo/check_test.go +++ b/internal/seo/check_test.go @@ -62,7 +62,7 @@ func TestMorningCheckAndReport(t *testing.T) { }) d.PutJSON(throughKey(site), "2026-11-19") - c, err := MorningCheck(d, site, DefaultSettings) + c, err := MorningCheck(d, Scope{Property: site}, DefaultSettings) if err != nil { t.Fatal(err) } @@ -84,7 +84,7 @@ func TestMorningCheckAndReport(t *testing.T) { // The "best" page lost 21 positions on paper, under one in reality. b := moves["page:"+best] why := strings.Join(b.Why, " ") - if b.PosDelta() < 20 || !strings.Contains(why, "Like for like it moved +0.3") || + if b.PosDelta() < 20 || !strings.Contains(why, "Like for like it moved 0.3 places down") || !strings.Contains(why, "“whey price comparison”, 0 → 0 clicks, 515 → 34 impressions, position 3.0 → 3.9") { t.Errorf("best: %+v %v", b, why) } @@ -100,12 +100,12 @@ func TestMorningCheckAndReport(t *testing.T) { } // Higher thresholds: quiet. - q, _ := MorningCheck(d, site, Settings{MinClicks: 50, MinPositions: 50, MinImpressions: 100000}) + q, _ := MorningCheck(d, Scope{Property: site}, Settings{MinClicks: 50, MinPositions: 50, MinImpressions: 100000}) if !q.Quiet() { t.Errorf("not quiet: %+v", q.Moves) } - rep, err := Weekly(d, site, time.Date(2026, 11, 23, 8, 0, 0, 0, time.UTC)) + rep, err := Weekly(d, Scope{Property: site}, time.Date(2026, 11, 23, 8, 0, 0, 0, time.UTC)) if err != nil { t.Fatal(err) } @@ -148,3 +148,56 @@ func TestWhere(t *testing.T) { } } } + +// A domain property covers every subdomain; a website's scope keeps only +// its own host, with or without www. +func TestScopeKeepsTheWebsite(t *testing.T) { + d := openDB(t) + const site = "sc-domain:whey.example" + week(t, d, site, "2026-11-06", row{clicks: 1000, impr: 5000, pos: 5}, []row{ + {"https://shop.whey.example/", "whey shop", 900, 1000, 1}, + {"https://whey.example/best/", "best whey", 40, 2000, 6}, + {"https://www.whey.example/", "whey", 60, 2000, 3}, + }) + week(t, d, site, "2026-11-13", row{clicks: 1000, impr: 5000, pos: 5}, []row{ + {"https://shop.whey.example/", "whey shop", 900, 1000, 1}, + {"https://whey.example/best/", "best whey", 40, 2000, 6}, + {"https://www.whey.example/", "whey", 60, 2000, 3}, + }) + d.PutJSON(throughKey(site), "2026-11-19") + + sc := NewScope(site, "https://whey.example") + r, err := WhatRanks(d, sc) + if err != nil || r == nil { + t.Fatal(r, err) + } + if r.Total.Clicks != 200 || r.Total.Impressions != 8000 { + t.Errorf("totals include another host: %+v", r.Total) + } + for _, p := range r.Pages { + if !sc.Has(p.Page) { + t.Errorf("page from another host: %s", p.Page) + } + } + if len(r.Pages) != 2 { + t.Errorf("pages: %+v", r.Pages) + } + c, err := MorningCheck(d, sc, DefaultSettings) + if err != nil || c == nil || c.After.Clicks != 100 || c.Pages != 2 || c.Queries != 2 { + t.Errorf("check: %+v %v", c, err) + } + if whole, _ := WhatRanks(d, Scope{Property: site}); whole == nil || whole.Total.Clicks != 2000 { + t.Errorf("whole property: %+v", whole) + } + if !sc.Has("https://www.whey.example/x") || sc.Has("https://shop.whey.example/") || sc.Has("https://whey.example.evil/") { + t.Error("Has") + } +} + +func TestPlaces(t *testing.T) { + for in, want := range map[float64]string{-12.8: "12.8 places up", 0.3: "0.3 places down", 0.01: "less than 0.1 places"} { + if got := places(in); got != want { + t.Errorf("places(%v) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/seo/keywords.go b/internal/seo/keywords.go index 8f954e9..bd9246d 100644 --- a/internal/seo/keywords.go +++ b/internal/seo/keywords.go @@ -166,12 +166,14 @@ func FindKeywords(ctx context.Context, d *db.DB, site, property string, p *profi // answers them, below page two. if property != "" { if from, to, ok := period(d, property, RanksDays); ok { + cond, args := NewScope(property, site).where() + args = append([]any{from, to}, args...) rows, err := d.Query(`SELECT query, sum(impressions), sum(pos_sum), (SELECT page FROM gsc_query_days q2 WHERE q2.site = q.site AND q2.query = q.query AND q2.date BETWEEN ? AND ? GROUP BY page ORDER BY sum(impressions) DESC LIMIT 1) - FROM gsc_query_days q WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query + FROM gsc_query_days q WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query HAVING sum(impressions) >= 20 AND sum(pos_sum) / sum(impressions) > 20 - ORDER BY sum(impressions) DESC LIMIT 200`, from, to, property, from, to) + ORDER BY sum(impressions) DESC LIMIT 200`, append(args, from, to)...) if err != nil { return 0, err } diff --git a/internal/seo/ranks.go b/internal/seo/ranks.go index ec1ba95..bafc724 100644 --- a/internal/seo/ranks.go +++ b/internal/seo/ranks.go @@ -92,30 +92,27 @@ func period(d *db.DB, site string, days int) (from, to string, ok bool) { // WhatRanks works out job 1 for a property, over the last RanksDays days // of final data. It returns nil if nothing is stored yet. -func WhatRanks(d *db.DB, site string) (*Ranks, error) { - from, to, ok := period(d, site, RanksDays) +func WhatRanks(d *db.DB, sc Scope) (*Ranks, error) { + from, to, ok := period(d, sc.Property, RanksDays) if !ok { return nil, nil } - r := &Ranks{Site: site, From: from, To: to, Anonymous: -1} - var posSum float64 - if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0) - FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, site, from, to). - Scan(&r.Total.Clicks, &r.Total.Impressions, &posSum); err != nil { + r := &Ranks{Site: sc.Property, From: from, To: to, Anonymous: -1} + var err error + if r.Total, err = siteNumbers(d, sc, from, to); err != nil { return nil, err } - r.Total.Position = position(posSum, r.Total.Impressions) - + cond, args := sc.where() var named int - if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE site = ? AND date BETWEEN ? AND ?`, - site, from, to).Scan(&named); err != nil { + if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE `+cond+` AND date BETWEEN ? AND ?`, + append(args, from, to)...).Scan(&named); err != nil { return nil, err } if r.Total.Clicks > 0 { r.Anonymous = 100 * float64(r.Total.Clicks-min(named, r.Total.Clicks)) / float64(r.Total.Clicks) } - pages, err := pageNumbers(d, site, from, to) + pages, err := pageNumbers(d, sc, from, to) if err != nil { return nil, err } @@ -127,9 +124,9 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) { } rows, err := d.Query(`SELECT query, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_query_days - WHERE site = ? AND date BETWEEN ? AND ? GROUP BY query + WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query HAVING sum(impressions) > 0 AND 100.0 * sum(clicks) / sum(impressions) < ? - ORDER BY sum(impressions) DESC LIMIT 10`, site, from, to, lowCTR) + ORDER BY sum(impressions) DESC LIMIT 10`, append(args, from, to, lowCTR)...) if err != nil { return nil, err } @@ -167,7 +164,7 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) { break } pick := Pick{Page: p.Page, Numbers: p.Numbers} - if err := mainQuery(d, site, from, to, &pick); err != nil { + if err := mainQuery(d, sc.Property, from, to, &pick); err != nil { return nil, err } pick.Why = fmt.Sprintf("Shown %s times at position %.1f, %s %s.", Thousands(p.Impressions), p.Position, Thousands(p.Clicks), plural(p.Clicks, "click", "clicks")) @@ -180,9 +177,10 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) { } // pageNumbers are every page's numbers over a period, most clicks first. -func pageNumbers(d *db.DB, site, from, to string) ([]PageRow, error) { +func pageNumbers(d *db.DB, sc Scope, from, to string) ([]PageRow, error) { + cond, args := sc.where() rows, err := d.Query(`SELECT page, sum(clicks), sum(impressions), sum(pos_sum) FROM gsc_page_days - WHERE site = ? AND date BETWEEN ? AND ? GROUP BY page ORDER BY sum(clicks) DESC, sum(impressions) DESC`, site, from, to) + WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY page ORDER BY sum(clicks) DESC, sum(impressions) DESC`, append(args, from, to)...) if err != nil { return nil, err } diff --git a/internal/seo/report.go b/internal/seo/report.go index 921b74c..753e88c 100644 --- a/internal/seo/report.go +++ b/internal/seo/report.go @@ -24,16 +24,18 @@ type Report struct { Where string `json:"where"` // where the change came from, in a sentence Pages []Move `json:"pages"` // the 3 pages that moved most Waiting []Pick `json:"waiting"` + // Candidates are the pages worth a proposal, when none is waiting. + Candidates []Pick `json:"candidates,omitempty"` } // Weekly builds the Monday report for the latest week of final data. The // "waiting for your yes" list holds at most 3 items. -func Weekly(d *db.DB, site string, now time.Time) (*Report, error) { - c, err := MorningCheck(d, site, Settings{}) // every change, to rank the pages +func Weekly(d *db.DB, sc Scope, now time.Time) (*Report, error) { + c, err := MorningCheck(d, sc, Settings{}) // every change, to rank the pages if err != nil || c == nil { return nil, err } - r := &Report{Site: site, WeekFrom: c.From, WeekTo: c.To, CreatedAt: now, Before: c.Before, After: c.After} + r := &Report{Site: sc.Property, WeekFrom: c.From, WeekTo: c.To, CreatedAt: now, Before: c.Before, After: c.After} r.Where = where(c.Before, c.After) var pages []Move for _, m := range c.Moves { @@ -59,11 +61,12 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) { pages = pages[:3] } // The causes, from the full check (which explains only real moves). - full, err := MorningCheck(d, site, LoadSettings(d)) + full, err := MorningCheck(d, sc, LoadSettings(d)) if err != nil { return nil, err } for i := range pages { + pages[i].Why = []string{"Under the thresholds for a real move: noise until it lasts."} for _, m := range full.Moves { if m.Kind == "page" && m.Key == pages[i].Key { pages[i].Why = m.Why @@ -73,7 +76,7 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) { r.Pages = pages // The changes proposed for the site, or else the pages to push. rows, err := d.Query(`SELECT `+changeCols+` FROM seo_changes WHERE property = ? AND status = ? ORDER BY id LIMIT ?`, - site, ChangeProposed, MaxWaiting) + sc.Property, ChangeProposed, MaxWaiting) if err != nil { return nil, err } @@ -91,13 +94,15 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) { } r.Waiting = append(r.Waiting, Pick{Page: c.Page, Why: strings.Join(what, " ") + " Why: " + c.Why}) } + // With nothing proposed, the pages worth a proposal, kept apart: they + // aren't waiting for a yes until a change is proposed for them. if len(r.Waiting) == 0 { - ranks, err := WhatRanks(d, site) + ranks, err := WhatRanks(d, sc) if err != nil { return nil, err } if ranks != nil { - r.Waiting = ranks.Push + r.Candidates = ranks.Push } } return r, nil @@ -212,10 +217,16 @@ func (r *Report) Text() string { } b.WriteString("\n3. Waiting for your yes\n") if len(r.Waiting) == 0 { - b.WriteString(" Nothing this week.\n") + b.WriteString(" Nothing is waiting: no change has been proposed.\n") } for i, p := range r.Waiting { fmt.Fprintf(&b, " %d. %s\n %s\n", i+1, p.Page, p.Why) } + if len(r.Candidates) > 0 { + b.WriteString("\n Worth a proposal (Propose changes, on SEO → Changes):\n") + for _, p := range r.Candidates { + fmt.Fprintf(&b, " - %s\n %s\n", p.Page, p.Why) + } + } return b.String() } diff --git a/internal/seo/scope.go b/internal/seo/scope.go new file mode 100644 index 0000000..5d46994 --- /dev/null +++ b/internal/seo/scope.go @@ -0,0 +1,73 @@ +package seo + +import ( + "net/url" + "strings" +) + +// Scope is one website's share of a Search Console property. A domain +// property (sc-domain:example.com) covers every subdomain — a shop, a Gitea, +// a forum — so its rows are narrowed to the website's own host, with or +// without www. With no hosts it's the whole property. +type Scope struct { + Property string + Hosts []string // lower case, without www. +} + +// NewScope is the scope of the website at siteURL within property. Only a +// domain property is narrowed, and only to a host within its domain: a +// URL-prefix property is one site already. +func NewScope(property, siteURL string) Scope { + s := Scope{Property: property} + domain, ok := strings.CutPrefix(strings.ToLower(property), "sc-domain:") + u, err := url.Parse(siteURL) + if !ok || err != nil { + return s + } + host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + if host == domain || strings.HasSuffix(host, "."+domain) { + s.Hosts = []string{host} + } + return s +} + +// Has says whether a page's address is on the website. +func (s Scope) Has(page string) bool { + if len(s.Hosts) == 0 { + return true + } + u, err := url.Parse(page) + if err != nil { + return false + } + h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + for _, want := range s.Hosts { + if h == want { + return true + } + } + return false +} + +// where is the SQL condition for the scope's rows of a gsc_ table, which +// has site and page columns, and its arguments. +func (s Scope) where() (string, []any) { + cond := "site = ?" + args := []any{s.Property} + if len(s.Hosts) == 0 { + return cond, args + } + var ors []string + for _, h := range s.Hosts { + h = likeEscape(h) + for _, prefix := range []string{"https://", "http://", "https://www.", "http://www."} { + ors = append(ors, `page LIKE ? ESCAPE '\'`, `page = ?`) + args = append(args, prefix+h+"/%", prefix+h) + } + } + return cond + " AND (" + strings.Join(ors, " OR ") + ")", args +} + +func likeEscape(s string) string { + return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s) +} diff --git a/internal/seo/seo_test.go b/internal/seo/seo_test.go index 3ed1dc5..64c8673 100644 --- a/internal/seo/seo_test.go +++ b/internal/seo/seo_test.go @@ -86,7 +86,7 @@ func TestSyncAndWhatRanks(t *testing.T) { if err != nil || len(sites) != 1 || sites[0].URL != "sc-domain:whey.example" { t.Fatalf("sites: %+v %v", sites, err) } - if r, _ := WhatRanks(d, "sc-domain:whey.example"); r != nil { + if r, _ := WhatRanks(d, Scope{Property: "sc-domain:whey.example"}); r != nil { t.Error("ranks before any data") } res, err := Sync(context.Background(), d, c, "sc-domain:whey.example", now) @@ -106,7 +106,7 @@ func TestSyncAndWhatRanks(t *testing.T) { t.Errorf("last sync: %+v", last) } - r, err := WhatRanks(d, "sc-domain:whey.example") + r, err := WhatRanks(d, Scope{Property: "sc-domain:whey.example"}) if err != nil { t.Fatal(err) } diff --git a/internal/signals/signals.go b/internal/signals/signals.go index bbc20c8..1614384 100644 --- a/internal/signals/signals.go +++ b/internal/signals/signals.go @@ -9,11 +9,11 @@ import ( "database/sql" "errors" "fmt" - "regexp" "strings" "time" "supermarket/internal/db" + "supermarket/internal/slug" ) // Statuses of a signal, in order. @@ -60,11 +60,9 @@ const timeFormat = time.RFC3339 func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) } -var nonSlug = regexp.MustCompile(`[^a-z0-9]+`) - // Slugify makes a utm_campaign-safe slug from a name. func Slugify(name string) string { - s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(name), "-"), "-") + s := slug.Make(name) if len(s) > 60 { s = strings.TrimRight(s[:60], "-") } diff --git a/internal/slug/slug.go b/internal/slug/slug.go new file mode 100644 index 0000000..f871de1 --- /dev/null +++ b/internal/slug/slug.go @@ -0,0 +1,29 @@ +// Package slug makes the lower-case, hyphenated names used in addresses +// and campaign tags, keeping accented letters as their plain ones +// ("Ünïcode" → "unicode") instead of dropping them. +package slug + +import ( + "regexp" + "strings" + "unicode" + + "golang.org/x/text/unicode/norm" +) + +// Letters that don't come apart into a plain letter and an accent. +var special = strings.NewReplacer("ß", "ss", "æ", "ae", "œ", "oe", "ø", "o", "đ", "d", "ð", "d", "ł", "l", "þ", "th", "ı", "i") + +var nonSlug = regexp.MustCompile(`[^a-z0-9]+`) + +// Make turns s into a slug. +func Make(s string) string { + s = special.Replace(strings.ToLower(s)) + var b strings.Builder + for _, r := range norm.NFD.String(s) { + if !unicode.Is(unicode.Mn, r) { + b.WriteRune(r) + } + } + return strings.Trim(nonSlug.ReplaceAllString(b.String(), "-"), "-") +} diff --git a/internal/slug/slug_test.go b/internal/slug/slug_test.go new file mode 100644 index 0000000..5a197ec --- /dev/null +++ b/internal/slug/slug_test.go @@ -0,0 +1,16 @@ +package slug + +import "testing" + +func TestMake(t *testing.T) { + for in, want := range map[string]string{ + "PW Test Signal Ünïcode & Co.": "pw-test-signal-unicode-co", + "Straße, Æsir, Łódź": "strasse-aesir-lodz", + " Leaving M365 ": "leaving-m365", + "日本": "", + } { + if got := Make(in); got != want { + t.Errorf("Make(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/web/audit_test.go b/internal/web/audit_test.go index 04c7f80..4dd71be 100644 --- a/internal/web/audit_test.go +++ b/internal/web/audit_test.go @@ -49,7 +49,7 @@ func TestAuditPage(t *testing.T) { } time.Sleep(50 * time.Millisecond) } - if rec := do(h, http.MethodGet, "/seo/audit/status?site=0", nil, nil); rec.Header().Get("HX-Refresh") != "true" { + if rec := do(h, http.MethodGet, "/seo/audit/status?site=0", nil, nil); !strings.HasPrefix(rec.Header().Get("HX-Redirect"), "/seo/audit?site=0") { t.Error("the status poll doesn't reload when done") } body := do(h, http.MethodGet, "/seo/audit", nil, nil).Body.String() diff --git a/internal/web/backups.go b/internal/web/backups.go index 1966a00..93a5b19 100644 --- a/internal/web/backups.go +++ b/internal/web/backups.go @@ -187,10 +187,17 @@ func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) { } tmp.Close() if err := backup.Check(tmp.Name()); err != nil { - s.renderBackups(w, r, hdr.Filename+" isn't a backup Supermarket can use: "+err.Error(), "") + s.renderBackups(w, r, hdr.Filename+" isn't a Supermarket backup: "+err.Error()+".", "") return } + // A backup downloaded from here keeps its note, not its whole name. note := "uploaded " + strings.TrimSuffix(filepath.Base(hdr.Filename), ".db") + if b, ok := backup.Parse(filepath.Base(hdr.Filename)); ok { + note = "uploaded " + b.Kind + if b.Note != "" { + note = "uploaded " + b.Note + } + } b, err := backup.Adopt(tmp.Name(), s.backupDir(), note, time.Now()) if err != nil { s.serverError(w, err) diff --git a/internal/web/backups_test.go b/internal/web/backups_test.go index 58bfce4..33a0b8b 100644 --- a/internal/web/backups_test.go +++ b/internal/web/backups_test.go @@ -104,7 +104,7 @@ func TestBackupUpload(t *testing.T) { if !strings.Contains(body, "Uploaded as app-") || !strings.Contains(body, "-manual-uploaded-app-from-laptop.db") { t.Errorf("upload: %s", body) } - if body := upload("notes.txt", []byte("hello")); !strings.Contains(body, "isn't a backup Supermarket can use") { + if body := upload("notes.txt", []byte("hello")); !strings.Contains(body, "isn't a Supermarket backup") { t.Errorf("bad upload: %s", body) } if bs, _ := backup.List(s.backupDir()); len(bs) != 1 { diff --git a/internal/web/briefs_test.go b/internal/web/briefs_test.go index d368d3c..dd28010 100644 --- a/internal/web/briefs_test.go +++ b/internal/web/briefs_test.go @@ -61,7 +61,7 @@ func TestBriefPages(t *testing.T) { if !strings.Contains(body, "We tested it with 12 users.") || !strings.Contains(body, `name="claim" value="We tested it with 12 users."`) { t.Error("the draft or its claim isn't shown") } - if rec := postForm(h, "/seo/briefs/1/pr", url.Values{}); !strings.Contains(rec.Body.String(), "save a Gitea token") { + if rec := postForm(h, "/seo/briefs/1/pr", url.Values{}); !strings.Contains(rec.Body.String(), "Save a Gitea token") { t.Errorf("pr without Gitea: %d", rec.Code) } s.Secrets.Set(map[string]string{secrets.GiteaToken: "tok"}) diff --git a/internal/web/changes.go b/internal/web/changes.go index 6d6c083..5efbe04 100644 --- a/internal/web/changes.go +++ b/internal/web/changes.go @@ -358,6 +358,7 @@ func (s *Server) seoKeywordAction(w http.ResponseWriter, r *http.Request) { } back := "/seo/keywords?site=" + strconv.Itoa(site.Index) + "#k-" + strconv.FormatInt(id, 10) now := time.Now() + var msg string switch r.PathValue("action") { case "top": rs, rerr := s.researcher() @@ -371,12 +372,13 @@ func (s *Server) seoKeywordAction(w http.ResponseWriter, r *http.Request) { return } redirect(w, r, back, "top-read") + return case "pick": - err = seo.SetKeywordStatus(s.DB, id, seo.KeywordPicked, now) + err, msg = seo.SetKeywordStatus(s.DB, id, seo.KeywordPicked, now), "keyword-picked" case "dismiss": - err = seo.SetKeywordStatus(s.DB, id, seo.KeywordDismissed, now) + err, msg = seo.SetKeywordStatus(s.DB, id, seo.KeywordDismissed, now), "keyword-dismissed" case "restore": - err = seo.SetKeywordStatus(s.DB, id, seo.KeywordNew, now) + err, msg = seo.SetKeywordStatus(s.DB, id, seo.KeywordNew, now), "keyword-back" default: http.NotFound(w, r) return @@ -385,5 +387,5 @@ func (s *Server) seoKeywordAction(w http.ResponseWriter, r *http.Request) { s.renderKeywords(w, r, err.Error()) return } - redirect(w, r, back, "saved") + redirect(w, r, back, msg) } diff --git a/internal/web/content_test.go b/internal/web/content_test.go index 76a78e2..3819227 100644 --- a/internal/web/content_test.go +++ b/internal/web/content_test.go @@ -53,7 +53,7 @@ func TestContentPages(t *testing.T) { t.Errorf("write with nothing selected: %d", rec.Code) } rec = postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}}) - if !strings.Contains(rec.Body.String(), "choose at least one channel") { + if !strings.Contains(rec.Body.String(), "Choose at least one channel") { t.Errorf("write without channels:\n%s", rec.Body.String()) } // No AI key: the provider's error is shown. @@ -142,10 +142,10 @@ func TestScheduleFromInbox(t *testing.T) { // 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") { + 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") { + 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()) } @@ -235,7 +235,7 @@ func TestRedditInInbox(t *testing.T) { if d, _ := content.GetDraft(s.DB, mustID(id)); d.Title != "Jitsi 3 is out" || d.Content != "Edited" { t.Errorf("saved: %+v", d) } - if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {""}}); !strings.Contains(rec.Body.String(), "the title is empty") { + if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {""}}); !strings.Contains(rec.Body.String(), "The title is empty") { t.Errorf("empty title: %s", rec.Body.String()) } if rec := postForm(h, "/drafts/"+id+"/publish", nil); !strings.Contains(rec.Body.String(), "Reddit isn't connected") { @@ -271,7 +271,7 @@ func TestWriteRedditNeedsSubreddit(t *testing.T) { } _ = s.Secrets.Set(map[string]string{secrets.AnthropicAPIKey: "k"}) rec := postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}, "channel": {"reddit"}, "subreddit": {" "}}) - if !strings.Contains(rec.Body.String(), "choose a subreddit") { + if !strings.Contains(rec.Body.String(), "Choose a subreddit") { t.Errorf("write without subreddit: %s", rec.Body.String()) } } diff --git a/internal/web/crm.go b/internal/web/crm.go index 5846f46..616964a 100644 --- a/internal/web/crm.go +++ b/internal/web/crm.go @@ -100,6 +100,22 @@ func unreachableError(actions []crm.Action) string { return "" } +// crmBroken says whether the newest finished action failed because +// EspoCRM couldn't be reached (and nothing has got through since). +func crmBroken(actions []crm.Action) bool { + for _, a := range actions { // newest first + switch a.Status { + case crm.StatusDone: + return false + case crm.StatusFailed: + if connErr.MatchString(a.Error) { + return true + } + } + } + return false +} + // crmReach is an htmx fragment shown when Hermes couldn't reach EspoCRM. // Hermes goes through the Core's MCP hub, which connects to EspoCRM with // its own settings; checking EspoCRM from here tells the user which side @@ -167,11 +183,12 @@ func (s *Server) crmAction(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } + msg := "" switch r.PathValue("action") { case "retry": - err = crm.Retry(s.DB, id) + err, msg = crm.Retry(s.DB, id), "crm-retried" case "cancel": - err = crm.Cancel(s.DB, id) + err, msg = crm.Cancel(s.DB, id), "crm-cancelled" default: http.NotFound(w, r) return @@ -184,6 +201,6 @@ func (s *Server) crmAction(w http.ResponseWriter, r *http.Request) { s.serverError(w, err) return } - redirect(w, r, "/crm", "saved") + redirect(w, r, "/crm", msg) } } diff --git a/internal/web/pages.go b/internal/web/pages.go index ca57f61..2b5efaf 100644 --- a/internal/web/pages.go +++ b/internal/web/pages.go @@ -16,6 +16,7 @@ import ( "supermarket/internal/bridge" "supermarket/internal/content" "supermarket/internal/core" + "supermarket/internal/crm" "supermarket/internal/inventory" "supermarket/internal/profile" "supermarket/internal/secrets" @@ -146,6 +147,12 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) { {Label: "Hermes bridge", Done: last != nil, Link: "/settings/core", Detail: ifElse(last != nil, "Last check-in "+ago(atOf(last)), "Hermes hasn't checked in yet")}, } + if actions, err := crm.List(s.DB, 50); err == nil && len(actions) > 0 { + broken := crmBroken(actions) + steps = append(steps, step{Label: "CRM through Hermes", Done: !broken, Link: "/crm", + Detail: ifElse(broken, "Hermes couldn't reach EspoCRM: see the CRM queue for what to send your Core's admin", + "Hermes reaches EspoCRM")}) + } queued, _ := content.CountDrafts(s.DB) scheduled, _ := content.ListDrafts(s.DB, 1000, content.StatusScheduled) diff --git a/internal/web/preview_sprites.go b/internal/web/preview_sprites.go new file mode 100644 index 0000000..61afbbb --- /dev/null +++ b/internal/web/preview_sprites.go @@ -0,0 +1,87 @@ +package web + +import ( + "bytes" + "os" + "path" + "path/filepath" + "regexp" + "strings" +) + +// A preview page is sandboxed, so it has an origin of its own, and a +// browser won't let it draw from a separate +// file: that counts as cross-origin. inlineSprites copies each local sprite +// file the page uses into the page itself, and points the elements +// at the copy, so icons show as they do on the live site. + +var ( + useHref = regexp.MustCompile(`(]*?\b(?:xlink:)?href=")([^"#:]+\.svg)#([^"]+)"`) + svgOpen = regexp.MustCompile(`(?is)^.*?]*>`) + svgClose = regexp.MustCompile(`(?is)\s*$`) + bodyOpen = regexp.MustCompile(`(?i)]*>`) + maxSprite = int64(2 << 20) +) + +// inlineSprites rewrites a page served from dir at urlPath (the page's +// path within the preview, e.g. "/about/"). +func inlineSprites(page []byte, dir, urlPath string) []byte { + base := urlPath + if !strings.HasSuffix(base, "/") { + base = path.Dir(base) + "/" + } + sprites := map[string]string{} // file (within the preview) → its symbols + var order []string + out := useHref.ReplaceAllFunc(page, func(m []byte) []byte { + g := useHref.FindSubmatch(m) + ref := string(g[2]) + file := path.Clean(path.Join(base, ref)) + if strings.HasPrefix(ref, "/") { + file = path.Clean(ref) + } + if _, ok := sprites[file]; !ok { + sprites[file] = readSprite(dir, file) + order = append(order, file) + } + if sprites[file] == "" { + return m + } + return []byte(string(g[1]) + "#" + string(g[3]) + `"`) + }) + var inline strings.Builder + for _, f := range order { + if s := sprites[f]; s != "" { + inline.WriteString(``) + } + } + if inline.Len() == 0 { + return page + } + loc := bodyOpen.FindIndex(out) + if loc == nil { + return page + } + return bytes.Join([][]byte{out[:loc[1]], []byte(inline.String()), out[loc[1]:]}, nil) +} + +// readSprite is the inside of an SVG file in the preview, or "" if it +// isn't one (or isn't inside the preview). +func readSprite(dir, file string) string { + p := filepath.Join(dir, filepath.FromSlash(file)) + if rel, err := filepath.Rel(dir, p); err != nil || strings.HasPrefix(rel, "..") { + return "" + } + st, err := os.Stat(p) + if err != nil || st.IsDir() || st.Size() > maxSprite { + return "" + } + raw, err := os.ReadFile(p) + if err != nil { + return "" + } + s := svgOpen.ReplaceAllString(string(raw), "") + if s == string(raw) { + return "" + } + return svgClose.ReplaceAllString(s, "") +} diff --git a/internal/web/preview_sprites_test.go b/internal/web/preview_sprites_test.go new file mode 100644 index 0000000..4f316b3 --- /dev/null +++ b/internal/web/preview_sprites_test.go @@ -0,0 +1,26 @@ +package web + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestInlineSprites(t *testing.T) { + dir := t.TempDir() + os.MkdirAll(filepath.Join(dir, "images"), 0o755) + os.WriteFile(filepath.Join(dir, "images", "icons.svg"), []byte(``), 0o644) + os.WriteFile(filepath.Join(dir, "secret.svg"), []byte(``), 0o644) + page := []byte(``) + out := string(inlineSprites(page, dir, "/about/")) + if !strings.Contains(out, ``) || !strings.Contains(out, `

no icons

`), dir, "/")) != `

no icons

` { + t.Error("a page without sprites changed") + } +} diff --git a/internal/web/prospects.go b/internal/web/prospects.go index 3785ac0..d2b2457 100644 --- a/internal/web/prospects.go +++ b/internal/web/prospects.go @@ -197,6 +197,8 @@ func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) { if action == "verify" { msg = "verified" } + case "company/delete", "contact/delete": + err, msg = prospects.Delete(s.DB, kind, id), "deleted" case "company/reconsider", "contact/reconsider": err, msg = prospects.Reconsider(s.DB, kind, id), "reconsidered" case "company/suppress": @@ -303,29 +305,32 @@ func (s *Server) prospectAdd(w http.ResponseWriter, r *http.Request) { fail("Give a company, a person, or both.") return } + added := false if d.CompanyID == 0 && hasCompany { if strings.TrimSpace(d.Company.Name) == "" { fail("Give the company's name.") return } - id, _, err := prospects.AddCompany(s.DB, d.Company, now) + id, isNew, err := prospects.AddCompany(s.DB, d.Company, now) if err != nil { fail(addError(err)) return } - d.CompanyID = id + d.CompanyID, added = id, isNew } if hasPerson { d.Contact.CompanyID = d.CompanyID - if _, _, err := prospects.AddContact(s.DB, d.Contact, now); err != nil { + _, isNew, err := prospects.AddContact(s.DB, d.Contact, now) + if err != nil { fail(addError(err)) return } + added = added || isNew } else if d.CompanyID != 0 && !hasCompany { fail("Give the person's name or email.") return } - redirect(w, r, "/prospects", "prospect-added") + redirect(w, r, "/prospects", ifElse(added, "prospect-added", "prospect-exists")) } func addError(err error) string { diff --git a/internal/web/seo.go b/internal/web/seo.go index 9ad7332..6351325 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -89,6 +89,9 @@ type seoSite struct { Last *seo.SyncResult } +// scope narrows the site's Search Console property to the website's host. +func (st seoSite) scope() seo.Scope { return seo.NewScope(st.Property, st.URL) } + func (s *Server) seoSites() []seoSite { p, _ := profile.Load(s.DB) if p == nil { @@ -290,7 +293,7 @@ func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) { data, cur := s.seoBase(r) data["Path"], data["Days"] = "/seo", seo.RanksDays if cur != nil { - ranks, err := seo.WhatRanks(s.DB, cur.Property) + ranks, err := seo.WhatRanks(s.DB, cur.scope()) if err != nil { s.serverError(w, err) return @@ -300,16 +303,22 @@ func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) { s.render(w, r, "seo", page{Title: "SEO", Nav: "seo/ranks", Data: data}) } -// pagePath shows a page's address without the site, for tables. +// pagePath shows a page's address without the site, for tables. A page on +// the www. form of the site keeps its host, so it doesn't look like the +// same page as the one without. func pagePath(u string) string { p, err := url.Parse(u) if err != nil || p.Path == "" { return u } + out := p.Path if p.RawQuery != "" { - return p.Path + "?" + p.RawQuery + out += "?" + p.RawQuery } - return p.Path + if h := strings.ToLower(p.Hostname()); strings.HasPrefix(h, "www.") { + out = h + out + } + return out } // seoCurrent is the site the request asks for (?site=), or the first. @@ -347,7 +356,7 @@ func (s *Server) seoCheckPage(w http.ResponseWriter, r *http.Request) { data, cur := s.seoBase(r) data["Path"] = "/seo/check" if cur != nil { - c, err := seo.MorningCheck(s.DB, cur.Property, seo.LoadSettings(s.DB)) + c, err := seo.MorningCheck(s.DB, cur.scope(), seo.LoadSettings(s.DB)) if err != nil { s.serverError(w, err) return @@ -413,7 +422,7 @@ func (s *Server) seoReportWrite(w http.ResponseWriter, r *http.Request) { // writeReport builds and stores a site's report, and emails it if the // settings say so (and email is set up). func (s *Server) writeReport(ctx context.Context, site seoSite, email bool) (*seo.Report, error) { - rep, err := seo.Weekly(s.DB, site.Property, time.Now()) + rep, err := seo.Weekly(s.DB, site.scope(), time.Now()) if err != nil || rep == nil { return rep, err } @@ -590,7 +599,16 @@ func (s *Server) seoAuditStatus(w http.ResponseWriter, r *http.Request) { return } if a == nil || a.Status != "running" { - w.Header().Set("HX-Refresh", "true") + // Reload without the "Auditing…" message the page was opened with. + msg := "audited" + if a != nil && a.Status == "failed" { + msg = "" + } + target := "/seo/audit?site=" + strconv.Itoa(cur.Index) + if msg != "" { + target += "&msg=" + msg + } + w.Header().Set("HX-Redirect", target) } w.Write([]byte("")) } diff --git a/internal/web/server.go b/internal/web/server.go index dfbaf69..b01566a 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -16,6 +16,8 @@ import ( "strings" "sync" "time" + "unicode" + "unicode/utf8" "supermarket/internal/api/reddit" "supermarket/internal/api/twitter" @@ -484,8 +486,9 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p p.NewProspects = s.newProspects() p.Drafts = s.outreachDrafts() if p.Flash == "" { - p.Flash = flashes[r.URL.Query().Get("msg")] + p.Flash = flashText(r.URL.Query()) } + p.Error = sentence(p.Error) w.Header().Set("Content-Type", "text/html; charset=utf-8") if err := t.ExecuteTemplate(w, "layout.html", p); err != nil { s.Log.Error("render", "page", name, "err", err) @@ -525,6 +528,10 @@ var flashes = map[string]string{ "proposed": "Proposed: read each one, edit it if you like, then say yes or no.", "approved": "Approved: Supermarket is making the pull request; it shows here in a minute.", "declined": "Declined.", + "keyword-picked": "Picked. Write its brief when you're ready.", + "keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.", + "keyword-back": "Back among the candidates.", + "audited": "The audit is done.", "auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.", "no-data": "There isn't two weeks of Search Console data yet.", "reddit-connected": "Reddit is connected.", @@ -536,10 +543,14 @@ var flashes = map[string]string{ "suppressed": "Added to the suppression list.", "unsuppressed": "Taken off the suppression list.", "prospect-added": "Added. Review it below.", + "crm-retried": "Queued again: Hermes tries it on its next run.", + "crm-cancelled": "Taken back: Hermes won't do it.", + "prospect-exists": "Already there: nothing new was added. It's in the list below.", "outcome": "Outcome recorded.", "discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.", "rules-refreshed": "Rules refreshed.", "imported": "Imported.", + "imported-counts": "Imported: %d new steps in the funnel, %d new people to review, %d new on the suppression list.", "hunter-done": "Hunter.io search done: the result is on the card.", "verified": "Checked with Hunter.io: the result is on each person.", "drafted-outreach": "Drafted. Read it, edit it, then queue it to send.", @@ -561,6 +572,48 @@ var flashes = map[string]string{ "unscheduled": "Back in Posts: edit it, then publish or schedule it again.", } +// sentence starts a message with a capital letter: errors from deeper +// down are written in lower case, to be wrapped. +func sentence(msg string) string { + r, n := utf8.DecodeRuneInString(msg) + if n == 0 || !unicode.IsLower(r) { + return msg + } + return string(unicode.ToUpper(r)) + msg[n:] +} + +// flashText is the message a redirect asked for (?msg=), from the fixed +// list. A message with %d verbs takes its numbers from n1, n2… (digits +// only), so nothing but a number can be put into it from the address. +func flashText(q url.Values) string { + msg := flashes[q.Get("msg")] + if n := strings.Count(msg, "%d"); n > 0 { + args := make([]any, n) + for i := range args { + v, _ := strconv.Atoi(q.Get("n" + strconv.Itoa(i+1))) + args[i] = v + } + msg = fmt.Sprintf(msg, args...) + } + return msg +} + +// redirectCounts redirects with a message that has numbers in it. +func redirectCounts(w http.ResponseWriter, r *http.Request, path, msg string, counts ...int) { + base, frag, hasFrag := strings.Cut(path, "#") + for i, c := range counts { + sep := "?" + if strings.Contains(base, "?") { + sep = "&" + } + base += sep + "n" + strconv.Itoa(i+1) + "=" + strconv.Itoa(c) + } + if hasFrag { + base += "#" + frag + } + redirect(w, r, base, msg) +} + func redirect(w http.ResponseWriter, r *http.Request, path, msg string) { if msg != "" { // The message goes in the query, before any #fragment. diff --git a/internal/web/signals.go b/internal/web/signals.go index f778110..931eb0e 100644 --- a/internal/web/signals.go +++ b/internal/web/signals.go @@ -470,7 +470,7 @@ func (s *Server) importSource(w http.ResponseWriter, r *http.Request) { s.renderSignals(w, r, "Importing from "+source+": "+err.Error()) return } - redirect(w, r, "/signals#campaigns", "imported") + redirectCounts(w, r, "/signals#campaigns", "imported-counts", res.Events, res.Prospects, res.Suppressed) } // runImport imports from one tool, if its key is saved. It returns nil, nil diff --git a/internal/web/sites.go b/internal/web/sites.go index 125b90f..0828708 100644 --- a/internal/web/sites.go +++ b/internal/web/sites.go @@ -6,6 +6,7 @@ import ( "net/http" "net/url" "os" + "path" "path/filepath" "strconv" "strings" @@ -344,9 +345,11 @@ func (s *Server) sitesPreviewDelete(w http.ResponseWriter, r *http.Request) { // pages, scripts and all, but whatever a branch holds mustn't be able to // act on Supermarket: sandbox gives each page an origin of its own, so // its requests to the app are cross-site (and refused), and nothing is -// sent anywhere else (no analytics from previews). +// sent anywhere else (no analytics from previews). Stylesheets and fonts +// may come from elsewhere, as web fonts do, so the page looks like the +// live one; scripts may not. const previewCSP = "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; default-src 'self'; " + - "img-src 'self' data: https:; media-src 'self' https:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; " + + "img-src 'self' data: https:; media-src 'self' https:; font-src 'self' data: https:; style-src 'self' 'unsafe-inline' https:; " + "script-src 'self' 'unsafe-inline'; connect-src 'none'; form-action 'none'; frame-ancestors 'none'" // previewServe serves a built preview. @@ -381,7 +384,22 @@ func (s *Server) previewServe(w http.ResponseWriter, r *http.Request) { h.Set("Content-Security-Policy", previewCSP) h.Set("Cache-Control", "no-store") prefix := strings.TrimSuffix(previewPrefix(site, slug), "/") - http.StripPrefix(prefix, http.FileServer(noListing{http.Dir(s.previewDir(cur.Repo, slug))})).ServeHTTP(w, r) + dir := s.previewDir(cur.Repo, slug) + // A page gets the site's icon sprites inlined (see inlineSprites). + if rest := strings.TrimPrefix(r.URL.Path, prefix); rest != r.URL.Path && !strings.Contains(rest, "..") { + file := rest + if strings.HasSuffix(file, "/") { + file += "index.html" + } + if strings.HasSuffix(file, ".html") { + if raw, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(path.Clean(file)))); err == nil { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write(inlineSprites(raw, dir, rest)) + return + } + } + } + http.StripPrefix(prefix, http.FileServer(noListing{http.Dir(dir)})).ServeHTTP(w, r) } // noListing serves files, and folders only through their index.html. diff --git a/internal/web/sites_test.go b/internal/web/sites_test.go index f450350..00c7203 100644 --- a/internal/web/sites_test.go +++ b/internal/web/sites_test.go @@ -284,7 +284,7 @@ func TestSitePageBuilder(t *testing.T) { } // The claim must be confirmed before the pull request. - if body := postForm(h, "/sites/pages/1/pr", form(good)).Body.String(); !strings.Contains(body, "confirm or remove this claim first") || len(pulls) != 0 { + if body := postForm(h, "/sites/pages/1/pr", form(good)).Body.String(); !strings.Contains(body, "Confirm or remove this claim first") || len(pulls) != 0 { t.Errorf("unconfirmed: %s", body) } body = postForm(h, "/sites/pages/1/pr", form(good, "We tested it with our own team.")).Body.String() diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 456c604..0547fea 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -464,3 +464,4 @@ input[type="color"] { height: 2.6rem; padding: 0.25rem; cursor: pointer; } .nav-sum { margin-left: auto; } .nav-row:not(.collapsed) .nav-sum { display: none; } .nav .nav-toggle:active { transform: none; } +.nav .nav-toggle:disabled, .nav .nav-toggle:disabled:hover { opacity: 0.35; cursor: default; background: transparent; color: hsl(var(--muted-foreground)); } diff --git a/internal/web/static/app.js b/internal/web/static/app.js index 16fb70e..d02c29d 100644 --- a/internal/web/static/app.js +++ b/internal/web/static/app.js @@ -161,7 +161,14 @@ total.title = sum + " waiting"; total.hidden = false; } - set(sub, btn, sub.hasAttribute("data-current") || state[sub.dataset.subnav] === true); + if (sub.hasAttribute("data-current")) { + // The module you're in stays open: its chevron shows it, but doesn't fold it. + set(sub, btn, true); + btn.disabled = true; + btn.title = "Open while you're in it"; + return; + } + set(sub, btn, state[sub.dataset.subnav] === true); btn.addEventListener("click", function () { var open = sub.hidden; set(sub, btn, open); diff --git a/internal/web/templates/ai.html b/internal/web/templates/ai.html index 12d12e7..990c3ae 100644 --- a/internal/web/templates/ai.html +++ b/internal/web/templates/ai.html @@ -27,7 +27,7 @@ Supermarket runs in Docker: for a server on this computer use http://host.docker.internal:11434, and use an IP address rather than a .local name. {{range .Servers}}{{end}} {{if .Servers}}

Found by CoreDesktop's configure ai-servers: {{range $i, $s := .Servers}}{{if $i}}, {{end}}{{$s.Name}} ({{$s.BaseURL}}){{end}}.

{{end}} - + Asking the server…
{{range .Keys}}{{if eq .Group "openai"}}{{template "key-field" (dict "F" . "Set" (index $set .Name))}}{{end}}{{end}} @@ -55,7 +55,7 @@
- + Asking the model…

Test uses the provider and model in the form, and the keys already saved: save a new key before testing it.

diff --git a/internal/web/templates/core.html b/internal/web/templates/core.html index 537803d..9a83e65 100644 --- a/internal/web/templates/core.html +++ b/internal/web/templates/core.html @@ -17,7 +17,7 @@

Hermes bridge

Hermes, CoreDesktop's agent, is the only thing that talks to your Core's MCP hub. It reaches Supermarket through the socket {{.MCPSocket}}; other agents, such as Claude Code, use {{.MCPURL}} with the MCP token.

{{with .Last}} -

Hermes last checked in {{ago .At}}{{if .Note}}: “{{.Note}}”{{end}}.

+

Hermes last checked in {{ago .At}}.{{if .Note}} It said: “{{.Note}}”{{end}}

{{if .MCPHubTools}}
It can use {{len .MCPHubTools}} tools from the MCP hub
    {{range .MCPHubTools}}
  • {{.}}
  • {{end}}
diff --git a/internal/web/templates/email.html b/internal/web/templates/email.html index a5fb08b..13e1ae7 100644 --- a/internal/web/templates/email.html +++ b/internal/web/templates/email.html @@ -58,7 +58,7 @@

Check

Signs in to both servers and looks up your domain's SPF, DKIM and DMARC records, which decide whether outreach reaches the inbox. Nothing is sent.

- +
Checking…
diff --git a/internal/web/templates/prospects.html b/internal/web/templates/prospects.html index e3bc3c2..2dd7722 100644 --- a/internal/web/templates/prospects.html +++ b/internal/web/templates/prospects.html @@ -58,6 +58,7 @@ {{else}}
{{end}} +
{{end}} @@ -141,6 +142,7 @@ {{else}}
{{end}} +
{{end}} diff --git a/internal/web/templates/search-engines.html b/internal/web/templates/search-engines.html index 80da90b..3b63815 100644 --- a/internal/web/templates/search-engines.html +++ b/internal/web/templates/search-engines.html @@ -46,7 +46,7 @@ {{template "key-field" (dict "F" .GiteaKey "Set" .GiteaSet)}} {{if .GiteaSet}} - + Checking…
{{end}} diff --git a/internal/web/templates/seo-keywords.html b/internal/web/templates/seo-keywords.html index 5bab4ac..ccfc539 100644 --- a/internal/web/templates/seo-keywords.html +++ b/internal/web/templates/seo-keywords.html @@ -42,7 +42,8 @@ {{if ne .Status "picked"}}
{{else}}
{{end}} {{if eq .Status "dismissed"}}
- {{else}}
{{end}} + {{else}}{{if eq .Status "picked"}}
{{end}} +
{{end}} {{if .Top}} diff --git a/internal/web/templates/seo-report.html b/internal/web/templates/seo-report.html index 631c5b3..f8be1cd 100644 --- a/internal/web/templates/seo-report.html +++ b/internal/web/templates/seo-report.html @@ -33,8 +33,13 @@

3. Waiting for your yes

{{range .Waiting}}

{{pagePath .Page}}
{{.Why}}

- {{else}}

Nothing this week.

{{end}} -

Say yes or no to each on Changes: a yes opens a pull request.

+ {{else}}

Nothing is waiting: no change has been proposed.

{{end}} + {{if .Waiting}}

Say yes or no to each on Changes: a yes opens a pull request.

{{end}} + {{with .Candidates}} +

Worth a proposal

+ {{range .}}

{{pagePath .Page}}
{{.Why}}

{{end}} +

Propose changes on Changes writes new wording for pages like these.

+ {{end}} {{else}}

No report yet. It's written on Monday once there are two weeks of data, or now with Write it now.

diff --git a/internal/web/templates/sources.html b/internal/web/templates/sources.html index 08d612d..71dea11 100644 --- a/internal/web/templates/sources.html +++ b/internal/web/templates/sources.html @@ -12,7 +12,7 @@ If your organization has projects, the ID of the one to read. Leave empty to read the whole organization. {{end}} {{if .Set}} - + Checking…
{{end}} @@ -36,7 +36,7 @@ {{if .Set}} - + Checking…
{{end}} diff --git a/internal/web/templates/tracking.html b/internal/web/templates/tracking.html index e5a0ce5..4a5bbbc 100644 --- a/internal/web/templates/tracking.html +++ b/internal/web/templates/tracking.html @@ -11,7 +11,7 @@

Sites read: {{if .Sites}}{{range $i, $s := .Sites}}{{if $i}}, {{end}}{{$s}}{{end}}{{else}}none yet: add your websites (and their Plausible site, if it differs from the domain) to the profile{{end}}.

{{if .PlausibleSet}}
- + Checking…
@@ -35,7 +35,7 @@ metadata[utm_content] = optional: which message or post
{{if .StripeSet}}
- + Checking…