diff --git a/README.md b/README.md index 4f802db..9e8877a 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Then open Supermarket and: 1. **Settings → AI**: Anthropic, with Hermes' key (shared by `supermarket hermes`) or your own, or an LLM server on your network, such as Ollama. Servers found by CoreDesktop's `configure ai-servers` are offered. 2. **Settings → Profile**: enter your website and press *Draft*. Correct the draft and save it. -3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits aren't checked with Reddit: open each before posting there. What you typed stays; nothing is saved until you press Save. +3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits aren't checked with Reddit: open each before posting there. What you typed stays; nothing is saved until you press Save. To add many at once, *Import* a list of just websites and relationships (`- url: https://…` / `relationship: competitor`) and tick *Fill in the empty boxes from each website*: each is filled in the same way in the background, a few at a time, and saved straight into the Market; ones already there (by name or website) are skipped without reading their site. 4. **Settings → Social accounts**: connect X and LinkedIn. Reddit needs nothing: you post Reddit drafts yourself. The menu on the left has a search box at the top (press `/` to jump to it), then the **Overview** with a card per module, the **Inventory**, and the modules: **Content** (Posts, Sources, Scheduled, Published), and the ones still to come. **Settings**, at the bottom, holds the Profile, Social accounts, Core & Hermes, and AI. Search finds posts, fetched items, inventory entries, your products and settings pages. The look follows brain (Federated's superbrain), including a dark theme that follows your system's setting. diff --git a/TEST.md b/TEST.md index c6e4722..5487021 100644 --- a/TEST.md +++ b/TEST.md @@ -179,6 +179,15 @@ Throughout, also notice: rest from its website. - [x] Edit and delete an entry. - [x] *Export*, then *Import* the file again: nothing is duplicated. +- [ ] **(costs)** On *Import*, paste a list of only `url:` and + `relationship:` (say three, one already in the Market, one a site + that doesn't exist) and tick *Fill in the empty boxes from each + website*. The page counts them off as they're done; the new ones are + in the Market, filled in, with the relationship given. The one already + there is skipped without its site being read; the bad site fails with + the reason. +- [ ] Without the AI set up, the box can't be ticked; a list of websites + only, imported without it, says to tick it. ## 5. Content diff --git a/internal/inventory/fillimport.go b/internal/inventory/fillimport.go new file mode 100644 index 0000000..21ae200 --- /dev/null +++ b/internal/inventory/fillimport.go @@ -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, "/")) +} diff --git a/internal/inventory/fillimport_test.go b/internal/inventory/fillimport_test.go new file mode 100644 index 0000000..c4c838b --- /dev/null +++ b/internal/inventory/fillimport_test.go @@ -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) + } +} diff --git a/internal/inventory/inventory.go b/internal/inventory/inventory.go index 18002ac..8864357 100644 --- a/internal/inventory/inventory.go +++ b/internal/inventory/inventory.go @@ -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) diff --git a/internal/web/inventory.go b/internal/web/inventory.go index 8b25572..99ee9a9 100644 --- a/internal/web/inventory.go +++ b/internal/web/inventory.go @@ -200,9 +200,19 @@ func (s *Server) inventoryDelete(w http.ResponseWriter, r *http.Request) { } func (s *Server) inventoryImportPage(w http.ResponseWriter, r *http.Request) { - s.render(w, r, "import", page{Title: "Import into the Market", Nav: "inventory", Data: map[string]any{ + s.render(w, r, "import", page{Title: "Import into the Market", Nav: "inventory", Data: s.importData(r, nil)}) +} + +// importData is the import page's: the form, and the last list filled in +// from the websites. +func (s *Server) importData(r *http.Request, res *inventory.ImportResult) map[string]any { + return map[string]any{ "Relationships": inventory.Relationships, - }}) + "Result": res, + "YAML": r.FormValue("yaml"), + "NoAI": !s.aiReady(), + "Fill": s.marketFill(), + } } const maxImportBytes = 4 << 20 @@ -216,11 +226,7 @@ func (s *Server) inventoryImport(w http.ResponseWriter, r *http.Request) { rel := r.FormValue("relationship") overwrite := r.FormValue("overwrite") == "on" show := func(errMsg string, res *inventory.ImportResult) { - s.render(w, r, "import", page{Title: "Import into the Market", Nav: "inventory", Error: errMsg, Data: map[string]any{ - "Relationships": inventory.Relationships, - "Result": res, - "YAML": r.FormValue("yaml"), - }}) + s.render(w, r, "import", page{Title: "Import into the Market", Nav: "inventory", Error: errMsg, Data: s.importData(r, res)}) } var data []byte @@ -252,6 +258,20 @@ func (s *Server) inventoryImport(w http.ResponseWriter, r *http.Request) { show(err.Error(), nil) return } + if r.FormValue("fill") == "on" && r.FormValue("example") == "" { + if err := s.startMarketFill(entries, overwrite); err != nil { + show(err.Error(), nil) + return + } + redirect(w, r, "/market/import", "filling") + return + } + for _, e := range entries { + if strings.TrimSpace(e.Name) == "" && len(e.Websites) > 0 { + show(`Some entries have only a website: tick "Fill in the empty boxes from each website" to have the AI fill them in.`, nil) + return + } + } res := inventory.Import(s.DB, entries, overwrite) show("", &res) } diff --git a/internal/web/inventory_test.go b/internal/web/inventory_test.go index 89b6d85..42f02db 100644 --- a/internal/web/inventory_test.go +++ b/internal/web/inventory_test.go @@ -47,3 +47,46 @@ func TestMarketMoved(t *testing.T) { t.Errorf("post: %d %s", rec.Code, rec.Header().Get("Location")) } } + +func TestMarketImportFill(t *testing.T) { + s, h := newTestServer(t, nil) + list := "- url: https://rival.example\n relationship: competitor\n" + + // Without AI: the box can't be ticked, and says why if it is. + body := do(h, http.MethodGet, "/market/import", nil, nil).Body.String() + if !strings.Contains(body, `name="fill" disabled`) || !strings.Contains(body, `Set up the AI`) { + t.Errorf("import page without AI:\n%s", body) + } + body = postForm(h, "/market/import", url.Values{"yaml": {list}, "fill": {"on"}}).Body.String() + if !strings.Contains(body, "set up the AI to fill entries in") || !strings.Contains(body, "rival.example") { + t.Errorf("fill without AI:\n%s", body) + } + // Websites only, without the box ticked: says to tick it. + body = postForm(h, "/market/import", url.Values{"yaml": {list}}).Body.String() + if !strings.Contains(body, "Some entries have only a website") { + t.Errorf("websites only, not filled:\n%s", body) + } + + // The last list's progress, from the setting. + st := marketFillState{Running: false, Total: 2, Lines: []inventory.FillLine{ + {Site: "https://rival.example", Name: "Rival", ID: 7, Outcome: inventory.FillAdded, Filled: []string{"X handle", "description"}}, + {Site: "https://gone.example", Outcome: inventory.FillFailed, Note: "no such host"}, + }} + if err := s.DB.PutJSON(marketFillKey, st); err != nil { + t.Fatal(err) + } + body = do(h, http.MethodGet, "/market/import", nil, nil).Body.String() + for _, want := range []string{"1 added, 0 updated, 0 skipped, 1 failed", `Rival`, "filled: X handle, description", "no such host"} { + if !strings.Contains(body, want) { + t.Errorf("progress lacks %q", want) + } + } + // One left running with nothing doing it was stopped with the app; + // the card stops polling. + st.Running = true + _ = s.DB.PutJSON(marketFillKey, st) + body = do(h, http.MethodGet, "/market/import/status", nil, nil).Body.String() + if !strings.Contains(body, "Stopped with the app after 2 of 2") || strings.Contains(body, "hx-trigger") { + t.Errorf("status:\n%s", body) + } +} diff --git a/internal/web/marketfill.go b/internal/web/marketfill.go new file mode 100644 index 0000000..50b388c --- /dev/null +++ b/internal/web/marketfill.go @@ -0,0 +1,132 @@ +package web + +import ( + "context" + "errors" + "net/http" + "sync" + "time" + + "supermarket/internal/ai" + "supermarket/internal/inventory" + "supermarket/internal/jobs" + "supermarket/internal/profile" +) + +// A list imported into the Market and filled in from the websites runs in +// the background; where it is is kept as a setting, so every copy of the +// app shows it. +const ( + marketFillKey = "market:fill" + marketFillLock = "market-fill" + // marketFillMax is how long a whole list may take. + marketFillMax = 2 * time.Hour +) + +// marketFillState is the last list filled in. +type marketFillState struct { + Running bool `json:"running"` + Stopped bool `json:"stopped,omitempty"` // the app stopped before it was done + Started time.Time `json:"started"` + Finished time.Time `json:"finished,omitzero"` + Total int `json:"total"` + Lines []inventory.FillLine `json:"lines"` +} + +func (f *marketFillState) Done() int { return len(f.Lines) } + +// Count is how many entries had the outcome. +func (f *marketFillState) Count(outcome string) int { + n := 0 + for _, l := range f.Lines { + if l.Outcome == outcome { + n++ + } + } + return n +} + +// marketFill is the last list filled in, or nil. One that says it's +// running when nothing holds its lock was stopped with the app. +func (s *Server) marketFill() *marketFillState { + var f marketFillState + ok, err := s.DB.GetJSON(marketFillKey, &f) + if err != nil { + s.Log.Warn("market: reading the fill", "err", err) + } + if !ok || err != nil { + return nil + } + if f.Running { + _, release, err := s.jobs().TryLock(context.Background(), s.lockName(marketFillLock)) + if err == nil { + release() + f.Running, f.Stopped = false, true + _ = s.DB.PutJSON(marketFillKey, f) + } + } + return &f +} + +// startMarketFill adds the entries in the background, each filled in from +// its website. +func (s *Server) startMarketFill(entries []inventory.Entry, overwrite bool) error { + if len(entries) == 0 { + return errors.New("the list has no entries") + } + cfg, err := ai.LoadConfig(s.DB) + if err != nil { + return err + } + client, err := ai.New(cfg, s.Secrets) + if err != nil { + return errors.New(err.Error() + ": set up the AI to fill entries in") + } + ours, err := profile.Load(s.DB) + if err != nil { + return err + } + lctx, release, err := s.jobs().TryLock(context.Background(), s.lockName(marketFillLock)) + if errors.Is(err, jobs.ErrBusy) { + return errors.New("a list is already being filled in: wait for it to finish") + } + if err != nil { + return err + } + st := marketFillState{Running: true, Started: time.Now(), Total: len(entries)} + if err := s.DB.PutJSON(marketFillKey, st); err != nil { + release() + return err + } + go func() { + defer release() + ctx, cancel := context.WithTimeout(lctx, marketFillMax) + defer cancel() + var mu sync.Mutex + save := func() { + if err := s.DB.PutJSON(marketFillKey, st); err != nil { + s.Log.Warn("market: saving the fill's progress", "err", err) + } + } + inventory.FillImport(ctx, s.DB, entries, inventory.FillOptions{ + Client: client, Ours: ours, Overwrite: overwrite, Room: s.limitSources, + Done: func(l inventory.FillLine) { + mu.Lock() + defer mu.Unlock() + st.Lines = append(st.Lines, l) + save() + }, + }) + mu.Lock() + defer mu.Unlock() + st.Running, st.Finished = false, time.Now() + save() + }() + return nil +} + +// inventoryFillStatus is polled while a list is filled in: the progress +// card, which stops polling once it's done. +func (s *Server) inventoryFillStatus(w http.ResponseWriter, r *http.Request) { + s.fragment(w, r, "import", "fill-status", s.marketFill()) +} diff --git a/internal/web/server.go b/internal/web/server.go index 03b0311..42a4057 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -397,6 +397,7 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /market/{id}/delete", (*Server).inventoryDelete) mux.HandleFunc("GET /market/import", (*Server).inventoryImportPage) mux.HandleFunc("POST /market/import", (*Server).inventoryImport) + mux.HandleFunc("GET /market/import/status", (*Server).inventoryFillStatus) mux.HandleFunc("GET /market/export", (*Server).inventoryExport) // The Market was the Inventory: its old addresses lead to the new ones // (308 keeps a form's POST a POST). @@ -1017,6 +1018,7 @@ var flashes = map[string]string{ "listed": "Added to the mailing list.", "bing-read": "Read the links from Bing.", "audited": "The audit is done.", + "filling": "Filling them in from their websites, a few at a time: each takes a minute or two. This page updates as they're 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.", "crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).", diff --git a/internal/web/templates/import.html b/internal/web/templates/import.html index e5eb795..22656b1 100644 --- a/internal/web/templates/import.html +++ b/internal/web/templates/import.html @@ -2,6 +2,8 @@

← Market

Import into the Market

+{{template "fill-status" .Fill}} + {{with .Result}}

{{.Added}} added, {{.Updated}} updated, {{.Skipped}} skipped (already in the Market).

@@ -16,7 +18,9 @@ - name: Example relationship: competitor twitter_handle: example - hashtags: ['#Example']">{{.YAML}} + hashtags: ['#Example'] +- url: https://rival.example + relationship: competitor">{{.YAML}}
+ +

{{if .NoAI}}Set up the AI to fill entries in. {{end}}Each entry then needs only its website, as url:, and its relationship; the AI fills in the rest, as on New entry, and they're saved straight into the Market. Entries already there, by name or website, are skipped without reading their site.

@@ -31,3 +37,25 @@

The Federated example is the 21 open source applications on a Federated Core, as partners.

{{end}}{{end}} + +{{define "fill-status"}}{{with .}} +
+

Filled in from their websites

+

{{if .Running}}{{.Done}} of {{.Total}} done…{{else if .Stopped}}Stopped with the app after {{.Done}} of {{.Total}}: import the rest again (the ones added are skipped).{{else}}Done: {{.Count "added"}} added, {{.Count "updated"}} updated, {{.Count "skipped"}} skipped, {{.Count "failed"}} failed.{{end}} + Started {{.Started.Format "2 Jan 15:04"}}.

+ {{if .Lines}} + + + {{range .Lines}} + + + + + + {{end}} + +
WebsiteNameResult
{{.Site}}{{if .ID}}{{.Name}}{{else}}{{.Name}}{{end}}{{.Outcome}}{{.Note}}{{if and .Note .Filled}}; {{end}}{{if .Filled}}filled: {{range $i, $f := .Filled}}{{if $i}}, {{end}}{{$f}}{{end}}{{end}}
+ {{end}} + {{if not .Running}}

See the Market

{{end}} +
+{{end}}{{end}}