// Package seo runs the weekly SEO loop for the company's websites, from // Google Search Console's own numbers: what already ranks, the morning // check, the Monday report, the audit, and the changes the user approves. // Every number is computed here, from the data; the AI only writes words // around them. package seo import ( "context" "fmt" "time" "supermarket/internal/api/gsc" "supermarket/internal/db" ) const dayFormat = "2006-01-02" // historyDays is how far back the first sync reads: Search Console keeps // about 16 months. const historyDays = 480 // refetchDays are read again on every sync: the last days' data can still // change before it's final. const refetchDays = 4 // chunkDays is how many days one set of requests covers. const chunkDays = 30 func throughKey(site string) string { return "seo:gsc-through:" + site } // SyncResult is what a sync read. type SyncResult struct { Site string `json:"site"` At time.Time `json:"at"` From string `json:"from"` Through string `json:"through"` // the latest day with final data Rows int `json:"rows"` Error string `json:"error,omitempty"` } func lastKey(site string) string { return "seo:gsc-last:" + site } // LastSync is a property's last sync, or nil. func LastSync(d *db.DB, site string) (*SyncResult, error) { var r SyncResult ok, err := d.GetJSON(lastKey(site), &r) if err != nil || !ok { return nil, err } return &r, nil } // Through is the latest day stored for a property, or "". func Through(d *db.DB, site string) string { var t string _, _ = d.GetJSON(throughKey(site), &t) return t } // Sync reads a property's Search Console data, by day: the totals, each // page, and each page and query. The first time it reads 16 months; after // that, from a few days before the last final day. func Sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time) (*SyncResult, error) { res := &SyncResult{Site: site, At: now} err := sync(ctx, d, c, site, now, res) if err != nil { res.Error = err.Error() } if perr := d.PutJSON(lastKey(site), res); perr != nil && err == nil { err = perr } return res, err } func sync(ctx context.Context, d *db.DB, c *gsc.Client, site string, now time.Time, res *SyncResult) error { today := now.UTC().Truncate(24 * time.Hour) from := today.AddDate(0, 0, -historyDays) if t := Through(d, site); t != "" { if last, err := time.Parse(dayFormat, t); err == nil { from = last.AddDate(0, 0, -refetchDays) } } res.From = from.Format(dayFormat) through := Through(d, site) for start := from; !start.After(today); start = start.AddDate(0, 0, chunkDays) { end := start.AddDate(0, 0, chunkDays-1) if end.After(today) { end = today } n, latest, err := syncRange(ctx, d, c, site, start.Format(dayFormat), end.Format(dayFormat)) if err != nil { return err } res.Rows += n if latest > through { through = latest } } res.Through = through if through == "" { return nil } return d.PutJSON(throughKey(site), through) } // syncRange replaces the stored days in [start, end] with Google's. It // returns the rows stored and the latest day that had data. func syncRange(ctx context.Context, d *db.DB, c *gsc.Client, site, start, end string) (int, string, error) { q := func(dims ...string) ([]gsc.Row, error) { return c.Analytics(ctx, site, gsc.Query{StartDate: start, EndDate: end, Dimensions: dims, Type: "web", DataState: "final"}) } days, err := q("date") if err != nil { return 0, "", err } pages, err := q("date", "page") if err != nil { return 0, "", err } queries, err := q("date", "page", "query") if err != nil { return 0, "", err } tx, err := d.Begin() if err != nil { return 0, "", err } defer tx.Rollback() for _, table := range []string{"gsc_site_days", "gsc_page_days", "gsc_query_days"} { if _, err := tx.Exec(`DELETE FROM `+table+` WHERE site = ? AND date BETWEEN ? AND ?`, site, start, end); err != nil { return 0, "", err } } latest := "" n := 0 for _, r := range days { if len(r.Keys) < 1 { continue } if r.Keys[0] > latest { latest = r.Keys[0] } if _, err := tx.Exec(`INSERT INTO gsc_site_days VALUES (?, ?, ?, ?, ?)`, site, r.Keys[0], int(r.Clicks), int(r.Impressions), r.Position*r.Impressions); err != nil { return 0, "", err } n++ } for _, r := range pages { if len(r.Keys) < 2 { continue } if _, err := tx.Exec(`INSERT INTO gsc_page_days VALUES (?, ?, ?, ?, ?, ?)`, site, r.Keys[0], r.Keys[1], int(r.Clicks), int(r.Impressions), r.Position*r.Impressions); err != nil { return 0, "", err } n++ } for _, r := range queries { if len(r.Keys) < 3 { continue } if _, err := tx.Exec(`INSERT INTO gsc_query_days VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (site, date, page, query) DO NOTHING`, site, r.Keys[0], r.Keys[1], r.Keys[2], int(r.Clicks), int(r.Impressions), r.Position*r.Impressions); err != nil { return 0, "", err } n++ } if err := tx.Commit(); err != nil { return 0, "", fmt.Errorf("saving Search Console data: %w", err) } return n, latest, nil }