| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "time" |
| 7 | |
| 8 | "gorm.io/gorm" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo/housekeeping" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // The conversation page's daily roll-up (Paul, 2026-11-12: "at the end |
| 15 | // of the day, the day's conversation gets rolled up and summarised into |
| 16 | // a box"). These are reads only: the transcript, the coordinator's |
| 17 | // context and its notebook are what they were. What a day held is read |
| 18 | // from records (messages, tasks, answered cards), never from a model. |
| 19 | |
| 20 | // Now is the store's clock (tests move it). |
| 21 | func (s *Store) Now() time.Time { return s.now() } |
| 22 | |
| 23 | // Zone is the person's time zone, the one their days end in and the |
| 24 | // housekeeping loop's (zone.go): what their browser, device or Base last |
| 25 | // said, Europe/Dublin until one has. |
| 26 | func (s *Store) Zone(person string) *time.Location { return (&txn{s: s}).zone(person) } |
| 27 | |
| 28 | // DayStart is the start of at's day in loc, in UTC. |
| 29 | func DayStart(at time.Time, loc *time.Location) time.Time { return housekeeping.DayStart(at, loc) } |
| 30 | |
| 31 | // NextDay is the start of the day after the one starting at start. |
| 32 | func NextDay(start time.Time, loc *time.Location) time.Time { |
| 33 | l := start.In(loc) |
| 34 | return time.Date(l.Year(), l.Month(), l.Day()+1, 0, 0, 0, 0, loc).UTC() |
| 35 | } |
| 36 | |
| 37 | // maxDayScan bounds how many messages EarlierDays reads to find days. |
| 38 | const maxDayScan = 20000 |
| 39 | |
| 40 | // EarlierDays is the start of each of the person's latest n days before |
| 41 | // before that have a message, newest first. |
| 42 | func (s *Store) EarlierDays(ctx context.Context, person string, before time.Time, n int) (out []time.Time, err error) { |
| 43 | loc := s.Zone(person) |
| 44 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 45 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | cut, scanned := before, 0 |
| 49 | for len(out) < n && scanned < maxDayScan { |
| 50 | var at []time.Time |
| 51 | if err := tx.Model(&messageRecord{}).Where("person = ? AND created_at < ? AND "+personLane, person, cut).Order("seq DESC").Limit(500).Pluck("created_at", &at).Error; err != nil { |
| 52 | return err |
| 53 | } |
| 54 | for _, t := range at { |
| 55 | if d := DayStart(t, loc); len(out) == 0 || d.Before(out[len(out)-1]) { |
| 56 | if len(out) == n { |
| 57 | break |
| 58 | } |
| 59 | out = append(out, d) |
| 60 | } |
| 61 | } |
| 62 | if len(at) < 500 || len(out) == n { |
| 63 | return nil |
| 64 | } |
| 65 | // The next page starts before the day already found: one query |
| 66 | // per day, not one per message. |
| 67 | cut, scanned = out[len(out)-1], scanned+len(at) |
| 68 | } |
| 69 | return nil |
| 70 | }) |
| 71 | return out, err |
| 72 | } |
| 73 | |
| 74 | // MessageAt is when one of the person's messages was written. |
| 75 | func (s *Store) MessageAt(ctx context.Context, person, id string) (at time.Time, err error) { |
| 76 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 77 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 78 | return err |
| 79 | } |
| 80 | var m messageRecord |
| 81 | if err := tx.Select("created_at").Where("id = ? AND person = ? AND "+personLane, id, person).First(&m).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 82 | return ErrNotFound |
| 83 | } else if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | at = m.CreatedAt |
| 87 | return nil |
| 88 | }) |
| 89 | return at, err |
| 90 | } |
| 91 | |
| 92 | // Window is a stretch of the person's conversation as the page shows |
| 93 | // it: the messages written in it (the newest limit), the cards that |
| 94 | // stand among them, and the tasks those cards name. |
| 95 | type Window struct { |
| 96 | Messages []wire.Message |
| 97 | Cards []wire.Card |
| 98 | Tasks []wire.Task |
| 99 | } |
| 100 | |
| 101 | // Placed is where a card stands in the conversation: a card a turn |
| 102 | // produced stands with that turn's last message; any other at the time |
| 103 | // it showed (after quiet hours). |
| 104 | func placed(c cardRecord, lastOfTurn map[string]time.Time) (time.Time, bool) { |
| 105 | if c.TurnID != "" { |
| 106 | at, ok := lastOfTurn[c.TurnID] |
| 107 | return at, ok |
| 108 | } |
| 109 | if c.VisibleAt != nil && c.VisibleAt.After(c.CreatedAt) { |
| 110 | return *c.VisibleAt, true |
| 111 | } |
| 112 | return c.CreatedAt, true |
| 113 | } |
| 114 | |
| 115 | func within(at, from, to time.Time) bool { |
| 116 | return !at.Before(from) && (to.IsZero() || at.Before(to)) |
| 117 | } |
| 118 | |
| 119 | // Window reads [from, to) of the person's conversation; a zero to is |
| 120 | // open-ended (today). |
| 121 | func (s *Store) Window(ctx context.Context, person string, from, to time.Time, limit int) (out Window, err error) { |
| 122 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 123 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 124 | return err |
| 125 | } |
| 126 | q := tx.Where("person = ? AND created_at >= ? AND "+personLane, person, from) |
| 127 | if !to.IsZero() { |
| 128 | q = q.Where("created_at < ?", to) |
| 129 | } |
| 130 | var rows []messageRecord |
| 131 | if err := q.Order("seq DESC").Limit(limit).Find(&rows).Error; err != nil { |
| 132 | return err |
| 133 | } |
| 134 | out.Messages = make([]wire.Message, 0, len(rows)) |
| 135 | var turns []string |
| 136 | for i := len(rows) - 1; i >= 0; i-- { |
| 137 | out.Messages = append(out.Messages, messageView(rows[i])) |
| 138 | if rows[i].TurnID != "" { |
| 139 | turns = append(turns, rows[i].TurnID) |
| 140 | } |
| 141 | } |
| 142 | if err := withFiles(tx, out.Messages); err != nil { |
| 143 | return err |
| 144 | } |
| 145 | t := &txn{s: s, db: tx} |
| 146 | last, err := t.lastOfTurns(person, turns) |
| 147 | if err != nil { |
| 148 | return err |
| 149 | } |
| 150 | // Cards with no turn showed at most a night after they were made. |
| 151 | cq := tx.Where("person = ? AND (held IS NULL OR held = ?) AND "+personLane, person, false).Where(tx.Where("turn_id IN ?", turns).Or("turn_id = ? AND created_at >= ?", "", from.Add(-24*time.Hour))) |
| 152 | if !to.IsZero() { |
| 153 | cq = cq.Where("created_at < ?", to) |
| 154 | } |
| 155 | var cards []cardRecord |
| 156 | if err := cq.Order("created_at, id").Find(&cards).Error; err != nil { |
| 157 | return err |
| 158 | } |
| 159 | names := map[string]bool{} |
| 160 | for _, c := range cards { |
| 161 | if at, ok := placed(c, last); !ok || !within(at, from, to) { |
| 162 | continue |
| 163 | } |
| 164 | v, err := t.cardView(c) |
| 165 | if err != nil { |
| 166 | return err |
| 167 | } |
| 168 | out.Cards = append(out.Cards, v) |
| 169 | if c.TaskID != "" { |
| 170 | names[c.TaskID] = true |
| 171 | } |
| 172 | } |
| 173 | out.Tasks, err = t.tasksNamed(names) |
| 174 | return err |
| 175 | }) |
| 176 | return out, err |
| 177 | } |
| 178 | |
| 179 | func (t *txn) lastOfTurns(person string, turns []string) (map[string]time.Time, error) { |
| 180 | out := map[string]time.Time{} |
| 181 | if len(turns) == 0 { |
| 182 | return out, nil |
| 183 | } |
| 184 | var rows []messageRecord |
| 185 | if err := t.db.Select("turn_id", "created_at").Where("person = ? AND turn_id IN ?", person, turns).Find(&rows).Error; err != nil { |
| 186 | return nil, err |
| 187 | } |
| 188 | for _, m := range rows { |
| 189 | if m.CreatedAt.After(out[m.TurnID]) { |
| 190 | out[m.TurnID] = m.CreatedAt |
| 191 | } |
| 192 | } |
| 193 | return out, nil |
| 194 | } |
| 195 | |
| 196 | func (t *txn) tasksNamed(ids map[string]bool) ([]wire.Task, error) { |
| 197 | if len(ids) == 0 { |
| 198 | return nil, nil |
| 199 | } |
| 200 | list := make([]string, 0, len(ids)) |
| 201 | for id := range ids { |
| 202 | list = append(list, id) |
| 203 | } |
| 204 | var rows []taskRecord |
| 205 | if err := t.db.Where("id IN ?", list).Order("created_at, id").Find(&rows).Error; err != nil { |
| 206 | return nil, err |
| 207 | } |
| 208 | out := make([]wire.Task, 0, len(rows)) |
| 209 | for _, k := range rows { |
| 210 | v, err := t.taskView(k) |
| 211 | if err != nil { |
| 212 | return nil, err |
| 213 | } |
| 214 | out = append(out, v) |
| 215 | } |
| 216 | return out, nil |
| 217 | } |
| 218 | |
| 219 | // Underway are the stages of a task that is being worked on: its |
| 220 | // creator sees it until it ends, whatever day it started. |
| 221 | var Underway = []string{wire.StageInProgress, wire.StageInReview, wire.StageReadyToMerge, wire.StageMerging} |
| 222 | |
| 223 | // StillOpen is what stands in the person's conversation before before |
| 224 | // and may need them: cards still asking (a question, a decision, access, |
| 225 | // a home to confirm) and the cards of their tasks still underway, with |
| 226 | // the tasks those cards name. The page shows these whatever day they |
| 227 | // are from; whether a card still asks is the page's reading of it. |
| 228 | func (s *Store) StillOpen(ctx context.Context, person string, before time.Time) (out Window, err error) { |
| 229 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 230 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 231 | return err |
| 232 | } |
| 233 | var cards []cardRecord |
| 234 | if err := tx.Where("person = ? AND (held IS NULL OR held = ?) AND "+personLane, person, false). |
| 235 | Where(tx.Where("kind IN ? AND state = ?", []string{wire.CardQuestion, wire.CardAccess, wire.CardMerge, wire.CardDirection, wire.CardMergeShips, wire.CardMergePolicy, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardPublish, wire.CardPlace, wire.CardMakerRemoved}, wire.CardOpen). |
| 236 | Or("kind = ? AND state = ?", wire.CardHome, wire.CardHomeAsk). |
| 237 | Or("kind = ? AND task_id IN (SELECT id FROM chat_tasks WHERE creator = ? AND stage IN ?)", wire.CardTask, person, Underway)). |
| 238 | Order("created_at, id").Find(&cards).Error; err != nil { |
| 239 | return err |
| 240 | } |
| 241 | var turns []string |
| 242 | for _, c := range cards { |
| 243 | if c.TurnID != "" { |
| 244 | turns = append(turns, c.TurnID) |
| 245 | } |
| 246 | } |
| 247 | t := &txn{s: s, db: tx} |
| 248 | last, err := t.lastOfTurns(person, turns) |
| 249 | if err != nil { |
| 250 | return err |
| 251 | } |
| 252 | names := map[string]bool{} |
| 253 | for _, c := range cards { |
| 254 | at, ok := placed(c, last) |
| 255 | if !ok { |
| 256 | // A turn with no message: never shown in the feed, so it |
| 257 | // stands with the earlier days rather than nowhere. |
| 258 | at = c.CreatedAt |
| 259 | } |
| 260 | if !at.Before(before) { |
| 261 | continue |
| 262 | } |
| 263 | v, err := t.cardView(c) |
| 264 | if err != nil { |
| 265 | return err |
| 266 | } |
| 267 | out.Cards = append(out.Cards, v) |
| 268 | if c.TaskID != "" { |
| 269 | names[c.TaskID] = true |
| 270 | } |
| 271 | } |
| 272 | out.Tasks, err = t.tasksNamed(names) |
| 273 | return err |
| 274 | }) |
| 275 | return out, err |
| 276 | } |
| 277 | |
| 278 | // DayTask is a task as a day's summary names it. |
| 279 | type DayTask struct { |
| 280 | ID, Title, Stage string |
| 281 | CreatedAt time.Time |
| 282 | DoneAt, MergedAt *time.Time |
| 283 | } |
| 284 | |
| 285 | // Decision is a card the person answered, and when. |
| 286 | type Decision struct { |
| 287 | Card wire.Card |
| 288 | At time.Time |
| 289 | // Task is the task the card asked about, when it names one. |
| 290 | Task *DayTask |
| 291 | } |
| 292 | |
| 293 | // Rollup is what [from, to) of the person's conversation held, for its |
| 294 | // days' summaries: when each message was written, the person's tasks |
| 295 | // started, finished or merged then, and the decisions they made. |
| 296 | type Rollup struct { |
| 297 | Messages []time.Time |
| 298 | Tasks []DayTask |
| 299 | Decisions []Decision |
| 300 | } |
| 301 | |
| 302 | // decisionKinds are the cards whose answer is a decision of the |
| 303 | // person's: merge or wait, a direction, a policy question, a question, |
| 304 | // adding a specialist, the pages Research reads and the addresses it |
| 305 | // reads from, publishing a merged website, and handing a task to |
| 306 | // Engineering once its maker was removed. |
| 307 | var decisionKinds = []string{wire.CardMerge, wire.CardDirection, wire.CardMergeShips, wire.CardMergePolicy, wire.CardQuestion, wire.CardSpecialist, wire.CardResearchSources, wire.CardResearchInventory, wire.CardPublish, wire.CardPlace, wire.CardMakerRemoved} |
| 308 | |
| 309 | // Rollup reads [from, to) for the day boxes. |
| 310 | func (s *Store) Rollup(ctx context.Context, person string, from, to time.Time) (out Rollup, err error) { |
| 311 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 312 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 313 | return err |
| 314 | } |
| 315 | if err := tx.Model(&messageRecord{}).Where("person = ? AND created_at >= ? AND created_at < ? AND "+personLane, person, from, to).Order("seq").Pluck("created_at", &out.Messages).Error; err != nil { |
| 316 | return err |
| 317 | } |
| 318 | var tasks []taskRecord |
| 319 | if err := tx.Select("id", "title", "stage", "created_at", "done_at", "merged_at").Where("creator = ?", person). |
| 320 | Where(tx.Where("created_at >= ? AND created_at < ?", from, to).Or("done_at >= ? AND done_at < ?", from, to).Or("merged_at >= ? AND merged_at < ?", from, to)). |
| 321 | Order("created_at, id").Find(&tasks).Error; err != nil { |
| 322 | return err |
| 323 | } |
| 324 | for _, k := range tasks { |
| 325 | out.Tasks = append(out.Tasks, dayTask(k)) |
| 326 | } |
| 327 | // An answer is the person's message with the card's choice; a card |
| 328 | // answered without one (no message) counts when it changed. |
| 329 | var cards []cardRecord |
| 330 | if err := tx.Where("person = ? AND state = ? AND kind IN ? AND updated_at >= ? AND "+personLane, person, wire.CardAnswered, decisionKinds, from).Order("created_at, id").Find(&cards).Error; err != nil { |
| 331 | return err |
| 332 | } |
| 333 | t := &txn{s: s, db: tx} |
| 334 | named := map[string]*DayTask{} |
| 335 | for _, c := range cards { |
| 336 | at := c.UpdatedAt |
| 337 | if c.AnswerMessage != "" { |
| 338 | var m messageRecord |
| 339 | if err := tx.Select("created_at").Where("id = ? AND person = ?", c.AnswerMessage, person).First(&m).Error; err == nil { |
| 340 | at = m.CreatedAt |
| 341 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 342 | return err |
| 343 | } |
| 344 | } |
| 345 | if !within(at, from, to) { |
| 346 | continue |
| 347 | } |
| 348 | v, err := t.cardView(c) |
| 349 | if err != nil { |
| 350 | return err |
| 351 | } |
| 352 | d := Decision{Card: v, At: at} |
| 353 | if c.TaskID != "" { |
| 354 | if named[c.TaskID] == nil { |
| 355 | var k taskRecord |
| 356 | if err := tx.Select("id", "title", "stage", "created_at", "done_at", "merged_at").Where("id = ?", c.TaskID).First(&k).Error; err == nil { |
| 357 | dt := dayTask(k) |
| 358 | named[c.TaskID] = &dt |
| 359 | } else if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 360 | return err |
| 361 | } |
| 362 | } |
| 363 | d.Task = named[c.TaskID] |
| 364 | } |
| 365 | out.Decisions = append(out.Decisions, d) |
| 366 | } |
| 367 | return nil |
| 368 | }) |
| 369 | return out, err |
| 370 | } |
| 371 | |
| 372 | func dayTask(k taskRecord) DayTask { |
| 373 | return DayTask{ID: k.ID, Title: k.Title, Stage: k.Stage, CreatedAt: k.CreatedAt, DoneAt: k.DoneAt, MergedAt: k.MergedAt} |
| 374 | } |
| 375 | |