oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "slices"
8 "strconv"
9 "time"
10
11 "gorm.io/gorm"
12
13 "amadan.net/oficina/equipo/internal/advice"
14 "amadan.net/oficina/equipo/internal/wire"
15)
16
17// Advice on the instance (connectors spec 2026-11-12 rev 3.2 §9, slice
18// S4). advice.Compute turns the person's recorded facts into advice; the
19// rules here keep at most one card open, at most one new card a day,
20// silence a key after Not now, withdraw advice whose facts stopped
21// holding without a word, and hold a card made in quiet hours until they
22// end (housekeeping's VisibleAt). A card is never Needs you and never a
23// push. Its action is the ordinary call, revision-checked, in the same
24// transaction as the advice it answers, and recorded with source advice
25// and the key. The coordinator cannot create, change or dismiss advice.
26
27// adviceRecord is one piece of advice shown to a person. The table only
28// moves forward: open, then acted, dismissed or withdrawn. Facts is the
29// action as the person saw it (advice.Advice JSON); ShownAt the time it
30// counts for (its visible time); CardID its quiet card.
31type adviceRecord struct {
32 ID string `gorm:"primaryKey"`
33 Person string `gorm:"index:chat_advice_person,priority:1"`
34 Key string `gorm:"index:chat_advice_person,priority:2"`
35 Kind string
36 State string
37 Subject string
38 Facts string
39 Text string
40 Act string
41 Dismiss string
42 CardID string
43 Revision int64
44 CreatedAt time.Time
45 UpdatedAt time.Time
46 VisibleAt *time.Time
47 ShownAt time.Time
48 DismissedAt *time.Time
49}
50
51func (adviceRecord) TableName() string { return "chat_advice" }
52
53func adviceView(r adviceRecord) wire.Advice {
54 v := wire.Advice{ID: r.ID, Kind: r.Kind, Key: r.Key, State: r.State, Text: r.Text, Act: r.Act, Dismiss: r.Dismiss, Revision: r.Revision, CreatedAt: r.CreatedAt, VisibleAt: r.VisibleAt}
55 _ = json.Unmarshal([]byte(r.Subject), &v.Subject)
56 return v
57}
58
59// Money is an amount of micro-units in words: $1, $0.84, $6.20.
60func Money(micros int64, currency string) string {
61 amount := strconv.FormatInt(micros/1_000_000, 10)
62 if micros%1_000_000 != 0 {
63 amount = strconv.FormatFloat(float64(micros)/1e6, 'f', 2, 64)
64 }
65 if currency == "USD" || currency == "" {
66 return "$" + amount
67 }
68 return amount + " " + currency
69}
70
71// adviceDay is a day as advice says it: Thu 19 Nov.
72func adviceDay(t time.Time) string { return t.UTC().Format("Mon 2 Jan") }
73
74// adviceFacts are the person's facts as advice reads them: their own
75// connections, preference, open tasks and those tasks' queued steps.
76func (t *txn) adviceFacts(person string) (advice.Facts, map[string]connectionRecord, error) {
77 f := advice.Facts{}
78 conns, err := t.connections(person)
79 if err != nil {
80 return f, nil, err
81 }
82 byID := map[string]connectionRecord{}
83 for _, r := range conns {
84 if r.State == wire.ConnConnecting || r.LocalID == "" {
85 continue
86 }
87 byID[r.ID] = r
88 c := advice.Conn{ID: r.ID, Provider: r.Provider, Runner: r.RunnerID, State: r.State, Billing: r.Billing}
89 if c.Billing == "" {
90 c.Billing = wire.BillingSubscription
91 }
92 var h wire.Headroom
93 if r.Headroom != "" && json.Unmarshal([]byte(r.Headroom), &h) == nil {
94 for _, w := range h.Windows {
95 c.Windows = append(c.Windows, advice.Window{Used: w.UsedPercent / 100, ResetsAt: w.ResetsAt})
96 }
97 if len(c.Windows) == 0 && h.Utilization != nil {
98 c.Windows = append(c.Windows, advice.Window{Used: *h.Utilization, ResetsAt: h.ResetsAt})
99 }
100 }
101 if b, ok := budgetOf(r); ok {
102 c.BudgetDay, c.BudgetMonth, c.BudgetRevision, c.Currency = b.Day, b.Month, b.Revision, b.Currency
103 }
104 var sp wire.Spend
105 if r.Spend != "" && json.Unmarshal([]byte(r.Spend), &sp) == nil {
106 c.SpendDay, c.SpendMonth, c.SpendUnknown = sp.Day, sp.Month, sp.Unknown
107 } else if c.Billing == wire.BillingMetered {
108 // No spend reported yet: nothing is near.
109 c.SpendUnknown = true
110 }
111 f.Conns = append(f.Conns, c)
112 }
113 pref, err := t.preferenceOf(person)
114 if err != nil {
115 return f, nil, err
116 }
117 f.Preference = advice.Preference{Provider: pref.Provider, Until: pref.Until, Revision: pref.Revision}
118 if t.s.authority.PrimaryRunner != nil {
119 if f.Primary, err = t.s.authority.PrimaryRunner(t.db, person); err != nil {
120 f.Primary = ""
121 }
122 }
123 var tasks []taskRecord
124 if err := t.db.Where("creator = ? AND cancel_requested = ? AND (folded_into IS NULL OR folded_into = '')", person, false).Find(&tasks).Error; err != nil {
125 return f, nil, err
126 }
127 open := map[string]bool{}
128 var ids []string
129 for _, k := range tasks {
130 if wire.FinalStage(k.Stage) {
131 continue
132 }
133 open[k.ID] = true
134 ids = append(ids, k.ID)
135 f.Tasks = append(f.Tasks, advice.Task{ID: k.ID, CreatedAt: k.CreatedAt, Priority: k.Priority, By: k.DueBy, Revision: k.Revision})
136 }
137 if len(ids) == 0 {
138 return f, byID, nil
139 }
140 var steps []stepRecord
141 if err := t.db.Where("task_id IN ? AND state = ?", ids, wire.StepQueued).Order("task_id, id").Find(&steps).Error; err != nil {
142 return f, nil, err
143 }
144 for _, s := range steps {
145 st := advice.Step{Task: s.TaskID, Role: s.Specialist, Runner: s.RunnerID, Housekeeping: housekeepingAttempt(s)}
146 if h := stepHold(s); h != nil {
147 st.Hold, st.HoldResets, st.HeldSince = h.Reason, h.ResetsAt, s.HeldAt
148 }
149 f.Steps = append(f.Steps, st)
150 }
151 return f, byID, nil
152}
153
154// adviceWords are a card's fixed words: its line, its action and its
155// Not now.
156func (t *txn) adviceWords(a advice.Advice, conns map[string]connectionRecord) (text, act, dismiss string) {
157 dismiss = t.words("advice.not_now")
158 n := len(a.Tasks)
159 switch a.Kind {
160 case wire.AdviceBudgetNear:
161 name := t.connectionLabel(conns[a.Connection])
162 dismiss = t.words("advice.leave_it")
163 if a.Window == advice.BudgetDay {
164 return t.words("advice.budget_near.day", name, Money(a.Spend, a.Currency), Money(a.Budget, a.Currency)), t.words("advice.budget_near.raise_day", Money(a.Raise, a.Currency)), dismiss
165 }
166 return t.words("advice.budget_near.month", name, Money(a.Spend, a.Currency), Money(a.Budget, a.Currency)), t.words("advice.budget_near.raise_month", Money(a.Raise, a.Currency)), dismiss
167 case wire.AdvicePreferSwitch:
168 from, to, until := providerWord(a.From), providerWord(a.To), adviceDay(a.Until)
169 return t.words("advice.prefer_switch", from, until, to, to), t.words("advice.prefer_switch.act", to, until), dismiss
170 case wire.AdviceDeferTasks:
171 act = t.words("advice.defer_tasks.act_many")
172 if n == 1 {
173 act = t.words("advice.defer_tasks.act_one")
174 }
175 switch {
176 case n == 1 && a.ResetsAt != nil:
177 return t.words("advice.defer_tasks.one", adviceDay(*a.ResetsAt)), act, dismiss
178 case n == 1:
179 return t.words("advice.defer_tasks.one_no_reset"), act, dismiss
180 case a.ResetsAt != nil:
181 return t.words("advice.defer_tasks.many", n, adviceDay(*a.ResetsAt)), act, dismiss
182 }
183 return t.words("advice.defer_tasks.many_no_reset", n), act, dismiss
184 case wire.AdviceHeldLong:
185 if n == 1 {
186 return t.words("advice.held_long.one"), t.words("advice.held_long.act_one"), dismiss
187 }
188 return t.words("advice.held_long.many", n), t.words("advice.held_long.act_many"), dismiss
189 }
190 return "", "", dismiss
191}
192
193// adviceRows are every piece of advice the person was shown, oldest
194// first.
195func (t *txn) adviceRows(person string) ([]adviceRecord, error) {
196 var rows []adviceRecord
197 err := t.db.Where("person = ?", person).Order("created_at, id").Find(&rows).Error
198 return rows, err
199}
200
201// RefreshAdvice looks at the person's facts now: open advice whose facts
202// stopped holding is withdrawn silently (its words follow facts that
203// moved but still hold); with none open, the first eligible key not
204// silenced becomes the day's one new card, held until quiet hours end.
205// It runs on the housekeeping loop's minute, so on fact changes and at
206// 08:00.
207func (s *Store) RefreshAdvice(ctx context.Context, person string) error {
208 return s.tx(ctx, func(t *txn) error { return t.refreshAdvice(person) })
209}
210
211func (t *txn) refreshAdvice(person string) error {
212 if ok, err := t.activeMember(person); err != nil || !ok {
213 return err
214 }
215 now := t.hkNow()
216 f, conns, err := t.adviceFacts(person)
217 if err != nil {
218 return err
219 }
220 eligible := advice.Compute(f, now)
221 rows, err := t.adviceRows(person)
222 if err != nil {
223 return err
224 }
225 open := false
226 for i := range rows {
227 r := &rows[i]
228 if r.State != wire.AdviceOpen {
229 continue
230 }
231 a, holds := advice.Holds(eligible, r.Key)
232 if !holds {
233 if err := t.closeAdvice(r, wire.AdviceWithdrawn, ""); err != nil {
234 return err
235 }
236 continue
237 }
238 open = true
239 if err := t.followAdvice(r, a, conns); err != nil {
240 return err
241 }
242 }
243 set, err := t.hkSettings(person)
244 if err != nil {
245 return err
246 }
247 loc := t.zone(person)
248 visible := set.quiet().VisibleAt(now, loc)
249 shown := now
250 if visible != nil {
251 shown = *visible
252 }
253 past := make([]advice.Past, 0, len(rows))
254 for _, r := range rows {
255 past = append(past, advice.Past{Key: r.Key, State: r.State, Shown: r.ShownAt, DismissedAt: r.DismissedAt})
256 }
257 pick := advice.Choose(eligible, past, open, now, shown, loc)
258 if pick == nil {
259 return nil
260 }
261 return t.newAdvice(person, *pick, conns, now, visible)
262}
263
264// newAdvice writes the day's card: the advice row and its quiet card in
265// the conversation, held until visible when it is quiet hours.
266func (t *txn) newAdvice(person string, a advice.Advice, conns map[string]connectionRecord, now time.Time, visible *time.Time) error {
267 text, act, dismiss := t.adviceWords(a, conns)
268 r := adviceRecord{ID: newID("ad_"), Person: person, Key: a.Key, Kind: a.Kind, State: wire.AdviceOpen, Subject: asJSON(a.Subject), Facts: asJSON(a), Text: text, Act: act, Dismiss: dismiss, Revision: 1, CreatedAt: now, UpdatedAt: now, VisibleAt: visible, ShownAt: now}
269 if visible != nil {
270 r.ShownAt = *visible
271 }
272 opts, _ := json.Marshal([]string{wire.ChoiceAct, wire.ChoiceDismiss})
273 c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardAdvice, State: wire.CardOpen, Question: text, Options: string(opts), Revision: 1, CreatedAt: now, UpdatedAt: now, VisibleAt: visible, Held: visible != nil}
274 r.CardID = c.ID
275 if err := t.db.Create(&r).Error; err != nil {
276 return err
277 }
278 if err := t.db.Create(&c).Error; err != nil {
279 return err
280 }
281 return t.cardEvent(c)
282}
283
284// followAdvice keeps open advice in step with facts that moved but still
285// hold (a spend figure, a task's revision): its words and action are the
286// facts now, at a new revision; the card's line follows.
287func (t *txn) followAdvice(r *adviceRecord, a advice.Advice, conns map[string]connectionRecord) error {
288 facts := asJSON(a)
289 text, act, dismiss := t.adviceWords(a, conns)
290 if facts == r.Facts && text == r.Text && act == r.Act {
291 return nil
292 }
293 r.Facts, r.Text, r.Act, r.Dismiss = facts, text, act, dismiss
294 r.Revision++
295 r.UpdatedAt = t.hkNow()
296 if err := t.db.Model(&adviceRecord{}).Where("id = ?", r.ID).Select("facts", "text", "act", "dismiss", "revision", "updated_at").Updates(r).Error; err != nil {
297 return err
298 }
299 c, err := t.loadCard(r.CardID)
300 if err != nil {
301 return err
302 }
303 c.Question = text
304 c.Revision++
305 c.UpdatedAt = r.UpdatedAt
306 if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("question", "revision", "updated_at").Updates(&c).Error; err != nil {
307 return err
308 }
309 return t.cardEvent(c)
310}
311
312// closeAdvice moves advice forward to state (acted, dismissed or
313// withdrawn) and its card with it: answered with the choice, or resolved
314// (withdrawn: the conversation shows nothing more of it).
315func (t *txn) closeAdvice(r *adviceRecord, state, choice string) error {
316 if r.State != wire.AdviceOpen {
317 return ErrConflict
318 }
319 now := t.hkNow()
320 r.State, r.UpdatedAt = state, now
321 if state == wire.AdviceDismissed {
322 r.DismissedAt = &now
323 }
324 r.Revision++
325 if err := t.db.Model(&adviceRecord{}).Where("id = ? AND state = ?", r.ID, wire.AdviceOpen).Select("state", "updated_at", "dismissed_at", "revision").Updates(r).Error; err != nil {
326 return err
327 }
328 c, err := t.loadCard(r.CardID)
329 if errors.Is(err, gorm.ErrRecordNotFound) {
330 return nil
331 }
332 if err != nil {
333 return err
334 }
335 c.State, c.Choice = wire.CardAnswered, choice
336 if state == wire.AdviceWithdrawn {
337 c.State = wire.CardResolved
338 }
339 c.Revision++
340 c.UpdatedAt = now
341 if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("state", "choice", "revision", "updated_at").Updates(&c).Error; err != nil {
342 return err
343 }
344 return t.cardEvent(c)
345}
346
347// Advice is GET /api/v1/advice: the person's open advice that may show
348// now (at most one).
349func (s *Store) Advice(ctx context.Context, person string) (out wire.AdviceList, err error) {
350 out.Items = []wire.Advice{}
351 err = s.read(ctx, func(tx *gorm.DB) error {
352 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
353 return err
354 }
355 var rows []adviceRecord
356 if err := tx.Where("person = ? AND state = ?", person, wire.AdviceOpen).Order("created_at, id").Find(&rows).Error; err != nil {
357 return err
358 }
359 now := s.hkClock()
360 for _, r := range rows {
361 if r.VisibleAt != nil && r.VisibleAt.After(now) {
362 continue
363 }
364 out.Items = append(out.Items, adviceView(r))
365 }
366 return nil
367 })
368 return out, err
369}
370
371// ownAdvice is one of the person's advice rows, open and visible now, at
372// the revision they saw; otherwise ErrConflict with it as it is.
373func (t *txn) ownAdvice(person, id string, revision int64) (adviceRecord, error) {
374 var r adviceRecord
375 err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error
376 if errors.Is(err, gorm.ErrRecordNotFound) {
377 return r, ErrNotFound
378 }
379 if err != nil {
380 return r, err
381 }
382 if r.State != wire.AdviceOpen || r.Revision != revision || r.VisibleAt != nil && r.VisibleAt.After(t.hkNow()) {
383 return r, ErrConflict
384 }
385 return r, nil
386}
387
388// ActAdvice is the advice's one action (POST /api/v1/advice/{id}/act):
389// the ordinary call with the facts the person saw, revision-checked, in
390// one transaction with the advice moving to acted. Advice whose facts no
391// longer hold acts on nothing (ErrConflict; the next look withdraws it).
392func (s *Store) ActAdvice(ctx context.Context, person, id string, in wire.AdviceAction) (out wire.Advice, err error) {
393 err = s.tx(ctx, func(t *txn) error {
394 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
395 return err
396 }
397 r, err := t.ownAdvice(person, id, in.Revision)
398 if err != nil {
399 out = adviceView(r)
400 return err
401 }
402 if err := t.actAdvice(person, &r); err != nil {
403 return err
404 }
405 out = adviceView(r)
406 return nil
407 })
408 return out, err
409}
410
411func (t *txn) actAdvice(person string, r *adviceRecord) error {
412 f, _, err := t.adviceFacts(person)
413 if err != nil {
414 return err
415 }
416 if _, holds := advice.Holds(advice.Compute(f, t.hkNow()), r.Key); !holds {
417 return ErrConflict
418 }
419 var a advice.Advice
420 if err := json.Unmarshal([]byte(r.Facts), &a); err != nil {
421 return err
422 }
423 switch a.Kind {
424 case wire.AdviceBudgetNear:
425 c, err := t.ownConnection(person, a.Connection)
426 if err != nil {
427 return err
428 }
429 b, _ := budgetOf(c)
430 in := wire.SetBudget{Day: b.Day, Month: b.Month, Revision: a.BudgetRevision}
431 if a.Window == advice.BudgetDay {
432 in.Day = a.Raise
433 } else {
434 in.Month = a.Raise
435 }
436 if _, err := t.setBudget(person, a.Connection, in); err != nil {
437 return err
438 }
439 case wire.AdvicePreferSwitch:
440 until := a.Until
441 if _, err := t.setPreference(person, wire.Preferences{Provider: a.To, Until: &until, Revision: a.PreferenceRevision}); err != nil {
442 return err
443 }
444 case wire.AdviceDeferTasks, wire.AdviceHeldLong:
445 to := wire.PriorityLow
446 if a.Kind == wire.AdviceHeldLong {
447 to = wire.PriorityNormal
448 }
449 for _, k := range a.Tasks {
450 task, err := t.loadTask(k.ID)
451 if err != nil {
452 return err
453 }
454 if _, err := t.setPriority(person, k.ID, wire.SetPriority{Priority: to, By: task.DueBy, Revision: k.Revision}); err != nil {
455 return err
456 }
457 }
458 default:
459 return ErrInvalid
460 }
461 if err := t.closeAdvice(r, wire.AdviceActed, wire.ChoiceAct); err != nil {
462 return err
463 }
464 // The ordinary call wrote its own audit; this one says advice made it.
465 return t.audit(person, "advice.act", "source=advice id="+r.ID+" key="+r.Key)
466}
467
468// DismissAdvice is Not now (or Leave it): POST /api/v1/advice/{id}/dismiss.
469// The key is silenced for 14 days, and for 60 after a second Not now.
470func (s *Store) DismissAdvice(ctx context.Context, person, id string, in wire.AdviceAction) (out wire.Advice, err error) {
471 err = s.tx(ctx, func(t *txn) error {
472 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
473 return err
474 }
475 r, err := t.ownAdvice(person, id, in.Revision)
476 if err != nil {
477 out = adviceView(r)
478 return err
479 }
480 if err := t.dismissAdvice(person, &r); err != nil {
481 return err
482 }
483 out = adviceView(r)
484 return nil
485 })
486 return out, err
487}
488
489func (t *txn) dismissAdvice(person string, r *adviceRecord) error {
490 if err := t.closeAdvice(r, wire.AdviceDismissed, wire.ChoiceDismiss); err != nil {
491 return err
492 }
493 return t.audit(person, "advice.dismiss", "source=advice id="+r.ID+" key="+r.Key)
494}
495
496// answerAdvice is the conversation card's answer: its action or Not now,
497// for the advice the card shows.
498func (t *txn) answerAdvice(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
499 current := func() wire.Card {
500 v, _ := t.cardView(c)
501 return v
502 }
503 if c.Person != person {
504 return wire.Card{}, wire.Card{}, ErrNotFound
505 }
506 if c.State != wire.CardOpen || c.Revision != in.Revision || !slices.Contains([]string{wire.ChoiceAct, wire.ChoiceDismiss}, in.Choice) {
507 return wire.Card{}, current(), ErrCardConflict
508 }
509 var r adviceRecord
510 if err := t.db.Where("card_id = ? AND person = ?", c.ID, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
511 return wire.Card{}, wire.Card{}, ErrNotFound
512 } else if err != nil {
513 return wire.Card{}, wire.Card{}, err
514 }
515 if r, err := t.ownAdvice(person, r.ID, r.Revision); err != nil {
516 if errors.Is(err, ErrConflict) {
517 return wire.Card{}, current(), ErrCardConflict
518 }
519 return wire.Card{}, wire.Card{}, err
520 } else if in.Choice == wire.ChoiceAct {
521 err = t.actAdvice(person, &r)
522 if errors.Is(err, ErrConflict) {
523 return wire.Card{}, current(), ErrCardConflict
524 }
525 if err != nil {
526 return wire.Card{}, wire.Card{}, err
527 }
528 } else if err := t.dismissAdvice(person, &r); err != nil {
529 return wire.Card{}, wire.Card{}, err
530 }
531 c, err := t.loadCard(c.ID)
532 if err != nil {
533 return wire.Card{}, wire.Card{}, err
534 }
535 v, err := t.cardView(c)
536 return v, wire.Card{}, err
537}
538
539// cardAdvice is an advice card's advice, for its view.
540func (t *txn) cardAdvice(c cardRecord) (*wire.Advice, error) {
541 var r adviceRecord
542 err := t.db.Where("card_id = ?", c.ID).First(&r).Error
543 if errors.Is(err, gorm.ErrRecordNotFound) {
544 return nil, nil
545 }
546 if err != nil {
547 return nil, err
548 }
549 v := adviceView(r)
550 return &v, nil
551}
552