| 1 | package fichas |
| 2 | |
| 3 | // History on the card (level-up §5.5) and the value window that bounds |
| 4 | // it (Q11: 90 days). Past the window an event keeps who, when and which |
| 5 | // fields; its before and after values are erased. |
| 6 | |
| 7 | import ( |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "log/slog" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 16 | "gorm.io/gorm" |
| 17 | ) |
| 18 | |
| 19 | // HistoryItem is one change to a card, as History lists it. |
| 20 | type HistoryItem struct { |
| 21 | EventID int64 |
| 22 | When time.Time |
| 23 | Who string // the person's address; "" for Fichas itself |
| 24 | Reason string // Fichas' reason, when Fichas acted |
| 25 | Kind string // created, updated, entry_added, deleted |
| 26 | Undo bool // an Undo's own event |
| 27 | Redo bool |
| 28 | // Held is true inside the value window: the values are still kept, |
| 29 | // so each field shows before and after, and can be restored. |
| 30 | Held bool |
| 31 | Fields []HistoryField |
| 32 | } |
| 33 | |
| 34 | // HistoryField is one field one change touched. |
| 35 | type HistoryField struct { |
| 36 | Key, Label, Kind string |
| 37 | Before, After string |
| 38 | Gone bool // the field no longer exists |
| 39 | } |
| 40 | |
| 41 | // historyLimit bounds one History page: a card edited daily for years |
| 42 | // still draws quickly, and the oldest changes are past the window anyway. |
| 43 | const historyLimit = 200 |
| 44 | |
| 45 | // CardHistory is a card's changes, newest first. |
| 46 | func CardHistory(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64) ([]HistoryItem, error) { |
| 47 | g := db.WithContext(ctx) |
| 48 | var card Card |
| 49 | if err := g.Where("id = ? AND gone = ?", cardID, false).First(&card).Error; err != nil { |
| 50 | return nil, err |
| 51 | } |
| 52 | var defs []FieldDef |
| 53 | if err := g.Where("card_type_id = ?", card.CardTypeID).Find(&defs).Error; err != nil { |
| 54 | return nil, fmt.Errorf("fichas: loading field definitions: %w", err) |
| 55 | } |
| 56 | byID := map[int64]FieldDef{} |
| 57 | labels := map[int64]string{} |
| 58 | for _, d := range defs { |
| 59 | byID[d.ID] = d |
| 60 | if labels[d.ID], _ = openLabel(s, d.SealedLabel); labels[d.ID] == "" { |
| 61 | labels[d.ID] = d.Key |
| 62 | } |
| 63 | } |
| 64 | var events []Event |
| 65 | if err := g.Where("object_kind = ? AND object_id = ?", ObjectCard, cardID). |
| 66 | Order("id desc").Limit(historyLimit).Find(&events).Error; err != nil { |
| 67 | return nil, fmt.Errorf("fichas: reading card %d's history: %w", cardID, err) |
| 68 | } |
| 69 | people := map[int64]string{} |
| 70 | out := make([]HistoryItem, 0, len(events)) |
| 71 | for _, e := range events { |
| 72 | item := HistoryItem{EventID: e.ID, When: e.CreatedAt, Kind: e.Kind, Reason: e.ActorReason} |
| 73 | if e.ActorID != nil { |
| 74 | if _, ok := people[*e.ActorID]; !ok { |
| 75 | people[*e.ActorID], _ = memberAddress(g, s, *e.ActorID) |
| 76 | } |
| 77 | item.Who = people[*e.ActorID] |
| 78 | } |
| 79 | p, held := readPayload(s, e) |
| 80 | item.Held = held && time.Since(e.CreatedAt) <= valueWindow |
| 81 | item.Undo, item.Redo = p.Undo, p.Redo |
| 82 | item.Fields = historyFields(e, p, item.Held, byID, labels) |
| 83 | out = append(out, item) |
| 84 | } |
| 85 | return out, nil |
| 86 | } |
| 87 | |
| 88 | // historyFields names the fields an event touched, with their values |
| 89 | // when they are still held. |
| 90 | func historyFields(e Event, p editPayload, held bool, byID map[int64]FieldDef, labels map[int64]string) []HistoryField { |
| 91 | var ids []int64 |
| 92 | _ = json.Unmarshal([]byte(e.ChangedFields), &ids) |
| 93 | values := map[string]change{} |
| 94 | if held { |
| 95 | for _, c := range p.Changes { |
| 96 | values[c.Field] = c |
| 97 | } |
| 98 | } |
| 99 | var out []HistoryField |
| 100 | for _, id := range ids { |
| 101 | d, ok := byID[id] |
| 102 | if !ok { |
| 103 | out = append(out, HistoryField{Label: "A removed field", Gone: true}) |
| 104 | continue |
| 105 | } |
| 106 | f := HistoryField{Key: d.Key, Label: labels[id], Kind: d.Kind} |
| 107 | if c, ok := values[d.Key]; ok { |
| 108 | f.Before, f.After = c.Before, c.After |
| 109 | } |
| 110 | out = append(out, f) |
| 111 | } |
| 112 | return out |
| 113 | } |
| 114 | |
| 115 | // ErasePayloads empties the before and after values of every event |
| 116 | // older than the value window, and stamps when. It logs no event: it |
| 117 | // removes only what nobody can still reach (level-up §9's named |
| 118 | // exemption), and an event would have to name Fichas as the actor. |
| 119 | func ErasePayloads(ctx context.Context, db *gorm.DB, now time.Time) (int64, error) { |
| 120 | res := db.WithContext(ctx).Model(&Event{}). |
| 121 | Where("created_at < ? AND payload_sealed IS NOT NULL", now.Add(-valueWindow)). |
| 122 | Updates(map[string]any{"payload_sealed": nil, "payload_erased_at": now}) |
| 123 | if res.Error != nil { |
| 124 | return 0, fmt.Errorf("fichas: erasing payloads past the value window: %w", res.Error) |
| 125 | } |
| 126 | return res.RowsAffected, nil |
| 127 | } |
| 128 | |
| 129 | // sweepEvery is how often a running Fichas sweeps. The window is days |
| 130 | // long, so an hour's lag past it costs nothing. |
| 131 | const sweepEvery = time.Hour |
| 132 | |
| 133 | // Sweep erases payloads past the window now and then every hour, until |
| 134 | // ctx ends. It never stops the app: a failed sweep is logged and tried |
| 135 | // again on the next tick. |
| 136 | func Sweep(ctx context.Context, db *gorm.DB, logger *slog.Logger) { |
| 137 | run := func() { |
| 138 | n, err := ErasePayloads(ctx, db, time.Now()) |
| 139 | if err != nil { |
| 140 | logger.Error("value window sweep", "err", err) |
| 141 | return |
| 142 | } |
| 143 | if n > 0 { |
| 144 | logger.Info("value window sweep", "erased", n) |
| 145 | } |
| 146 | } |
| 147 | run() |
| 148 | t := time.NewTicker(sweepEvery) |
| 149 | defer t.Stop() |
| 150 | for { |
| 151 | select { |
| 152 | case <-ctx.Done(): |
| 153 | return |
| 154 | case <-t.C: |
| 155 | run() |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | // personName is how a person is shown until rosters carry names (§6.5): |
| 161 | // the part of their address before the @. |
| 162 | func personName(address string) string { |
| 163 | if address == "" { |
| 164 | return "Fichas" |
| 165 | } |
| 166 | name, _, _ := strings.Cut(address, "@") |
| 167 | return name |
| 168 | } |
| 169 | |