| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "testing" |
| 8 | |
| 9 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | func ctx() context.Context { return context.Background() } |
| 14 | |
| 15 | func seeded(t testing.TB) (*gorm.DB, *seal.Sealer) { |
| 16 | t.Helper() |
| 17 | g, s := testDB(t), testSealer(t) |
| 18 | if err := Seed(g, s); err != nil { |
| 19 | t.Fatalf("Seed: %v", err) |
| 20 | } |
| 21 | // Members are a real foreign key now, so the people these tests name |
| 22 | // have to exist. Ids 1..10 cover every actor used below. |
| 23 | for i := 1; i <= 10; i++ { |
| 24 | pr, err := s.Print("f_member", []byte(fmt.Sprintf("person-%d@example.com", i))) |
| 25 | if err != nil { |
| 26 | t.Fatalf("print: %v", err) |
| 27 | } |
| 28 | if err := g.Create(&Member{AddressPrint: pr}).Error; err != nil { |
| 29 | t.Fatalf("creating member %d: %v", i, err) |
| 30 | } |
| 31 | } |
| 32 | return g, s |
| 33 | } |
| 34 | |
| 35 | func events(t *testing.T, g *gorm.DB, kind string, id int64) []Event { |
| 36 | t.Helper() |
| 37 | var out []Event |
| 38 | if err := g.Where("object_kind = ? AND object_id = ?", kind, id).Order("id").Find(&out).Error; err != nil { |
| 39 | t.Fatalf("loading events: %v", err) |
| 40 | } |
| 41 | return out |
| 42 | } |
| 43 | |
| 44 | func TestCreateCardSealsAndLogs(t *testing.T) { |
| 45 | g, s := seeded(t) |
| 46 | card, err := CreateCard(ctx(), g, s, TypeCustomer, Person(7), map[string]string{ |
| 47 | FieldName: "Cnoc Teoranta", |
| 48 | FieldEmail: "ana@example.com", |
| 49 | FieldNotes: "spoke at the trade show", |
| 50 | }) |
| 51 | if err != nil { |
| 52 | t.Fatalf("CreateCard: %v", err) |
| 53 | } |
| 54 | // A new card's revision is random and positive, and so is its nonce |
| 55 | // (store.go nextRevision, randomPositive). |
| 56 | if card.ID == 0 || card.Revision < 1 || card.Nonce < 1 || card.OwnerID == nil || *card.OwnerID != 7 { |
| 57 | t.Fatalf("card is %+v", card) |
| 58 | } |
| 59 | |
| 60 | var vals []CardValue |
| 61 | g.Where("card_id = ?", card.ID).Find(&vals) |
| 62 | if len(vals) != 3 { |
| 63 | t.Fatalf("wrote %d values, want 3", len(vals)) |
| 64 | } |
| 65 | for _, v := range vals { |
| 66 | if len(v.SealedValue) == 0 { |
| 67 | t.Fatal("a value was stored with nothing sealed in it") |
| 68 | } |
| 69 | raw, err := s.Open(seal.PurposeValue, v.SealedValue) |
| 70 | if err != nil { |
| 71 | t.Fatalf("opening a value: %v", err) |
| 72 | } |
| 73 | if string(raw) == "" { |
| 74 | t.Fatal("a sealed value opened to nothing") |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | ev := events(t, g, ObjectCard, card.ID) |
| 79 | if len(ev) != 1 || ev[0].Kind != EventCreated || ev[0].ActorID == nil || *ev[0].ActorID != 7 || ev[0].Revision != card.Revision { |
| 80 | t.Fatalf("events are %+v", ev) |
| 81 | } |
| 82 | var changed []int64 |
| 83 | if err := json.Unmarshal([]byte(ev[0].ChangedFields), &changed); err != nil { |
| 84 | t.Fatalf("ChangedFields is not a JSON array: %q", ev[0].ChangedFields) |
| 85 | } |
| 86 | if len(changed) != 3 { |
| 87 | t.Fatalf("logged %d changed fields, want 3", len(changed)) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // Only printed fields get a print, and a print must actually be usable to |
| 92 | // find the row again — that is the entire point of it. |
| 93 | func TestCreateCardPrintsOnlyPrintedFields(t *testing.T) { |
| 94 | g, s := seeded(t) |
| 95 | card, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{ |
| 96 | FieldName: "Cnoc Teoranta", |
| 97 | FieldEmail: "Ana@Example.com", // capitalised on purpose |
| 98 | FieldNotes: "not a printed field", |
| 99 | }) |
| 100 | if err != nil { |
| 101 | t.Fatalf("CreateCard: %v", err) |
| 102 | } |
| 103 | |
| 104 | var email, notes FieldDef |
| 105 | g.Where("key = ?", FieldEmail).First(&email) |
| 106 | g.Where("key = ?", FieldNotes).First(¬es) |
| 107 | |
| 108 | var ev, nv CardValue |
| 109 | g.Where("card_id = ? AND field_def_id = ?", card.ID, email.ID).First(&ev) |
| 110 | g.Where("card_id = ? AND field_def_id = ?", card.ID, notes.ID).First(&nv) |
| 111 | |
| 112 | if ev.Print == "" { |
| 113 | t.Fatal("a TierPrint field was stored with no print") |
| 114 | } |
| 115 | if nv.Print != "" { |
| 116 | t.Fatal("a TierSealed field was stored with a print: its equality classes are published") |
| 117 | } |
| 118 | |
| 119 | // Canonicalisation means the lowercase form finds the capitalised row. |
| 120 | want, err := printFor(s, email, "ana@example.com") |
| 121 | if err != nil { |
| 122 | t.Fatalf("printFor: %v", err) |
| 123 | } |
| 124 | if ev.Print != want { |
| 125 | t.Fatal("the stored print does not match the canonical form; dedupe would miss") |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func TestUpdateCardLogsBeforeAndAfter(t *testing.T) { |
| 130 | g, s := seeded(t) |
| 131 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta", FieldStage: "Lead"}) |
| 132 | |
| 133 | if err := UpdateCard(ctx(), g, s, card.ID, Person(2), map[string]string{FieldStage: "Proposal"}); err != nil { |
| 134 | t.Fatalf("UpdateCard: %v", err) |
| 135 | } |
| 136 | |
| 137 | ev := events(t, g, ObjectCard, card.ID) |
| 138 | if len(ev) != 2 { |
| 139 | t.Fatalf("%d events after one update, want 2", len(ev)) |
| 140 | } |
| 141 | last := ev[1] |
| 142 | var reread Card |
| 143 | g.First(&reread, card.ID) |
| 144 | if last.Kind != EventUpdated || last.ActorID == nil || *last.ActorID != 2 || |
| 145 | last.Revision == card.Revision || last.Revision < 1 || last.Revision != reread.Revision { |
| 146 | t.Fatalf("update event is %+v (card created at %d, now at %d)", last, card.Revision, reread.Revision) |
| 147 | } |
| 148 | raw, err := s.Open(seal.PurposeEventPayload, last.PayloadSealed) |
| 149 | if err != nil { |
| 150 | t.Fatalf("opening the payload: %v", err) |
| 151 | } |
| 152 | var changes []change |
| 153 | if err := json.Unmarshal(raw, &changes); err != nil { |
| 154 | t.Fatalf("payload is not changes: %v", err) |
| 155 | } |
| 156 | if len(changes) != 1 || changes[0].Before != "Lead" || changes[0].After != "Proposal" { |
| 157 | t.Fatalf("payload is %+v", changes) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // A log full of no-op rows is a log nobody reads, and "who touched this" |
| 162 | // stops meaning anything if pressing save counts. |
| 163 | func TestUpdateCardWithNoChangeWritesNoEvent(t *testing.T) { |
| 164 | g, s := seeded(t) |
| 165 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta", FieldStage: "Lead"}) |
| 166 | |
| 167 | if err := UpdateCard(ctx(), g, s, card.ID, Person(1), map[string]string{FieldName: "Cnoc Teoranta", FieldStage: "Lead"}); err != nil { |
| 168 | t.Fatalf("UpdateCard: %v", err) |
| 169 | } |
| 170 | if n := len(events(t, g, ObjectCard, card.ID)); n != 1 { |
| 171 | t.Fatalf("%d events after a no-op update, want 1", n) |
| 172 | } |
| 173 | var reread Card |
| 174 | g.First(&reread, card.ID) |
| 175 | if reread.Revision != card.Revision { |
| 176 | t.Fatalf("a no-op update moved the revision from %d to %d", card.Revision, reread.Revision) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // A field the card type does not define must fail, not be dropped: a |
| 181 | // silently ignored field is a value a person believes they saved. |
| 182 | func TestWritingAnUnknownFieldFails(t *testing.T) { |
| 183 | g, s := seeded(t) |
| 184 | if _, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{"f_nonsense": "x"}); err == nil { |
| 185 | t.Fatal("an unknown field key was accepted") |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func TestDeleteCardKeepsTheRowAndTheActor(t *testing.T) { |
| 190 | g, s := seeded(t) |
| 191 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 192 | |
| 193 | if err := DeleteCard(ctx(), g, s, card.ID, Person(9)); err != nil { |
| 194 | t.Fatalf("DeleteCard: %v", err) |
| 195 | } |
| 196 | var reread Card |
| 197 | if err := g.First(&reread, card.ID).Error; err != nil { |
| 198 | t.Fatalf("the row is gone from the table, not marked gone: %v", err) |
| 199 | } |
| 200 | if !reread.Gone { |
| 201 | t.Fatal("the card is not marked gone") |
| 202 | } |
| 203 | ev := events(t, g, ObjectCard, card.ID) |
| 204 | last := ev[len(ev)-1] |
| 205 | if last.Kind != EventDeleted || last.ActorID == nil || *last.ActorID != 9 { |
| 206 | t.Fatalf("who deleted this is unanswerable: %+v", last) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func TestAddEntryLogsAndMovesTheCardRevision(t *testing.T) { |
| 211 | g, s := seeded(t) |
| 212 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 213 | |
| 214 | entry, err := AddEntry(ctx(), g, s, card.ID, Person(3), TypeCallLog, "manual", map[string]string{ |
| 215 | FieldBody: "talked about renewal", |
| 216 | FieldOccurredAt: "2026-09-20", |
| 217 | }) |
| 218 | if err != nil { |
| 219 | t.Fatalf("AddEntry: %v", err) |
| 220 | } |
| 221 | if entry.ID == 0 || entry.ActorID == nil || *entry.ActorID != 3 { |
| 222 | t.Fatalf("entry is %+v", entry) |
| 223 | } |
| 224 | |
| 225 | var reread Card |
| 226 | g.First(&reread, card.ID) |
| 227 | if reread.Revision == card.Revision { |
| 228 | t.Fatalf("card revision is still %d after an entry landed", reread.Revision) |
| 229 | } |
| 230 | if n := len(events(t, g, ObjectEntry, entry.ID)); n != 1 { |
| 231 | t.Fatalf("%d events for the entry, want 1", n) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // The ruling is that a change which lands is a change which is logged. |
| 236 | // If the event write fails, the change must not survive it. |
| 237 | func TestAChangeThatCannotBeLoggedDoesNotLand(t *testing.T) { |
| 238 | g, s := seeded(t) |
| 239 | // Drop the events table so the log write fails inside the transaction. |
| 240 | if err := g.Exec("DROP TABLE events").Error; err != nil { |
| 241 | t.Fatalf("dropping events: %v", err) |
| 242 | } |
| 243 | if _, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}); err == nil { |
| 244 | t.Fatal("a card was created while its event could not be written") |
| 245 | } |
| 246 | var cards int64 |
| 247 | g.Model(&Card{}).Count(&cards) |
| 248 | if cards != 0 { |
| 249 | t.Fatalf("%d card(s) survived a failed event write", cards) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // A type is a card's or an entry's, never both. Before this, AddEntry |
| 254 | // looked up the Call Log type by a constant regardless of what it was |
| 255 | // asked for, and CreateCard would make a *card* of type Call Log — and |
| 256 | // entries are immutable, so every row written that way is a row that |
| 257 | // cannot be corrected. |
| 258 | func TestATypeIsACardsOrAnEntrys(t *testing.T) { |
| 259 | g, s := seeded(t) |
| 260 | if _, err := CreateCard(ctx(), g, s, TypeCallLog, Person(1), nil); err == nil { |
| 261 | t.Error("a card was created with an entry type") |
| 262 | } |
| 263 | card, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 264 | if err != nil { |
| 265 | t.Fatalf("CreateCard: %v", err) |
| 266 | } |
| 267 | if _, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCustomer, "manual", nil); err == nil { |
| 268 | t.Error("an entry was added with a card type") |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | // The app-as-itself actor must be asked for, never arrived at by default. |
| 273 | func TestAnActorIsAPersonOrADeclaredAppAction(t *testing.T) { |
| 274 | g, s := seeded(t) |
| 275 | if _, err := CreateCard(ctx(), g, s, TypeCustomer, Actor{}, map[string]string{FieldName: "Cnoc Teoranta"}); err == nil { |
| 276 | t.Error("a zero Actor was accepted; a handler that forgot the session would write as the app") |
| 277 | } |
| 278 | if _, err := CreateCard(ctx(), g, s, TypeCustomer, Person(0), map[string]string{FieldName: "Cnoc Teoranta"}); err == nil { |
| 279 | t.Error("member 0 was accepted as a person") |
| 280 | } |
| 281 | |
| 282 | card, err := CreateCard(ctx(), g, s, TypeCustomer, AppBecause(0, "intake form"), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 283 | if err != nil { |
| 284 | t.Fatalf("an app action with a reason was refused: %v", err) |
| 285 | } |
| 286 | ev := events(t, g, ObjectCard, card.ID) |
| 287 | if ev[0].ActorID != nil { |
| 288 | t.Error("an app action named a member") |
| 289 | } |
| 290 | if ev[0].ActorReason != "intake form" { |
| 291 | t.Errorf("the app's reason is %q", ev[0].ActorReason) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // Finding 9: an entry landing used to consume a CARD revision while being |
| 296 | // logged under object_kind=entry, which left the card's own chain with |
| 297 | // gaps. Revisions are random now (nextRevision), so the chain is ordered by |
| 298 | // event id and does not count 1, 2, 3: it is unbroken when every card event |
| 299 | // carries a revision of its own, none repeated, and the last is the card's. |
| 300 | func TestTheCardsRevisionChainIsUnbroken(t *testing.T) { |
| 301 | g, s := seeded(t) |
| 302 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 303 | if _, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "called"}); err != nil { |
| 304 | t.Fatalf("AddEntry: %v", err) |
| 305 | } |
| 306 | if err := UpdateCard(ctx(), g, s, card.ID, Person(1), map[string]string{FieldStage: "Proposal"}); err != nil { |
| 307 | t.Fatalf("UpdateCard: %v", err) |
| 308 | } |
| 309 | |
| 310 | ev := events(t, g, ObjectCard, card.ID) |
| 311 | if len(ev) != 3 { |
| 312 | t.Fatalf("%d card events, want 3 (created, entry, update)", len(ev)) |
| 313 | } |
| 314 | seen := map[int64]bool{} |
| 315 | for i, e := range ev { |
| 316 | if e.Revision < 1 || seen[e.Revision] { |
| 317 | t.Fatalf("card event %d is at revision %d: zero, negative or repeated", i, e.Revision) |
| 318 | } |
| 319 | seen[e.Revision] = true |
| 320 | } |
| 321 | var reread Card |
| 322 | g.First(&reread, card.ID) |
| 323 | if ev[len(ev)-1].Revision != reread.Revision { |
| 324 | t.Fatalf("the chain ends at %d and the card is at %d", ev[len(ev)-1].Revision, reread.Revision) |
| 325 | } |
| 326 | if ev[1].Kind != EventEntryAdded || ev[1].ChildID == 0 { |
| 327 | t.Fatalf("the entry landing is not named on the card's chain: %+v", ev[1]) |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // "No UpdateEntry exists" was a convention, not an invariant. |
| 332 | func TestEntriesCannotBeRewrittenOrRemoved(t *testing.T) { |
| 333 | g, s := seeded(t) |
| 334 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 335 | entry, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "as said"}) |
| 336 | if err != nil { |
| 337 | t.Fatalf("AddEntry: %v", err) |
| 338 | } |
| 339 | |
| 340 | if err := g.Model(&Entry{}).Where("id = ?", entry.ID).Update("source", "rewritten").Error; err == nil { |
| 341 | t.Error("an entry was rewritten") |
| 342 | } |
| 343 | if err := g.Exec("UPDATE entry_values SET print = 'x' WHERE entry_id = ?", entry.ID).Error; err == nil { |
| 344 | t.Error("an entry value was rewritten") |
| 345 | } |
| 346 | if err := g.Exec("DELETE FROM entries WHERE id = ?", entry.ID).Error; err == nil { |
| 347 | t.Error("an entry was deleted") |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | // A hard delete would cascade a card's values, entries and refs away while |
| 352 | // its events survived pointing at nothing. |
| 353 | func TestACardCannotBeHardDeleted(t *testing.T) { |
| 354 | g, s := seeded(t) |
| 355 | card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| 356 | if err := g.Exec("DELETE FROM cards WHERE id = ?", card.ID).Error; err == nil { |
| 357 | t.Fatal("a card was hard-deleted; its cascades would have taken everything with it") |
| 358 | } |
| 359 | if err := DeleteCard(ctx(), g, s, card.ID, Person(1)); err != nil { |
| 360 | t.Fatalf("DeleteCard: %v", err) |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | // The partial-failure shape: a write that fails on the third key must |
| 365 | // leave nothing behind from the first two. |
| 366 | func TestAPartialWriteLeavesNothing(t *testing.T) { |
| 367 | g, s := seeded(t) |
| 368 | _, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{ |
| 369 | FieldName: "Cnoc Teoranta", |
| 370 | FieldEmail: "ana@example.com", |
| 371 | "f_nonsense": "boom", |
| 372 | }) |
| 373 | if err == nil { |
| 374 | t.Fatal("a card with an unknown field was created") |
| 375 | } |
| 376 | var cards, values int64 |
| 377 | g.Model(&Card{}).Count(&cards) |
| 378 | g.Model(&CardValue{}).Count(&values) |
| 379 | if cards != 0 || values != 0 { |
| 380 | t.Fatalf("a failed write left %d card(s) and %d value(s)", cards, values) |
| 381 | } |
| 382 | } |
| 383 | |