| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/binary" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | // The write path. Every function here does its work and writes its Event |
| 19 | // in ONE transaction, because Paul's 2026-09-19 ruling — every change to |
| 20 | // every object is logged with what changed and who did it — is worth |
| 21 | // nothing if the log can be missing for a change that landed. A change |
| 22 | // that is not logged must not be a change that happened. |
| 23 | // |
| 24 | // Object kinds, for Event.ObjectKind. |
| 25 | const ( |
| 26 | ObjectCard = "card" |
| 27 | ObjectEntry = "entry" |
| 28 | ) |
| 29 | |
| 30 | // Event kinds. |
| 31 | const ( |
| 32 | EventCreated = "created" |
| 33 | EventUpdated = "updated" |
| 34 | EventDeleted = "deleted" |
| 35 | EventEntryAdded = "entry_added" |
| 36 | ) |
| 37 | |
| 38 | // Actor is who is making a change, per suite ruling 9: "a write names its |
| 39 | // real actor; no sibling ever acts as a person." |
| 40 | // |
| 41 | // A struct rather than an int64 because the app-as-itself case must be |
| 42 | // ASKED FOR, never arrived at by default. As a bare int64 the zero value |
| 43 | // meant both "member 0" and "fichas did this", so a handler that forgot to |
| 44 | // resolve the session wrote rows indistinguishable from an honest machine |
| 45 | // write — and TriggerID was zero everywhere too, so the honest machine |
| 46 | // write was indistinguishable from the forgetful one in the other |
| 47 | // direction as well. |
| 48 | type Actor struct { |
| 49 | memberID *int64 |
| 50 | trigger int64 |
| 51 | reason string |
| 52 | } |
| 53 | |
| 54 | // Person is a member of the team making a change through their own session. |
| 55 | func Person(memberID int64) Actor { return Actor{memberID: &memberID} } |
| 56 | |
| 57 | // AppBecause is fichas acting as itself — a derived summary, an intake |
| 58 | // form. It requires the event that provoked it and a reason, because §5's |
| 59 | // honesty about a machine-written change is exactly those two things: the |
| 60 | // summary names the entry that caused it, and is never attributed to |
| 61 | // whoever triggered it. |
| 62 | func AppBecause(triggerEventID int64, reason string) Actor { |
| 63 | return Actor{trigger: triggerEventID, reason: reason} |
| 64 | } |
| 65 | |
| 66 | // valid refuses an actor that is neither a named person nor a declared app |
| 67 | // action. logEvent calls it, so no write path can skip it. |
| 68 | func (a Actor) valid() error { |
| 69 | if a.memberID != nil { |
| 70 | if *a.memberID == 0 { |
| 71 | return fmt.Errorf("fichas: member 0 is not a member; Person was called with a zero id") |
| 72 | } |
| 73 | return nil |
| 74 | } |
| 75 | if a.reason == "" { |
| 76 | return fmt.Errorf("fichas: an actor is neither a person nor a declared app action; use Person or AppBecause") |
| 77 | } |
| 78 | return nil |
| 79 | } |
| 80 | |
| 81 | // change is one field's before and after, as the sealed payload records it. |
| 82 | type change struct { |
| 83 | Field string `json:"field"` |
| 84 | Before string `json:"before,omitempty"` |
| 85 | After string `json:"after,omitempty"` |
| 86 | } |
| 87 | |
| 88 | // typeByKey loads a type and refuses it if its scope is not the one the |
| 89 | // caller needs. This is what stops CreateCard making a card of type "Call |
| 90 | // log", and AddEntry binding every entry to one type's field definitions |
| 91 | // regardless of what it was asked for. |
| 92 | func typeByKey(tx *gorm.DB, key, scope string) (CardType, error) { |
| 93 | var ct CardType |
| 94 | if err := tx.Where("key = ?", key).First(&ct).Error; err != nil { |
| 95 | return ct, fmt.Errorf("fichas: no type %s: %w", key, err) |
| 96 | } |
| 97 | if ct.Scope != scope { |
| 98 | return ct, fmt.Errorf("fichas: %s is a %s type, not a %s type", key, ct.Scope, scope) |
| 99 | } |
| 100 | return ct, nil |
| 101 | } |
| 102 | |
| 103 | // fieldsFor loads a card type's definitions, keyed by field key. |
| 104 | func fieldsFor(tx *gorm.DB, cardTypeID int64) (map[string]FieldDef, error) { |
| 105 | var defs []FieldDef |
| 106 | if err := tx.Where("card_type_id = ?", cardTypeID).Find(&defs).Error; err != nil { |
| 107 | return nil, fmt.Errorf("fichas: loading field definitions: %w", err) |
| 108 | } |
| 109 | out := make(map[string]FieldDef, len(defs)) |
| 110 | for _, d := range defs { |
| 111 | out[d.Key] = d |
| 112 | } |
| 113 | return out, nil |
| 114 | } |
| 115 | |
| 116 | // logEvent writes one Event. changed is the set of FieldDef ids the caller |
| 117 | // touched; changes is the before/after detail, sealed. |
| 118 | // |
| 119 | // ChangedFields is plaintext and stays forever; the payload is sealed and |
| 120 | // is what a bounded window later erases. That split is §5's whole retention |
| 121 | // rule: after erasure a reader can still see THAT a field changed and who |
| 122 | // changed it, which is what an audit log is for. |
| 123 | func logEvent(tx *gorm.DB, s *seal.Sealer, kind, objectKind string, objectID, childID, revision int64, actor Actor, changed []int64, changes []change) error { |
| 124 | if err := actor.valid(); err != nil { |
| 125 | return err |
| 126 | } |
| 127 | sort.Slice(changed, func(i, j int) bool { return changed[i] < changed[j] }) |
| 128 | if changed == nil { |
| 129 | changed = []int64{} // "[]", never the string "null" |
| 130 | } |
| 131 | ids, err := json.Marshal(changed) |
| 132 | if err != nil { |
| 133 | return fmt.Errorf("fichas: encoding changed fields: %w", err) |
| 134 | } |
| 135 | |
| 136 | var payload []byte |
| 137 | if len(changes) > 0 { |
| 138 | raw, err := json.Marshal(changes) |
| 139 | if err != nil { |
| 140 | return fmt.Errorf("fichas: encoding the change payload: %w", err) |
| 141 | } |
| 142 | if payload, err = s.Seal(seal.PurposeEventPayload, raw); err != nil { |
| 143 | return fmt.Errorf("fichas: sealing the change payload: %w", err) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | e := Event{ |
| 148 | Kind: kind, |
| 149 | ObjectKind: objectKind, |
| 150 | ObjectID: objectID, |
| 151 | ChildID: childID, |
| 152 | ActorID: actor.memberID, |
| 153 | ActorReason: actor.reason, |
| 154 | Revision: revision, |
| 155 | ChangedFields: string(ids), |
| 156 | PayloadSealed: payload, |
| 157 | TriggerID: actor.trigger, |
| 158 | Nonce: randomPositive(), |
| 159 | } |
| 160 | if err := tx.Create(&e).Error; err != nil { |
| 161 | return fmt.Errorf("fichas: writing the event: %w", err) |
| 162 | } |
| 163 | return nil |
| 164 | } |
| 165 | |
| 166 | // writeValues seals each value, computes its print where the definition |
| 167 | // asks for one, and returns the ids touched plus the before/after detail. |
| 168 | // |
| 169 | // values is keyed by FIELD KEY, not by column: a request body is never |
| 170 | // bound onto a model here (AGENTS.md), and a key the card type does not |
| 171 | // define is an error rather than something quietly dropped — a silently |
| 172 | // ignored field is a value a person believes they saved. |
| 173 | func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]FieldDef, values map[string]string) ([]int64, []change, error) { |
| 174 | values, err := checkValues(s, defs, values) |
| 175 | if err != nil { |
| 176 | return nil, nil, err |
| 177 | } |
| 178 | keys := make([]string, 0, len(values)) |
| 179 | for k := range values { |
| 180 | keys = append(keys, k) |
| 181 | } |
| 182 | sort.Strings(keys) |
| 183 | |
| 184 | var changed []int64 |
| 185 | var detail []change |
| 186 | for _, key := range keys { |
| 187 | def := defs[key] |
| 188 | after := values[key] |
| 189 | before, err := currentValue(tx, s, cardID, def) |
| 190 | if err != nil { |
| 191 | return nil, nil, err |
| 192 | } |
| 193 | if before == after { |
| 194 | continue // not a change; it must not appear in the log as one |
| 195 | } |
| 196 | if err := writeValue(tx, s, cardID, def, after); err != nil { |
| 197 | return nil, nil, err |
| 198 | } |
| 199 | changed = append(changed, def.ID) |
| 200 | detail = append(detail, change{Field: key, Before: before, After: after}) |
| 201 | } |
| 202 | return changed, detail, nil |
| 203 | } |
| 204 | |
| 205 | // normaliseValue is the stored form of what a person typed, by kind. |
| 206 | // Numbers are stored bare: "1,200" is accepted from a person and kept |
| 207 | // as "1200", or it would sort as text and never compare as a number. |
| 208 | // (A form reads numbers in the reader's locale first, §6.8; this keeps |
| 209 | // the store's own callers, which pass canonical text, as they were.) |
| 210 | func normaliseValue(def FieldDef, v string) string { |
| 211 | v = lf(v) |
| 212 | switch def.Kind { |
| 213 | case KindNumber: |
| 214 | v = strings.ReplaceAll(strings.TrimSpace(v), ",", "") |
| 215 | case KindEmail: |
| 216 | // The domain is case-blind; the local part is the server's |
| 217 | // business, so it is left as typed. |
| 218 | if local, domain, ok := strings.Cut(strings.TrimSpace(v), "@"); ok { |
| 219 | v = local + "@" + strings.ToLower(domain) |
| 220 | } |
| 221 | case KindPhone: |
| 222 | v = strings.Join(strings.Fields(v), " ") |
| 223 | case KindURL: |
| 224 | // A value that will not normalise is left as typed so that |
| 225 | // validateValues can say what is wrong with it. |
| 226 | if n, err := normaliseURL(v); err == nil { |
| 227 | v = n |
| 228 | } |
| 229 | } |
| 230 | return v |
| 231 | } |
| 232 | |
| 233 | // lf is text with every line ending a line feed. A browser posts a |
| 234 | // textarea's and a hidden field's lines with CRLF, the DOM hands script |
| 235 | // LF, and Notes written before this rule hold CRLF; compared byte for |
| 236 | // byte, each would conflict with the other (Fable, Phase 1 review, H1). |
| 237 | func lf(s string) string { |
| 238 | if !strings.Contains(s, "\r") { |
| 239 | return s |
| 240 | } |
| 241 | return strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\r", "\n") |
| 242 | } |
| 243 | |
| 244 | // sameText reports whether two values are the same but for line endings. |
| 245 | func sameText(a, b string) bool { return lf(a) == lf(b) } |
| 246 | |
| 247 | // checkValues normalises values and refuses, with a FormError, any a |
| 248 | // person must fix: a bad value for its kind, an empty title, a choice |
| 249 | // that is not an option. A key that is not a field is a programming |
| 250 | // error, not a person's. |
| 251 | func checkValues(s *seal.Sealer, defs map[string]FieldDef, values map[string]string) (map[string]string, error) { |
| 252 | normalised := make(map[string]string, len(values)) |
| 253 | for k, v := range values { |
| 254 | def, ok := defs[k] |
| 255 | if !ok { |
| 256 | return nil, fmt.Errorf("fichas: %s is not a field of this card type", k) |
| 257 | } |
| 258 | normalised[k] = normaliseValue(def, v) |
| 259 | } |
| 260 | fe := validateValues(defs, normalised) |
| 261 | // Every card has a name (UX review, 2026-11-12: an empty "Add a |
| 262 | // customer" made a card called "Card 305"). The browser's required |
| 263 | // attribute is a convenience; this is the rule. A write that does not |
| 264 | // touch the title (a partial update) is not asked for it. |
| 265 | if title := titleOf(defs); title != "" { |
| 266 | if v, ok := normalised[title]; ok && strings.TrimSpace(v) == "" { |
| 267 | if fe == nil { |
| 268 | fe = FormError{} |
| 269 | } |
| 270 | fe[title] = "Give it a name." |
| 271 | } |
| 272 | } |
| 273 | fe, err := optionsError(s, defs, normalised, fe) |
| 274 | if err != nil { |
| 275 | return nil, err |
| 276 | } |
| 277 | if fe != nil { |
| 278 | return nil, fe |
| 279 | } |
| 280 | return normalised, nil |
| 281 | } |
| 282 | |
| 283 | // currentValue is a card's stored value for one field, opened. |
| 284 | func currentValue(tx *gorm.DB, s *seal.Sealer, cardID int64, def FieldDef) (string, error) { |
| 285 | var existing CardValue |
| 286 | err := tx.Where("card_id = ? AND field_def_id = ?", cardID, def.ID).First(&existing).Error |
| 287 | if err == gorm.ErrRecordNotFound { |
| 288 | return "", nil |
| 289 | } |
| 290 | if err != nil { |
| 291 | return "", fmt.Errorf("fichas: reading %s: %w", def.Key, err) |
| 292 | } |
| 293 | if len(existing.SealedValue) == 0 { |
| 294 | return "", nil |
| 295 | } |
| 296 | raw, err := s.Open(seal.PurposeValue, existing.SealedValue) |
| 297 | if err != nil { |
| 298 | return "", fmt.Errorf("fichas: opening the previous %s: %w", def.Key, err) |
| 299 | } |
| 300 | return string(raw), nil |
| 301 | } |
| 302 | |
| 303 | // writeValue seals and stores one value, with its print when the field |
| 304 | // is printed. |
| 305 | func writeValue(tx *gorm.DB, s *seal.Sealer, cardID int64, def FieldDef, after string) error { |
| 306 | sealed, err := s.Seal(seal.PurposeValue, []byte(after)) |
| 307 | if err != nil { |
| 308 | return fmt.Errorf("fichas: sealing %s: %w", def.Key, err) |
| 309 | } |
| 310 | row := CardValue{CardID: cardID, FieldDefID: def.ID, SealedValue: sealed} |
| 311 | if def.Tier == TierPrint { |
| 312 | p, perr := printFor(s, def, after) |
| 313 | if perr != nil { |
| 314 | return perr |
| 315 | } |
| 316 | row.Print = p |
| 317 | } |
| 318 | if err := tx.Save(&row).Error; err != nil { |
| 319 | return fmt.Errorf("fichas: writing %s: %w", def.Key, err) |
| 320 | } |
| 321 | return nil |
| 322 | } |
| 323 | |
| 324 | // randomBytes is where randomPositive draws from: crypto/rand. A variable |
| 325 | // so a test can force the draws its redraw guards exist for; nothing else |
| 326 | // sets it. |
| 327 | var randomBytes io.Reader = rand.Reader |
| 328 | |
| 329 | // randomPositive is a random positive int63 from crypto/rand: a card's |
| 330 | // revisions and the nonces in its item id and the feed's cursor (spec |
| 331 | // §6.2). Zero, which the triggers in migrations/0005 refuse and which |
| 332 | // memoria reads as "no revision", is redrawn. |
| 333 | func randomPositive() int64 { |
| 334 | var b [8]byte |
| 335 | for { |
| 336 | if _, err := io.ReadFull(randomBytes, b[:]); err != nil { |
| 337 | // crypto/rand does not fail (it aborts the process instead), |
| 338 | // so this is a broken substitute: never fall back to anything |
| 339 | // guessable. |
| 340 | panic("fichas: no randomness: " + err.Error()) |
| 341 | } |
| 342 | if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 { |
| 343 | return n |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // newRevision issues a card revision. A variable so the suite tests can |
| 349 | // pin it to a readable count; nothing else sets it. |
| 350 | var newRevision = randomRevision |
| 351 | |
| 352 | // randomRevision is a fresh random positive int63 that differs from the |
| 353 | // card's current revision. |
| 354 | // |
| 355 | // Why not a counter, or the clock (spec §6.2): memoria holds (item, |
| 356 | // revision) and asks S2 whether that revision is current. Restore an |
| 357 | // older backup and a counter hands the same numbers out again for |
| 358 | // different text — S2 then says VISIBLE for the abandoned copy. A clock |
| 359 | // does the same if it is frozen, or behind by less than the backup's age. |
| 360 | // A random revision is reissued only with negligible probability (2^-63 per |
| 361 | // draw); memoria compares revisions only for equality, and the ORDER of a |
| 362 | // card's revisions is its event log's, which S2 reads for STALE. |
| 363 | func randomRevision(current int64) int64 { |
| 364 | for { |
| 365 | if r := randomPositive(); r != current { |
| 366 | return r |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | // nextRevision is a draw for the revision a change to a card at current |
| 372 | // moves it to. A new card takes it as it comes: it has no log yet, so there |
| 373 | // is nothing to collide with (its id is fresh — AUTOINCREMENT never hands |
| 374 | // out an id this database has used, and cards are never hard-deleted). A |
| 375 | // change to an existing card goes through freshRevision. |
| 376 | func nextRevision(current int64) int64 { return newRevision(current) } |
| 377 | |
| 378 | // maxRevisionDraws bounds freshRevision. A real draw collides with a card's |
| 379 | // log with probability (log length) × 2^-63, so a second draw is already |
| 380 | // beyond anything that happens; the bound exists so that a broken source — |
| 381 | // one that keeps answering a revision the log holds — fails the write |
| 382 | // loudly instead of spinning inside its transaction. |
| 383 | const maxRevisionDraws = 8 |
| 384 | |
| 385 | // freshRevision draws card's next revision and redraws it while it is any |
| 386 | // revision the card's log holds, not only the current one (suite doctrine |
| 387 | // §6.6, revision 11, L4). A draw equal to a revision the card had before |
| 388 | // would give an old name to new bytes: memoria may still hold that |
| 389 | // (item, revision) with the old text, and S2 would call it VISIBLE. The log |
| 390 | // is the card's own card-kind events, read inside the write's transaction, |
| 391 | // so a revision cannot be added between the check and the write (SQLite has |
| 392 | // one writer). |
| 393 | func freshRevision(tx *gorm.DB, card *Card) (int64, error) { |
| 394 | for range maxRevisionDraws { |
| 395 | next := nextRevision(card.Revision) |
| 396 | if next == card.Revision { |
| 397 | continue |
| 398 | } |
| 399 | var held int64 |
| 400 | if err := tx.Model(&Event{}). |
| 401 | Where("object_kind = ? AND object_id = ? AND revision = ?", ObjectCard, card.ID, next). |
| 402 | Count(&held).Error; err != nil { |
| 403 | return 0, fmt.Errorf("fichas: reading card %d's revision history: %w", card.ID, err) |
| 404 | } |
| 405 | if held == 0 { |
| 406 | return next, nil |
| 407 | } |
| 408 | } |
| 409 | return 0, fmt.Errorf("fichas: no revision for card %d after %d draws that its log does not already hold", card.ID, maxRevisionDraws) |
| 410 | } |
| 411 | |
| 412 | // bumpRevision moves a card's revision, guarded on the revision it read. |
| 413 | // |
| 414 | // The guard makes the invariant LOCAL. Concurrent updates are safe today |
| 415 | // only because rastrillo's writer pool is a single connection; a blind |
| 416 | // UPDATE would silently start losing revisions the day that changes, and |
| 417 | // the log would stop being a truthful account of what happened. Costs one |
| 418 | // clause. |
| 419 | func bumpRevision(tx *gorm.DB, card *Card, extra map[string]any) error { |
| 420 | next, err := freshRevision(tx, card) |
| 421 | if err != nil { |
| 422 | return err |
| 423 | } |
| 424 | set := map[string]any{"revision": next, "updated_at": time.Now()} |
| 425 | for k, v := range extra { |
| 426 | set[k] = v |
| 427 | } |
| 428 | res := tx.Model(&Card{}). |
| 429 | Where("id = ? AND revision = ?", card.ID, card.Revision). |
| 430 | Updates(set) |
| 431 | if res.Error != nil { |
| 432 | return fmt.Errorf("fichas: bumping the revision: %w", res.Error) |
| 433 | } |
| 434 | if res.RowsAffected != 1 { |
| 435 | return fmt.Errorf("fichas: card %d moved under this write (expected revision %d)", card.ID, card.Revision) |
| 436 | } |
| 437 | card.Revision = next |
| 438 | return nil |
| 439 | } |
| 440 | |
| 441 | // CreateCard writes a card, its values and its creation event. |
| 442 | func CreateCard(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string, actor Actor, values map[string]string) (Card, error) { |
| 443 | var card Card |
| 444 | err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 445 | ct, err := typeByKey(tx, typeKey, ScopeCard) |
| 446 | if err != nil { |
| 447 | return err |
| 448 | } |
| 449 | defs, err := fieldsFor(tx, ct.ID) |
| 450 | if err != nil { |
| 451 | return err |
| 452 | } |
| 453 | |
| 454 | // A new card is asked for its name even if the caller left the |
| 455 | // title out altogether. |
| 456 | if t := titleOf(defs); t != "" { |
| 457 | if _, ok := values[t]; !ok { |
| 458 | withTitle := make(map[string]string, len(values)+1) |
| 459 | for k, v := range values { |
| 460 | withTitle[k] = v |
| 461 | } |
| 462 | withTitle[t] = "" |
| 463 | values = withTitle |
| 464 | } |
| 465 | } |
| 466 | card = Card{CardTypeID: ct.ID, OwnerID: actor.memberID, Revision: nextRevision(0), Nonce: randomPositive()} |
| 467 | if err := tx.Create(&card).Error; err != nil { |
| 468 | return fmt.Errorf("fichas: creating the card: %w", err) |
| 469 | } |
| 470 | changed, detail, err := writeValues(tx, s, card.ID, defs, values) |
| 471 | if err != nil { |
| 472 | return err |
| 473 | } |
| 474 | return logEvent(tx, s, EventCreated, ObjectCard, card.ID, 0, card.Revision, actor, changed, detail) |
| 475 | }) |
| 476 | if err != nil { |
| 477 | // The transaction rolled back, so the id this carries names no |
| 478 | // row. Returning it invites a caller to use it. |
| 479 | return Card{}, err |
| 480 | } |
| 481 | return card, nil |
| 482 | } |
| 483 | |
| 484 | // UpdateCard changes values on a card and logs exactly what moved. |
| 485 | // |
| 486 | // A write that changes nothing writes no event. That is deliberate: a log |
| 487 | // full of no-op rows is a log nobody reads, and "who touched this" stops |
| 488 | // meaning anything if opening a form and pressing save counts. |
| 489 | func UpdateCard(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, values map[string]string) error { |
| 490 | return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 491 | var card Card |
| 492 | if err := tx.First(&card, cardID).Error; err != nil { |
| 493 | return fmt.Errorf("fichas: no card %d: %w", cardID, err) |
| 494 | } |
| 495 | if card.Gone { |
| 496 | return fmt.Errorf("fichas: card %d is deleted", cardID) |
| 497 | } |
| 498 | defs, err := fieldsFor(tx, card.CardTypeID) |
| 499 | if err != nil { |
| 500 | return err |
| 501 | } |
| 502 | changed, detail, err := writeValues(tx, s, card.ID, defs, values) |
| 503 | if err != nil { |
| 504 | return err |
| 505 | } |
| 506 | if len(changed) == 0 { |
| 507 | return nil |
| 508 | } |
| 509 | if err := bumpRevision(tx, &card, nil); err != nil { |
| 510 | return err |
| 511 | } |
| 512 | return logEvent(tx, s, EventUpdated, ObjectCard, card.ID, 0, card.Revision, actor, changed, detail) |
| 513 | }) |
| 514 | } |
| 515 | |
| 516 | // DeleteCard marks a card gone. The row stays and so does its log: §5 keeps |
| 517 | // the actor permanently precisely so "who deleted this" has somewhere to |
| 518 | // live, and suite ruling 14 retires by feed rather than by erasure. |
| 519 | func DeleteCard(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor) error { |
| 520 | return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 521 | var card Card |
| 522 | if err := tx.First(&card, cardID).Error; err != nil { |
| 523 | return fmt.Errorf("fichas: no card %d: %w", cardID, err) |
| 524 | } |
| 525 | if card.Gone { |
| 526 | return nil |
| 527 | } |
| 528 | if err := bumpRevision(tx, &card, map[string]any{"gone": true}); err != nil { |
| 529 | return err |
| 530 | } |
| 531 | return logEvent(tx, s, EventDeleted, ObjectCard, card.ID, 0, card.Revision, actor, nil, nil) |
| 532 | }) |
| 533 | } |
| 534 | |
| 535 | // AddEntry appends an entry to a card. |
| 536 | // |
| 537 | // An entry is immutable once written (§3), so there is no UpdateEntry: a |
| 538 | // correction is a new entry that supersedes. The card's revision moves |
| 539 | // because the feed's consumers care that the card changed, and an entry |
| 540 | // landing IS the card changing. |
| 541 | func AddEntry(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, typeKey, source string, values map[string]string) (Entry, error) { |
| 542 | var entry Entry |
| 543 | err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 544 | var card Card |
| 545 | if err := tx.First(&card, cardID).Error; err != nil { |
| 546 | return fmt.Errorf("fichas: no card %d: %w", cardID, err) |
| 547 | } |
| 548 | if card.Gone { |
| 549 | return fmt.Errorf("fichas: card %d is deleted", cardID) |
| 550 | } |
| 551 | |
| 552 | ct, err := typeByKey(tx, typeKey, ScopeEntry) |
| 553 | if err != nil { |
| 554 | return err |
| 555 | } |
| 556 | defs, err := fieldsFor(tx, ct.ID) |
| 557 | if err != nil { |
| 558 | return err |
| 559 | } |
| 560 | |
| 561 | entry = Entry{CardID: cardID, TypeID: ct.ID, Kind: typeKey, Source: source, ActorID: actor.memberID} |
| 562 | if err := tx.Create(&entry).Error; err != nil { |
| 563 | return fmt.Errorf("fichas: creating the entry: %w", err) |
| 564 | } |
| 565 | |
| 566 | var changed []int64 |
| 567 | var detail []change |
| 568 | keys := make([]string, 0, len(values)) |
| 569 | for k := range values { |
| 570 | keys = append(keys, k) |
| 571 | } |
| 572 | sort.Strings(keys) // deterministic payload order, as writeValues has |
| 573 | for _, key := range keys { |
| 574 | v := values[key] |
| 575 | def, ok := defs[key] |
| 576 | if !ok { |
| 577 | return fmt.Errorf("fichas: %s is not a field of an entry", key) |
| 578 | } |
| 579 | sealed, serr := s.Seal(seal.PurposeValue, []byte(v)) |
| 580 | if serr != nil { |
| 581 | return fmt.Errorf("fichas: sealing %s: %w", key, serr) |
| 582 | } |
| 583 | row := EntryValue{EntryID: entry.ID, FieldDefID: def.ID, SealedValue: sealed} |
| 584 | if def.Tier == TierPrint { |
| 585 | p, perr := printFor(s, def, v) |
| 586 | if perr != nil { |
| 587 | return perr |
| 588 | } |
| 589 | row.Print = p |
| 590 | } |
| 591 | if err := tx.Create(&row).Error; err != nil { |
| 592 | return fmt.Errorf("fichas: writing %s: %w", key, err) |
| 593 | } |
| 594 | changed = append(changed, def.ID) |
| 595 | detail = append(detail, change{Field: key, After: v}) |
| 596 | } |
| 597 | |
| 598 | if err := bumpRevision(tx, &card, nil); err != nil { |
| 599 | return err |
| 600 | } |
| 601 | // TWO events, and the split is finding 9's. The entry's own |
| 602 | // creation carries no revision: a revision belongs to the card, |
| 603 | // and logging the entry under object_kind=entry while consuming a |
| 604 | // card revision left the CARD's chain with gaps that a |
| 605 | // contiguity check reads as broken. The card's event names the |
| 606 | // entry through ChildID, so "what happened at revision 2" is |
| 607 | // answerable from the card's own chain. |
| 608 | if err := logEvent(tx, s, EventCreated, ObjectEntry, entry.ID, 0, 0, actor, changed, detail); err != nil { |
| 609 | return err |
| 610 | } |
| 611 | return logEvent(tx, s, EventEntryAdded, ObjectCard, card.ID, entry.ID, card.Revision, actor, nil, nil) |
| 612 | }) |
| 613 | if err != nil { |
| 614 | return Entry{}, err |
| 615 | } |
| 616 | return entry, nil |
| 617 | } |
| 618 | |
| 619 | // titleOf is the field a type's cards are named by: Name where the type |
| 620 | // has it, otherwise its first field (CardView.titleKey's rule). |
| 621 | func titleOf(defs map[string]FieldDef) string { |
| 622 | if _, ok := defs[FieldName]; ok { |
| 623 | return FieldName |
| 624 | } |
| 625 | first, best := "", 0 |
| 626 | for k, d := range defs { |
| 627 | if first == "" || d.Ordinal < best || (d.Ordinal == best && k < first) { |
| 628 | first, best = k, d.Ordinal |
| 629 | } |
| 630 | } |
| 631 | return first |
| 632 | } |
| 633 | |