Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop, Gitea and forum were counted as the website. What ranks, the morning check, the Monday report, keywords, change candidates and the audit's traffic now read only the website's own host (with or without www). The report keeps pages worth a proposal apart from "Waiting for your yes", explains only moves past the thresholds, and says "places up/down". Also: - Feed summaries drop the posts' scripts and styles. - Spend you log can't be negative. - Test and check buttons can't be clicked twice while they run. - Previews show the site's web fonts and icon sprites. - Backups are read without leaving -wal/-shm files; deleting one removes them, and leftovers are swept at start. - The Overview's setup flags a CRM that Hermes can't reach. - Import now says what came in; adding a prospect that exists says so; prospects can be deleted. - Signal tags and brief addresses keep accented letters (Ü → u). - Page errors start with a capital; clearer messages for bad uploads, CRM retry and cancel, keywords, and the finished audit. - The module you're in stays unfolded in the sidebar. - A picked keyword can be unpicked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -98,6 +98,9 @@ func run(log *slog.Logger) error {
|
|||||||
}); n > 0 {
|
}); n > 0 {
|
||||||
log.Info("backups: moved old copies into the backups folder", "count", n)
|
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 {
|
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())
|
b, err := backup.Make(d, backup.Dir(dataDir), backup.Migration, fmt.Sprintf("before-schema-%d", to), time.Now())
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ require (
|
|||||||
github.com/emersion/go-message v0.18.2
|
github.com/emersion/go-message v0.18.2
|
||||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||||
golang.org/x/net v0.63.0
|
golang.org/x/net v0.63.0
|
||||||
|
golang.org/x/text v0.44.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
modernc.org/sqlite v1.62.0
|
modernc.org/sqlite v1.62.0
|
||||||
)
|
)
|
||||||
@@ -42,7 +43,6 @@ require (
|
|||||||
golang.org/x/oauth2 v0.35.0 // indirect
|
golang.org/x/oauth2 v0.35.0 // indirect
|
||||||
golang.org/x/sync v0.25.0 // indirect
|
golang.org/x/sync v0.25.0 // indirect
|
||||||
golang.org/x/sys v0.50.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
|
golang.org/x/time v0.15.0 // indirect
|
||||||
modernc.org/libc v1.80.1 // indirect
|
modernc.org/libc v1.80.1 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
|||||||
+12
-3
@@ -174,14 +174,23 @@ func itemID(key string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
// Elements whose text isn't text: a post's own scripts and styles.
|
||||||
|
code = regexp.MustCompile(`(?is)<(script|style|noscript|template)\b[^>]*>.*?</(script|style|noscript|template)\s*>`)
|
||||||
tags = regexp.MustCompile(`(?s)<[^>]*>`)
|
tags = regexp.MustCompile(`(?s)<[^>]*>`)
|
||||||
spaces = 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 {
|
func clean(s string, n int) string {
|
||||||
s = tags.ReplaceAllString(s, " ")
|
strip := func(s string) string { return tags.ReplaceAllString(code.ReplaceAllString(s, " "), " ") }
|
||||||
s = html.UnescapeString(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, " "))
|
s = strings.TrimSpace(spaces.ReplaceAllString(s, " "))
|
||||||
if r := []rune(s); len(r) > n {
|
if r := []rune(s); len(r) > n {
|
||||||
s = string(r[:n-1]) + "…"
|
s = string(r[:n-1]) + "…"
|
||||||
|
|||||||
@@ -57,3 +57,14 @@ func TestParseRejectsHTML(t *testing.T) {
|
|||||||
t.Fatal("expected an error for an HTML page")
|
t.Fatal("expected an error for an HTML page")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCleanDropsScripts(t *testing.T) {
|
||||||
|
in := `<p>Table</p><script>document.addEventListener('DOMContentLoaded', function () { var x = 1; });</script>
|
||||||
|
<style>.nc-toc { color: red }</style><p>How to set up & share</p>`
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -135,9 +135,11 @@ func (b *Backup) read() {
|
|||||||
b.Schema = v
|
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) {
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -154,11 +156,17 @@ func SchemaOf(path string) (int, error) {
|
|||||||
defer d.Close()
|
defer d.Close()
|
||||||
var v int
|
var v int
|
||||||
if err := d.QueryRow(`PRAGMA user_version`).Scan(&v); err != nil {
|
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
|
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
|
// Check checks a database file: SQLite's integrity check, and that it's a
|
||||||
// Supermarket database (it has the settings table).
|
// Supermarket database (it has the settings table).
|
||||||
func Check(path string) error {
|
func Check(path string) error {
|
||||||
@@ -169,14 +177,14 @@ func Check(path string) error {
|
|||||||
defer d.Close()
|
defer d.Close()
|
||||||
var res string
|
var res string
|
||||||
if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&res); err != nil {
|
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" {
|
if res != "ok" {
|
||||||
return fmt.Errorf("the database is damaged: %s", res)
|
return fmt.Errorf("the database is damaged: %s", res)
|
||||||
}
|
}
|
||||||
var n int
|
var n int
|
||||||
if err := d.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'settings'`).Scan(&n); err != nil || n == 0 {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
@@ -223,13 +231,37 @@ func Find(dir, name string) (*Backup, error) {
|
|||||||
return nil, os.ErrNotExist
|
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 {
|
func Delete(dir, name string) error {
|
||||||
b, err := Find(dir, name)
|
b, err := Find(dir, name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
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
|
// 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 {
|
if err := os.Remove(b.Path); err != nil {
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
removeSidecars(b.Path)
|
||||||
n++
|
n++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
RemoveOrphans(dir)
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ func TestCheckNotSupermarket(t *testing.T) {
|
|||||||
d, _ := sql.Open("sqlite", "file:"+path)
|
d, _ := sql.Open("sqlite", "file:"+path)
|
||||||
d.Exec(`CREATE TABLE x (y)`)
|
d.Exec(`CREATE TABLE x (y)`)
|
||||||
d.Close()
|
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)
|
t.Errorf("check: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -190,3 +190,37 @@ func TestAdoptLegacy(t *testing.T) {
|
|||||||
t.Errorf("second run moved %d", n)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func TestStageAndApply(t *testing.T) {
|
|||||||
nd.Close()
|
nd.Close()
|
||||||
junk := filepath.Join(t.TempDir(), "junk.db")
|
junk := filepath.Join(t.TempDir(), "junk.db")
|
||||||
os.WriteFile(junk, []byte("junk"), 0o600)
|
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) {
|
if _, err := Stage(cur, data, src, 24, now); err == nil || !strings.Contains(err.Error(), want) {
|
||||||
t.Errorf("%s: %v", src, err)
|
t.Errorf("%s: %v", src, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,13 +97,17 @@ func SpendLog(d *db.DB, limit int) ([]Spend, error) {
|
|||||||
return out, rows.Err()
|
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) {
|
func ParseAmount(s string) (int64, error) {
|
||||||
s = strings.NewReplacer("$", "", ",", "", " ", "").Replace(strings.TrimSpace(s))
|
s = strings.NewReplacer("$", "", ",", "", " ", "").Replace(strings.TrimSpace(s))
|
||||||
f, err := strconv.ParseFloat(s, 64)
|
f, err := strconv.ParseFloat(s, 64)
|
||||||
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) {
|
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) {
|
||||||
return 0, fmt.Errorf("%q isn't an amount", s)
|
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
|
return int64(math.Round(f * 100)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ func TestSpendLog(t *testing.T) {
|
|||||||
t.Errorf("accepted %+v", bad)
|
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 {
|
if c, err := ParseAmount("$1,250.50"); err != nil || c != 125050 {
|
||||||
t.Errorf("amount: %d %v", c, err)
|
t.Errorf("amount: %d %v", c, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -998,3 +998,79 @@ func Search(d *db.DB, words []string, limit int) ([]Company, []Contact, error) {
|
|||||||
contacts, err := scanContacts(rows)
|
contacts, err := scanContacts(rows)
|
||||||
return companies, contacts, err
|
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()
|
||||||
|
}
|
||||||
|
|||||||
@@ -248,3 +248,41 @@ func TestAddWithoutEmails(t *testing.T) {
|
|||||||
t.Error("a namesake without a company was merged")
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property strin
|
|||||||
traffic := map[string]Numbers{}
|
traffic := map[string]Numbers{}
|
||||||
if property != "" {
|
if property != "" {
|
||||||
if from, to, ok := period(d, property, RanksDays); ok {
|
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 {
|
for _, p := range rows {
|
||||||
traffic[normalize(p.Page)] = p.Numbers
|
traffic[normalize(p.Page)] = p.Numbers
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
"supermarket/internal/db"
|
"supermarket/internal/db"
|
||||||
"supermarket/internal/hugorepo"
|
"supermarket/internal/hugorepo"
|
||||||
"supermarket/internal/profile"
|
"supermarket/internal/profile"
|
||||||
|
"supermarket/internal/slug"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Brief statuses.
|
// Brief statuses.
|
||||||
@@ -308,11 +309,7 @@ Answer with JSON only, in this shape:
|
|||||||
return b, nil
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
|
func slugify(s string) string { return slug.Make(s) }
|
||||||
|
|
||||||
func slugify(s string) string {
|
|
||||||
return strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(s), "-"), "-")
|
|
||||||
}
|
|
||||||
|
|
||||||
// EditBrief saves the user's changes to a brief and their answers.
|
// 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 {
|
func EditBrief(d *db.DB, id int64, plan Plan, answers []string, pagePath string) error {
|
||||||
|
|||||||
@@ -248,7 +248,7 @@ func Candidates(d *db.DB, site, property string, now time.Time) ([]Candidate, er
|
|||||||
out = append(out, c)
|
out = append(out, c)
|
||||||
}
|
}
|
||||||
if property != "" {
|
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 {
|
for _, p := range r.Push {
|
||||||
add(Candidate{Page: p.Page, Why: p.Why, Title: true, Desc: true, Traffic: p.Numbers})
|
add(Candidate{Page: p.Page, Why: p.Why, Title: true, Desc: true, Traffic: p.Numbers})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
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")
|
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)
|
t.Errorf("report's waiting list: %+v", r)
|
||||||
}
|
}
|
||||||
if err := EditChange(d, c.ID, "Pricing and plans from $5 · Site", c.NewDescription); err != nil {
|
if err := EditChange(d, c.ID, "Pricing and plans from $5 · Site", c.NewDescription); err != nil {
|
||||||
|
|||||||
+46
-23
@@ -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
|
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 n Numbers
|
||||||
var ps float64
|
var ps float64
|
||||||
err := d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0)
|
var err error
|
||||||
FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, site, from, to).Scan(&n.Clicks, &n.Impressions, &ps)
|
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)
|
n.Position = position(ps, n.Impressions)
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
@@ -118,22 +127,23 @@ func grouped(d *db.DB, query string, args ...any) (map[string]Numbers, error) {
|
|||||||
return out, rows.Err()
|
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
|
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
|
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
|
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 {
|
func (s Settings) real(before, after Numbers) bool {
|
||||||
if abs(after.Clicks-before.Clicks) > s.MinClicks {
|
if abs(after.Clicks-before.Clicks) > s.MinClicks {
|
||||||
return true
|
return true
|
||||||
@@ -165,17 +175,17 @@ func abs(n int) int {
|
|||||||
// MorningCheck compares the last 7 days of final data with the 7 before,
|
// 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
|
// by page and by query, and keeps only real moves. It returns nil if there
|
||||||
// isn't two weeks of data yet.
|
// isn't two weeks of data yet.
|
||||||
func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) {
|
func MorningCheck(d *db.DB, sc Scope, set Settings) (*Check, error) {
|
||||||
from, to, pfrom, pto, ok := weeks(d, site)
|
from, to, pfrom, pto, ok := weeks(d, sc.Property)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, nil
|
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
|
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
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, kind := range []string{"page", "query"} {
|
for _, kind := range []string{"page", "query"} {
|
||||||
@@ -183,11 +193,11 @@ func MorningCheck(d *db.DB, site string, set Settings) (*Check, error) {
|
|||||||
if kind == "query" {
|
if kind == "query" {
|
||||||
load = queriesIn
|
load = queriesIn
|
||||||
}
|
}
|
||||||
after, err := load(d, site, from, to)
|
after, err := load(d, sc, from, to)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
before, err := load(d, site, pfrom, pto)
|
before, err := load(d, sc, pfrom, pto)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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.")
|
m.Why = append(m.Why, "No row the week before: new in Search Console this week.")
|
||||||
}
|
}
|
||||||
if kind == "page" && hasA && hasB {
|
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
|
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
|
// 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
|
// query's clicks changed most, and whether a position change is real or
|
||||||
// comes from Google showing it for a different mix of searches.
|
// 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 {
|
func explainPage(d *db.DB, sc Scope, m *Move, from, to, pfrom, pto string, set Settings) error {
|
||||||
after, err := pageQueriesIn(d, site, m.Key, from, to)
|
after, err := pageQueriesIn(d, sc, m.Key, from, to)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
before, err := pageQueriesIn(d, site, m.Key, pfrom, pto)
|
before, err := pageQueriesIn(d, sc, m.Key, pfrom, pto)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -302,13 +312,13 @@ func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, se
|
|||||||
if w > 0 {
|
if w > 0 {
|
||||||
like := moved / w
|
like := moved / w
|
||||||
if math.Abs(like) < math.Abs(m.PosDelta())/2 {
|
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 != "" {
|
if shift != "" {
|
||||||
m.Why = append(m.Why, fmt.Sprintf("Biggest change: “%s”, %s.", shift, change(before[shift], after[shift])))
|
m.Why = append(m.Why, fmt.Sprintf("Biggest change: “%s”, %s.", shift, change(before[shift], after[shift])))
|
||||||
}
|
}
|
||||||
return nil
|
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
|
return nil
|
||||||
}
|
}
|
||||||
if shift != "" {
|
if shift != "" {
|
||||||
@@ -317,6 +327,19 @@ func explainPage(d *db.DB, site string, m *Move, from, to, pfrom, pto string, se
|
|||||||
return nil
|
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 {
|
func union(a, b map[string]Numbers) map[string]bool {
|
||||||
out := map[string]bool{}
|
out := map[string]bool{}
|
||||||
for k := range a {
|
for k := range a {
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ func TestMorningCheckAndReport(t *testing.T) {
|
|||||||
})
|
})
|
||||||
d.PutJSON(throughKey(site), "2026-11-19")
|
d.PutJSON(throughKey(site), "2026-11-19")
|
||||||
|
|
||||||
c, err := MorningCheck(d, site, DefaultSettings)
|
c, err := MorningCheck(d, Scope{Property: site}, DefaultSettings)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -84,7 +84,7 @@ func TestMorningCheckAndReport(t *testing.T) {
|
|||||||
// The "best" page lost 21 positions on paper, under one in reality.
|
// The "best" page lost 21 positions on paper, under one in reality.
|
||||||
b := moves["page:"+best]
|
b := moves["page:"+best]
|
||||||
why := strings.Join(b.Why, " ")
|
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") {
|
!strings.Contains(why, "“whey price comparison”, 0 → 0 clicks, 515 → 34 impressions, position 3.0 → 3.9") {
|
||||||
t.Errorf("best: %+v %v", b, why)
|
t.Errorf("best: %+v %v", b, why)
|
||||||
}
|
}
|
||||||
@@ -100,12 +100,12 @@ func TestMorningCheckAndReport(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Higher thresholds: quiet.
|
// 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() {
|
if !q.Quiet() {
|
||||||
t.Errorf("not quiet: %+v", q.Moves)
|
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 {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -166,12 +166,14 @@ func FindKeywords(ctx context.Context, d *db.DB, site, property string, p *profi
|
|||||||
// answers them, below page two.
|
// answers them, below page two.
|
||||||
if property != "" {
|
if property != "" {
|
||||||
if from, to, ok := period(d, property, RanksDays); ok {
|
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),
|
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 ?
|
(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)
|
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
|
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 {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-17
@@ -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
|
// WhatRanks works out job 1 for a property, over the last RanksDays days
|
||||||
// of final data. It returns nil if nothing is stored yet.
|
// of final data. It returns nil if nothing is stored yet.
|
||||||
func WhatRanks(d *db.DB, site string) (*Ranks, error) {
|
func WhatRanks(d *db.DB, sc Scope) (*Ranks, error) {
|
||||||
from, to, ok := period(d, site, RanksDays)
|
from, to, ok := period(d, sc.Property, RanksDays)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
r := &Ranks{Site: site, From: from, To: to, Anonymous: -1}
|
r := &Ranks{Site: sc.Property, From: from, To: to, Anonymous: -1}
|
||||||
var posSum float64
|
var err error
|
||||||
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0), coalesce(sum(impressions), 0), coalesce(sum(pos_sum), 0)
|
if r.Total, err = siteNumbers(d, sc, from, to); err != nil {
|
||||||
FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ?`, site, from, to).
|
|
||||||
Scan(&r.Total.Clicks, &r.Total.Impressions, &posSum); err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
r.Total.Position = position(posSum, r.Total.Impressions)
|
cond, args := sc.where()
|
||||||
|
|
||||||
var named int
|
var named int
|
||||||
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE site = ? AND date BETWEEN ? AND ?`,
|
if err := d.QueryRow(`SELECT coalesce(sum(clicks), 0) FROM gsc_query_days WHERE `+cond+` AND date BETWEEN ? AND ?`,
|
||||||
site, from, to).Scan(&named); err != nil {
|
append(args, from, to)...).Scan(&named); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if r.Total.Clicks > 0 {
|
if r.Total.Clicks > 0 {
|
||||||
r.Anonymous = 100 * float64(r.Total.Clicks-min(named, r.Total.Clicks)) / float64(r.Total.Clicks)
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
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
|
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) < ?
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -167,7 +164,7 @@ func WhatRanks(d *db.DB, site string) (*Ranks, error) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
pick := Pick{Page: p.Page, Numbers: p.Numbers}
|
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
|
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"))
|
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.
|
// 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
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-8
@@ -24,16 +24,18 @@ type Report struct {
|
|||||||
Where string `json:"where"` // where the change came from, in a sentence
|
Where string `json:"where"` // where the change came from, in a sentence
|
||||||
Pages []Move `json:"pages"` // the 3 pages that moved most
|
Pages []Move `json:"pages"` // the 3 pages that moved most
|
||||||
Waiting []Pick `json:"waiting"`
|
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
|
// Weekly builds the Monday report for the latest week of final data. The
|
||||||
// "waiting for your yes" list holds at most 3 items.
|
// "waiting for your yes" list holds at most 3 items.
|
||||||
func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
|
func Weekly(d *db.DB, sc Scope, now time.Time) (*Report, error) {
|
||||||
c, err := MorningCheck(d, site, Settings{}) // every change, to rank the pages
|
c, err := MorningCheck(d, sc, Settings{}) // every change, to rank the pages
|
||||||
if err != nil || c == nil {
|
if err != nil || c == nil {
|
||||||
return nil, err
|
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)
|
r.Where = where(c.Before, c.After)
|
||||||
var pages []Move
|
var pages []Move
|
||||||
for _, m := range c.Moves {
|
for _, m := range c.Moves {
|
||||||
@@ -59,11 +61,12 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
|
|||||||
pages = pages[:3]
|
pages = pages[:3]
|
||||||
}
|
}
|
||||||
// The causes, from the full check (which explains only real moves).
|
// 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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for i := range pages {
|
for i := range pages {
|
||||||
|
pages[i].Why = []string{"Under the thresholds for a real move: noise until it lasts."}
|
||||||
for _, m := range full.Moves {
|
for _, m := range full.Moves {
|
||||||
if m.Kind == "page" && m.Key == pages[i].Key {
|
if m.Kind == "page" && m.Key == pages[i].Key {
|
||||||
pages[i].Why = m.Why
|
pages[i].Why = m.Why
|
||||||
@@ -73,7 +76,7 @@ func Weekly(d *db.DB, site string, now time.Time) (*Report, error) {
|
|||||||
r.Pages = pages
|
r.Pages = pages
|
||||||
// The changes proposed for the site, or else the pages to push.
|
// 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 ?`,
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
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})
|
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 {
|
if len(r.Waiting) == 0 {
|
||||||
ranks, err := WhatRanks(d, site)
|
ranks, err := WhatRanks(d, sc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if ranks != nil {
|
if ranks != nil {
|
||||||
r.Waiting = ranks.Push
|
r.Candidates = ranks.Push
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return r, nil
|
return r, nil
|
||||||
@@ -212,10 +217,16 @@ func (r *Report) Text() string {
|
|||||||
}
|
}
|
||||||
b.WriteString("\n3. Waiting for your yes\n")
|
b.WriteString("\n3. Waiting for your yes\n")
|
||||||
if len(r.Waiting) == 0 {
|
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 {
|
for i, p := range r.Waiting {
|
||||||
fmt.Fprintf(&b, " %d. %s\n %s\n", i+1, p.Page, p.Why)
|
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()
|
return b.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -86,7 +86,7 @@ func TestSyncAndWhatRanks(t *testing.T) {
|
|||||||
if err != nil || len(sites) != 1 || sites[0].URL != "sc-domain:whey.example" {
|
if err != nil || len(sites) != 1 || sites[0].URL != "sc-domain:whey.example" {
|
||||||
t.Fatalf("sites: %+v %v", sites, err)
|
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")
|
t.Error("ranks before any data")
|
||||||
}
|
}
|
||||||
res, err := Sync(context.Background(), d, c, "sc-domain:whey.example", now)
|
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)
|
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 {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"supermarket/internal/db"
|
"supermarket/internal/db"
|
||||||
|
"supermarket/internal/slug"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Statuses of a signal, in order.
|
// 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) }
|
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.
|
// Slugify makes a utm_campaign-safe slug from a name.
|
||||||
func Slugify(name string) string {
|
func Slugify(name string) string {
|
||||||
s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(name), "-"), "-")
|
s := slug.Make(name)
|
||||||
if len(s) > 60 {
|
if len(s) > 60 {
|
||||||
s = strings.TrimRight(s[:60], "-")
|
s = strings.TrimRight(s[:60], "-")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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(), "-"), "-")
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,7 +49,7 @@ func TestAuditPage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
time.Sleep(50 * time.Millisecond)
|
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")
|
t.Error("the status poll doesn't reload when done")
|
||||||
}
|
}
|
||||||
body := do(h, http.MethodGet, "/seo/audit", nil, nil).Body.String()
|
body := do(h, http.MethodGet, "/seo/audit", nil, nil).Body.String()
|
||||||
|
|||||||
@@ -187,10 +187,17 @@ func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
tmp.Close()
|
tmp.Close()
|
||||||
if err := backup.Check(tmp.Name()); err != nil {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
// A backup downloaded from here keeps its note, not its whole name.
|
||||||
note := "uploaded " + strings.TrimSuffix(filepath.Base(hdr.Filename), ".db")
|
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())
|
b, err := backup.Adopt(tmp.Name(), s.backupDir(), note, time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
|
|||||||
@@ -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") {
|
if !strings.Contains(body, "Uploaded as app-") || !strings.Contains(body, "-manual-uploaded-app-from-laptop.db") {
|
||||||
t.Errorf("upload: %s", body)
|
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)
|
t.Errorf("bad upload: %s", body)
|
||||||
}
|
}
|
||||||
if bs, _ := backup.List(s.backupDir()); len(bs) != 1 {
|
if bs, _ := backup.List(s.backupDir()); len(bs) != 1 {
|
||||||
|
|||||||
@@ -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."`) {
|
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")
|
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)
|
t.Errorf("pr without Gitea: %d", rec.Code)
|
||||||
}
|
}
|
||||||
s.Secrets.Set(map[string]string{secrets.GiteaToken: "tok"})
|
s.Secrets.Set(map[string]string{secrets.GiteaToken: "tok"})
|
||||||
|
|||||||
@@ -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)
|
back := "/seo/keywords?site=" + strconv.Itoa(site.Index) + "#k-" + strconv.FormatInt(id, 10)
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
var msg string
|
||||||
switch r.PathValue("action") {
|
switch r.PathValue("action") {
|
||||||
case "top":
|
case "top":
|
||||||
rs, rerr := s.researcher()
|
rs, rerr := s.researcher()
|
||||||
@@ -371,12 +372,13 @@ func (s *Server) seoKeywordAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
redirect(w, r, back, "top-read")
|
redirect(w, r, back, "top-read")
|
||||||
|
return
|
||||||
case "pick":
|
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":
|
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":
|
case "restore":
|
||||||
err = seo.SetKeywordStatus(s.DB, id, seo.KeywordNew, now)
|
err, msg = seo.SetKeywordStatus(s.DB, id, seo.KeywordNew, now), "keyword-back"
|
||||||
default:
|
default:
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
@@ -385,5 +387,5 @@ func (s *Server) seoKeywordAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.renderKeywords(w, r, err.Error())
|
s.renderKeywords(w, r, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
redirect(w, r, back, "saved")
|
redirect(w, r, back, msg)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ func TestContentPages(t *testing.T) {
|
|||||||
t.Errorf("write with nothing selected: %d", rec.Code)
|
t.Errorf("write with nothing selected: %d", rec.Code)
|
||||||
}
|
}
|
||||||
rec = postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}})
|
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())
|
t.Errorf("write without channels:\n%s", rec.Body.String())
|
||||||
}
|
}
|
||||||
// No AI key: the provider's error is shown.
|
// 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.
|
// A past time, or none, is refused.
|
||||||
past := time.Now().Add(-time.Hour).Format(dateTimeLocal)
|
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())
|
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())
|
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" {
|
if d, _ := content.GetDraft(s.DB, mustID(id)); d.Title != "Jitsi 3 is out" || d.Content != "Edited" {
|
||||||
t.Errorf("saved: %+v", d)
|
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())
|
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") {
|
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"})
|
_ = s.Secrets.Set(map[string]string{secrets.AnthropicAPIKey: "k"})
|
||||||
rec := postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}, "channel": {"reddit"}, "subreddit": {" "}})
|
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())
|
t.Errorf("write without subreddit: %s", rec.Body.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-3
@@ -100,6 +100,22 @@ func unreachableError(actions []crm.Action) string {
|
|||||||
return ""
|
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.
|
// 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
|
// 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
|
// 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)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
msg := ""
|
||||||
switch r.PathValue("action") {
|
switch r.PathValue("action") {
|
||||||
case "retry":
|
case "retry":
|
||||||
err = crm.Retry(s.DB, id)
|
err, msg = crm.Retry(s.DB, id), "crm-retried"
|
||||||
case "cancel":
|
case "cancel":
|
||||||
err = crm.Cancel(s.DB, id)
|
err, msg = crm.Cancel(s.DB, id), "crm-cancelled"
|
||||||
default:
|
default:
|
||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
@@ -184,6 +201,6 @@ func (s *Server) crmAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
redirect(w, r, "/crm", "saved")
|
redirect(w, r, "/crm", msg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"supermarket/internal/bridge"
|
"supermarket/internal/bridge"
|
||||||
"supermarket/internal/content"
|
"supermarket/internal/content"
|
||||||
"supermarket/internal/core"
|
"supermarket/internal/core"
|
||||||
|
"supermarket/internal/crm"
|
||||||
"supermarket/internal/inventory"
|
"supermarket/internal/inventory"
|
||||||
"supermarket/internal/profile"
|
"supermarket/internal/profile"
|
||||||
"supermarket/internal/secrets"
|
"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",
|
{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")},
|
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)
|
queued, _ := content.CountDrafts(s.DB)
|
||||||
scheduled, _ := content.ListDrafts(s.DB, 1000, content.StatusScheduled)
|
scheduled, _ := content.ListDrafts(s.DB, 1000, content.StatusScheduled)
|
||||||
|
|||||||
@@ -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 <use href="icons.svg#name"> 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 <use> elements
|
||||||
|
// at the copy, so icons show as they do on the live site.
|
||||||
|
|
||||||
|
var (
|
||||||
|
useHref = regexp.MustCompile(`(<use\b[^>]*?\b(?:xlink:)?href=")([^"#:]+\.svg)#([^"]+)"`)
|
||||||
|
svgOpen = regexp.MustCompile(`(?is)^.*?<svg\b[^>]*>`)
|
||||||
|
svgClose = regexp.MustCompile(`(?is)</svg>\s*$`)
|
||||||
|
bodyOpen = regexp.MustCompile(`(?i)<body\b[^>]*>`)
|
||||||
|
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(`<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">` + s + `</svg>`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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, "")
|
||||||
|
}
|
||||||
@@ -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(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg"><symbol id="cloud"><path d="M0 0"/></symbol></svg>`), 0o644)
|
||||||
|
os.WriteFile(filepath.Join(dir, "secret.svg"), []byte(`<svg><symbol id="x"/></svg>`), 0o644)
|
||||||
|
page := []byte(`<html><body class="a"><svg><use href="../images/icons.svg#cloud"></use></svg><svg><use href="images/missing.svg#y"></use></svg><svg><use href="../../../secret.svg#x"></use></svg></body></html>`)
|
||||||
|
out := string(inlineSprites(page, dir, "/about/"))
|
||||||
|
if !strings.Contains(out, `<use href="#cloud">`) || !strings.Contains(out, `<body class="a"><svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true"><symbol id="cloud">`) {
|
||||||
|
t.Errorf("not inlined: %s", out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, `images/missing.svg#y`) {
|
||||||
|
t.Errorf("a missing sprite should be left alone: %s", out)
|
||||||
|
}
|
||||||
|
if string(inlineSprites([]byte(`<body><p>no icons</p></body>`), dir, "/")) != `<body><p>no icons</p></body>` {
|
||||||
|
t.Error("a page without sprites changed")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -197,6 +197,8 @@ func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
if action == "verify" {
|
if action == "verify" {
|
||||||
msg = "verified"
|
msg = "verified"
|
||||||
}
|
}
|
||||||
|
case "company/delete", "contact/delete":
|
||||||
|
err, msg = prospects.Delete(s.DB, kind, id), "deleted"
|
||||||
case "company/reconsider", "contact/reconsider":
|
case "company/reconsider", "contact/reconsider":
|
||||||
err, msg = prospects.Reconsider(s.DB, kind, id), "reconsidered"
|
err, msg = prospects.Reconsider(s.DB, kind, id), "reconsidered"
|
||||||
case "company/suppress":
|
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.")
|
fail("Give a company, a person, or both.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
added := false
|
||||||
if d.CompanyID == 0 && hasCompany {
|
if d.CompanyID == 0 && hasCompany {
|
||||||
if strings.TrimSpace(d.Company.Name) == "" {
|
if strings.TrimSpace(d.Company.Name) == "" {
|
||||||
fail("Give the company's name.")
|
fail("Give the company's name.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id, _, err := prospects.AddCompany(s.DB, d.Company, now)
|
id, isNew, err := prospects.AddCompany(s.DB, d.Company, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fail(addError(err))
|
fail(addError(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
d.CompanyID = id
|
d.CompanyID, added = id, isNew
|
||||||
}
|
}
|
||||||
if hasPerson {
|
if hasPerson {
|
||||||
d.Contact.CompanyID = d.CompanyID
|
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))
|
fail(addError(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
added = added || isNew
|
||||||
} else if d.CompanyID != 0 && !hasCompany {
|
} else if d.CompanyID != 0 && !hasCompany {
|
||||||
fail("Give the person's name or email.")
|
fail("Give the person's name or email.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
redirect(w, r, "/prospects", "prospect-added")
|
redirect(w, r, "/prospects", ifElse(added, "prospect-added", "prospect-exists"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func addError(err error) string {
|
func addError(err error) string {
|
||||||
|
|||||||
+25
-7
@@ -89,6 +89,9 @@ type seoSite struct {
|
|||||||
Last *seo.SyncResult
|
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 {
|
func (s *Server) seoSites() []seoSite {
|
||||||
p, _ := profile.Load(s.DB)
|
p, _ := profile.Load(s.DB)
|
||||||
if p == nil {
|
if p == nil {
|
||||||
@@ -290,7 +293,7 @@ func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
data, cur := s.seoBase(r)
|
data, cur := s.seoBase(r)
|
||||||
data["Path"], data["Days"] = "/seo", seo.RanksDays
|
data["Path"], data["Days"] = "/seo", seo.RanksDays
|
||||||
if cur != nil {
|
if cur != nil {
|
||||||
ranks, err := seo.WhatRanks(s.DB, cur.Property)
|
ranks, err := seo.WhatRanks(s.DB, cur.scope())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
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})
|
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 {
|
func pagePath(u string) string {
|
||||||
p, err := url.Parse(u)
|
p, err := url.Parse(u)
|
||||||
if err != nil || p.Path == "" {
|
if err != nil || p.Path == "" {
|
||||||
return u
|
return u
|
||||||
}
|
}
|
||||||
|
out := p.Path
|
||||||
if p.RawQuery != "" {
|
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.
|
// 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, cur := s.seoBase(r)
|
||||||
data["Path"] = "/seo/check"
|
data["Path"] = "/seo/check"
|
||||||
if cur != nil {
|
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 {
|
if err != nil {
|
||||||
s.serverError(w, err)
|
s.serverError(w, err)
|
||||||
return
|
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
|
// writeReport builds and stores a site's report, and emails it if the
|
||||||
// settings say so (and email is set up).
|
// settings say so (and email is set up).
|
||||||
func (s *Server) writeReport(ctx context.Context, site seoSite, email bool) (*seo.Report, error) {
|
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 {
|
if err != nil || rep == nil {
|
||||||
return rep, err
|
return rep, err
|
||||||
}
|
}
|
||||||
@@ -590,7 +599,16 @@ func (s *Server) seoAuditStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if a == nil || a.Status != "running" {
|
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(""))
|
w.Write([]byte(""))
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-1
@@ -16,6 +16,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"supermarket/internal/api/reddit"
|
"supermarket/internal/api/reddit"
|
||||||
"supermarket/internal/api/twitter"
|
"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.NewProspects = s.newProspects()
|
||||||
p.Drafts = s.outreachDrafts()
|
p.Drafts = s.outreachDrafts()
|
||||||
if p.Flash == "" {
|
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")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
if err := t.ExecuteTemplate(w, "layout.html", p); err != nil {
|
if err := t.ExecuteTemplate(w, "layout.html", p); err != nil {
|
||||||
s.Log.Error("render", "page", name, "err", err)
|
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.",
|
"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.",
|
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
|
||||||
"declined": "Declined.",
|
"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.",
|
"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.",
|
"no-data": "There isn't two weeks of Search Console data yet.",
|
||||||
"reddit-connected": "Reddit is connected.",
|
"reddit-connected": "Reddit is connected.",
|
||||||
@@ -536,10 +543,14 @@ var flashes = map[string]string{
|
|||||||
"suppressed": "Added to the suppression list.",
|
"suppressed": "Added to the suppression list.",
|
||||||
"unsuppressed": "Taken off the suppression list.",
|
"unsuppressed": "Taken off the suppression list.",
|
||||||
"prospect-added": "Added. Review it below.",
|
"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.",
|
"outcome": "Outcome recorded.",
|
||||||
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
|
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
|
||||||
"rules-refreshed": "Rules refreshed.",
|
"rules-refreshed": "Rules refreshed.",
|
||||||
"imported": "Imported.",
|
"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.",
|
"hunter-done": "Hunter.io search done: the result is on the card.",
|
||||||
"verified": "Checked with Hunter.io: the result is on each person.",
|
"verified": "Checked with Hunter.io: the result is on each person.",
|
||||||
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
|
"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.",
|
"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) {
|
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
|
||||||
if msg != "" {
|
if msg != "" {
|
||||||
// The message goes in the query, before any #fragment.
|
// The message goes in the query, before any #fragment.
|
||||||
|
|||||||
@@ -470,7 +470,7 @@ func (s *Server) importSource(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.renderSignals(w, r, "Importing from "+source+": "+err.Error())
|
s.renderSignals(w, r, "Importing from "+source+": "+err.Error())
|
||||||
return
|
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
|
// runImport imports from one tool, if its key is saved. It returns nil, nil
|
||||||
|
|||||||
+21
-3
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"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
|
// 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
|
// 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
|
// 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'; " +
|
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'"
|
"script-src 'self' 'unsafe-inline'; connect-src 'none'; form-action 'none'; frame-ancestors 'none'"
|
||||||
|
|
||||||
// previewServe serves a built preview.
|
// 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("Content-Security-Policy", previewCSP)
|
||||||
h.Set("Cache-Control", "no-store")
|
h.Set("Cache-Control", "no-store")
|
||||||
prefix := strings.TrimSuffix(previewPrefix(site, slug), "/")
|
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.
|
// noListing serves files, and folders only through their index.html.
|
||||||
|
|||||||
@@ -284,7 +284,7 @@ func TestSitePageBuilder(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The claim must be confirmed before the pull request.
|
// 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)
|
t.Errorf("unconfirmed: %s", body)
|
||||||
}
|
}
|
||||||
body = postForm(h, "/sites/pages/1/pr", form(good, "We tested it with our own team.")).Body.String()
|
body = postForm(h, "/sites/pages/1/pr", form(good, "We tested it with our own team.")).Body.String()
|
||||||
|
|||||||
@@ -464,3 +464,4 @@ input[type="color"] { height: 2.6rem; padding: 0.25rem; cursor: pointer; }
|
|||||||
.nav-sum { margin-left: auto; }
|
.nav-sum { margin-left: auto; }
|
||||||
.nav-row:not(.collapsed) .nav-sum { display: none; }
|
.nav-row:not(.collapsed) .nav-sum { display: none; }
|
||||||
.nav .nav-toggle:active { transform: 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)); }
|
||||||
|
|||||||
@@ -161,7 +161,14 @@
|
|||||||
total.title = sum + " waiting";
|
total.title = sum + " waiting";
|
||||||
total.hidden = false;
|
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 () {
|
btn.addEventListener("click", function () {
|
||||||
var open = sub.hidden;
|
var open = sub.hidden;
|
||||||
set(sub, btn, open);
|
set(sub, btn, open);
|
||||||
|
|||||||
@@ -27,7 +27,7 @@
|
|||||||
<span class="help">Supermarket runs in Docker: for a server on this computer use <code>http://host.docker.internal:11434</code>, and use an IP address rather than a <code>.local</code> name.</span></label>
|
<span class="help">Supermarket runs in Docker: for a server on this computer use <code>http://host.docker.internal:11434</code>, and use an IP address rather than a <code>.local</code> name.</span></label>
|
||||||
<datalist id="servers">{{range .Servers}}<option value="{{.BaseURL}}">{{.Name}}</option>{{end}}</datalist>
|
<datalist id="servers">{{range .Servers}}<option value="{{.BaseURL}}">{{.Name}}</option>{{end}}</datalist>
|
||||||
{{if .Servers}}<p class="help">Found by CoreDesktop's <code>configure ai-servers</code>: {{range $i, $s := .Servers}}{{if $i}}, {{end}}{{$s.Name}} ({{$s.BaseURL}}){{end}}.</p>{{end}}
|
{{if .Servers}}<p class="help">Found by CoreDesktop's <code>configure ai-servers</code>: {{range $i, $s := .Servers}}{{if $i}}, {{end}}{{$s.Name}} ({{$s.BaseURL}}){{end}}.</p>{{end}}
|
||||||
<button type="button" class="secondary" hx-get="/settings/ai/models" hx-include="#base_url" hx-target="#model-list">List its models</button>
|
<button hx-disabled-elt="this" type="button" class="secondary" hx-get="/settings/ai/models" hx-include="#base_url" hx-target="#model-list" hx-indicator="#listing-models">List its models</button> <span id="listing-models" class="htmx-indicator">Asking the server…</span>
|
||||||
<div id="model-list"></div>
|
<div id="model-list"></div>
|
||||||
{{range .Keys}}{{if eq .Group "openai"}}{{template "key-field" (dict "F" . "Set" (index $set .Name))}}{{end}}{{end}}
|
{{range .Keys}}{{if eq .Group "openai"}}{{template "key-field" (dict "F" . "Set" (index $set .Name))}}{{end}}{{end}}
|
||||||
</section>
|
</section>
|
||||||
@@ -55,7 +55,7 @@
|
|||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button type="submit">Save</button>
|
<button type="submit">Save</button>
|
||||||
<button type="button" class="secondary" hx-post="/settings/ai/test" hx-include="#ai-form" hx-target="#test-result" hx-indicator="#testing">Test</button>
|
<button hx-disabled-elt="this" type="button" class="secondary" hx-post="/settings/ai/test" hx-include="#ai-form" hx-target="#test-result" hx-indicator="#testing">Test</button>
|
||||||
<span id="testing" class="htmx-indicator">Asking the model…</span>
|
<span id="testing" class="htmx-indicator">Asking the model…</span>
|
||||||
</div>
|
</div>
|
||||||
<p class="help">Test uses the provider and model in the form, and the keys already saved: save a new key before testing it.</p>
|
<p class="help">Test uses the provider and model in the form, and the keys already saved: save a new key before testing it.</p>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
<h2>Hermes bridge</h2>
|
<h2>Hermes bridge</h2>
|
||||||
<p>Hermes, CoreDesktop's agent, is the only thing that talks to your Core's MCP hub. It reaches Supermarket through the socket <code>{{.MCPSocket}}</code>; other agents, such as Claude Code, use <code>{{.MCPURL}}</code> with the MCP token.</p>
|
<p>Hermes, CoreDesktop's agent, is the only thing that talks to your Core's MCP hub. It reaches Supermarket through the socket <code>{{.MCPSocket}}</code>; other agents, such as Claude Code, use <code>{{.MCPURL}}</code> with the MCP token.</p>
|
||||||
{{with .Last}}
|
{{with .Last}}
|
||||||
<p class="ok">Hermes last checked in {{ago .At}}{{if .Note}}: “{{.Note}}”{{end}}.</p>
|
<p class="ok">Hermes last checked in {{ago .At}}.{{if .Note}} It said: “{{.Note}}”{{end}}</p>
|
||||||
{{if .MCPHubTools}}
|
{{if .MCPHubTools}}
|
||||||
<details><summary>It can use {{len .MCPHubTools}} tools from the MCP hub</summary>
|
<details><summary>It can use {{len .MCPHubTools}} tools from the MCP hub</summary>
|
||||||
<ul class="pills">{{range .MCPHubTools}}<li><span class="pill">{{.}}</span></li>{{end}}</ul>
|
<ul class="pills">{{range .MCPHubTools}}<li><span class="pill">{{.}}</span></li>{{end}}</ul>
|
||||||
|
|||||||
@@ -58,7 +58,7 @@
|
|||||||
<h3>Check</h3>
|
<h3>Check</h3>
|
||||||
<p class="small">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.</p>
|
<p class="small">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.</p>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<button type="button" class="secondary small" hx-post="/settings/email/test" hx-target="#email-test" hx-indicator="#testing-email">Check the settings</button>
|
<button hx-disabled-elt="this" type="button" class="secondary small" hx-post="/settings/email/test" hx-target="#email-test" hx-indicator="#testing-email">Check the settings</button>
|
||||||
<form method="post" action="/settings/email/send-test" data-busy="Sending…"><button type="submit" class="secondary small">Send a test email to {{or $s.FromAddress "the From address"}}</button></form>
|
<form method="post" action="/settings/email/send-test" data-busy="Sending…"><button type="submit" class="secondary small">Send a test email to {{or $s.FromAddress "the From address"}}</button></form>
|
||||||
<span id="testing-email" class="htmx-indicator">Checking…</span>
|
<span id="testing-email" class="htmx-indicator">Checking…</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -58,6 +58,7 @@
|
|||||||
{{else}}
|
{{else}}
|
||||||
<form method="post" action="/prospects/company/{{.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
<form method="post" action="/prospects/company/{{.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
<form method="post" action="/prospects/company/{{.ID}}/delete" data-confirm="Delete {{.Name}}{{if .Contacts}} and its people{{end}}? Their steps in the funnel go too, and a CRM action not yet done is taken back. Anything already in EspoCRM stays there."><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="link small">Delete</button></form>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
@@ -141,6 +142,7 @@
|
|||||||
{{else}}
|
{{else}}
|
||||||
<form method="post" action="/prospects/contact/{{$p.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
<form method="post" action="/prospects/contact/{{$p.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
<form method="post" action="/prospects/contact/{{$p.ID}}/delete" data-confirm="Delete {{$p.Name}}? Their steps in the funnel go too, and a CRM action not yet done is taken back. Anything already in EspoCRM stays there."><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="link small">Delete</button></form>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -46,7 +46,7 @@
|
|||||||
<label>Gitea's address <input name="gitea_url" value="{{.GiteaURL}}" placeholder="https://gitea.example.com"></label>
|
<label>Gitea's address <input name="gitea_url" value="{{.GiteaURL}}" placeholder="https://gitea.example.com"></label>
|
||||||
{{template "key-field" (dict "F" .GiteaKey "Set" .GiteaSet)}}
|
{{template "key-field" (dict "F" .GiteaKey "Set" .GiteaSet)}}
|
||||||
{{if .GiteaSet}}
|
{{if .GiteaSet}}
|
||||||
<button type="button" class="secondary small" hx-post="/settings/search/test/gitea" hx-target="#test-gitea" hx-indicator="#testing-gitea">Test</button>
|
<button hx-disabled-elt="this" type="button" class="secondary small" hx-post="/settings/search/test/gitea" hx-target="#test-gitea" hx-indicator="#testing-gitea">Test</button>
|
||||||
<span id="testing-gitea" class="htmx-indicator">Checking…</span>
|
<span id="testing-gitea" class="htmx-indicator">Checking…</span>
|
||||||
<div id="test-gitea"></div>
|
<div id="test-gitea"></div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|||||||
@@ -42,7 +42,8 @@
|
|||||||
{{if ne .Status "picked"}}<form method="post" action="/seo/keywords/{{.ID}}/pick"><button type="submit" class="small">Pick this one</button></form>
|
{{if ne .Status "picked"}}<form method="post" action="/seo/keywords/{{.ID}}/pick"><button type="submit" class="small">Pick this one</button></form>
|
||||||
{{else}}<form method="post" action="/seo/briefs" data-busy="Writing the brief…"><input type="hidden" name="site_url" value="{{.Site}}"><input type="hidden" name="keyword" value="{{.Keyword}}"><button type="submit" class="small">Write the brief</button></form>{{end}}
|
{{else}}<form method="post" action="/seo/briefs" data-busy="Writing the brief…"><input type="hidden" name="site_url" value="{{.Site}}"><input type="hidden" name="keyword" value="{{.Keyword}}"><button type="submit" class="small">Write the brief</button></form>{{end}}
|
||||||
{{if eq .Status "dismissed"}}<form method="post" action="/seo/keywords/{{.ID}}/restore"><button type="submit" class="secondary small">Bring back</button></form>
|
{{if eq .Status "dismissed"}}<form method="post" action="/seo/keywords/{{.ID}}/restore"><button type="submit" class="secondary small">Bring back</button></form>
|
||||||
{{else}}<form method="post" action="/seo/keywords/{{.ID}}/dismiss"><button type="submit" class="secondary small">Dismiss</button></form>{{end}}
|
{{else}}{{if eq .Status "picked"}}<form method="post" action="/seo/keywords/{{.ID}}/restore"><button type="submit" class="secondary small">Unpick</button></form>{{end}}
|
||||||
|
<form method="post" action="/seo/keywords/{{.ID}}/dismiss"><button type="submit" class="secondary small">Dismiss</button></form>{{end}}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{if .Top}}
|
{{if .Top}}
|
||||||
|
|||||||
@@ -33,8 +33,13 @@
|
|||||||
<h2>3. Waiting for your yes</h2>
|
<h2>3. Waiting for your yes</h2>
|
||||||
{{range .Waiting}}
|
{{range .Waiting}}
|
||||||
<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>
|
<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>
|
||||||
{{else}}<p class="help">Nothing this week.</p>{{end}}
|
{{else}}<p class="help">Nothing is waiting: no change has been proposed.</p>{{end}}
|
||||||
<p class="help">Say yes or no to each on <a href="/seo/changes?site={{$d.Current.Index}}">Changes</a>: a yes opens a pull request.</p>
|
{{if .Waiting}}<p class="help">Say yes or no to each on <a href="/seo/changes?site={{$d.Current.Index}}">Changes</a>: a yes opens a pull request.</p>{{end}}
|
||||||
|
{{with .Candidates}}
|
||||||
|
<h3>Worth a proposal</h3>
|
||||||
|
{{range .}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>{{end}}
|
||||||
|
<p class="help"><em>Propose changes</em> on <a href="/seo/changes?site={{$d.Current.Index}}">Changes</a> writes new wording for pages like these.</p>
|
||||||
|
{{end}}
|
||||||
</section>
|
</section>
|
||||||
{{else}}
|
{{else}}
|
||||||
<section class="card empty"><p>No report yet. It's written on Monday once there are two weeks of data, or now with <em>Write it now</em>.</p></section>
|
<section class="card empty"><p>No report yet. It's written on Monday once there are two weeks of data, or now with <em>Write it now</em>.</p></section>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
<span class="help">If your organization has projects, the ID of the one to read. Leave empty to read the whole organization.</span></label>
|
<span class="help">If your organization has projects, the ID of the one to read. Leave empty to read the whole organization.</span></label>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{if .Set}}
|
{{if .Set}}
|
||||||
<button type="button" class="secondary small" hx-post="/settings/sources/test/{{.ID}}" hx-target="#test-{{.ID}}" hx-indicator="#testing-{{.ID}}">Test</button>
|
<button hx-disabled-elt="this" type="button" class="secondary small" hx-post="/settings/sources/test/{{.ID}}" hx-target="#test-{{.ID}}" hx-indicator="#testing-{{.ID}}">Test</button>
|
||||||
<span id="testing-{{.ID}}" class="htmx-indicator">Checking…</span>
|
<span id="testing-{{.ID}}" class="htmx-indicator">Checking…</span>
|
||||||
<div id="test-{{.ID}}"></div>
|
<div id="test-{{.ID}}"></div>
|
||||||
{{end}}
|
{{end}}
|
||||||
@@ -36,7 +36,7 @@
|
|||||||
</label>
|
</label>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
{{if .Set}}
|
{{if .Set}}
|
||||||
<button type="button" class="secondary small" hx-post="/settings/sources/test/hunter" hx-target="#test-hunter" hx-indicator="#testing-hunter">Test</button>
|
<button hx-disabled-elt="this" type="button" class="secondary small" hx-post="/settings/sources/test/hunter" hx-target="#test-hunter" hx-indicator="#testing-hunter">Test</button>
|
||||||
<span id="testing-hunter" class="htmx-indicator">Checking…</span>
|
<span id="testing-hunter" class="htmx-indicator">Checking…</span>
|
||||||
<div id="test-hunter"></div>
|
<div id="test-hunter"></div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
<p class="help">Sites read: {{if .Sites}}{{range $i, $s := .Sites}}{{if $i}}, {{end}}<code>{{$s}}</code>{{end}}{{else}}none yet: add your websites (and their Plausible site, if it differs from the domain) to the <a href="/settings/profile">profile</a>{{end}}.</p>
|
<p class="help">Sites read: {{if .Sites}}{{range $i, $s := .Sites}}{{if $i}}, {{end}}<code>{{$s}}</code>{{end}}{{else}}none yet: add your websites (and their Plausible site, if it differs from the domain) to the <a href="/settings/profile">profile</a>{{end}}.</p>
|
||||||
{{if .PlausibleSet}}
|
{{if .PlausibleSet}}
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<button type="button" class="secondary small" hx-post="/settings/tracking/test/plausible" hx-target="#test-plausible" hx-indicator="#testing-plausible">Test</button>
|
<button hx-disabled-elt="this" type="button" class="secondary small" hx-post="/settings/tracking/test/plausible" hx-target="#test-plausible" hx-indicator="#testing-plausible">Test</button>
|
||||||
<button type="submit" class="secondary small" formaction="/settings/tracking/run/plausible" formnovalidate>Import now</button>
|
<button type="submit" class="secondary small" formaction="/settings/tracking/run/plausible" formnovalidate>Import now</button>
|
||||||
<span id="testing-plausible" class="htmx-indicator">Checking…</span>
|
<span id="testing-plausible" class="htmx-indicator">Checking…</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -35,7 +35,7 @@ metadata[utm_content] = optional: which message or post</pre>
|
|||||||
</details>
|
</details>
|
||||||
{{if .StripeSet}}
|
{{if .StripeSet}}
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<button type="button" class="secondary small" hx-post="/settings/tracking/test/stripe" hx-target="#test-stripe" hx-indicator="#testing-stripe">Test</button>
|
<button hx-disabled-elt="this" type="button" class="secondary small" hx-post="/settings/tracking/test/stripe" hx-target="#test-stripe" hx-indicator="#testing-stripe">Test</button>
|
||||||
<button type="submit" class="secondary small" formaction="/settings/tracking/run/stripe" formnovalidate>Sync now</button>
|
<button type="submit" class="secondary small" formaction="/settings/tracking/run/stripe" formnovalidate>Sync now</button>
|
||||||
<span id="testing-stripe" class="htmx-indicator">Checking…</span>
|
<span id="testing-stripe" class="htmx-indicator">Checking…</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user