| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | |
| 7 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 8 | "gorm.io/gorm" |
| 9 | ) |
| 10 | |
| 11 | // The seeded catalogue (§4.4): "ship a catalogue, not a builder". |
| 12 | // |
| 13 | // A card type is rows, never DDL (§4.3), so adding one costs seed data and |
| 14 | // no migration. What it is NOT free of is a leak-list decision: every field |
| 15 | // below carries a Tier, and a Tier ships as a default nobody will revisit. |
| 16 | // A seeded type with a plaintext salary_band would be a leak this app |
| 17 | // shipped into every team that ever clicked it. **A type joins this list |
| 18 | // only with a per-field tier review**, which is why slice 1 ships two. |
| 19 | // |
| 20 | // Keys are opaque constants of OURS and never the user's words, because |
| 21 | // they are the one part of a type that reaches the durable file in the |
| 22 | // clear. Labels are sealed, even here. |
| 23 | |
| 24 | // Card type keys. |
| 25 | const ( |
| 26 | TypeCustomer = "t_customer" |
| 27 | TypeCallLog = "t_calllog" |
| 28 | ) |
| 29 | |
| 30 | // Field keys. Stable forever once shipped: a print is derived from the key |
| 31 | // (seal.Print), so renaming one silently invalidates every print taken |
| 32 | // under the old name and equality lookups start missing. |
| 33 | const ( |
| 34 | FieldName = "f_name" |
| 35 | FieldDomain = "f_domain" |
| 36 | FieldEmail = "f_email" |
| 37 | FieldPhone = "f_phone" |
| 38 | FieldStage = "f_stage" |
| 39 | FieldNextAction = "f_next_action" |
| 40 | FieldNotes = "f_notes" |
| 41 | |
| 42 | FieldOccurredAt = "f_occurred_at" |
| 43 | FieldBody = "f_body" |
| 44 | FieldDuration = "f_duration" |
| 45 | ) |
| 46 | |
| 47 | // There is deliberately no f_calls_ref field. The Calls meeting an entry |
| 48 | // came from is a Ref row with EntryID set, not a field value: memoria's |
| 49 | // seal keeps purposes separate by WHO RECEIVES the value, and an id that |
| 50 | // goes back on the wire to Calls is its own kind. Sealed as an ordinary |
| 51 | // field value it would share a purpose with a phone number. |
| 52 | |
| 53 | // Field kinds — this app's vocabulary for a value's shape, plaintext |
| 54 | // because it is ours and not the team's content. |
| 55 | const ( |
| 56 | KindText = "text" |
| 57 | KindDate = "date" |
| 58 | KindEnum = "enum" |
| 59 | KindNumber = "number" |
| 60 | KindRef = "ref" |
| 61 | // KindLongText is paragraphs: a textarea, and cut short on a card |
| 62 | // face. The seeded Notes field predates it and is KindText — changing |
| 63 | // a shipped field's kind refuses to boot (Seed) — so isLong also |
| 64 | // treats FieldNotes as long. |
| 65 | KindLongText = "longtext" |
| 66 | // KindEmail and KindPhone (UX review, 2026-11-12): an email address and |
| 67 | // a phone number, each with its own keyboard, a forgiving check, and a |
| 68 | // mailto: or tel: link on the card. Both were Text before. |
| 69 | KindEmail = "email" |
| 70 | KindPhone = "phone" |
| 71 | ) |
| 72 | |
| 73 | // FaceLatestCall is the FaceKeys token for "the most recent entry". |
| 74 | const FaceLatestCall = "_latest_call" |
| 75 | |
| 76 | // isLong reports whether a field is paragraphs rather than a line. |
| 77 | func isLong(fd FieldDef) bool { return fd.Kind == KindLongText || fd.Key == FieldNotes } |
| 78 | |
| 79 | type seedField struct { |
| 80 | Key string |
| 81 | Label string |
| 82 | Kind string |
| 83 | Tier Tier |
| 84 | // Options is a KindEnum's permitted values, sealed at seed time. |
| 85 | // "Lead", "Won" are user-facing vocabulary and never reach the |
| 86 | // durable file in the clear. |
| 87 | Options []string |
| 88 | } |
| 89 | |
| 90 | type seedType struct { |
| 91 | Key string |
| 92 | Label string |
| 93 | // Scope is ScopeCard or ScopeEntry. A type is one or the other and |
| 94 | // never both: CreateCard refuses an entry type and AddEntry refuses a |
| 95 | // card type. |
| 96 | Scope string |
| 97 | Fields []seedField |
| 98 | } |
| 99 | |
| 100 | // catalogue is the shipped set. The Tier column is the whole of §4.2 and |
| 101 | // each one has a reason; see the design's §4.2 table before changing any. |
| 102 | var catalogue = []seedType{ |
| 103 | { |
| 104 | Key: TypeCustomer, |
| 105 | Label: "Customer", |
| 106 | Scope: ScopeCard, |
| 107 | Fields: []seedField{ |
| 108 | // Printed: high-cardinality, and the equality question is |
| 109 | // worth answering without the key — "is this the same |
| 110 | // company", "do we already have this contact". |
| 111 | {Key: FieldName, Label: "Name", Kind: KindText, Tier: TierPrint}, |
| 112 | // A web address since 2026-09-30 (kindUpgrades): forgiving about |
| 113 | // the scheme, stored as https://, compared by host. |
| 114 | {Key: FieldDomain, Label: "Domain", Kind: KindURL, Tier: TierPrint}, |
| 115 | // Email and Phone since 2026-11-12 (kindUpgrades); their prints |
| 116 | // are the same as Text's were, so a value's print does not move. |
| 117 | {Key: FieldEmail, Label: "Email", Kind: KindEmail, Tier: TierPrint}, |
| 118 | {Key: FieldPhone, Label: "Phone", Kind: KindPhone, Tier: TierPrint}, |
| 119 | |
| 120 | // Sealed. Stage is low-cardinality, so a print would publish |
| 121 | // its equality classes and frequency analysis would order |
| 122 | // them — and a pipeline's composition is commercially |
| 123 | // sensitive. Grouped in the in-memory index instead. |
| 124 | {Key: FieldStage, Label: "Stage", Kind: KindEnum, Tier: TierSealed, |
| 125 | Options: []string{"Lead", "Contacted", "Proposal", "Won", "Lost"}}, |
| 126 | // Sealed although it is the field most wanted for ranges |
| 127 | // ("no call in six weeks"). §4.1: the index is in memory, so |
| 128 | // sealed is not unqueryable, and plaintext here would buy |
| 129 | // nothing the index does not already give. |
| 130 | {Key: FieldNextAction, Label: "Next action", Kind: KindDate, Tier: TierSealed}, |
| 131 | {Key: FieldNotes, Label: "Notes", Kind: KindText, Tier: TierSealed}, |
| 132 | }, |
| 133 | }, |
| 134 | { |
| 135 | Key: TypeCallLog, |
| 136 | Label: "Call log", |
| 137 | Scope: ScopeEntry, |
| 138 | Fields: []seedField{ |
| 139 | // Deliberately distinct from Entry.CreatedAt, which is |
| 140 | // plaintext because the feed needs to know a row was written. |
| 141 | // WHEN YOU CALLED THEM is content, and is sealed. |
| 142 | {Key: FieldOccurredAt, Label: "When", Kind: KindDate, Tier: TierSealed}, |
| 143 | {Key: FieldBody, Label: "What was said", Kind: KindText, Tier: TierSealed}, |
| 144 | {Key: FieldDuration, Label: "Duration", Kind: KindNumber, Tier: TierSealed}, |
| 145 | }, |
| 146 | }, |
| 147 | } |
| 148 | |
| 149 | // Seed writes the catalogue, and reconciles it, on every boot. |
| 150 | // |
| 151 | // It matches on Key and never on Label, because a Label is sealed and |
| 152 | // sealing is not deterministic — two seals of "Customer" differ, so a label |
| 153 | // comparison would insert a duplicate type on every start. |
| 154 | // |
| 155 | // **A missing field is added; a changed Kind or Tier refuses to boot.** The |
| 156 | // first draft skipped an existing type entirely, which meant a later |
| 157 | // release adding a field would never reach a team that already had the |
| 158 | // type — while the design says adding a field is a row and not a migration. |
| 159 | // The reasoning it borrowed was about changing a TIER, which really is a |
| 160 | // re-encryption of every value under it, and applying that to an ADDITION |
| 161 | // was a bug the comment had talked itself into. Refusing loudly on a tier |
| 162 | // change is the other half: seeding past it would leave the definition |
| 163 | // lying about the values already sealed under it. |
| 164 | // |
| 165 | // All of it in one transaction, because a crash between the type row and |
| 166 | // its last field used to leave a partial type that the skip-if-present |
| 167 | // path would then ignore forever. |
| 168 | func Seed(db *gorm.DB, s *seal.Sealer) error { |
| 169 | return db.Transaction(func(tx *gorm.DB) error { |
| 170 | for _, t := range catalogue { |
| 171 | ct, err := seedType_(tx, s, t) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | for i, f := range t.Fields { |
| 176 | if err := seedField_(tx, s, ct.ID, i, f); err != nil { |
| 177 | return err |
| 178 | } |
| 179 | } |
| 180 | } |
| 181 | return nil |
| 182 | }) |
| 183 | } |
| 184 | |
| 185 | func seedType_(tx *gorm.DB, s *seal.Sealer, t seedType) (CardType, error) { |
| 186 | var ct CardType |
| 187 | err := tx.Where("key = ?", t.Key).First(&ct).Error |
| 188 | if err == nil { |
| 189 | // Scope describes how every row under this type was written, so |
| 190 | // it may not drift any more than a field's Tier may. |
| 191 | if ct.Scope != t.Scope { |
| 192 | return ct, fmt.Errorf( |
| 193 | "seed: %s is stored with scope %q but the catalogue now says %q; a type is a card's or an entry's, never both", |
| 194 | t.Key, ct.Scope, t.Scope) |
| 195 | } |
| 196 | return ct, nil |
| 197 | } |
| 198 | if err != gorm.ErrRecordNotFound { |
| 199 | return ct, fmt.Errorf("seed: looking up %s: %w", t.Key, err) |
| 200 | } |
| 201 | label, err := s.Seal(seal.PurposeLabel, []byte(t.Label)) |
| 202 | if err != nil { |
| 203 | return ct, fmt.Errorf("seed: sealing the label for %s: %w", t.Key, err) |
| 204 | } |
| 205 | if t.Scope != ScopeCard && t.Scope != ScopeEntry { |
| 206 | return ct, fmt.Errorf("seed: %s has scope %q, which is neither %q nor %q", t.Key, t.Scope, ScopeCard, ScopeEntry) |
| 207 | } |
| 208 | ct = CardType{Key: t.Key, Scope: t.Scope, SealedLabel: label} |
| 209 | if err := tx.Create(&ct).Error; err != nil { |
| 210 | return ct, fmt.Errorf("seed: creating %s: %w", t.Key, err) |
| 211 | } |
| 212 | // Logged like any schema change. The first version wrote none, which |
| 213 | // made the index's "a type or field changed: rebuild" path unreachable |
| 214 | // and its claim to follow a complete change feed untrue for the |
| 215 | // catalogue — safe only because Seed happens to run before the index |
| 216 | // loads. |
| 217 | if err := logEvent(tx, s, EventCreated, ObjectType, ct.ID, 0, 0, seedActor, nil, nil); err != nil { |
| 218 | return ct, err |
| 219 | } |
| 220 | return ct, nil |
| 221 | } |
| 222 | |
| 223 | func seedField_(tx *gorm.DB, s *seal.Sealer, cardTypeID int64, ordinal int, f seedField) error { |
| 224 | var fd FieldDef |
| 225 | err := tx.Where("key = ?", f.Key).First(&fd).Error |
| 226 | switch { |
| 227 | case err == nil: |
| 228 | // A key is unique across the whole table, so finding one under a |
| 229 | // DIFFERENT type means two definitions are claiming one key — |
| 230 | // and a print is derived from the key, so they would share an |
| 231 | // equality space. Refuse rather than silently ignoring the |
| 232 | // second, which is what returning early here used to do. |
| 233 | if fd.CardTypeID != cardTypeID { |
| 234 | return fmt.Errorf( |
| 235 | "seed: %s is already defined under another card type; a field key is unique across the "+ |
| 236 | "catalogue because the print purpose derives from it", f.Key) |
| 237 | } |
| 238 | // Label and ordinal may drift freely — they are presentation. |
| 239 | // Kind and Tier may not: both describe how the values already in |
| 240 | // the database were written. |
| 241 | if fd.Kind != f.Kind && fd.Tier == f.Tier && kindUpgrades[f.Key] == [2]string{fd.Kind, f.Kind} { |
| 242 | return upgradeKind(tx, s, fd, f.Kind) |
| 243 | } |
| 244 | if fd.Kind != f.Kind || fd.Tier != f.Tier { |
| 245 | return fmt.Errorf( |
| 246 | "seed: %s is stored as kind=%s tier=%s but the catalogue now says kind=%s tier=%s; "+ |
| 247 | "changing either is a re-encryption of every value under it, not a seed-time edit", |
| 248 | f.Key, fd.Kind, fd.Tier, f.Kind, f.Tier) |
| 249 | } |
| 250 | return nil |
| 251 | case err != gorm.ErrRecordNotFound: |
| 252 | return fmt.Errorf("seed: looking up %s: %w", f.Key, err) |
| 253 | } |
| 254 | |
| 255 | label, err := s.Seal(seal.PurposeLabel, []byte(f.Label)) |
| 256 | if err != nil { |
| 257 | return fmt.Errorf("seed: sealing the label for %s: %w", f.Key, err) |
| 258 | } |
| 259 | var options []byte |
| 260 | if len(f.Options) > 0 { |
| 261 | raw, err := json.Marshal(f.Options) |
| 262 | if err != nil { |
| 263 | return fmt.Errorf("seed: encoding the options for %s: %w", f.Key, err) |
| 264 | } |
| 265 | if options, err = s.Seal(seal.PurposeLabel, raw); err != nil { |
| 266 | return fmt.Errorf("seed: sealing the options for %s: %w", f.Key, err) |
| 267 | } |
| 268 | } |
| 269 | fd = FieldDef{ |
| 270 | CardTypeID: cardTypeID, |
| 271 | Key: f.Key, |
| 272 | SealedLabel: label, |
| 273 | SealedOptions: options, |
| 274 | Kind: f.Kind, |
| 275 | Tier: f.Tier, |
| 276 | Ordinal: ordinal, |
| 277 | } |
| 278 | if err := tx.Create(&fd).Error; err != nil { |
| 279 | return fmt.Errorf("seed: creating %s: %w", f.Key, err) |
| 280 | } |
| 281 | return logEvent(tx, s, EventCreated, ObjectField, fd.ID, 0, 0, seedActor, nil, nil) |
| 282 | } |
| 283 | |
| 284 | // seedActor is the app writing its own catalogue — ruling 9's app-as-itself, |
| 285 | // with its reason, never attributed to whoever's boot triggered it. |
| 286 | var seedActor = AppBecause(0, "catalogue seed") |
| 287 | |
| 288 | // openOptions unseals a KindEnum's permitted values. |
| 289 | func openOptions(s *seal.Sealer, sealed []byte) ([]string, error) { |
| 290 | raw, err := s.Open(seal.PurposeLabel, sealed) |
| 291 | if err != nil { |
| 292 | return nil, fmt.Errorf("fichas: opening enum options: %w", err) |
| 293 | } |
| 294 | var out []string |
| 295 | if err := json.Unmarshal(raw, &out); err != nil { |
| 296 | return nil, fmt.Errorf("fichas: decoding enum options: %w", err) |
| 297 | } |
| 298 | return out, nil |
| 299 | } |
| 300 | |
| 301 | // kindUpgrades are the kind changes Seed is allowed to apply to a shipped |
| 302 | // field, as {from, to}. Every other change still refuses to boot: a kind |
| 303 | // describes how the values already stored were written, and changing it |
| 304 | // silently would leave the definition lying about them. |
| 305 | // |
| 306 | // An upgrade is listed here only when every existing value can be carried |
| 307 | // across by re-normalising it — Text to Web address is: a value is either an |
| 308 | // address already, or it is kept exactly as it was and flagged the next time |
| 309 | // someone edits it. |
| 310 | var kindUpgrades = map[string][2]string{ |
| 311 | FieldDomain: {KindText, KindURL}, |
| 312 | // Every Text value is kept as it was; Email and Phone check new input |
| 313 | // only, and a stored value they would refuse is flagged at next edit. |
| 314 | FieldEmail: {KindText, KindEmail}, |
| 315 | FieldPhone: {KindText, KindPhone}, |
| 316 | } |
| 317 | |
| 318 | // upgradeKind moves a shipped field to a new kind and carries its values |
| 319 | // across: each is re-normalised, re-sealed if it changed, and re-printed |
| 320 | // under the new kind's canonical form, and each card whose value changed |
| 321 | // gets an event and a revision — the ruling that every change to every |
| 322 | // object is logged applies to a change the app makes as much as to one a |
| 323 | // person does. |
| 324 | func upgradeKind(tx *gorm.DB, s *seal.Sealer, fd FieldDef, to string) error { |
| 325 | next := fd |
| 326 | next.Kind = to |
| 327 | var values []CardValue |
| 328 | if err := tx.Where("field_def_id = ?", fd.ID).Find(&values).Error; err != nil { |
| 329 | return fmt.Errorf("seed: loading %s values to upgrade: %w", fd.Key, err) |
| 330 | } |
| 331 | for _, v := range values { |
| 332 | raw, err := s.Open(seal.PurposeValue, v.SealedValue) |
| 333 | if err != nil { |
| 334 | return fmt.Errorf("seed: opening a %s value: %w", fd.Key, err) |
| 335 | } |
| 336 | before := string(raw) |
| 337 | after := before |
| 338 | if to == KindURL { |
| 339 | if n, err := normaliseURL(before); err == nil { |
| 340 | after = n |
| 341 | } |
| 342 | } |
| 343 | set := map[string]any{} |
| 344 | if after != before { |
| 345 | sealed, err := s.Seal(seal.PurposeValue, []byte(after)) |
| 346 | if err != nil { |
| 347 | return err |
| 348 | } |
| 349 | set["sealed_value"] = sealed |
| 350 | } |
| 351 | if fd.Tier == TierPrint { |
| 352 | pr, err := printFor(s, next, after) |
| 353 | if err != nil { |
| 354 | return err |
| 355 | } |
| 356 | set["print"] = pr |
| 357 | } |
| 358 | if len(set) > 0 { |
| 359 | if err := tx.Model(&CardValue{}).Where("card_id = ? AND field_def_id = ?", v.CardID, v.FieldDefID).Updates(set).Error; err != nil { |
| 360 | return err |
| 361 | } |
| 362 | } |
| 363 | if after != before { |
| 364 | var card Card |
| 365 | if err := tx.First(&card, v.CardID).Error; err != nil { |
| 366 | return err |
| 367 | } |
| 368 | if err := bumpRevision(tx, &card, nil); err != nil { |
| 369 | return err |
| 370 | } |
| 371 | if err := logEvent(tx, s, EventUpdated, ObjectCard, card.ID, 0, card.Revision, |
| 372 | AppBecause(0, "field kind upgrade"), []int64{fd.ID}, |
| 373 | []change{{Field: fd.Key, Before: before, After: after}}); err != nil { |
| 374 | return err |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | if err := tx.Model(&FieldDef{}).Where("id = ?", fd.ID).Update("kind", to).Error; err != nil { |
| 379 | return err |
| 380 | } |
| 381 | return logEvent(tx, s, EventUpdated, ObjectField, fd.ID, 0, 0, AppBecause(0, "field kind upgrade"), nil, |
| 382 | []change{{Field: "kind", Before: fd.Kind, After: to}}) |
| 383 | } |
| 384 | |