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, "/")) }