package prospects import ( "time" "supermarket/internal/db" ) // ListMember is a mailing list a person was added to. type ListMember struct { ListID int64 List string Confirmed bool // added as having agreed; else the list asked them to confirm At time.Time } // AddedToList records that a person was added to a mailing list. func AddedToList(d *db.DB, contactID, listID int64, list string, confirmed bool, now time.Time) error { c := 0 if confirmed { c = 1 } _, err := d.Exec(`INSERT INTO list_members (contact_id, list_id, list_name, confirmed, at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (contact_id, list_id) DO UPDATE SET list_name = excluded.list_name, confirmed = max(confirmed, excluded.confirmed)`, contactID, listID, list, c, now.UTC().Format(time.RFC3339)) return err } // ListsOf are the mailing lists each person was added to, by contact ID. func ListsOf(d *db.DB) (map[int64][]ListMember, error) { rows, err := d.Query(`SELECT contact_id, list_id, list_name, confirmed, at FROM list_members ORDER BY at`) if err != nil { return nil, err } defer rows.Close() out := map[int64][]ListMember{} for rows.Next() { var id int64 var m ListMember var at string var c int if err := rows.Scan(&id, &m.ListID, &m.List, &c, &at); err != nil { return nil, err } m.Confirmed = c == 1 m.At, _ = time.Parse(time.RFC3339, at) out[id] = append(out[id], m) } return out, rows.Err() }