Market import: fill entries in from their websites

A list of just websites and relationships (url:, website:, or a bare
address) can be imported with "Fill in the empty boxes from each
website": each entry is filled in as on New entry, in the background a
few at a time, and saved straight into the Market. Entries already there,
by name or website, are skipped before their site is read; the plan's
limit is kept. The import page shows the progress and each entry's result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 06:41:54 -07:00
co-authored by Claude Opus 5.5
parent 185522c0c3
commit 4692d72d58
10 changed files with 659 additions and 9 deletions
+260
View File
@@ -0,0 +1,260 @@
package inventory
import (
"context"
"fmt"
"strings"
"sync"
"time"
"supermarket/internal/ai"
"supermarket/internal/db"
"supermarket/internal/profile"
"supermarket/internal/site"
)
// What happened to an entry of a list imported with FillImport.
const (
FillAdded = "added"
FillUpdated = "updated"
FillSkipped = "skipped"
FillFailed = "failed"
)
// FillLine is what happened to one entry of the list.
type FillLine struct {
Site string `json:"site,omitempty"` // the address it was filled in from
Name string `json:"name,omitempty"`
ID int64 `json:"id,omitempty"` // the entry in the Market, if saved
Outcome string `json:"outcome"`
Note string `json:"note,omitempty"` // why it was skipped or failed, or what went wrong on the way
Filled []string `json:"filled,omitempty"`
}
// FillOptions are how FillImport works.
type FillOptions struct {
Client ai.Client
Ours *profile.Profile // the user's own company, for talking points; may be nil
Overwrite bool // replace entries already in the Market
// Room says why the Market can't take another entry, given how many it
// has (the plan's limit), or nil. nil: no limit.
Room func(existing int) error
Workers int // websites read at once; 0: fillWorkers
Timeout time.Duration // for each entry; 0: fillTimeout
// Done is told about each entry as it's done, one at a time.
Done func(FillLine)
}
const (
fillWorkers = 3
fillTimeout = 4 * time.Minute
)
// FillImport adds the entries to the Market, each first filled in from
// its website, as Fill does on the New entry page: what the list gives is
// kept, the empty fields are filled. An entry without a website is saved as
// it is.
//
// Entries already in the Market, by name or by website, are skipped before
// their website is read (nothing spent on them) unless Overwrite is set; a
// name found only by filling in is checked again before saving.
func FillImport(ctx context.Context, d *db.DB, entries []Entry, o FillOptions) []FillLine {
if o.Workers <= 0 {
o.Workers = fillWorkers
}
if o.Timeout <= 0 {
o.Timeout = fillTimeout
}
var (
mu sync.Mutex // the maps, count, lines, and saving
lines []FillLine
)
finish := func(l FillLine) { // under mu
lines = append(lines, l)
if o.Done != nil {
o.Done(l)
}
}
existing, err := List(d, "")
if err != nil {
finish(FillLine{Outcome: FillFailed, Note: err.Error()})
return lines
}
count := len(existing)
byName := map[string]int64{}
bySite := map[string]int64{}
for _, e := range existing {
byName[strings.ToLower(e.Name)] = e.ID
for _, w := range e.Websites {
if k := siteKey(w); k != "" {
bySite[k] = e.ID
}
}
}
// save saves e (under mu), as the entry id if not 0.
save := func(e *Entry, id int64, l FillLine) {
l.Name = strings.TrimSpace(e.Name)
if l.Name == "" {
l.Outcome = FillFailed
if l.Note == "" {
l.Note = "their name wasn't found on the website"
}
finish(l)
return
}
if other, ok := byName[strings.ToLower(l.Name)]; ok && other != id {
if id != 0 || !o.Overwrite {
l.Outcome, l.Note, l.ID = FillSkipped, "already in the Market", other
finish(l)
return
}
id = other
}
if id == 0 && o.Room != nil {
if err := o.Room(count); err != nil {
l.Outcome, l.Note = FillFailed, err.Error()
finish(l)
return
}
}
e.ID = id
if err := Save(d, e); err != nil {
l.Outcome, l.Note = FillFailed, err.Error()
finish(l)
return
}
l.ID = e.ID
if id != 0 {
l.Outcome = FillUpdated
} else {
l.Outcome = FillAdded
count++
}
byName[strings.ToLower(e.Name)] = e.ID
for _, w := range e.Websites {
if k := siteKey(w); k != "" {
bySite[k] = e.ID
}
}
finish(l)
}
// First what's known without reading a website: what's already there,
// listed twice, or can't be read.
type job struct {
e Entry
id int64
}
var queue []job
seen := map[string]bool{}
mu.Lock()
for _, e := range entries {
e.Websites = profile.CleanList(e.Websites)
l := FillLine{Name: strings.TrimSpace(e.Name)}
if len(e.Websites) > 0 {
l.Site = e.Websites[0]
}
if l.Site == "" && l.Name == "" {
l.Outcome, l.Note = FillFailed, "no website or name"
finish(l)
continue
}
if l.Site != "" {
if _, err := site.Normalize(l.Site); err != nil {
l.Outcome, l.Note = FillFailed, err.Error()
finish(l)
continue
}
}
var keys []string
if l.Name != "" {
keys = append(keys, "name:"+strings.ToLower(l.Name))
}
for _, w := range e.Websites {
if k := siteKey(w); k != "" {
keys = append(keys, "site:"+k)
}
}
twice := false
for _, k := range keys {
twice = twice || seen[k]
seen[k] = true
}
if twice {
l.Outcome, l.Note = FillSkipped, "listed twice"
finish(l)
continue
}
id, found := byName[strings.ToLower(l.Name)]
if !found {
for _, w := range e.Websites {
if id, found = bySite[siteKey(w)]; found {
break
}
}
}
if found && !o.Overwrite {
l.Outcome, l.Note, l.ID = FillSkipped, "already in the Market", id
finish(l)
continue
}
if l.Site == "" {
save(&e, id, l) // nothing to fill in from
continue
}
queue = append(queue, job{e, id})
}
mu.Unlock()
work := make(chan job)
var wg sync.WaitGroup
for range min(o.Workers, len(queue)) {
wg.Add(1)
go func() {
defer wg.Done()
for j := range work {
e := j.e
l := FillLine{Site: e.Websites[0]}
fctx, cancel := context.WithTimeout(ctx, o.Timeout)
res, err := Fill(fctx, o.Client, &e, l.Site, o.Ours)
cancel()
l.Filled = res.Filled
if err != nil {
if strings.TrimSpace(e.Name) != "" {
l.Note = "only partly filled in: " + err.Error()
} else {
l.Note = err.Error()
}
}
mu.Lock()
save(&e, j.id, l)
mu.Unlock()
}
}()
}
for _, j := range queue {
if ctx.Err() != nil {
mu.Lock()
finish(FillLine{Site: j.e.Websites[0], Name: j.e.Name, Outcome: FillFailed, Note: "stopped: " + ctx.Err().Error()})
mu.Unlock()
continue
}
work <- j
}
close(work)
wg.Wait()
return lines
}
// siteKey is a website's address to compare by: host without www., and
// path, without the scheme or a trailing slash.
func siteKey(raw string) string {
u, err := site.Normalize(raw)
if err != nil {
return ""
}
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
return fmt.Sprintf("%s%s", host, strings.TrimRight(u.Path, "/"))
}
+121
View File
@@ -0,0 +1,121 @@
package inventory
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
"supermarket/internal/db"
)
func TestParseYAMLWebsiteOnly(t *testing.T) {
doc := "- url: https://a.example\n relationship: competitor\n- website: b.example\n- https://c.example\n" +
"- name: D\n url: https://d.example\n websites: [https://d.example, https://blog.d.example]\n"
entries, err := ParseYAML([]byte(doc), Partner)
if err != nil || len(entries) != 4 {
t.Fatalf("%+v %v", entries, err)
}
var got []string
for _, e := range entries {
got = append(got, fmt.Sprintf("%s|%s|%s", e.Name, e.Relationship, strings.Join(e.Websites, ",")))
}
want := "|competitor|https://a.example |partner|b.example |partner|https://c.example D|partner|https://d.example,https://blog.d.example"
if strings.Join(got, " ") != want {
t.Errorf("got %s\nwant %s", strings.Join(got, " "), want)
}
// Exported entries don't grow a url:.
out, _ := ExportYAML(entries[:1])
if strings.Contains(string(out), "url:") {
t.Errorf("export:\n%s", out)
}
}
func testDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
func TestFillImport(t *testing.T) {
d := testDB(t)
srv := rivalSite(t)
if err := Save(d, &Entry{Name: "Old", Relationship: Partner, Websites: []string{"https://www.old.invalid/"}}); err != nil {
t.Fatal(err)
}
fake := &fakeAI{reply: map[string]any{
"name": "Rival Inc", "description": "Hosted widgets.", "talking_points": "", "keywords": []string{}, "hashtags": []string{},
"subreddits": []map[string]string{},
}}
in := []Entry{
{Websites: []string{srv.URL}, Relationship: Competitor},
{Websites: []string{srv.URL + "/"}, Relationship: Partner}, // the same site
{Websites: []string{"old.invalid"}, Relationship: Partner}, // already there: never read
{Name: "Plain", Relationship: Watch}, // nothing to fill in from
{Websites: []string{"ftp://nope"}},
{},
}
var told int
lines := FillImport(context.Background(), d, in, FillOptions{Client: fake, Workers: 1, Done: func(FillLine) { told++ }})
var got []string
for _, l := range lines {
got = append(got, l.Name+":"+l.Outcome)
}
// Those known without reading a site first, then the ones filled in.
if sum := strings.Join(got, " "); sum != ":skipped :skipped Plain:added :failed :failed Rival Inc:added" {
t.Errorf("lines = %q", sum)
}
if told != len(in) || fake.calls != 1 {
t.Errorf("told %d, model called %d times", told, fake.calls)
}
if lines[0].Note != "listed twice" || lines[1].Note != "already in the Market" || lines[1].ID == 0 {
t.Errorf("notes: %+v %+v", lines[0], lines[1])
}
e, _ := Get(d, lines[len(lines)-1].ID)
if e == nil || e.Relationship != Competitor || e.Description != "Hosted widgets." || e.TwitterHandle != "rivalhq" ||
e.Websites[0] != srv.URL || e.MentionPolicy != MentionCategory {
t.Errorf("saved: %+v", e)
}
// Again: already there, by website, before reading it.
lines = FillImport(context.Background(), d, in[:1], FillOptions{Client: fake})
if len(lines) != 1 || lines[0].Outcome != FillSkipped || fake.calls != 1 {
t.Errorf("again: %+v, %d calls", lines, fake.calls)
}
// Replacing it reads it again, and keeps its id.
id := e.ID
lines = FillImport(context.Background(), d, in[:1], FillOptions{Client: fake, Overwrite: true})
if len(lines) != 1 || lines[0].Outcome != FillUpdated || lines[0].ID != id || fake.calls != 2 {
t.Errorf("overwrite: %+v, %d calls", lines, fake.calls)
}
}
func TestFillImportLimitsAndFailures(t *testing.T) {
d := testDB(t)
srv := rivalSite(t)
fake := &fakeAI{reply: map[string]any{"name": "", "description": "", "talking_points": "", "keywords": []string{},
"hashtags": []string{}, "subreddits": []map[string]string{}}}
full := errors.New("the plan is full")
lines := FillImport(context.Background(), d, []Entry{{Name: "Named", Websites: []string{srv.URL}, Relationship: Partner}},
FillOptions{Client: fake, Room: func(int) error { return full }})
if len(lines) != 1 || lines[0].Outcome != FillFailed || lines[0].Note != full.Error() {
t.Errorf("limit: %+v", lines)
}
// No name typed and none found: not saved.
lines = FillImport(context.Background(), d, []Entry{{Websites: []string{srv.URL}, Relationship: Partner}}, FillOptions{Client: fake})
if len(lines) != 1 || lines[0].Outcome != FillFailed || !strings.Contains(lines[0].Note, "name wasn't found") {
t.Errorf("no name: %+v", lines)
}
// A site that can't be read, with a name typed: saved, with what went wrong.
lines = FillImport(context.Background(), d, []Entry{{Name: "Gone", Websites: []string{srv.URL + "/missing"}, Relationship: Watch}},
FillOptions{Client: fake})
if len(lines) != 1 || lines[0].Outcome != FillAdded || !strings.Contains(lines[0].Note, "only partly") {
t.Errorf("unreadable: %+v", lines)
}
}
+35
View File
@@ -54,6 +54,41 @@ type Entry struct {
Prices []Price `json:"prices,omitempty" yaml:"prices,omitempty"` // their plans' prices, as checked
}
// UnmarshalYAML reads an entry as written, and two shorter forms for a
// list to be filled in from the websites: `url:` or `website:` for one
// address, and a bare address in place of the whole entry.
func (e *Entry) UnmarshalYAML(n *yaml.Node) error {
if n.Kind == yaml.ScalarNode {
*e = Entry{Websites: []string{n.Value}}
return nil
}
type plain Entry // without this method
var aux struct {
plain `yaml:",inline"`
URL string `yaml:"url"`
Website string `yaml:"website"`
}
if err := n.Decode(&aux); err != nil {
return err
}
*e = Entry(aux.plain)
for _, u := range []string{aux.Website, aux.URL} {
if u = strings.TrimSpace(u); u != "" && !containsFold(e.Websites, u) {
e.Websites = append([]string{u}, e.Websites...)
}
}
return nil
}
func containsFold(list []string, s string) bool {
for _, v := range list {
if strings.EqualFold(strings.TrimSpace(v), s) {
return true
}
}
return false
}
// Normalize tidies an entry and checks it.
func (e *Entry) Normalize() error {
e.Name = strings.TrimSpace(e.Name)