| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "sort" |
| 7 | "strings" |
| 8 | |
| 9 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | // The read path. Everything here unseals, which is the point: §4.1's whole |
| 14 | // argument is that sealed is not unqueryable, because the values come back |
| 15 | // into memory to be read, sorted and grouped. |
| 16 | // |
| 17 | // Slice 1 reads straight from the tables. The in-memory index §4.1 talks |
| 18 | // about is what replaces these ORDER BYs once there is enough data for it |
| 19 | // to matter; there is a trigger for that in §4.2 and no point paying for it |
| 20 | // at a few hundred cards. |
| 21 | |
| 22 | // FieldView is one field of a card or entry, ready to render. |
| 23 | type FieldView struct { |
| 24 | Def FieldDef |
| 25 | Label string |
| 26 | Value string |
| 27 | // Options is a KindEnum's permitted values, unsealed. |
| 28 | Options []string |
| 29 | } |
| 30 | |
| 31 | // CardView is a card with its type, its fields and their values. |
| 32 | type CardView struct { |
| 33 | Card Card |
| 34 | TypeKey string |
| 35 | TypeLabel string |
| 36 | Fields []FieldView |
| 37 | Entries []EntryView |
| 38 | // Latest is the most recent entry, filled by ListCards for the table's |
| 39 | // "Last call" column and the card face. Nil when there is none. |
| 40 | Latest *EntryView |
| 41 | } |
| 42 | |
| 43 | // Title is what a card is called in a list. The first printed text field |
| 44 | // with a value, because that is the name-shaped one; falls back to the id |
| 45 | // so a card with nothing in it is still reachable. |
| 46 | func (c CardView) Title() string { |
| 47 | if v := c.Field(c.titleKey()).Value; v != "" { |
| 48 | return v |
| 49 | } |
| 50 | for _, f := range c.Fields { |
| 51 | if f.Def.Kind == KindText && f.Value != "" { |
| 52 | return f.Value |
| 53 | } |
| 54 | } |
| 55 | return fmt.Sprintf("Card %d", c.Card.ID) |
| 56 | } |
| 57 | |
| 58 | // Field returns one field by key, for a template that wants a specific one. |
| 59 | func (c CardView) Field(key string) FieldView { |
| 60 | for _, f := range c.Fields { |
| 61 | if f.Def.Key == key { |
| 62 | return f |
| 63 | } |
| 64 | } |
| 65 | return FieldView{} |
| 66 | } |
| 67 | |
| 68 | // EntryView is an entry with its values. |
| 69 | type EntryView struct { |
| 70 | Entry Entry |
| 71 | TypeLabel string |
| 72 | Fields []FieldView |
| 73 | } |
| 74 | |
| 75 | // Body is the entry's main text, for a compact rendering. |
| 76 | func (e EntryView) Body() string { |
| 77 | for _, f := range e.Fields { |
| 78 | if f.Def.Key == FieldBody { |
| 79 | return f.Value |
| 80 | } |
| 81 | } |
| 82 | return "" |
| 83 | } |
| 84 | |
| 85 | func openLabel(s *seal.Sealer, b []byte) (string, error) { |
| 86 | if len(b) == 0 { |
| 87 | return "", nil |
| 88 | } |
| 89 | raw, err := s.Open(seal.PurposeLabel, b) |
| 90 | if err != nil { |
| 91 | return "", fmt.Errorf("fichas: opening a label: %w", err) |
| 92 | } |
| 93 | return string(raw), nil |
| 94 | } |
| 95 | |
| 96 | // fieldViews builds the ordered field list for a type, filling in values |
| 97 | // from valuesByDef. |
| 98 | func fieldViews(s *seal.Sealer, defs []FieldDef, valuesByDef map[int64][]byte) ([]FieldView, error) { |
| 99 | sort.Slice(defs, func(i, j int) bool { return defs[i].Ordinal < defs[j].Ordinal }) |
| 100 | out := make([]FieldView, 0, len(defs)) |
| 101 | for _, d := range defs { |
| 102 | label, err := openLabel(s, d.SealedLabel) |
| 103 | if err != nil { |
| 104 | return nil, err |
| 105 | } |
| 106 | fv := FieldView{Def: d, Label: label} |
| 107 | if sealed, ok := valuesByDef[d.ID]; ok && len(sealed) > 0 { |
| 108 | raw, err := s.Open(seal.PurposeValue, sealed) |
| 109 | if err != nil { |
| 110 | return nil, fmt.Errorf("fichas: opening %s: %w", d.Key, err) |
| 111 | } |
| 112 | fv.Value = string(raw) |
| 113 | } |
| 114 | if len(d.SealedOptions) > 0 { |
| 115 | opts, err := openOptions(s, d.SealedOptions) |
| 116 | if err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | fv.Options = opts |
| 120 | } |
| 121 | out = append(out, fv) |
| 122 | } |
| 123 | return out, nil |
| 124 | } |
| 125 | |
| 126 | // ListCards returns every card of a type that is not gone, newest first. |
| 127 | func ListCards(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string) ([]CardView, error) { |
| 128 | g := db.WithContext(ctx) |
| 129 | ct, err := typeByKey(g, typeKey, ScopeCard) |
| 130 | if err != nil { |
| 131 | return nil, err |
| 132 | } |
| 133 | typeLabel, err := openLabel(s, ct.SealedLabel) |
| 134 | if err != nil { |
| 135 | return nil, err |
| 136 | } |
| 137 | |
| 138 | var defs []FieldDef |
| 139 | if err := g.Where("card_type_id = ?", ct.ID).Find(&defs).Error; err != nil { |
| 140 | return nil, fmt.Errorf("fichas: loading field definitions: %w", err) |
| 141 | } |
| 142 | |
| 143 | var cards []Card |
| 144 | if err := g.Where("card_type_id = ? AND gone = ?", ct.ID, false). |
| 145 | Order("updated_at desc").Find(&cards).Error; err != nil { |
| 146 | return nil, fmt.Errorf("fichas: listing cards: %w", err) |
| 147 | } |
| 148 | if len(cards) == 0 { |
| 149 | return nil, nil |
| 150 | } |
| 151 | |
| 152 | ids := make([]int64, len(cards)) |
| 153 | for i, c := range cards { |
| 154 | ids[i] = c.ID |
| 155 | } |
| 156 | var values []CardValue |
| 157 | if err := g.Where("card_id IN ?", ids).Find(&values).Error; err != nil { |
| 158 | return nil, fmt.Errorf("fichas: loading values: %w", err) |
| 159 | } |
| 160 | byCard := map[int64]map[int64][]byte{} |
| 161 | for _, v := range values { |
| 162 | if byCard[v.CardID] == nil { |
| 163 | byCard[v.CardID] = map[int64][]byte{} |
| 164 | } |
| 165 | byCard[v.CardID][v.FieldDefID] = v.SealedValue |
| 166 | } |
| 167 | |
| 168 | latest, err := latestEntries(g, s, ids) |
| 169 | if err != nil { |
| 170 | return nil, err |
| 171 | } |
| 172 | |
| 173 | out := make([]CardView, 0, len(cards)) |
| 174 | for _, c := range cards { |
| 175 | fields, err := fieldViews(s, append([]FieldDef(nil), defs...), byCard[c.ID]) |
| 176 | if err != nil { |
| 177 | return nil, err |
| 178 | } |
| 179 | out = append(out, CardView{Card: c, TypeKey: ct.Key, TypeLabel: typeLabel, Fields: fields, Latest: latest[c.ID]}) |
| 180 | } |
| 181 | return out, nil |
| 182 | } |
| 183 | |
| 184 | // latestEntries returns each card's most recent entry, unsealed. |
| 185 | // |
| 186 | // Batched: one query for the newest entry id per card, then ONE load for all |
| 187 | // of those entries together. The first version loaded them one card at a |
| 188 | // time — four queries each — and its cold-load timing was taken on cards |
| 189 | // with no calls, so the path never ran: 238ms and 8,004 queries at 2,000 |
| 190 | // cards that each had a call, under the index's write lock. A review found it. |
| 191 | func latestEntries(g *gorm.DB, s *seal.Sealer, cardIDs []int64) (map[int64]*EntryView, error) { |
| 192 | var newest []int64 |
| 193 | if err := g.Model(&Entry{}).Select("MAX(id)"). |
| 194 | Where("card_id IN ?", cardIDs).Group("card_id").Scan(&newest).Error; err != nil { |
| 195 | return nil, fmt.Errorf("fichas: finding latest entries: %w", err) |
| 196 | } |
| 197 | out := map[int64]*EntryView{} |
| 198 | if len(newest) == 0 { |
| 199 | return out, nil |
| 200 | } |
| 201 | views, err := loadEntriesWhere(g, s, "id IN ?", newest) |
| 202 | if err != nil { |
| 203 | return nil, err |
| 204 | } |
| 205 | for i := range views { |
| 206 | v := views[i] |
| 207 | out[v.Entry.CardID] = &v |
| 208 | } |
| 209 | return out, nil |
| 210 | } |
| 211 | |
| 212 | // LoadCard returns one card with its fields and its entries, newest entry |
| 213 | // first. A gone card is not found: retirement is by feed, and a retired |
| 214 | // card is not a page. |
| 215 | func LoadCard(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64) (CardView, error) { |
| 216 | g := db.WithContext(ctx) |
| 217 | var card Card |
| 218 | if err := g.Where("id = ? AND gone = ?", cardID, false).First(&card).Error; err != nil { |
| 219 | return CardView{}, err |
| 220 | } |
| 221 | |
| 222 | var ct CardType |
| 223 | if err := g.First(&ct, card.CardTypeID).Error; err != nil { |
| 224 | return CardView{}, fmt.Errorf("fichas: loading the card type: %w", err) |
| 225 | } |
| 226 | typeLabel, err := openLabel(s, ct.SealedLabel) |
| 227 | if err != nil { |
| 228 | return CardView{}, err |
| 229 | } |
| 230 | |
| 231 | var defs []FieldDef |
| 232 | if err := g.Where("card_type_id = ?", ct.ID).Find(&defs).Error; err != nil { |
| 233 | return CardView{}, fmt.Errorf("fichas: loading field definitions: %w", err) |
| 234 | } |
| 235 | var values []CardValue |
| 236 | if err := g.Where("card_id = ?", card.ID).Find(&values).Error; err != nil { |
| 237 | return CardView{}, fmt.Errorf("fichas: loading values: %w", err) |
| 238 | } |
| 239 | byDef := map[int64][]byte{} |
| 240 | for _, v := range values { |
| 241 | byDef[v.FieldDefID] = v.SealedValue |
| 242 | } |
| 243 | fields, err := fieldViews(s, defs, byDef) |
| 244 | if err != nil { |
| 245 | return CardView{}, err |
| 246 | } |
| 247 | |
| 248 | entries, err := loadEntries(g, s, card.ID) |
| 249 | if err != nil { |
| 250 | return CardView{}, err |
| 251 | } |
| 252 | return CardView{Card: card, TypeKey: ct.Key, TypeLabel: typeLabel, Fields: fields, Entries: entries}, nil |
| 253 | } |
| 254 | |
| 255 | func loadEntries(g *gorm.DB, s *seal.Sealer, cardID int64) ([]EntryView, error) { |
| 256 | return loadEntriesWhere(g, s, "card_id = ?", cardID) |
| 257 | } |
| 258 | |
| 259 | func loadEntriesWhere(g *gorm.DB, s *seal.Sealer, where string, arg any) ([]EntryView, error) { |
| 260 | var entries []Entry |
| 261 | if err := g.Where(where, arg).Order("created_at desc, id desc").Find(&entries).Error; err != nil { |
| 262 | return nil, fmt.Errorf("fichas: loading entries: %w", err) |
| 263 | } |
| 264 | if len(entries) == 0 { |
| 265 | return nil, nil |
| 266 | } |
| 267 | |
| 268 | ids := make([]int64, len(entries)) |
| 269 | typeIDs := map[int64]bool{} |
| 270 | for i, e := range entries { |
| 271 | ids[i] = e.ID |
| 272 | typeIDs[e.TypeID] = true |
| 273 | } |
| 274 | var values []EntryValue |
| 275 | if err := g.Where("entry_id IN ?", ids).Find(&values).Error; err != nil { |
| 276 | return nil, fmt.Errorf("fichas: loading entry values: %w", err) |
| 277 | } |
| 278 | byEntry := map[int64]map[int64][]byte{} |
| 279 | for _, v := range values { |
| 280 | if byEntry[v.EntryID] == nil { |
| 281 | byEntry[v.EntryID] = map[int64][]byte{} |
| 282 | } |
| 283 | byEntry[v.EntryID][v.FieldDefID] = v.SealedValue |
| 284 | } |
| 285 | |
| 286 | defsByType := map[int64][]FieldDef{} |
| 287 | labelByType := map[int64]string{} |
| 288 | for id := range typeIDs { |
| 289 | var defs []FieldDef |
| 290 | if err := g.Where("card_type_id = ?", id).Find(&defs).Error; err != nil { |
| 291 | return nil, fmt.Errorf("fichas: loading entry field definitions: %w", err) |
| 292 | } |
| 293 | defsByType[id] = defs |
| 294 | var ct CardType |
| 295 | if err := g.First(&ct, id).Error; err == nil { |
| 296 | l, lerr := openLabel(s, ct.SealedLabel) |
| 297 | if lerr != nil { |
| 298 | return nil, lerr |
| 299 | } |
| 300 | labelByType[id] = l |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | out := make([]EntryView, 0, len(entries)) |
| 305 | for _, e := range entries { |
| 306 | fields, err := fieldViews(s, append([]FieldDef(nil), defsByType[e.TypeID]...), byEntry[e.ID]) |
| 307 | if err != nil { |
| 308 | return nil, err |
| 309 | } |
| 310 | out = append(out, EntryView{Entry: e, TypeLabel: labelByType[e.TypeID], Fields: fields}) |
| 311 | } |
| 312 | return out, nil |
| 313 | } |
| 314 | |
| 315 | // EntryFields returns the blank field set for a new entry of a type, so a |
| 316 | // form can be rendered without inventing its own list. |
| 317 | func EntryFields(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string) ([]FieldView, error) { |
| 318 | g := db.WithContext(ctx) |
| 319 | ct, err := typeByKey(g, typeKey, ScopeEntry) |
| 320 | if err != nil { |
| 321 | return nil, err |
| 322 | } |
| 323 | var defs []FieldDef |
| 324 | if err := g.Where("card_type_id = ?", ct.ID).Find(&defs).Error; err != nil { |
| 325 | return nil, fmt.Errorf("fichas: loading field definitions: %w", err) |
| 326 | } |
| 327 | return fieldViews(s, defs, nil) |
| 328 | } |
| 329 | |
| 330 | // CardFields is EntryFields for a card type. |
| 331 | func CardFields(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string) ([]FieldView, error) { |
| 332 | g := db.WithContext(ctx) |
| 333 | ct, err := typeByKey(g, typeKey, ScopeCard) |
| 334 | if err != nil { |
| 335 | return nil, err |
| 336 | } |
| 337 | var defs []FieldDef |
| 338 | if err := g.Where("card_type_id = ?", ct.ID).Find(&defs).Error; err != nil { |
| 339 | return nil, fmt.Errorf("fichas: loading field definitions: %w", err) |
| 340 | } |
| 341 | return fieldViews(s, defs, nil) |
| 342 | } |
| 343 | |
| 344 | // memberByAddress finds or creates the Member for an address. |
| 345 | // |
| 346 | // The address itself never lands in the clear: it is printed for lookup |
| 347 | // and sealed for display, which is memoria's shape rather than Sheets'. |
| 348 | // Creating on first sight is right for a per-team instance — a person who |
| 349 | // can sign in is a member — and it is the one place a Member row is born. |
| 350 | func memberByAddress(ctx context.Context, db *gorm.DB, s *seal.Sealer, address string) (Member, error) { |
| 351 | g := db.WithContext(ctx) |
| 352 | print, err := s.Print("f_member", []byte(address)) |
| 353 | if err != nil { |
| 354 | return Member{}, fmt.Errorf("fichas: printing an address: %w", err) |
| 355 | } |
| 356 | |
| 357 | var m Member |
| 358 | err = g.Where("address_print = ?", print).First(&m).Error |
| 359 | if err == nil { |
| 360 | return m, nil |
| 361 | } |
| 362 | if err != gorm.ErrRecordNotFound { |
| 363 | return Member{}, fmt.Errorf("fichas: looking up a member: %w", err) |
| 364 | } |
| 365 | |
| 366 | sealed, err := s.Seal(seal.PurposeLabel, []byte(address)) |
| 367 | if err != nil { |
| 368 | return Member{}, fmt.Errorf("fichas: sealing an address: %w", err) |
| 369 | } |
| 370 | m = Member{AddressPrint: print, SealedAddress: sealed} |
| 371 | if err := g.Create(&m).Error; err != nil { |
| 372 | return Member{}, fmt.Errorf("fichas: creating a member: %w", err) |
| 373 | } |
| 374 | return m, nil |
| 375 | } |
| 376 | |
| 377 | // EnsureMember is memberByAddress for callers outside the package — the |
| 378 | // preview server, which needs a real member to attribute its seed data to. |
| 379 | func EnsureMember(ctx context.Context, db *gorm.DB, s *seal.Sealer, address string) (Member, error) { |
| 380 | return memberByAddress(ctx, db, s, address) |
| 381 | } |
| 382 | |
| 383 | // titleKey is the field a card is named by: Name where the type has it, |
| 384 | // otherwise the type's first field — which CreateType makes its name. |
| 385 | func (c CardView) titleKey() string { |
| 386 | for _, f := range c.Fields { |
| 387 | if f.Def.Key == FieldName { |
| 388 | return FieldName |
| 389 | } |
| 390 | } |
| 391 | if len(c.Fields) > 0 { |
| 392 | return c.Fields[0].Def.Key |
| 393 | } |
| 394 | return "" |
| 395 | } |
| 396 | |
| 397 | // IsTitle reports whether a field is the card's title. |
| 398 | func (c CardView) IsTitle(key string) bool { return key == c.titleKey() } |
| 399 | |
| 400 | // FaceLine is one line on a card face. |
| 401 | type FaceLine struct { |
| 402 | Label, Value string |
| 403 | Kind string // a field kind, or "call" for the latest call |
| 404 | Date string // for a date field: the stored value, for <time datetime> |
| 405 | } |
| 406 | |
| 407 | // CardFace is what the Cards view draws for one card. |
| 408 | type CardFace struct { |
| 409 | Pill string // the first choice field on the face, beside the title |
| 410 | Lines []FaceLine |
| 411 | } |
| 412 | |
| 413 | // Face lays a card out by the type's face keys. |
| 414 | func (c CardView) Face(keys []string) CardFace { |
| 415 | var face CardFace |
| 416 | for _, k := range keys { |
| 417 | if k == FaceLatestCall { |
| 418 | if c.Latest != nil && c.Latest.Body() != "" { |
| 419 | face.Lines = append(face.Lines, FaceLine{Kind: "call", Value: c.Latest.Body()}) |
| 420 | } |
| 421 | continue |
| 422 | } |
| 423 | if k == c.titleKey() { |
| 424 | continue |
| 425 | } |
| 426 | f := c.Field(k) |
| 427 | if f.Value == "" { |
| 428 | continue |
| 429 | } |
| 430 | if f.Def.Kind == KindEnum && face.Pill == "" { |
| 431 | face.Pill = f.Value |
| 432 | continue |
| 433 | } |
| 434 | line := FaceLine{Label: f.Label, Value: f.Value, Kind: f.Def.Kind} |
| 435 | if isLong(f.Def) { |
| 436 | line.Kind = KindLongText |
| 437 | } |
| 438 | if f.Def.Kind == KindDate { |
| 439 | line.Date = f.Value |
| 440 | } |
| 441 | face.Lines = append(face.Lines, line) |
| 442 | } |
| 443 | return face |
| 444 | } |
| 445 | |
| 446 | // LongFields are the card's paragraph fields that have a value, for the read |
| 447 | // view, which gives each its own box. |
| 448 | func (c CardView) LongFields() []FieldView { |
| 449 | var out []FieldView |
| 450 | for _, f := range c.Fields { |
| 451 | if isLong(f.Def) && f.Value != "" { |
| 452 | out = append(out, f) |
| 453 | } |
| 454 | } |
| 455 | return out |
| 456 | } |
| 457 | |
| 458 | // telDigits is a phone number as a tel: link wants it: ASCII digits and a |
| 459 | // leading +. Not stripPhoneFormatting, whose output is a print's canonical |
| 460 | // form and must not change; it keeps any Unicode digit, which a dialler |
| 461 | // cannot use. |
| 462 | func telDigits(v string) string { |
| 463 | var b strings.Builder |
| 464 | for i, r := range strings.TrimSpace(v) { |
| 465 | if (r >= '0' && r <= '9') || (r == '+' && i == 0) { |
| 466 | b.WriteRune(r) |
| 467 | } |
| 468 | } |
| 469 | return b.String() |
| 470 | } |
| 471 | |