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:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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, `<a href="/settings/ai">Set up the AI</a>`) {
|
||||
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", `<a href="/market/7">Rival</a>`, "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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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).",
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
<p><a href="/market">← Market</a></p>
|
||||
<h1>Import into the Market</h1>
|
||||
|
||||
{{template "fill-status" .Fill}}
|
||||
|
||||
{{with .Result}}
|
||||
<section class="card {{if .Errors}}warn{{end}}">
|
||||
<p>{{.Added}} added, {{.Updated}} updated, {{.Skipped}} skipped (already in the Market).</p>
|
||||
@@ -16,7 +18,9 @@
|
||||
- name: Example
|
||||
relationship: competitor
|
||||
twitter_handle: example
|
||||
hashtags: ['#Example']">{{.YAML}}</textarea></label>
|
||||
hashtags: ['#Example']
|
||||
- url: https://rival.example
|
||||
relationship: competitor">{{.YAML}}</textarea></label>
|
||||
<label>…or choose a file <input type="file" name="file" accept=".yaml,.yml,text/yaml"></label>
|
||||
<div class="cols">
|
||||
<label>Relationship for entries without one
|
||||
@@ -24,6 +28,8 @@
|
||||
</label>
|
||||
<label class="check"><input type="checkbox" name="overwrite"> Replace entries that already exist</label>
|
||||
</div>
|
||||
<label class="check"><input type="checkbox" name="fill" {{if .NoAI}}disabled{{end}}> Fill in the empty boxes from each website</label>
|
||||
<p class="help">{{if .NoAI}}<a href="/settings/ai">Set up the AI</a> to fill entries in. {{end}}Each entry then needs only its website, as <code>url:</code>, 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.</p>
|
||||
<div class="actions">
|
||||
<button type="submit">Import</button>
|
||||
<button type="submit" name="example" value="federated" class="secondary">Load the Federated example</button>
|
||||
@@ -31,3 +37,25 @@
|
||||
<p class="help">The Federated example is the 21 open source applications on a Federated Core, as partners.</p>
|
||||
</form>
|
||||
{{end}}{{end}}
|
||||
|
||||
{{define "fill-status"}}{{with .}}
|
||||
<section class="card {{if or .Stopped (.Count "failed")}}warn{{end}}" id="fill-status"{{if .Running}} hx-get="/market/import/status" hx-trigger="every 4s" hx-swap="outerHTML"{{end}}>
|
||||
<h2>Filled in from their websites</h2>
|
||||
<p>{{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"}}.</p>
|
||||
{{if .Lines}}
|
||||
<table>
|
||||
<thead><tr><th>Website</th><th>Name</th><th>Result</th><th></th></tr></thead>
|
||||
<tbody>{{range .Lines}}
|
||||
<tr>
|
||||
<td>{{.Site}}</td>
|
||||
<td>{{if .ID}}<a href="/market/{{.ID}}">{{.Name}}</a>{{else}}{{.Name}}{{end}}</td>
|
||||
<td>{{.Outcome}}</td>
|
||||
<td>{{.Note}}{{if and .Note .Filled}}; {{end}}{{if .Filled}}filled: {{range $i, $f := .Filled}}{{if $i}}, {{end}}{{$f}}{{end}}{{end}}</td>
|
||||
</tr>{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
{{if not .Running}}<p><a href="/market">See the Market</a></p>{{end}}
|
||||
</section>
|
||||
{{end}}{{end}}
|
||||
|
||||
Reference in New Issue
Block a user