| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strings" |
| 6 | |
| 7 | "gorm.io/gorm" |
| 8 | "testing" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | func names(r Result) []string { |
| 13 | var out []string |
| 14 | for _, c := range r.Cards { |
| 15 | out = append(out, c.Title()) |
| 16 | } |
| 17 | return out |
| 18 | } |
| 19 | |
| 20 | func mustQuery(t *testing.T, ix *Index, q Query) Result { |
| 21 | t.Helper() |
| 22 | if err := ix.Sync(ctx()); err != nil { |
| 23 | t.Fatalf("Sync: %v", err) |
| 24 | } |
| 25 | r, err := ix.Query(TypeCustomer, q) |
| 26 | if err != nil { |
| 27 | t.Fatalf("Query: %v", err) |
| 28 | } |
| 29 | return r |
| 30 | } |
| 31 | |
| 32 | // The index learns about every kind of write from the event log alone — |
| 33 | // nothing in store.go tells it anything. |
| 34 | func TestTheIndexFollowsTheEventLog(t *testing.T) { |
| 35 | g, s := seeded(t) |
| 36 | ix := NewIndex(g, s) |
| 37 | if r := mustQuery(t, ix, Query{}); r.Total != 0 { |
| 38 | t.Fatalf("a fresh instance has %d cards", r.Total) |
| 39 | } |
| 40 | |
| 41 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 42 | if r := mustQuery(t, ix, Query{}); r.Total != 1 { |
| 43 | t.Fatalf("a created card is not in the index (total %d)", r.Total) |
| 44 | } |
| 45 | |
| 46 | UpdateCard(ctx(), g, s, card.ID, Person(1), map[string]string{FieldName: "Cnoc Teoranta Group"}) |
| 47 | if got := names(mustQuery(t, ix, Query{})); len(got) != 1 || got[0] != "Cnoc Teoranta Group" { |
| 48 | t.Fatalf("an update is not in the index: %v", got) |
| 49 | } |
| 50 | |
| 51 | AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "talked about the renewal"}) |
| 52 | r := mustQuery(t, ix, Query{Text: "renewal"}) |
| 53 | if r.Total != 1 || r.Cards[0].Latest == nil { |
| 54 | t.Fatalf("a logged call is not searchable (total %d)", r.Total) |
| 55 | } |
| 56 | |
| 57 | DeleteCard(ctx(), g, s, card.ID, Person(1)) |
| 58 | if r := mustQuery(t, ix, Query{}); r.Total != 0 { |
| 59 | t.Fatalf("a deleted card is still in the index") |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | func seedMany(t *testing.T, n int) (*Index, func()) { |
| 64 | t.Helper() |
| 65 | g, s := seeded(t) |
| 66 | stages := []string{"Lead", "Contacted", "Proposal", "Won", "Lost"} |
| 67 | for i := 0; i < n; i++ { |
| 68 | v := map[string]string{ |
| 69 | FieldName: fmt.Sprintf("Company %04d", i), |
| 70 | FieldEmail: fmt.Sprintf("hello%04d@example.com", i), |
| 71 | FieldStage: stages[i%len(stages)], |
| 72 | } |
| 73 | if i%3 == 0 { |
| 74 | v[FieldNextAction] = time.Date(2026, 10, 1+i%28, 0, 0, 0, 0, time.UTC).Format("2006-01-02") |
| 75 | } |
| 76 | if _, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), v); err != nil { |
| 77 | t.Fatalf("seeding card %d: %v", i, err) |
| 78 | } |
| 79 | } |
| 80 | return NewIndex(g, s), func() {} |
| 81 | } |
| 82 | |
| 83 | func TestSearchNeedsEveryTerm(t *testing.T) { |
| 84 | ix, _ := seedMany(t, 30) |
| 85 | r := mustQuery(t, ix, Query{Text: "company 0012"}) |
| 86 | if r.Total != 1 || r.Cards[0].Title() != "Company 0012" { |
| 87 | t.Fatalf("two-term search found %v", names(r)) |
| 88 | } |
| 89 | if r := mustQuery(t, ix, Query{Text: "COMPANY"}); r.Total != 30 { |
| 90 | t.Fatalf("search is case-sensitive: %d of 30", r.Total) |
| 91 | } |
| 92 | if r := mustQuery(t, ix, Query{Text: "company nosuchthing"}); r.Total != 0 { |
| 93 | t.Fatalf("a term that matches nothing still matched %d", r.Total) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | func TestFiltersApplyToChoiceFieldsOnly(t *testing.T) { |
| 98 | ix, _ := seedMany(t, 30) |
| 99 | r := mustQuery(t, ix, Query{Filters: map[string]string{FieldStage: "Won"}}) |
| 100 | if r.Total != 6 { |
| 101 | t.Fatalf("Stage = Won matched %d, want 6", r.Total) |
| 102 | } |
| 103 | for _, c := range r.Cards { |
| 104 | if c.Field(FieldStage).Value != "Won" { |
| 105 | t.Fatalf("a filtered result has stage %q", c.Field(FieldStage).Value) |
| 106 | } |
| 107 | } |
| 108 | // Equality on a free-text field would silently miss on case and |
| 109 | // spacing, so it is ignored rather than honoured. |
| 110 | if r := mustQuery(t, ix, Query{Filters: map[string]string{FieldName: "company 0001"}}); r.Total != 30 { |
| 111 | t.Fatalf("a filter on a text field was applied (%d results)", r.Total) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | func TestSortingPutsEmptyValuesLast(t *testing.T) { |
| 116 | ix, _ := seedMany(t, 30) |
| 117 | for _, desc := range []bool{false, true} { |
| 118 | r := mustQuery(t, ix, Query{Sort: FieldNextAction, Desc: desc}) |
| 119 | seenEmpty := false |
| 120 | prev := "" |
| 121 | for _, c := range r.Cards { |
| 122 | v := c.Field(FieldNextAction).Value |
| 123 | if v == "" { |
| 124 | seenEmpty = true |
| 125 | continue |
| 126 | } |
| 127 | if seenEmpty { |
| 128 | t.Fatalf("desc=%v: a card with a next action sorted after one without", desc) |
| 129 | } |
| 130 | if prev != "" && ((!desc && v < prev) || (desc && v > prev)) { |
| 131 | t.Fatalf("desc=%v: %s came after %s", desc, v, prev) |
| 132 | } |
| 133 | prev = v |
| 134 | } |
| 135 | } |
| 136 | r := mustQuery(t, ix, Query{Sort: FieldName}) |
| 137 | if r.Cards[0].Title() != "Company 0000" || r.Cards[len(r.Cards)-1].Title() != "Company 0029" { |
| 138 | t.Fatalf("name sort is %v…", names(r)[:3]) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | func TestPaging(t *testing.T) { |
| 143 | ix, _ := seedMany(t, 250) |
| 144 | r := mustQuery(t, ix, Query{Sort: FieldName, Page: 3, PerPage: 100}) |
| 145 | if r.Pages != 3 || r.Page != 3 || len(r.Cards) != 50 || r.First != 201 || r.Last != 250 { |
| 146 | t.Fatalf("page 3 of 250 at 100: pages=%d page=%d rows=%d first=%d last=%d", |
| 147 | r.Pages, r.Page, len(r.Cards), r.First, r.Last) |
| 148 | } |
| 149 | if r := mustQuery(t, ix, Query{Page: 99}); r.Page != 3 { |
| 150 | t.Fatalf("a page past the end is %d, want clamped to 3", r.Page) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | // BenchmarkSearch is the "instant at thousands of rows" claim, measured. |
| 155 | // |
| 156 | // go test ./internal/fichas -run xxx -bench Search -benchtime 200x |
| 157 | func BenchmarkSearch(b *testing.B) { |
| 158 | b.StopTimer() |
| 159 | g, s := seeded(b) |
| 160 | stages := []string{"Lead", "Contacted", "Proposal", "Won", "Lost"} |
| 161 | // Every card gets two calls. The first version of this benchmark seeded |
| 162 | // none, so the cold load it reported never ran the latest-call path — |
| 163 | // which was the slow one. |
| 164 | for i := 0; i < 5000; i++ { |
| 165 | c, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{ |
| 166 | FieldName: fmt.Sprintf("Company %04d", i), |
| 167 | FieldEmail: fmt.Sprintf("hello%04d@example.com", i), |
| 168 | FieldStage: stages[i%5], |
| 169 | FieldNotes: "Renewal is tied to their grant cycle; the budget holder signs off in March.", |
| 170 | }) |
| 171 | for k := 0; k < 2; k++ { |
| 172 | AddEntry(ctx(), g, s, c.ID, Person(1), TypeCallLog, "manual", |
| 173 | map[string]string{FieldBody: fmt.Sprintf("Call %d about the pilot scope.", k)}) |
| 174 | } |
| 175 | } |
| 176 | ix := NewIndex(g, s) |
| 177 | start := time.Now() |
| 178 | if err := ix.Sync(ctx()); err != nil { |
| 179 | b.Fatal(err) |
| 180 | } |
| 181 | b.ReportMetric(float64(time.Since(start).Milliseconds()), "ms-cold-load") |
| 182 | b.StartTimer() |
| 183 | for i := 0; i < b.N; i++ { |
| 184 | if err := ix.Sync(ctx()); err != nil { |
| 185 | b.Fatal(err) |
| 186 | } |
| 187 | r, err := ix.Query(TypeCustomer, Query{Text: "renewal 042", Filters: map[string]string{FieldStage: "Proposal"}, Sort: FieldName, PerPage: 100}) |
| 188 | if err != nil || r.All != 5000 { |
| 189 | b.Fatalf("query: %v (all=%d)", err, r.All) |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | func TestSearchTermsAreBounded(t *testing.T) { |
| 195 | long := strings.Repeat("a b c ", 10000) |
| 196 | if n := len(searchTerms(long)); n != 3 { |
| 197 | t.Fatalf("duplicate terms were not collapsed: %d", n) |
| 198 | } |
| 199 | var many []string |
| 200 | for i := 0; i < 100; i++ { |
| 201 | many = append(many, fmt.Sprintf("t%d", i)) |
| 202 | } |
| 203 | if n := len(searchTerms(strings.Join(many, " "))); n != maxTerms { |
| 204 | t.Fatalf("%d terms kept, want %d", n, maxTerms) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // The latest-call load is batched: its query count must not grow with the |
| 209 | // number of cards. |
| 210 | func TestLatestEntriesIsBatched(t *testing.T) { |
| 211 | g, s := seeded(t) |
| 212 | var ids []int64 |
| 213 | for i := 0; i < 40; i++ { |
| 214 | c, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: fmt.Sprintf("C%d", i)}) |
| 215 | AddEntry(ctx(), g, s, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "hello"}) |
| 216 | ids = append(ids, c.ID) |
| 217 | } |
| 218 | var queries int |
| 219 | cb := "count_queries" |
| 220 | g.Callback().Query().After("gorm:query").Register(cb, func(*gorm.DB) { queries++ }) |
| 221 | defer g.Callback().Query().Remove(cb) |
| 222 | got, err := latestEntries(g, s, ids) |
| 223 | if err != nil || len(got) != 40 { |
| 224 | t.Fatalf("latestEntries: %v, %d found", err, len(got)) |
| 225 | } |
| 226 | if queries > 6 { |
| 227 | t.Fatalf("latestEntries ran %d queries for 40 cards; it is not batched", queries) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // Seeding writes events, so a field the catalogue adds after an index has |
| 232 | // loaded reaches it — the rebuild branch the first version could never take. |
| 233 | func TestSeedingIsInTheChangeFeed(t *testing.T) { |
| 234 | g, s := seeded(t) |
| 235 | var n int64 |
| 236 | g.Model(&Event{}).Where("object_kind IN ?", []string{ObjectType, ObjectField}).Count(&n) |
| 237 | want := int64(len(catalogue)) |
| 238 | for _, c := range catalogue { |
| 239 | want += int64(len(c.Fields)) |
| 240 | } |
| 241 | if n != want { |
| 242 | t.Fatalf("seeding logged %d schema events, want %d", n, want) |
| 243 | } |
| 244 | |
| 245 | ix := NewIndex(g, s) |
| 246 | mustQuery(t, ix, Query{}) |
| 247 | restore := catalogue |
| 248 | catalogue = append([]seedType(nil), catalogue...) |
| 249 | catalogue[0].Fields = append(append([]seedField(nil), catalogue[0].Fields...), |
| 250 | seedField{Key: "f_website", Label: "Website", Kind: KindText, Tier: TierPrint}) |
| 251 | t.Cleanup(func() { catalogue = restore }) |
| 252 | if err := Seed(g, s); err != nil { |
| 253 | t.Fatalf("Seed: %v", err) |
| 254 | } |
| 255 | ix.Sync(ctx()) |
| 256 | fields, _ := ix.Fields(TypeCustomer) |
| 257 | for _, f := range fields { |
| 258 | if f.Def.Key == "f_website" { |
| 259 | return |
| 260 | } |
| 261 | } |
| 262 | t.Fatal("a field seeded after the index loaded never reached it") |
| 263 | } |
| 264 | |