| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "time" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/wire" |
| 9 | "gorm.io/gorm" |
| 10 | "gorm.io/gorm/clause" |
| 11 | ) |
| 12 | |
| 13 | type cardVisibility struct { |
| 14 | Person string `gorm:"primaryKey"` |
| 15 | CardID string `gorm:"primaryKey"` |
| 16 | Aside bool |
| 17 | UpdatedAt time.Time |
| 18 | } |
| 19 | |
| 20 | func (cardVisibility) TableName() string { return "chat_card_visibility" } |
| 21 | |
| 22 | type cardThreadRecord struct { |
| 23 | MessageID string `gorm:"index:chat_card_thread_message"` |
| 24 | ID string `gorm:"primaryKey"` |
| 25 | CardID string `gorm:"index:chat_card_thread_card"` |
| 26 | Person string |
| 27 | TurnID string |
| 28 | StepID string |
| 29 | Text string |
| 30 | CreatedAt time.Time |
| 31 | } |
| 32 | |
| 33 | func (cardThreadRecord) TableName() string { return "chat_card_threads" } |
| 34 | |
| 35 | // CardPresentation is browser presentation only. Visibility is separate |
| 36 | // from the decision and never changes a card's revision or authority. |
| 37 | type CardContext struct { |
| 38 | ProjectID, ProjectTitle, TaskTitle string |
| 39 | } |
| 40 | |
| 41 | type CardPresentation struct { |
| 42 | Context CardContext |
| 43 | OwnMessages []string |
| 44 | Activity []wire.ActivityLine |
| 45 | ThreadState string |
| 46 | StepID string |
| 47 | Coverage CardCopyCoverage |
| 48 | Turns []string |
| 49 | Aside bool |
| 50 | Thread []CardThreadTurn |
| 51 | Waiting bool |
| 52 | TurnID string |
| 53 | } |
| 54 | type CardThreadTurn struct { |
| 55 | Own bool |
| 56 | Text string |
| 57 | At time.Time |
| 58 | } |
| 59 | |
| 60 | func (s *Store) SetCardAside(ctx context.Context, person, id string, revision int64, aside bool) error { |
| 61 | return s.tx(ctx, func(t *txn) error { |
| 62 | _, err := t.setCardAside(person, id, revision, aside) |
| 63 | return err |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | // SetCardVisibility is POST /api/v1/cards/{id}/visibility: SetCardAside |
| 68 | // for a device, answering the card as the person sees it now, and on a |
| 69 | // stale revision ErrCardConflict with the card as it is. |
| 70 | func (s *Store) SetCardVisibility(ctx context.Context, person, id string, in wire.SetCardVisibility) (out wire.Card, err error) { |
| 71 | var c cardRecord |
| 72 | err = s.tx(ctx, func(t *txn) error { |
| 73 | var err error |
| 74 | c, err = t.setCardAside(person, id, in.Revision, in.Aside) |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | out, err = t.cardView(c) |
| 79 | return err |
| 80 | }) |
| 81 | if errors.Is(err, ErrCardConflict) && c.ID != "" { |
| 82 | if rerr := s.read(ctx, func(tx *gorm.DB) error { |
| 83 | var e error |
| 84 | out, e = (&txn{s: s, ctx: ctx, db: tx}).cardView(c) |
| 85 | return e |
| 86 | }); rerr != nil { |
| 87 | return out, rerr |
| 88 | } |
| 89 | } |
| 90 | return out, err |
| 91 | } |
| 92 | |
| 93 | // setCardAside sets the card aside (or back) for its person: the card, and |
| 94 | // ErrCardConflict with it when its revision moved or it no longer waits. |
| 95 | func (t *txn) setCardAside(person, id string, revision int64, aside bool) (c cardRecord, err error) { |
| 96 | s := t.s |
| 97 | ctx := t.ctx |
| 98 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 99 | return c, err |
| 100 | } |
| 101 | if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 102 | return c, ErrNotFound |
| 103 | } else if err != nil { |
| 104 | return c, err |
| 105 | } |
| 106 | return c, func() error { |
| 107 | if c.Revision != revision { |
| 108 | return ErrCardConflict |
| 109 | } |
| 110 | if c.State != wire.CardOpen && c.State != wire.CardHomeAsk && c.Kind != wire.CardTask { |
| 111 | return ErrCardConflict |
| 112 | } |
| 113 | if c.Kind == wire.CardTask { |
| 114 | k, err := t.loadTask(c.TaskID) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 119 | return ErrCardConflict |
| 120 | } |
| 121 | v, err := t.taskView(k) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | if !v.CopyHold && !v.CopyCanSkip { |
| 126 | return ErrCardConflict |
| 127 | } |
| 128 | } |
| 129 | v := cardVisibility{Person: person, CardID: id, Aside: aside, UpdatedAt: t.now()} |
| 130 | if err := t.db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "person"}, {Name: "card_id"}}, DoUpdates: clause.AssignmentColumns([]string{"aside", "updated_at"})}).Create(&v).Error; err != nil { |
| 131 | return err |
| 132 | } |
| 133 | if err := s.authority.Audit(t.db, person, "card.visibility", id); err != nil { |
| 134 | return err |
| 135 | } |
| 136 | // Setting aside is no news to the person's devices: no push rule. |
| 137 | return t.cardEventPush(c, false) |
| 138 | }() |
| 139 | } |
| 140 | |
| 141 | func (s *Store) CardPresentations(ctx context.Context, person string, ids []string) (out map[string]CardPresentation, err error) { |
| 142 | out = map[string]CardPresentation{} |
| 143 | if len(ids) == 0 { |
| 144 | return out, nil |
| 145 | } |
| 146 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 147 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 148 | return err |
| 149 | } |
| 150 | var cards []cardRecord |
| 151 | if err := tx.Where("person = ? AND id IN ? AND "+coordinatorRole, person, ids).Find(&cards).Error; err != nil { |
| 152 | return err |
| 153 | } |
| 154 | contexts, err := cardContexts(tx, person, cards) |
| 155 | if err != nil { |
| 156 | return err |
| 157 | } |
| 158 | var visibility []cardVisibility |
| 159 | if err := tx.Where("person = ? AND card_id IN ?", person, ids).Find(&visibility).Error; err != nil { |
| 160 | return err |
| 161 | } |
| 162 | aside := map[string]bool{} |
| 163 | for _, v := range visibility { |
| 164 | aside[v.CardID] = v.Aside |
| 165 | } |
| 166 | var records []cardThreadRecord |
| 167 | if err := tx.Where("person = ? AND card_id IN ?", person, ids).Order("created_at, id").Find(&records).Error; err != nil { |
| 168 | return err |
| 169 | } |
| 170 | links := map[string][]cardThreadRecord{} |
| 171 | var answerIDs, turnIDs, stepIDs []string |
| 172 | for _, c := range cards { |
| 173 | if c.Kind == wire.CardQuestion && c.AnswerMessage != "" { |
| 174 | answerIDs = append(answerIDs, c.AnswerMessage) |
| 175 | } |
| 176 | } |
| 177 | var answers []messageRecord |
| 178 | if len(answerIDs) > 0 { |
| 179 | if err := tx.Where("person = ? AND id IN ?", person, answerIDs).Find(&answers).Error; err != nil { |
| 180 | return err |
| 181 | } |
| 182 | } |
| 183 | answerByID := map[string]messageRecord{} |
| 184 | for _, m := range answers { |
| 185 | answerByID[m.ID] = m |
| 186 | } |
| 187 | for _, c := range cards { |
| 188 | if m, ok := answerByID[c.AnswerMessage]; ok { |
| 189 | links[c.ID] = append(links[c.ID], cardThreadRecord{TurnID: m.TurnID, MessageID: m.ID}) |
| 190 | } |
| 191 | } |
| 192 | for _, link := range records { |
| 193 | links[link.CardID] = append(links[link.CardID], link) |
| 194 | } |
| 195 | for _, ls := range links { |
| 196 | for _, l := range ls { |
| 197 | if l.TurnID != "" { |
| 198 | turnIDs = append(turnIDs, l.TurnID) |
| 199 | } else if l.StepID != "" { |
| 200 | stepIDs = append(stepIDs, l.StepID) |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | var turns []turnRecord |
| 205 | var messages []messageRecord |
| 206 | if len(turnIDs) > 0 { |
| 207 | if err := tx.Where("person = ? AND id IN ?", person, turnIDs).Find(&turns).Error; err != nil { |
| 208 | return err |
| 209 | } |
| 210 | if err := tx.Where("person = ? AND turn_id IN ?", person, turnIDs).Order("seq").Find(&messages).Error; err != nil { |
| 211 | return err |
| 212 | } |
| 213 | } |
| 214 | turnByID := map[string]turnRecord{} |
| 215 | for _, turn := range turns { |
| 216 | turnByID[turn.ID] = turn |
| 217 | } |
| 218 | messagesByTurn := map[string][]messageRecord{} |
| 219 | for _, m := range messages { |
| 220 | messagesByTurn[m.TurnID] = append(messagesByTurn[m.TurnID], m) |
| 221 | } |
| 222 | var steps []stepRecord |
| 223 | if len(stepIDs) > 0 { |
| 224 | if err := tx.Where("person = ? AND id IN ?", person, stepIDs).Find(&steps).Error; err != nil { |
| 225 | return err |
| 226 | } |
| 227 | } |
| 228 | stepByID := map[string]stepRecord{} |
| 229 | for _, step := range steps { |
| 230 | stepByID[step.ID] = step |
| 231 | } |
| 232 | for _, c := range cards { |
| 233 | p := CardPresentation{Aside: aside[c.ID], Context: contexts[c.ID]} |
| 234 | if c.Kind == wire.CardTask { |
| 235 | var err error |
| 236 | p.Coverage, err = cardCopyCoverage(tx, c.TaskID) |
| 237 | if err != nil { |
| 238 | return err |
| 239 | } |
| 240 | } |
| 241 | for _, link := range links[c.ID] { |
| 242 | // Access resumes the main conversation. Hide only its generated |
| 243 | // prompt, never the coordinator's thinking or eventual reply. |
| 244 | continuation := false |
| 245 | if c.Kind == wire.CardAccess && c.Access != "" { |
| 246 | for _, m := range messagesByTurn[link.TurnID] { |
| 247 | if m.ID == link.MessageID && m.IdempotencyKey == "access-approved:"+c.ID { |
| 248 | p.OwnMessages = append(p.OwnMessages, m.ID) |
| 249 | continuation = true |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | if continuation { |
| 254 | continue |
| 255 | } |
| 256 | |
| 257 | // A retained reply can outlive its execution record. Keep its |
| 258 | // text and clear pending state when that record is absent. |
| 259 | p.Waiting, p.TurnID, p.StepID, p.ThreadState = false, "", "", "" |
| 260 | p.Activity = nil |
| 261 | if link.TurnID != "" { |
| 262 | p.Turns = append(p.Turns, link.TurnID) |
| 263 | for _, m := range messagesByTurn[link.TurnID] { |
| 264 | if m.Role == wire.RolePerson && m.ID != link.MessageID { |
| 265 | continue |
| 266 | } |
| 267 | if m.Role == wire.RolePerson { |
| 268 | p.OwnMessages = append(p.OwnMessages, m.ID) |
| 269 | } |
| 270 | p.Thread = append(p.Thread, CardThreadTurn{Own: m.Role == wire.RolePerson, Text: m.Text, At: m.CreatedAt}) |
| 271 | } |
| 272 | if turn, ok := turnByID[link.TurnID]; ok { |
| 273 | p.Waiting = turn.State == wire.TurnQueued || turn.State == wire.TurnRunning || turn.State == wire.TurnWaiting |
| 274 | p.TurnID, p.ThreadState = turn.ID, turn.State |
| 275 | } |
| 276 | } else { |
| 277 | p.Thread = append(p.Thread, CardThreadTurn{Own: true, Text: link.Text, At: link.CreatedAt}) |
| 278 | if step, ok := stepByID[link.StepID]; ok { |
| 279 | p.StepID = step.ID |
| 280 | p.Waiting = step.State == wire.StepQueued || step.State == wire.StepRunning |
| 281 | p.Activity = decodeActivity(step.Activity) |
| 282 | if step.Summary != "" { |
| 283 | p.Thread = append(p.Thread, CardThreadTurn{Text: step.Summary, At: step.UpdatedAt}) |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | out[c.ID] = p |
| 289 | } |
| 290 | return nil |
| 291 | }) |
| 292 | return |
| 293 | } |
| 294 | |
| 295 | // OpenStandaloneCards keeps questions without a task reachable in Needs |
| 296 | // you, and open place and publish cards: their task is done, so no |
| 297 | // task's line stands for them there. |
| 298 | type StandaloneCard struct { |
| 299 | wire.Card |
| 300 | Job string |
| 301 | } |
| 302 | |
| 303 | func (s *Store) OpenStandaloneCards(ctx context.Context, person string) (out []StandaloneCard, err error) { |
| 304 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 305 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 306 | return err |
| 307 | } |
| 308 | var cs []cardRecord |
| 309 | if err := tx.Where("person = ? AND (coalesce(task_id, '') = '' OR kind IN ?) AND state IN ? AND "+coordinatorRole, person, []string{wire.CardPlace, wire.CardPublish}, []string{wire.CardOpen, wire.CardHomeAsk}).Order("created_at, id").Find(&cs).Error; err != nil { |
| 310 | return err |
| 311 | } |
| 312 | t := &txn{s: s, db: tx, ctx: ctx} |
| 313 | for _, c := range cs { |
| 314 | v, err := t.cardView(c) |
| 315 | if err != nil { |
| 316 | return err |
| 317 | } |
| 318 | job, _ := wire.JobOf(c.Lane) |
| 319 | out = append(out, StandaloneCard{Card: v, Job: job}) |
| 320 | } |
| 321 | return nil |
| 322 | }) |
| 323 | return |
| 324 | } |
| 325 | |
| 326 | // ReplyCard continues an answered question or discusses a task report in its private lane. |
| 327 | // The original decision remains answered; the new message owns its turn. |
| 328 | func (s *Store) ReplyCard(ctx context.Context, person, id, key, text string) error { |
| 329 | text, ok := cleanText(text, 2000) |
| 330 | if !ok || !validKey(key) { |
| 331 | return ErrInvalid |
| 332 | } |
| 333 | return s.tx(ctx, func(t *txn) error { |
| 334 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 335 | return err |
| 336 | } |
| 337 | var c cardRecord |
| 338 | if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 339 | return ErrNotFound |
| 340 | } else if err != nil { |
| 341 | return err |
| 342 | } |
| 343 | if c.Kind != wire.CardTask && (c.Kind != wire.CardQuestion || c.State != wire.CardAnswered) { |
| 344 | return ErrCardConflict |
| 345 | } |
| 346 | if c.Kind == wire.CardTask { |
| 347 | if _, err := t.loadTask(c.TaskID); err != nil { |
| 348 | return err |
| 349 | } |
| 350 | } |
| 351 | if _, job := wire.JobOf(c.Lane); job { |
| 352 | if err := t.jobRunner(person); err != nil { |
| 353 | return err |
| 354 | } |
| 355 | } |
| 356 | _, _, err := t.sendOrigin(c.Lane, person, "card:reply:"+c.ID+":"+key, text, nil, originComposer, func(m messageRecord) error { |
| 357 | if err := t.db.Create(&cardThreadRecord{ID: newID("ct_"), CardID: c.ID, Person: person, TurnID: m.TurnID, MessageID: m.ID, CreatedAt: t.now()}).Error; err != nil { |
| 358 | return err |
| 359 | } |
| 360 | if err := s.authority.Audit(t.db, person, "card.reply", c.ID); err != nil { |
| 361 | return err |
| 362 | } |
| 363 | return t.followAnswer(c, m) |
| 364 | }) |
| 365 | return err |
| 366 | }) |
| 367 | } |
| 368 | |
| 369 | // StopConversationTurn stops a verified person's own or job Coordinator, |
| 370 | // with its audit and cancellation command in the same transaction. |
| 371 | func (s *Store) StopConversationTurn(ctx context.Context, person, id string) error { |
| 372 | return s.tx(ctx, func(t *txn) error { |
| 373 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 374 | return err |
| 375 | } |
| 376 | var turn turnRecord |
| 377 | if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&turn).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 378 | return ErrNotFound |
| 379 | } else if err != nil { |
| 380 | return err |
| 381 | } |
| 382 | if wire.Terminal(turn.State) { |
| 383 | return ErrTerminal |
| 384 | } |
| 385 | if err := s.authority.Audit(t.db, person, "turn.cancel", id); err != nil { |
| 386 | return err |
| 387 | } |
| 388 | return t.cancelTurn(turn) |
| 389 | }) |
| 390 | } |
| 391 | |
| 392 | // ResolvedAsideCards keeps today's resolution of an older stub in place |
| 393 | // even when the original question belongs to a collapsed earlier day. |
| 394 | func (s *Store) ResolvedAsideCards(ctx context.Context, person, lane string, since time.Time) (out []wire.Card, err error) { |
| 395 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 396 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 397 | return err |
| 398 | } |
| 399 | var cs []cardRecord |
| 400 | if err := tx.Where("person = ? AND coalesce(lane, '') = ? AND updated_at >= ? AND state IN ? AND EXISTS (SELECT 1 FROM chat_card_visibility v WHERE v.card_id = chat_cards.id AND v.person = chat_cards.person AND v.aside = ?)", person, lane, since, []string{wire.CardAnswered, wire.CardResolved}, true).Order("created_at, id").Find(&cs).Error; err != nil { |
| 401 | return err |
| 402 | } |
| 403 | t := &txn{s: s, db: tx, ctx: ctx} |
| 404 | for _, c := range cs { |
| 405 | v, err := t.cardView(c) |
| 406 | if err != nil { |
| 407 | return err |
| 408 | } |
| 409 | out = append(out, v) |
| 410 | } |
| 411 | return nil |
| 412 | }) |
| 413 | return |
| 414 | } |
| 415 | |
| 416 | // cardContexts reads the current task/project names for the authorised cards, |
| 417 | // including historical cards whose project is no longer active. |
| 418 | func cardContexts(tx *gorm.DB, person string, cards []cardRecord) (map[string]CardContext, error) { |
| 419 | out := map[string]CardContext{} |
| 420 | if len(cards) == 0 { |
| 421 | return out, nil |
| 422 | } |
| 423 | ids := make([]string, 0, len(cards)) |
| 424 | for _, c := range cards { |
| 425 | ids = append(ids, c.ID) |
| 426 | } |
| 427 | var rows []struct { |
| 428 | ID, Repo string |
| 429 | TitleSet bool |
| 430 | CardContext |
| 431 | } |
| 432 | err := tx.Table("chat_cards AS c"). |
| 433 | Select("c.id, p.id AS project_id, p.title AS project_title, coalesce(p.title_set, 0) AS title_set, p.repo, t.title AS task_title"). |
| 434 | Joins("LEFT JOIN chat_tasks AS t ON t.id = c.task_id"). |
| 435 | Joins("LEFT JOIN chat_projects AS p ON p.id = coalesce(nullif(t.project_id, ''), c.project_id)"). |
| 436 | Where("c.person = ? AND c.id IN ?", person, ids).Scan(&rows).Error |
| 437 | if err != nil { |
| 438 | return nil, err |
| 439 | } |
| 440 | for _, row := range rows { |
| 441 | if row.Repo != "" { |
| 442 | // The same title every other reader shows (shownTitle). |
| 443 | row.ProjectTitle = projectRecord{Repo: row.Repo, Title: row.ProjectTitle, TitleSet: row.TitleSet}.shownTitle() |
| 444 | } |
| 445 | out[row.ID] = row.CardContext |
| 446 | } |
| 447 | return out, nil |
| 448 | } |
| 449 | |