package content import ( "fmt" "strings" "time" "supermarket/internal/db" "supermarket/internal/inventory" "supermarket/internal/models" "supermarket/internal/profile" "supermarket/internal/utm" ) // The company's own content (its products, feeds and site pages) is handled // like an inventory entry that isn't stored: OwnEntry builds it from the // profile. Its items are stored under OwnName. const ( OwnName = "_own" KindProduct = "product" ) // OwnEntry is the company as a content source. func OwnEntry(p *profile.Profile) *inventory.Entry { e := &inventory.Entry{Name: OwnName, Relationship: KindProduct, RSS: p.Feeds, Description: p.Description, Subreddits: p.Accounts.Subreddits} for _, w := range p.Websites { e.Websites = append(e.Websites, w.URL) } return e } // IsOwn reports whether e is the company itself. func IsOwn(e *inventory.Entry) bool { return e.Name == OwnName } // SyncProducts keeps an item for each product in the profile, so products // can be selected and written about like fetched items. Removed products' // items go; a product's item keeps its ID (and "drafted" mark) while its // name stays the same. func SyncProducts(d *db.DB, p *profile.Profile) error { tx, err := d.Begin() if err != nil { return err } defer tx.Rollback() keep := map[string]bool{} for _, pr := range p.Products { id := "product:" + utm.Slug(pr.Name) if id == "product:" || keep[id] { continue } keep[id] = true var body strings.Builder body.WriteString(pr.Description) if len(pr.Benefits) > 0 { fmt.Fprintf(&body, "\nBenefits: %s.", strings.Join(pr.Benefits, "; ")) } if pr.Pricing != "" { fmt.Fprintf(&body, "\nPricing: %s", pr.Pricing) } if _, err := tx.Exec(`INSERT INTO content_items (id, inventory_name, source, title, body, url, published_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET title = excluded.title, body = excluded.body, url = excluded.url`, id, OwnName, string(models.SourceProduct), pr.Name, strings.TrimSpace(body.String()), pr.URL, formatTime(time.Now())); err != nil { return err } } rows, err := tx.Query(`SELECT id FROM content_items WHERE inventory_name = ? AND source = ?`, OwnName, string(models.SourceProduct)) if err != nil { return err } var stale []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { rows.Close() return err } if !keep[id] { stale = append(stale, id) } } rows.Close() for _, id := range stale { if _, err := tx.Exec(`DELETE FROM content_items WHERE id = ?`, id); err != nil { return err } } return tx.Commit() }