package seo import ( "database/sql" "fmt" "net/url" "slices" "strings" "time" "supermarket/internal/db" ) // Day is one day's clicks and impressions. type Day struct { Date string `json:"date"` Clicks int `json:"clicks"` Impressions int `json:"impressions"` } // days are the scope's numbers for each day from from to to, with 0 for a // day Search Console has no row for. func days(d *db.DB, sc Scope, from, to string) ([]Day, error) { var rows *sql.Rows var err error if len(sc.Hosts) == 0 { rows, err = d.Query(`SELECT date, sum(clicks), sum(impressions) FROM gsc_site_days WHERE site = ? AND date BETWEEN ? AND ? GROUP BY date`, sc.Property, from, to) } else { cond, args := sc.where() rows, err = d.Query(`SELECT date, sum(clicks), sum(impressions) FROM gsc_page_days WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY date`, append(args, from, to)...) } if err != nil { return nil, err } defer rows.Close() got := map[string]Day{} for rows.Next() { var day Day if err := rows.Scan(&day.Date, &day.Clicks, &day.Impressions); err != nil { return nil, err } got[day.Date] = day } if err := rows.Err(); err != nil { return nil, err } start, err1 := time.Parse(dayFormat, from) end, err2 := time.Parse(dayFormat, to) if err1 != nil || err2 != nil { return nil, fmt.Errorf("bad period %s to %s", from, to) } var out []Day for t := start; !t.After(end); t = t.AddDate(0, 0, 1) { k := t.Format(dayFormat) day := got[k] day.Date = k out = append(out, day) } return out, nil } // QueryChange is a search's numbers this week and the week before. type QueryChange struct { Query string `json:"query"` Before Numbers `json:"before"` After Numbers `json:"after"` NoData bool `json:"no_data,omitempty"` // no row this week New bool `json:"new,omitempty"` // no row the week before } // ClickDelta is the change in clicks. func (q QueryChange) ClickDelta() int { return q.After.Clicks - q.Before.Clicks } // PosDelta is the change in average position (negative is up), or 0 when // either week has no position. func (q QueryChange) PosDelta() float64 { if q.Before.Impressions == 0 || q.After.Impressions == 0 { return 0 } return q.After.Position - q.Before.Position } // TopChanges is how many searches the gaining and losing lists hold. const TopChanges = 5 // topQueries are the searches whose clicks rose most, and fell most, from // one week to the next: every change counts here, not only real moves. func topQueries(before, after map[string]Numbers, n int) (gains, losses []QueryChange) { for q := range union(after, before) { a, hasA := after[q] b, hasB := before[q] c := QueryChange{Query: q, Before: b, After: a, NoData: !hasA, New: !hasB} switch { case c.ClickDelta() > 0: gains = append(gains, c) case c.ClickDelta() < 0: losses = append(losses, c) } } order := func(x, y QueryChange) int { if dx, dy := abs(x.ClickDelta()), abs(y.ClickDelta()); dx != dy { return dy - dx } if ix, iy := max(x.Before.Impressions, x.After.Impressions), max(y.Before.Impressions, y.After.Impressions); ix != iy { return iy - ix } return strings.Compare(x.Query, y.Query) } slices.SortFunc(gains, order) slices.SortFunc(losses, order) return gains[:min(n, len(gains))], losses[:min(n, len(losses))] } // Outside is the clicks a domain property sent to another of its hosts in // a week: a shop, a forum, a Gitea… with the search that brought most. type Outside struct { Host string `json:"host"` Clicks int `json:"clicks"` Impressions int `json:"impressions"` Query string `json:"query,omitempty"` } // MaxOutside is how many other hosts are named. const MaxOutside = 3 // outside sums a week's clicks on the property's other hosts, most first. // It's empty unless the scope narrows a domain property. func outside(d *db.DB, sc Scope, from, to string) ([]Outside, error) { if len(sc.Hosts) == 0 { return nil, nil } cond, args := sc.where() _, inside, _ := strings.Cut(cond, " AND ") notIn := "site = ? AND NOT " + inside rows, err := d.Query(`SELECT page, sum(clicks), sum(impressions) FROM gsc_page_days WHERE `+notIn+` AND date BETWEEN ? AND ? GROUP BY page`, append(args, from, to)...) if err != nil { return nil, err } byHost := map[string]*Outside{} for rows.Next() { var page string var clicks, impr int if err := rows.Scan(&page, &clicks, &impr); err != nil { rows.Close() return nil, err } h := hostOf(page) if byHost[h] == nil { byHost[h] = &Outside{Host: h} } byHost[h].Clicks += clicks byHost[h].Impressions += impr } rows.Close() if err := rows.Err(); err != nil { return nil, err } var out []Outside for _, o := range byHost { if o.Clicks > 0 { out = append(out, *o) } } slices.SortFunc(out, func(a, b Outside) int { if a.Clicks != b.Clicks { return b.Clicks - a.Clicks } return strings.Compare(a.Host, b.Host) }) out = out[:min(MaxOutside, len(out))] // The search that brought each host most clicks. qrows, err := d.Query(`SELECT page, query, sum(clicks) FROM gsc_query_days WHERE `+notIn+` AND date BETWEEN ? AND ? GROUP BY page, query HAVING sum(clicks) > 0`, append(args, from, to)...) if err != nil { return nil, err } defer qrows.Close() best := map[string]int{} for qrows.Next() { var page, q string var clicks int if err := qrows.Scan(&page, &q, &clicks); err != nil { return nil, err } h := hostOf(page) for i := range out { if out[i].Host == h && (clicks > best[h] || (clicks == best[h] && q < out[i].Query)) { best[h], out[i].Query = clicks, q } } } return out, qrows.Err() } func hostOf(page string) string { if u, err := url.Parse(page); err == nil && u.Hostname() != "" { return strings.ToLower(u.Hostname()) } return page } // Percent is a change as a percentage of where it started ("+52.3%", // "−18.9%"), or "" when there's nothing to compare with. func Percent(before, after int) string { if before == 0 { return "" } p := 100 * float64(after-before) / float64(before) switch { case p > 0: return fmt.Sprintf("+%.1f%%", p) case p < 0: return fmt.Sprintf("−%.1f%%", -p) } return "0%" } // Summary is a search's change in words, as the email shows it. func (q QueryChange) Summary() string { clicks := fmt.Sprintf("clicks %d → %d", q.Before.Clicks, q.After.Clicks) switch { case q.NoData: return clicks[:strings.Index(clicks, "→")+len("→")] + " no data (no row this week)" case q.New: return fmt.Sprintf("clicks %d, new this week, position %.1f", q.After.Clicks, q.After.Position) } return fmt.Sprintf("%s, position %.1f → %.1f", clicks, q.Before.Position, q.After.Position) } // Sentence says where the clicks went, in one line. func (o Outside) Sentence() string { s := fmt.Sprintf("Not counted: %d %s went to %s", o.Clicks, plural(o.Clicks, "click", "clicks"), o.Host) if o.Query != "" { s += fmt.Sprintf(", most for “%s”", o.Query) } return s + "." }