oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3// Editing in place (level-up spec §5.2, §5.3): writes that carry what
4// the editor saw, so they never cross a teammate's, and Undo as a new
5// event, never a rewind.
6
7import (
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "sort"
13 "strings"
14 "time"
15
16 "amadan.net/oficina/fichas/internal/fichas/seal"
17 "gorm.io/gorm"
18)
19
20// editPayload is a card event's sealed payload from Phase 1 on. Older
21// events hold a bare JSON array of changes, which reads as an edit that
22// is not undoable.
23type editPayload struct {
24 Changes []change `json:"changes"`
25 // Undoable marks a person's own edit, the only kind of event Undo
26 // takes (§5.3). A redo is one too, so ⌘Z after ⌘⇧Z undoes it again.
27 Undoable bool `json:"undoable,omitempty"`
28 // Undo marks an Undo's own event, which only Redo takes.
29 Undo bool `json:"undo,omitempty"`
30 Redo bool `json:"redo,omitempty"`
31}
32
33func readPayload(s *seal.Sealer, e Event) (editPayload, bool) {
34 if len(e.PayloadSealed) == 0 || e.PayloadErasedAt != nil {
35 return editPayload{}, false
36 }
37 raw, err := s.Open(seal.PurposeEventPayload, e.PayloadSealed)
38 if err != nil {
39 return editPayload{}, false
40 }
41 var p editPayload
42 if json.Unmarshal(raw, &p) == nil {
43 return p, true
44 }
45 var legacy []change
46 if json.Unmarshal(raw, &legacy) == nil {
47 return editPayload{Changes: legacy}, true
48 }
49 return editPayload{}, false
50}
51
52// logCardEdit writes one card `updated` event with an editPayload, in
53// the caller's transaction. trigger names the event an Undo or Redo
54// answers; 0 for an edit.
55func logCardEdit(tx *gorm.DB, s *seal.Sealer, card Card, actor Actor, changed []int64, p editPayload, trigger int64) (int64, error) {
56 if err := actor.valid(); err != nil {
57 return 0, err
58 }
59 sort.Slice(changed, func(i, j int) bool { return changed[i] < changed[j] })
60 ids, err := json.Marshal(append([]int64{}, changed...))
61 if err != nil {
62 return 0, fmt.Errorf("fichas: encoding changed fields: %w", err)
63 }
64 raw, err := json.Marshal(p)
65 if err != nil {
66 return 0, fmt.Errorf("fichas: encoding the change payload: %w", err)
67 }
68 sealed, err := s.Seal(seal.PurposeEventPayload, raw)
69 if err != nil {
70 return 0, fmt.Errorf("fichas: sealing the change payload: %w", err)
71 }
72 if trigger == 0 {
73 trigger = actor.trigger
74 }
75 e := Event{
76 Kind: EventUpdated, ObjectKind: ObjectCard, ObjectID: card.ID,
77 ActorID: actor.memberID, ActorReason: actor.reason, Revision: card.Revision,
78 ChangedFields: string(ids), PayloadSealed: sealed, TriggerID: trigger,
79 Nonce: randomPositive(),
80 }
81 if err := tx.Create(&e).Error; err != nil {
82 return 0, fmt.Errorf("fichas: writing the event: %w", err)
83 }
84 return e.ID, nil
85}
86
87// Conflict is one field a write did not land on, because someone
88// changed it after the editor drew it.
89type Conflict struct {
90 Theirs string // the value it holds now, canonical
91 By string // who last changed it, an address, or "" when unknown
92}
93
94// ConflictError refuses a write whose `was` is stale (§5.2, 409).
95type ConflictError struct{ Fields map[string]Conflict }
96
97func (e *ConflictError) Error() string {
98 keys := make([]string, 0, len(e.Fields))
99 for k := range e.Fields {
100 keys = append(keys, k)
101 }
102 sort.Strings(keys)
103 return "fichas: changed since it was drawn: " + strings.Join(keys, ", ")
104}
105
106// IsConflict reports a stale write.
107func IsConflict(err error) (*ConflictError, bool) {
108 var c *ConflictError
109 return c, errors.As(err, &c)
110}
111
112// EditResult is what an edit did.
113type EditResult struct {
114 EventID int64 // 0 when nothing changed
115 Changes []change // what changed, canonical
116 Values map[string]string // the values the fields now hold, canonical
117}
118
119// SetField writes one field, given what the editor saw (§5.2).
120func SetField(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, key, value, was string) (EditResult, error) {
121 return EditFields(ctx, db, s, cardID, actor, map[string]string{key: value}, map[string]string{key: was})
122}
123
124// EditFields writes several fields of one card, all or nothing, each
125// checked against what the editor saw, in one transaction:
126// 1. a field already holding its new value is not a change, so a Retry
127// or a second tab making the same change succeeds with no event;
128// 2. a field holding its `was` takes the new value;
129// 3. any other field is a conflict, and then nothing is written.
130//
131// The changes land as one `updated` event, marked undoable, and one new
132// revision. A key that is not a field of the card's type, or a card
133// that is gone, is gorm.ErrRecordNotFound: the caller's 404.
134func EditFields(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, values, was map[string]string) (EditResult, error) {
135 var res EditResult
136 err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
137 card, defs, err := liveCard(tx, cardID)
138 if err != nil {
139 return err
140 }
141 for k := range values {
142 if _, ok := defs[k]; !ok {
143 return gorm.ErrRecordNotFound
144 }
145 }
146 values, err := checkValues(s, defs, values)
147 if err != nil {
148 return err
149 }
150 res.Values = map[string]string{}
151 conflicts := map[string]Conflict{}
152 var changed []int64
153 for _, key := range sortedKeys(values) {
154 def, after := defs[key], values[key]
155 before, err := currentValue(tx, s, cardID, def)
156 if err != nil {
157 return err
158 }
159 res.Values[key] = before
160 switch {
161 case sameText(before, after):
162 case sameText(before, was[key]):
163 res.Changes = append(res.Changes, change{Field: key, Before: before, After: after})
164 changed = append(changed, def.ID)
165 res.Values[key] = after
166 default:
167 by, err := lastEditor(tx, s, cardID, def.ID)
168 if err != nil {
169 return err
170 }
171 conflicts[key] = Conflict{Theirs: before, By: by}
172 }
173 }
174 if len(conflicts) > 0 {
175 res = EditResult{}
176 return &ConflictError{Fields: conflicts}
177 }
178 if len(res.Changes) == 0 {
179 return nil
180 }
181 for _, c := range res.Changes {
182 if err := writeValue(tx, s, cardID, defs[c.Field], c.After); err != nil {
183 return err
184 }
185 }
186 if err := bumpRevision(tx, &card, nil); err != nil {
187 return err
188 }
189 res.EventID, err = logCardEdit(tx, s, card, actor, changed, editPayload{Changes: res.Changes, Undoable: true}, 0)
190 return err
191 })
192 if err != nil {
193 return EditResult{}, err
194 }
195 return res, nil
196}
197
198// liveCard is a card that is not gone, with its type's fields by key.
199func liveCard(tx *gorm.DB, cardID int64) (Card, map[string]FieldDef, error) {
200 var card Card
201 if err := tx.Where("id = ? AND gone = ?", cardID, false).First(&card).Error; err != nil {
202 return Card{}, nil, err
203 }
204 var ct CardType
205 if err := tx.First(&ct, card.CardTypeID).Error; err != nil {
206 return Card{}, nil, fmt.Errorf("fichas: loading card %d's type: %w", cardID, err)
207 }
208 if ct.Scope != ScopeCard {
209 return Card{}, nil, gorm.ErrRecordNotFound
210 }
211 defs, err := fieldsFor(tx, card.CardTypeID)
212 return card, defs, err
213}
214
215func sortedKeys(m map[string]string) []string {
216 keys := make([]string, 0, len(m))
217 for k := range m {
218 keys = append(keys, k)
219 }
220 sort.Strings(keys)
221 return keys
222}
223
224// lastEditor is the address of whoever last wrote a field of a card, by
225// the event log; "" when the last write was Fichas' own or unknown.
226func lastEditor(tx *gorm.DB, s *seal.Sealer, cardID, fieldID int64) (string, error) {
227 var events []Event
228 if err := tx.Where("object_kind = ? AND object_id = ? AND kind IN ?", ObjectCard, cardID,
229 []string{EventCreated, EventUpdated}).Order("id desc").Limit(200).Find(&events).Error; err != nil {
230 return "", fmt.Errorf("fichas: reading card %d's history: %w", cardID, err)
231 }
232 for _, e := range events {
233 if !changedField(e, fieldID) {
234 continue
235 }
236 if e.ActorID == nil {
237 return "", nil
238 }
239 return memberAddress(tx, s, *e.ActorID)
240 }
241 return "", nil
242}
243
244func changedField(e Event, fieldID int64) bool {
245 var ids []int64
246 if json.Unmarshal([]byte(e.ChangedFields), &ids) != nil {
247 return false
248 }
249 for _, id := range ids {
250 if id == fieldID {
251 return true
252 }
253 }
254 return false
255}
256
257// memberAddress opens a member's sealed address.
258func memberAddress(tx *gorm.DB, s *seal.Sealer, id int64) (string, error) {
259 var m Member
260 if err := tx.First(&m, id).Error; err != nil {
261 return "", fmt.Errorf("fichas: loading member %d: %w", id, err)
262 }
263 raw, err := s.Open(seal.PurposeLabel, m.SealedAddress)
264 if err != nil {
265 return "", fmt.Errorf("fichas: opening member %d's address: %w", id, err)
266 }
267 return string(raw), nil
268}
269
270// valueWindow is how long an event's before and after values are kept
271// (Q11, ruled 2026-11-17): Undo past the toast, Restore in History, and
272// detached files all live inside it.
273const valueWindow = 90 * 24 * time.Hour
274
275// UndoResult is what an Undo or Redo did.
276type UndoResult struct {
277 EventID int64 // the new event; 0 when nothing could be put back
278 Redo bool // the event named was an Undo, so this redid it
279 Applied []change // each field put back, canonical
280 Left []Left // each field left as it is, and why
281}
282
283// Left is a field an Undo did not put back.
284type Left struct {
285 Field string
286 By string // who changed it again; "" when the reason is Gone
287 Gone bool // its old value can no longer be written
288}
289
290// Undo reverses one event by a new one (§5.3). The event must be an
291// `updated` event on this card, by this person, whose payload is still
292// held and marked undoable, or an Undo's own event, which Redo takes.
293// Anything else is gorm.ErrRecordNotFound, the app's 404. Each field
294// goes back only if it still holds the event's after value.
295func Undo(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, eventID int64) (UndoResult, error) {
296 var res UndoResult
297 err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
298 ev, p, err := undoableEvent(tx, s, cardID, actor, eventID)
299 if err != nil {
300 return err
301 }
302 res.Redo = p.Undo
303 card, defs, err := liveCard(tx, cardID)
304 if err != nil {
305 return err
306 }
307 var changed []int64
308 for _, c := range p.Changes {
309 def, ok := defs[c.Field]
310 if !ok {
311 res.Left = append(res.Left, Left{Field: c.Field, Gone: true})
312 continue
313 }
314 now, err := currentValue(tx, s, cardID, def)
315 if err != nil {
316 return err
317 }
318 if !sameText(now, c.After) {
319 by, err := lastEditor(tx, s, cardID, def.ID)
320 if err != nil {
321 return err
322 }
323 res.Left = append(res.Left, Left{Field: c.Field, By: by})
324 continue
325 }
326 if _, err := checkValues(s, defs, map[string]string{c.Field: c.Before}); err != nil {
327 if _, person := IsFormError(err); !person {
328 return err
329 }
330 res.Left = append(res.Left, Left{Field: c.Field, Gone: true})
331 continue
332 }
333 if err := writeValue(tx, s, cardID, def, c.Before); err != nil {
334 return err
335 }
336 res.Applied = append(res.Applied, change{Field: c.Field, Before: now, After: c.Before})
337 changed = append(changed, def.ID)
338 }
339 if len(res.Applied) == 0 {
340 return nil
341 }
342 if err := bumpRevision(tx, &card, nil); err != nil {
343 return err
344 }
345 payload := editPayload{Changes: res.Applied, Undo: !res.Redo, Redo: res.Redo, Undoable: res.Redo}
346 res.EventID, err = logCardEdit(tx, s, card, actor, changed, payload, ev.ID)
347 return err
348 })
349 if err != nil {
350 return UndoResult{}, err
351 }
352 return res, nil
353}
354
355// undoableEvent is the event an Undo names, if this person may undo it.
356func undoableEvent(tx *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, eventID int64) (Event, editPayload, error) {
357 var ev Event
358 err := tx.Where("id = ? AND object_kind = ? AND object_id = ? AND kind = ?",
359 eventID, ObjectCard, cardID, EventUpdated).First(&ev).Error
360 if err != nil {
361 return Event{}, editPayload{}, err
362 }
363 if actor.memberID == nil || ev.ActorID == nil || *ev.ActorID != *actor.memberID ||
364 time.Since(ev.CreatedAt) > valueWindow {
365 return Event{}, editPayload{}, gorm.ErrRecordNotFound
366 }
367 p, ok := readPayload(s, ev)
368 if !ok || !(p.Undoable || p.Undo) {
369 return Event{}, editPayload{}, gorm.ErrRecordNotFound
370 }
371 return ev, p, nil
372}
373