| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "time" |
| 12 | "unicode/utf8" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | var ( |
| 19 | // ErrNotAllowed means the repository is not in the person's |
| 20 | // runner-advertised allowlist. |
| 21 | ErrNotAllowed = errors.New("chat: repository not allowed") |
| 22 | // ErrCardConflict means a stale revision or a card already answered. |
| 23 | ErrCardConflict = errors.New("chat: card conflict") |
| 24 | ) |
| 25 | |
| 26 | // projectRecord is a repository the team works on. Projects are team |
| 27 | // records: every active member sees the same list. |
| 28 | type projectRecord struct { |
| 29 | MetadataSet bool |
| 30 | TitleSet bool |
| 31 | DescriptionSet bool |
| 32 | Description string |
| 33 | Autonomy string |
| 34 | AutonomyOwner string |
| 35 | AutonomyRevision int64 |
| 36 | CopyOwner string |
| 37 | CopyRevision int64 |
| 38 | ID string `gorm:"primaryKey"` |
| 39 | Repo string `gorm:"uniqueIndex:chat_project_repo"` |
| 40 | // Title is the product's name, from the catalog when it was added. |
| 41 | Title string |
| 42 | State string |
| 43 | AddedBy string |
| 44 | Revision int64 |
| 45 | CreatedAt time.Time |
| 46 | UpdatedAt time.Time |
| 47 | // SiteApp is the Carloku app the project's website publishes as, |
| 48 | // minted at its first publish card and never shared (publish.go). |
| 49 | SiteApp *string `gorm:"uniqueIndex:chat_project_site_app"` |
| 50 | } |
| 51 | |
| 52 | func (projectRecord) TableName() string { return "chat_projects" } |
| 53 | |
| 54 | // shownTitle is the project's title: the person's when they named it, |
| 55 | // else its repository's name. A title Equipo stored itself never shows, |
| 56 | // so a stored "Create" or "Store" (#49) cannot come back. |
| 57 | func (p projectRecord) shownTitle() string { |
| 58 | if p.TitleSet && p.Title != "" { |
| 59 | return p.Title |
| 60 | } |
| 61 | return ProjectTitle(p.Repo) |
| 62 | } |
| 63 | |
| 64 | // cardRecord is a card in one person's conversation. |
| 65 | type cardRecord struct { |
| 66 | Access string |
| 67 | Placement string |
| 68 | ID string `gorm:"primaryKey"` |
| 69 | Person string `gorm:"index:chat_card_person"` |
| 70 | Kind string |
| 71 | State string |
| 72 | TurnID string |
| 73 | ProjectID string `gorm:"index:chat_card_project"` |
| 74 | Question string |
| 75 | Options string |
| 76 | Choice string |
| 77 | AnswerMessage string `gorm:"index:chat_card_answer"` |
| 78 | // TaskID names the task a task card reports. |
| 79 | TaskID string `gorm:"index:chat_card_task"` |
| 80 | // Name is an access card's namespace, when the name looked for says it. |
| 81 | Name string |
| 82 | // Undo is a home card's homeUndo JSON: the setting it replaced and the |
| 83 | // setting revision its change made. |
| 84 | Undo string |
| 85 | Revision int64 |
| 86 | CreatedAt time.Time |
| 87 | UpdatedAt time.Time |
| 88 | // ActionID is the housekeeping action a receipt reports; VisibleAt is |
| 89 | // when it shows in the conversation; Held while it waits for that |
| 90 | // (quiet hours): a held card is on the Housekeeping view only. |
| 91 | ActionID string |
| 92 | VisibleAt *time.Time |
| 93 | Held bool |
| 94 | // Lane is the lane of the conversation it is in. |
| 95 | Lane string |
| 96 | // SourceCard is the team card an Assistant card points at; Links its |
| 97 | // links (wire.CardLink JSON) and Result what became of it |
| 98 | // (outcome.go). |
| 99 | SourceCard string `gorm:"index:chat_card_source"` |
| 100 | Links string |
| 101 | Result string |
| 102 | // HandoffID is the hand-off a job card shows (kind wire.CardJob); |
| 103 | // Detail its one sentence more than Result. |
| 104 | HandoffID string `gorm:"index:chat_card_handoff"` |
| 105 | Detail string |
| 106 | // Place is a place card's proposal (placeProposal JSON); '' on every |
| 107 | // other card. |
| 108 | Place string |
| 109 | // CarryOn: a paused job card offers Carry on now, on |
| 110 | // CarryOnConnection (the offer's connection id), which pins it. |
| 111 | CarryOn bool |
| 112 | CarryOnConnection string |
| 113 | } |
| 114 | |
| 115 | func (cardRecord) TableName() string { return "chat_cards" } |
| 116 | |
| 117 | // toolCallRecord stores each tool result by call id, so a repeated call |
| 118 | // gets the same answer instead of a second effect. |
| 119 | type toolCallRecord struct { |
| 120 | CallID string `gorm:"primaryKey"` |
| 121 | Person string |
| 122 | TurnID string `gorm:"index:chat_tool_call_turn,priority:1"` |
| 123 | // Attempt and ArgsHash bind a replay to the same call: same turn, |
| 124 | // attempt, tool and arguments. |
| 125 | Attempt int64 |
| 126 | ArgsHash string |
| 127 | Name string |
| 128 | // Op is the mutation a completed write made, by kind and target |
| 129 | // ("ask", "record#2", "start:<task>", "add:<repo>"): the turn's |
| 130 | // mutation ledger, which a later attempt of the turn is held to. |
| 131 | Op string `gorm:"index:chat_tool_call_turn,priority:2"` |
| 132 | Result string |
| 133 | CreatedAt time.Time |
| 134 | // Lane is the turn's lane. |
| 135 | Lane string |
| 136 | // State is an Assistant call to a provider made outside the tool |
| 137 | // call's transaction: callPending while it is made, callWaiting on an |
| 138 | // earlier call with the same LedgerKey, callDone (or empty: every |
| 139 | // other call) once it has its Result. Operation is what a describe |
| 140 | // or use named; LedgerKey is a use's turn, operation and input |
| 141 | // (assistant_tools.go). Args are a pending call's arguments, kept |
| 142 | // until it is done so the next process can make it. |
| 143 | State string `gorm:"index:chat_tool_call_state"` |
| 144 | Operation string |
| 145 | LedgerKey string |
| 146 | Args string |
| 147 | } |
| 148 | |
| 149 | func (toolCallRecord) TableName() string { return "chat_tool_calls" } |
| 150 | |
| 151 | // settingRecord is one team setting, such as where new projects go. |
| 152 | type settingRecord struct { |
| 153 | Key string `gorm:"primaryKey"` |
| 154 | Value string |
| 155 | // Unset marks a setting returned to never set; the row stays so its |
| 156 | // revision only grows (home cards bind Undo to it). |
| 157 | Unset bool |
| 158 | Revision int64 |
| 159 | UpdatedBy string |
| 160 | UpdatedAt time.Time |
| 161 | } |
| 162 | |
| 163 | func (settingRecord) TableName() string { return "chat_settings" } |
| 164 | |
| 165 | // settingProjectHome is the namespace new projects are created in. |
| 166 | const settingProjectHome = "project_home" |
| 167 | |
| 168 | // setting reads a team setting; set is false when it was never set, so |
| 169 | // an explicit empty value (a clear) is told apart from no value. |
| 170 | func (t *txn) setting(key string) (value string, set bool, err error) { |
| 171 | value, set, _, err = t.settingRevision(key) |
| 172 | return value, set, err |
| 173 | } |
| 174 | |
| 175 | // settingRevision also returns the setting's revision (0 when no row). |
| 176 | func (t *txn) settingRevision(key string) (value string, set bool, revision int64, err error) { |
| 177 | var r settingRecord |
| 178 | err = t.db.Where("key = ?", key).First(&r).Error |
| 179 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 180 | return "", false, 0, nil |
| 181 | } |
| 182 | if err != nil { |
| 183 | return "", false, 0, err |
| 184 | } |
| 185 | return r.Value, !r.Unset, r.Revision, nil |
| 186 | } |
| 187 | |
| 188 | // unsetSetting returns a setting to never set, as a new revision. |
| 189 | func (t *txn) unsetSetting(key, person string) (int64, error) { |
| 190 | return t.writeSetting(key, "", true, person) |
| 191 | } |
| 192 | |
| 193 | // setSetting sets a value and returns the new revision. |
| 194 | func (t *txn) setSetting(key, value, person string) (int64, error) { |
| 195 | return t.writeSetting(key, value, false, person) |
| 196 | } |
| 197 | |
| 198 | func (t *txn) writeSetting(key, value string, unset bool, person string) (int64, error) { |
| 199 | // Housekeeping never changes a setting. |
| 200 | if err := t.hkForbid("setting"); err != nil { |
| 201 | return 0, err |
| 202 | } |
| 203 | var r settingRecord |
| 204 | err := t.db.Where("key = ?", key).First(&r).Error |
| 205 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 206 | return 1, t.db.Create(&settingRecord{Key: key, Value: value, Unset: unset, Revision: 1, UpdatedBy: person, UpdatedAt: t.now()}).Error |
| 207 | } |
| 208 | if err != nil { |
| 209 | return 0, err |
| 210 | } |
| 211 | next := r.Revision + 1 |
| 212 | return next, t.db.Model(&settingRecord{}).Where("key = ?", key).Select("value", "unset", "revision", "updated_by", "updated_at").Updates(&settingRecord{Value: value, Unset: unset, Revision: next, UpdatedBy: person, UpdatedAt: t.now()}).Error |
| 213 | } |
| 214 | |
| 215 | // homeUndo is what a home card's Undo restores: the previous setting |
| 216 | // (Prev "unset", or "set:<value>") and the revision its change made. |
| 217 | // Undo applies only while the setting is still at that revision. |
| 218 | type homeUndo struct { |
| 219 | Prev string `json:"prev"` |
| 220 | Revision int64 `json:"revision"` |
| 221 | } |
| 222 | |
| 223 | // changeHome sets (or, with "", clears) where new projects go and returns |
| 224 | // the card's Undo record for this change. |
| 225 | func (t *txn) changeHome(ns, person string) (string, error) { |
| 226 | prev, set, err := t.setting(settingProjectHome) |
| 227 | if err != nil { |
| 228 | return "", err |
| 229 | } |
| 230 | u := homeUndo{Prev: "unset"} |
| 231 | if set { |
| 232 | u.Prev = "set:" + prev |
| 233 | } |
| 234 | if u.Revision, err = t.setSetting(settingProjectHome, ns, person); err != nil { |
| 235 | return "", err |
| 236 | } |
| 237 | raw, _ := json.Marshal(u) |
| 238 | return string(raw), nil |
| 239 | } |
| 240 | |
| 241 | // projectHome is where new projects go: the team setting when the runner |
| 242 | // may still create there, else the runner's own home, else none (the |
| 243 | // coordinator then takes the best-fitting existing repository). An |
| 244 | // explicit clear is none: it never falls back to the runner's home. |
| 245 | func (t *txn) projectHome(h wire.Hello) (string, error) { |
| 246 | home, set, err := t.setting(settingProjectHome) |
| 247 | if err != nil || set && home == "" { |
| 248 | return "", err |
| 249 | } |
| 250 | for _, ns := range []string{home, h.Home} { |
| 251 | if ns != "" && slices.Contains(h.CreateIn, ns) { |
| 252 | return ns, nil |
| 253 | } |
| 254 | } |
| 255 | return "", nil |
| 256 | } |
| 257 | |
| 258 | // ProjectName drops the forge host: amadan.net/oficina/sample is |
| 259 | // oficina/sample. |
| 260 | func ProjectName(repo string) string { return forgekey.Display(repo) } |
| 261 | |
| 262 | // NormalizeRepo turns what a person or the model typed into a forge key. |
| 263 | func NormalizeRepo(raw string) string { return forgekey.Normalize(raw) } |
| 264 | |
| 265 | func (t *txn) projectView(p projectRecord) (wire.Project, error) { |
| 266 | title := p.shownTitle() |
| 267 | v := wire.Project{CopyOwner: p.CopyOwner, CopyRevision: p.CopyRevision, ID: p.ID, Revision: p.Revision, Repo: p.Repo, Name: ProjectName(p.Repo), Title: title, State: p.State, AddedBy: p.AddedBy, CreatedAt: p.CreatedAt, UpdatedAt: p.UpdatedAt} |
| 268 | var err error |
| 269 | if v.Autonomy, err = t.autonomyOf(p); err != nil { |
| 270 | return v, err |
| 271 | } |
| 272 | if v.Attachments, err = t.attachments(p.ID); err != nil { |
| 273 | return v, err |
| 274 | } |
| 275 | // A project is its repository first. Projects made before attachments |
| 276 | // were recorded (and those create_project made) have no row for it: |
| 277 | // it is still theirs. |
| 278 | if !slices.ContainsFunc(v.Attachments, func(a wire.Attachment) bool { return a.Kind == wire.AttachmentRepo && a.Ref == p.Repo }) { |
| 279 | v.Attachments = append([]wire.Attachment{{Kind: wire.AttachmentRepo, Ref: p.Repo, Name: ProjectName(p.Repo)}}, v.Attachments...) |
| 280 | } |
| 281 | if err := t.projectFacts(&v, p); err != nil { |
| 282 | return v, err |
| 283 | } |
| 284 | return v, t.projectMetadata(&v, p) |
| 285 | } |
| 286 | |
| 287 | func (t *txn) cardView(c cardRecord) (wire.Card, error) { |
| 288 | v := wire.Card{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, TurnID: c.TurnID, ProjectID: c.ProjectID, Question: c.Question, Options: []string{}, Choice: c.Choice, TaskID: c.TaskID, CreatedAt: c.CreatedAt, UpdatedAt: c.UpdatedAt, ActionID: c.ActionID, VisibleAt: c.VisibleAt} |
| 289 | if c.Placement != "" { |
| 290 | var data placementData |
| 291 | if err := json.Unmarshal([]byte(c.Placement), &data); err != nil { |
| 292 | return v, err |
| 293 | } |
| 294 | v.RememberName = data.RequestedName |
| 295 | v.PlacementByName = data.ByName |
| 296 | v.PlacementQuestion = c.Kind == wire.CardQuestion |
| 297 | } |
| 298 | if c.Access != "" { |
| 299 | if err := json.Unmarshal([]byte(c.Access), &v.Access); err != nil { |
| 300 | return v, err |
| 301 | } |
| 302 | } |
| 303 | if c.Options != "" { |
| 304 | if err := json.Unmarshal([]byte(c.Options), &v.Options); err != nil { |
| 305 | return v, err |
| 306 | } |
| 307 | } |
| 308 | if c.ProjectID != "" { |
| 309 | var p projectRecord |
| 310 | if err := t.db.Where("id = ?", c.ProjectID).First(&p).Error; err != nil { |
| 311 | return v, err |
| 312 | } |
| 313 | v.Name = ProjectName(p.Repo) |
| 314 | } |
| 315 | if c.Kind == wire.CardHome { |
| 316 | v.Name = c.Choice |
| 317 | } |
| 318 | // Set aside is the card's person's presentation (D5), never its state. |
| 319 | var aside []bool |
| 320 | if err := t.db.Model(&cardVisibility{}).Where("person = ? AND card_id = ?", c.Person, c.ID).Pluck("aside", &aside).Error; err != nil { |
| 321 | return v, err |
| 322 | } |
| 323 | v.Aside = len(aside) == 1 && aside[0] |
| 324 | if c.Kind == wire.CardAccess || c.Kind == wire.CardMerge || c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt || c.Kind == wire.CardPublish { |
| 325 | v.Name = c.Name |
| 326 | } |
| 327 | if c.Kind == wire.CardMerge { |
| 328 | if err := t.mergeCardView(&v, c); err != nil { |
| 329 | return v, err |
| 330 | } |
| 331 | } |
| 332 | if c.Kind == wire.CardPublish { |
| 333 | if err := t.publishCardView(&v, c); err != nil { |
| 334 | return v, err |
| 335 | } |
| 336 | } |
| 337 | if c.Kind == wire.CardPlace { |
| 338 | v.Name = c.Name |
| 339 | placeCardView(&v, c) |
| 340 | } |
| 341 | if c.Kind == wire.CardSpecialist { |
| 342 | sv, err := t.specialistCard(c.ID) |
| 343 | if err != nil { |
| 344 | return v, err |
| 345 | } |
| 346 | v.Name, v.Specialist = sv.Name, &sv |
| 347 | } |
| 348 | if c.Kind == wire.CardResearchSources { |
| 349 | rv, err := t.researchCard(c) |
| 350 | if err != nil { |
| 351 | return v, err |
| 352 | } |
| 353 | k, err := t.loadTask(c.TaskID) |
| 354 | if err != nil { |
| 355 | return v, err |
| 356 | } |
| 357 | v.Name, v.Research = k.Title, rv |
| 358 | } |
| 359 | if c.Kind == wire.CardResearchInventory { |
| 360 | iv, err := t.inventoryView(c) |
| 361 | if err != nil { |
| 362 | return v, err |
| 363 | } |
| 364 | v.Inventory = iv |
| 365 | } |
| 366 | if c.Kind == wire.CardInstanceInventory { |
| 367 | iv, _, err := t.instanceInventoryView(c) |
| 368 | if err != nil { |
| 369 | return v, err |
| 370 | } |
| 371 | v.Inventory = iv |
| 372 | } |
| 373 | if c.Kind == wire.CardAdvice { |
| 374 | av, err := t.cardAdvice(c) |
| 375 | if err != nil { |
| 376 | return v, err |
| 377 | } |
| 378 | v.Advice = av |
| 379 | } |
| 380 | if c.Kind == wire.CardTask { |
| 381 | k, err := t.loadTask(c.TaskID) |
| 382 | if err != nil { |
| 383 | return v, err |
| 384 | } |
| 385 | v.Name, v.State = k.Title, k.Stage |
| 386 | } |
| 387 | return v, nil |
| 388 | } |
| 389 | |
| 390 | func (t *txn) cardEvent(c cardRecord) error { return t.cardEventPush(c, true) } |
| 391 | |
| 392 | // cardEventPush is cardEvent; pushes false for a change that is no card |
| 393 | // change to its person's devices (setting it aside), which runs no push |
| 394 | // rule. |
| 395 | func (t *txn) cardEventPush(c cardRecord, pushes bool) error { |
| 396 | if c.Held { |
| 397 | // Quiet hours: the conversation hears of it at its visible time. |
| 398 | return nil |
| 399 | } |
| 400 | if c.Lane == wire.LaneAssistant { |
| 401 | v, err := t.assistantCardView(c) |
| 402 | if err != nil { |
| 403 | return err |
| 404 | } |
| 405 | return t.event(c.Lane, c.Person, wire.EventCard, "card", c.ID, c.Revision, c.TurnID, "", 0, v) |
| 406 | } |
| 407 | v, err := t.cardView(c) |
| 408 | if err != nil { |
| 409 | return err |
| 410 | } |
| 411 | if err := t.event(c.Lane, c.Person, wire.EventCard, "card", c.ID, c.Revision, c.TurnID, "", 0, v); err != nil { |
| 412 | return err |
| 413 | } |
| 414 | if pushes { |
| 415 | if err := t.pushCard(c, v); err != nil { |
| 416 | return err |
| 417 | } |
| 418 | } |
| 419 | // A hand-off's team card is the Assistant's too. A card in a job |
| 420 | // thread goes to the thread's stream, never the person's. |
| 421 | return t.mirrorCard(c) |
| 422 | } |
| 423 | |
| 424 | func (t *txn) saveCard(c *cardRecord) error { |
| 425 | // Housekeeping never answers, resolves or withdraws a card (a merge |
| 426 | // card through withdrawMergeCards included); its receipts are created, |
| 427 | // not saved. |
| 428 | if err := t.hkForbid("card"); err != nil { |
| 429 | return err |
| 430 | } |
| 431 | c.Revision++ |
| 432 | c.UpdatedAt = t.now() |
| 433 | fields := []string{"state", "choice", "answer_message", "undo", "revision", "updated_at"} |
| 434 | if c.Kind == wire.CardAccess { |
| 435 | fields = append(fields, "access", "name", "question") |
| 436 | } |
| 437 | if c.Kind == wire.CardQuestion && c.Placement != "" { |
| 438 | fields = append(fields, "placement", "options", "question") |
| 439 | } |
| 440 | if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select(fields).Updates(c).Error; err != nil { |
| 441 | return err |
| 442 | } |
| 443 | return t.cardEvent(*c) |
| 444 | } |
| 445 | |
| 446 | // projectEvent tells every active member: projects are team records. |
| 447 | func (t *txn) projectEvent(p projectRecord) error { |
| 448 | viewer := t.viewer |
| 449 | t.viewer = "" |
| 450 | defer func() { t.viewer = viewer }() |
| 451 | var members []string |
| 452 | if err := t.db.Raw("SELECT address FROM members WHERE active = 1 ORDER BY address").Scan(&members).Error; err != nil { |
| 453 | return err |
| 454 | } |
| 455 | for _, m := range members { |
| 456 | t.viewer = m |
| 457 | v, err := t.projectView(p) |
| 458 | if err != nil { |
| 459 | return err |
| 460 | } |
| 461 | if err := t.event("", m, wire.EventProject, "project", p.ID, p.Revision, "", "", 0, v); err != nil { |
| 462 | return err |
| 463 | } |
| 464 | } |
| 465 | return nil |
| 466 | } |
| 467 | |
| 468 | // hello is the newest hello of the person's primary runner. |
| 469 | func (t *txn) hello(person string) (wire.Hello, error) { |
| 470 | id, err := t.s.authority.PrimaryRunner(t.db, person) |
| 471 | if err != nil || id == "" { |
| 472 | return wire.Hello{}, err |
| 473 | } |
| 474 | var r runnerSessionRecord |
| 475 | err = t.db.Where("runner_id = ?", id).First(&r).Error |
| 476 | if errors.Is(err, gorm.ErrRecordNotFound) || err == nil && r.Hello == "" { |
| 477 | return wire.Hello{}, nil |
| 478 | } |
| 479 | if err != nil { |
| 480 | return wire.Hello{}, err |
| 481 | } |
| 482 | var h wire.Hello |
| 483 | return h, json.Unmarshal([]byte(r.Hello), &h) |
| 484 | } |
| 485 | |
| 486 | // allowed is the person's runner-advertised allowlist: the repositories in |
| 487 | // the newest hello of their primary runner. |
| 488 | func (t *txn) allowed(person string) ([]string, error) { |
| 489 | h, err := t.hello(person) |
| 490 | if err != nil { |
| 491 | return nil, err |
| 492 | } |
| 493 | out := []string{} |
| 494 | for _, repo := range h.Repos { |
| 495 | if forgekey.HasHubPrefix(repo) && !slices.Contains(out, repo) { |
| 496 | out = append(out, repo) |
| 497 | } |
| 498 | } |
| 499 | slices.Sort(out) |
| 500 | return out, nil |
| 501 | } |
| 502 | |
| 503 | // addProject adds or restores a project. Adding grants nothing: publishing |
| 504 | // authority stays with the runner's forge checks. |
| 505 | func (t *txn) addProject(person, raw string) (projectRecord, bool, error) { |
| 506 | repo := NormalizeRepo(raw) |
| 507 | allowed, err := t.allowed(person) |
| 508 | if err != nil { |
| 509 | return projectRecord{}, false, err |
| 510 | } |
| 511 | if !slices.Contains(allowed, repo) { |
| 512 | return projectRecord{}, false, ErrNotAllowed |
| 513 | } |
| 514 | var p projectRecord |
| 515 | err = t.db.Where("repo = ?", repo).First(&p).Error |
| 516 | now := t.now() |
| 517 | switch { |
| 518 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 519 | if err := t.isOwner(person); err != nil { |
| 520 | return p, false, err |
| 521 | } |
| 522 | // No stored title: until the person names it, a project shows its |
| 523 | // repository's name (shownTitle), as create_project's do. |
| 524 | p = projectRecord{ID: newID("p_"), Repo: repo, State: wire.ProjectActive, AddedBy: person, Revision: 1, CreatedAt: now, UpdatedAt: now} |
| 525 | if err = t.db.Create(&p).Error; err != nil { |
| 526 | return p, false, err |
| 527 | } |
| 528 | if err = t.attach(p); err != nil { |
| 529 | return p, false, err |
| 530 | } |
| 531 | case err != nil: |
| 532 | return p, false, err |
| 533 | case p.State == wire.ProjectActive: |
| 534 | return p, false, nil |
| 535 | default: |
| 536 | if err := t.isOwner(person); err != nil { |
| 537 | return p, false, err |
| 538 | } |
| 539 | p.State, p.AddedBy, p.Revision, p.UpdatedAt = wire.ProjectActive, person, p.Revision+1, now |
| 540 | if err = t.db.Model(&projectRecord{}).Where("id = ?", p.ID).Select("state", "added_by", "revision", "updated_at").Updates(&p).Error; err != nil { |
| 541 | return p, false, err |
| 542 | } |
| 543 | } |
| 544 | if err := t.s.authority.Audit(t.db, person, "project.added", p.ID); err != nil { |
| 545 | return p, false, err |
| 546 | } |
| 547 | return p, true, t.projectEvent(p) |
| 548 | } |
| 549 | |
| 550 | func (t *txn) isOwner(person string) error { |
| 551 | me, err := t.s.authority.Me(t.db, person) |
| 552 | if err != nil { |
| 553 | return err |
| 554 | } |
| 555 | if me.Role != "owner" { |
| 556 | return ErrForbidden |
| 557 | } |
| 558 | return nil |
| 559 | } |
| 560 | |
| 561 | // Projects lists the team's active projects and the person's allowlist. |
| 562 | func (s *Store) Projects(ctx context.Context, person string) (out wire.ProjectList, err error) { |
| 563 | err = s.tx(ctx, func(t *txn) error { |
| 564 | t.viewer = person |
| 565 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 566 | return err |
| 567 | } |
| 568 | var rows []projectRecord |
| 569 | if err := t.db.Where("state = ?", wire.ProjectActive).Order("repo").Find(&rows).Error; err != nil { |
| 570 | return err |
| 571 | } |
| 572 | out.Items = make([]wire.Project, 0, len(rows)) |
| 573 | for _, p := range rows { |
| 574 | v, err := t.projectView(p) |
| 575 | if err != nil { |
| 576 | return err |
| 577 | } |
| 578 | out.Items = append(out.Items, v) |
| 579 | } |
| 580 | if out.Allowed, err = t.allowed(person); err != nil { |
| 581 | return err |
| 582 | } |
| 583 | h, err := t.hello(person) |
| 584 | if err != nil { |
| 585 | return err |
| 586 | } |
| 587 | out.Home, err = t.projectHome(h) |
| 588 | if err != nil { |
| 589 | return err |
| 590 | } |
| 591 | if err := t.projectListExtras(person, h, &out); err != nil { |
| 592 | return err |
| 593 | } |
| 594 | out.Cursor, err = maxEvent(t.db) |
| 595 | return err |
| 596 | }) |
| 597 | return out, err |
| 598 | } |
| 599 | |
| 600 | // AddProject is POST /projects: only an owner, only from their allowlist. |
| 601 | func (s *Store) AddProject(ctx context.Context, person, repo string) (out wire.Project, created bool, err error) { |
| 602 | if repo == "" || len(repo) > 300 || !utf8.ValidString(repo) || strings.ContainsAny(repo, "\x00\r\n") { |
| 603 | return out, false, ErrInvalid |
| 604 | } |
| 605 | err = s.tx(ctx, func(t *txn) error { |
| 606 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 607 | return err |
| 608 | } |
| 609 | if err := t.isOwner(person); err != nil { |
| 610 | return err |
| 611 | } |
| 612 | p, added, err := t.addProject(person, repo) |
| 613 | if err != nil { |
| 614 | return err |
| 615 | } |
| 616 | out, err = t.projectView(p) |
| 617 | created = added |
| 618 | return err |
| 619 | }) |
| 620 | return out, created, err |
| 621 | } |
| 622 | |
| 623 | // RemoveProject is DELETE /projects/{id} and the card's Remove. Removing |
| 624 | // a removed project returns it unchanged. |
| 625 | func (s *Store) RemoveProject(ctx context.Context, person, id string) (out wire.Project, err error) { |
| 626 | err = s.tx(ctx, func(t *txn) error { |
| 627 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 628 | return err |
| 629 | } |
| 630 | out, err = t.removeProject(person, id) |
| 631 | return err |
| 632 | }) |
| 633 | return out, err |
| 634 | } |
| 635 | |
| 636 | // removeProject takes a project off the team's list; an owner only, and |
| 637 | // never housekeeping. |
| 638 | func (t *txn) removeProject(person, id string) (wire.Project, error) { |
| 639 | if err := t.hkForbid("delete"); err != nil { |
| 640 | return wire.Project{}, err |
| 641 | } |
| 642 | if err := t.isOwner(person); err != nil { |
| 643 | return wire.Project{}, err |
| 644 | } |
| 645 | var p projectRecord |
| 646 | if err := t.db.Where("id = ?", id).First(&p).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 647 | return wire.Project{}, ErrNotFound |
| 648 | } else if err != nil { |
| 649 | return wire.Project{}, err |
| 650 | } |
| 651 | if p.State == wire.ProjectRemoved { |
| 652 | return t.projectView(p) |
| 653 | } |
| 654 | p.State, p.Revision, p.UpdatedAt = wire.ProjectRemoved, p.Revision+1, t.now() |
| 655 | if err := t.db.Model(&projectRecord{}).Where("id = ?", p.ID).Select("state", "revision", "updated_at").Updates(&p).Error; err != nil { |
| 656 | return wire.Project{}, err |
| 657 | } |
| 658 | if err := t.projectEvent(p); err != nil { |
| 659 | return wire.Project{}, err |
| 660 | } |
| 661 | var cards []cardRecord |
| 662 | if err := t.db.Where("project_id = ? AND state IN ?", p.ID, []string{wire.CardAdded, wire.CardWorking, wire.CardCreated}).Find(&cards).Error; err != nil { |
| 663 | return wire.Project{}, err |
| 664 | } |
| 665 | for i := range cards { |
| 666 | cards[i].State = wire.CardRemoved |
| 667 | if err := t.saveCard(&cards[i]); err != nil { |
| 668 | return wire.Project{}, err |
| 669 | } |
| 670 | } |
| 671 | return t.projectView(p) |
| 672 | } |
| 673 | |
| 674 | // CardFor finds the person's project card for a project, for the page. |
| 675 | func (s *Store) Card(ctx context.Context, person, id string) (out wire.Card, err error) { |
| 676 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 677 | var c cardRecord |
| 678 | if err := tx.Where("id = ? AND person = ? AND "+personLane, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 679 | return ErrNotFound |
| 680 | } else if err != nil { |
| 681 | return err |
| 682 | } |
| 683 | out, err = (&txn{s: s, db: tx}).cardView(c) |
| 684 | return err |
| 685 | }) |
| 686 | return out, err |
| 687 | } |
| 688 | |
| 689 | // Answer answers a question card. The answer becomes the person's next |
| 690 | // message, so the coordinator reads it in a new turn. A stale revision or |
| 691 | // a card already answered is a conflict carrying the current card. |
| 692 | func (s *Store) Answer(ctx context.Context, person, id string, in wire.AnswerCard) (wire.Answered, wire.Card, error) { |
| 693 | return s.AnswerDevice(ctx, person, "", id, in) |
| 694 | } |
| 695 | |
| 696 | func (s *Store) AnswerDevice(ctx context.Context, person, credential, id string, in wire.AnswerCard) (out wire.Answered, current wire.Card, err error) { |
| 697 | digestInput := in |
| 698 | in.Choice = strings.TrimSpace(in.Choice) |
| 699 | if in.Choice == "" || len(in.Choice) > wire.MaxMessageBytes || !utf8.ValidString(in.Choice) || strings.ContainsRune(in.Choice, 0) { |
| 700 | return out, current, ErrInvalid |
| 701 | } |
| 702 | s.refreshBeforeAct(ctx, person) |
| 703 | err = s.tx(ctx, func(t *txn) error { |
| 704 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 705 | return err |
| 706 | } |
| 707 | var receipt *notificationReceipt |
| 708 | if in.IdempotencyKey != "" { |
| 709 | var prior bool |
| 710 | receipt, prior, err = t.actionReceipt(person, credential, "answer", id, in.IdempotencyKey, digestInput) |
| 711 | if err != nil { |
| 712 | return err |
| 713 | } |
| 714 | if prior { |
| 715 | out, err = t.receiptAnswer(*receipt) |
| 716 | return err |
| 717 | } |
| 718 | } |
| 719 | acted := "" |
| 720 | err = func() error { |
| 721 | var c cardRecord |
| 722 | if err := t.db.Where("id = ? AND person = ? AND "+coordinatorRole, id, person).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 723 | return ErrNotFound |
| 724 | } else if err != nil { |
| 725 | return err |
| 726 | } |
| 727 | // A card in a held job's thread that would start or change |
| 728 | // work can't be answered; dropping the job still can, and so |
| 729 | // can Publish and Not now (going live, which go_live governs). |
| 730 | if in.Choice != "drop" && in.Choice != wire.ChoicePublish && in.Choice != wire.ChoiceNotNow { |
| 731 | if held, err := t.turnHeld(c.TurnID, c.Lane); err != nil || held { |
| 732 | if held { |
| 733 | return ErrAbilityOff |
| 734 | } |
| 735 | return err |
| 736 | } |
| 737 | } |
| 738 | if c.TaskID != "" { |
| 739 | // An answer on one of a task's cards by its creator is its |
| 740 | // person acting on it: Design's attempts count from none |
| 741 | // (before the answer, so work it starts counts), and one |
| 742 | // the limit held goes after it. Another member's answer |
| 743 | // does neither. |
| 744 | ok, err := t.personActed(c.TaskID, person) |
| 745 | if err != nil { |
| 746 | return err |
| 747 | } |
| 748 | if ok { |
| 749 | acted = c.TaskID |
| 750 | } |
| 751 | } |
| 752 | if c.Kind == wire.CardMakerRemoved { |
| 753 | card, cur, e := t.answerMakerRemoved(person, c, in) |
| 754 | out.Card, current = card, cur |
| 755 | return e |
| 756 | } |
| 757 | if c.Kind == wire.CardHome { |
| 758 | card, cur, e := t.answerHome(person, c, in) |
| 759 | out.Card, current = card, cur |
| 760 | return e |
| 761 | } |
| 762 | if c.Kind == wire.CardAccess { |
| 763 | card, cur, e := t.answerAccess(person, c, in) |
| 764 | out.Card, current = card, cur |
| 765 | return e |
| 766 | } |
| 767 | if c.Kind == wire.CardCombined { |
| 768 | card, cur, e := t.answerCombined(person, c, in) |
| 769 | out.Card, current = card, cur |
| 770 | return e |
| 771 | } |
| 772 | if c.Kind == wire.CardDirection { |
| 773 | card, cur, e := t.answerDirection(person, c, in) |
| 774 | out.Card, current = card, cur |
| 775 | return e |
| 776 | } |
| 777 | if c.Kind == wire.CardSpecialist { |
| 778 | card, cur, e := t.answerSpecialist(person, c, in) |
| 779 | out.Card, current = card, cur |
| 780 | return e |
| 781 | } |
| 782 | if c.Kind == wire.CardResearchSources { |
| 783 | card, cur, e := t.answerResearchSources(person, c, in) |
| 784 | out.Card, current = card, cur |
| 785 | return e |
| 786 | } |
| 787 | if c.Kind == wire.CardResearchInventory { |
| 788 | card, cur, e := t.answerResearchInventory(person, c, in) |
| 789 | out.Card, current = card, cur |
| 790 | return e |
| 791 | } |
| 792 | if c.Kind == wire.CardInstanceInventory { |
| 793 | card, cur, e := t.answerInstanceInventory(person, c, in) |
| 794 | out.Card, current = card, cur |
| 795 | return e |
| 796 | } |
| 797 | if c.Kind == wire.CardAdvice { |
| 798 | card, cur, e := t.answerAdvice(person, c, in) |
| 799 | out.Card, current = card, cur |
| 800 | return e |
| 801 | } |
| 802 | if c.Kind == wire.CardHeld { |
| 803 | card, cur, e := t.answerHeld(person, c, in) |
| 804 | out.Card, current = card, cur |
| 805 | return e |
| 806 | } |
| 807 | if c.Kind == wire.CardMerge { |
| 808 | card, cur, e := t.answerMerge(person, c, in) |
| 809 | out.Card, current = card, cur |
| 810 | return e |
| 811 | } |
| 812 | if c.Kind == wire.CardPublish { |
| 813 | card, cur, e := t.answerPublish(person, c, in) |
| 814 | out.Card, current = card, cur |
| 815 | return e |
| 816 | } |
| 817 | if c.Kind == wire.CardPlace { |
| 818 | card, cur, e := t.answerPlace(person, c, in) |
| 819 | out.Card, current = card, cur |
| 820 | return e |
| 821 | } |
| 822 | if c.Kind == wire.CardMergeShips || c.Kind == wire.CardMergePolicy || c.Kind == wire.CardMergeReceipt { |
| 823 | var card, cur wire.Card |
| 824 | var e error |
| 825 | switch c.Kind { |
| 826 | case wire.CardMergeShips: |
| 827 | card, cur, e = t.answerShips(person, c, in) |
| 828 | case wire.CardMergePolicy: |
| 829 | card, cur, e = t.answerPolicyCard(person, c, in) |
| 830 | default: |
| 831 | card, cur, e = t.answerReceipt(person, c, in) |
| 832 | } |
| 833 | out.Card, current = card, cur |
| 834 | return e |
| 835 | } |
| 836 | if c.Kind != wire.CardQuestion && c.Kind != wire.CardProject { |
| 837 | return ErrNotFound |
| 838 | } |
| 839 | var e error |
| 840 | out, current, e = t.answerQuestionOrigin(person, c, in, originComposer) |
| 841 | return e |
| 842 | }() |
| 843 | if err == nil && acted != "" { |
| 844 | err = t.releaseDesignHeld(acted) |
| 845 | } |
| 846 | if err != nil || receipt == nil { |
| 847 | return err |
| 848 | } |
| 849 | receipt.CardID, receipt.MessageID, receipt.TurnID = out.Card.ID, out.Message.ID, out.Turn.ID |
| 850 | return t.db.Create(receipt).Error |
| 851 | }) |
| 852 | return out, current, err |
| 853 | } |
| 854 | |
| 855 | // answerQuestion answers a question or project card: the answer becomes |
| 856 | // the person's next Coordinator message in the card's lane: their own |
| 857 | // conversation, or the job thread the card was raised in. |
| 858 | func (t *txn) answerQuestion(person string, c cardRecord, in wire.AnswerCard) (out wire.Answered, current wire.Card, err error) { |
| 859 | return t.answerQuestionOrigin(person, c, in, originGenerated) |
| 860 | } |
| 861 | |
| 862 | func (t *txn) answerQuestionOrigin(person string, c cardRecord, in wire.AnswerCard, origin string) (out wire.Answered, current wire.Card, err error) { |
| 863 | return t.answerQuestionSend(person, c, in, origin, "card:"+c.ID, nil) |
| 864 | } |
| 865 | |
| 866 | func (t *txn) answerQuestionSend(person string, c cardRecord, in wire.AnswerCard, origin, key string, files []string) (out wire.Answered, current wire.Card, err error) { |
| 867 | open := c.State == wire.CardOpen |
| 868 | if c.Kind == wire.CardProject { |
| 869 | open = c.State == wire.CardAdded || c.State == wire.CardWorking || c.State == wire.CardCreated |
| 870 | } |
| 871 | if !open || c.Revision != in.Revision { |
| 872 | v, err := t.cardView(c) |
| 873 | if err != nil { |
| 874 | return out, current, err |
| 875 | } |
| 876 | return out, v, ErrCardConflict |
| 877 | } |
| 878 | if c.Placement != "" && in.RememberName != nil { |
| 879 | var data placementData |
| 880 | if err := json.Unmarshal([]byte(c.Placement), &data); err != nil { |
| 881 | return out, current, err |
| 882 | } |
| 883 | if data.RequestedName != "" { |
| 884 | data.RequestedName = strings.TrimSpace(*in.RememberName) |
| 885 | } |
| 886 | if !eligibleProjectName(data.RequestedName) { |
| 887 | data.RequestedName = "" |
| 888 | } |
| 889 | raw, _ := json.Marshal(data) |
| 890 | c.Placement = string(raw) |
| 891 | } |
| 892 | if expanded, err := t.expandNamedAnswer(&c, &in.Choice); err != nil { |
| 893 | return out, current, err |
| 894 | } else if expanded { |
| 895 | out.Card, err = t.cardView(c) |
| 896 | return out, current, err |
| 897 | } |
| 898 | var options []string |
| 899 | _ = json.Unmarshal([]byte(c.Options), &options) |
| 900 | if c.Kind == wire.CardProject { |
| 901 | // Change: the person points the work at another repository. |
| 902 | choices, err := t.projectChoices(person) |
| 903 | if err != nil { |
| 904 | return out, current, err |
| 905 | } |
| 906 | options = choices |
| 907 | in.Choice = ProjectName(NormalizeRepo(in.Choice)) |
| 908 | } |
| 909 | if len(options) > 0 && !slices.Contains(options, in.Choice) || c.Kind == wire.CardProject && len(options) == 0 { |
| 910 | return out, current, ErrInvalid |
| 911 | } |
| 912 | if len(options) > 0 { |
| 913 | origin = originGenerated |
| 914 | } |
| 915 | if err := t.validatePlacementAnswer(c, in.Choice); err != nil { |
| 916 | return out, current, err |
| 917 | } |
| 918 | if err := t.learnPlacement(c, in.Choice, in.RememberName != nil); err != nil { |
| 919 | return out, current, err |
| 920 | } |
| 921 | // An answer in a job thread is a turn there: it needs a primary that |
| 922 | // can carry it, now (it may have come back older since the question, |
| 923 | // after Connect's fencing ran). Refused, the card stays open. |
| 924 | if _, job := wire.JobOf(c.Lane); job { |
| 925 | if err := t.jobRunner(person); err != nil { |
| 926 | return out, current, err |
| 927 | } |
| 928 | } |
| 929 | // The card points at its answer before the answer is dispatched, so |
| 930 | // the coordinator gets the question (or the replaced project) with it. |
| 931 | sent, _, err := t.sendSelectedOrigin(c.Lane, person, key, in.Choice, files, origin, "", func(m messageRecord) error { |
| 932 | c.State, c.Choice, c.AnswerMessage = wire.CardAnswered, in.Choice, m.ID |
| 933 | if c.Kind == wire.CardProject { |
| 934 | c.State = wire.CardChanged |
| 935 | } |
| 936 | if err := t.saveCard(&c); err != nil { |
| 937 | return err |
| 938 | } |
| 939 | if c.Placement != "" { |
| 940 | if err := t.s.authority.Audit(t.db, person, "placement.answered", c.ID+":"+c.Choice); err != nil { |
| 941 | return err |
| 942 | } |
| 943 | } |
| 944 | // The work the answer starts is the hand-off's, when the |
| 945 | // card's turn was. |
| 946 | return t.followAnswer(c, m) |
| 947 | }, true) |
| 948 | if err != nil { |
| 949 | return out, current, err |
| 950 | } |
| 951 | out.Card, err = t.cardView(c) |
| 952 | out.Message, out.Turn = sent.Message, sent.Turn |
| 953 | return out, current, err |
| 954 | } |
| 955 | |
| 956 | // answerHome confirms a home question (the owner's one tap applies it) or |
| 957 | // undoes a change. Only an owner. Undo applies only while the setting is |
| 958 | // still at the revision the card's change made, so a card superseded by a |
| 959 | // later change is refused even when the value matches again. No message |
| 960 | // is sent: the coordinator reads the setting from status. |
| 961 | func (t *txn) answerHome(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 962 | if err := t.isOwner(person); err != nil { |
| 963 | return wire.Card{}, wire.Card{}, err |
| 964 | } |
| 965 | conflict := func() (wire.Card, wire.Card, error) { |
| 966 | v, err := t.cardView(c) |
| 967 | if err == nil { |
| 968 | err = ErrCardConflict |
| 969 | } |
| 970 | return wire.Card{}, v, err |
| 971 | } |
| 972 | if c.Revision != in.Revision { |
| 973 | return conflict() |
| 974 | } |
| 975 | switch { |
| 976 | case c.State == wire.CardHomeAsk && in.Choice == wire.ChoiceConfirm: |
| 977 | h, err := t.hello(person) |
| 978 | if err != nil { |
| 979 | return wire.Card{}, wire.Card{}, err |
| 980 | } |
| 981 | if c.Choice != "" && !slices.Contains(h.CreateIn, c.Choice) { |
| 982 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 983 | } |
| 984 | if c.Undo, err = t.changeHome(c.Choice, person); err != nil { |
| 985 | return wire.Card{}, wire.Card{}, err |
| 986 | } |
| 987 | c.State = wire.CardHomeSet |
| 988 | case c.State == wire.CardHomeSet && in.Choice == wire.ChoiceUndo: |
| 989 | var u homeUndo |
| 990 | _, _, revision, err := t.settingRevision(settingProjectHome) |
| 991 | if err != nil { |
| 992 | return wire.Card{}, wire.Card{}, err |
| 993 | } |
| 994 | if json.Unmarshal([]byte(c.Undo), &u) != nil || u.Revision == 0 || u.Revision != revision { |
| 995 | return conflict() |
| 996 | } |
| 997 | if prev, ok := strings.CutPrefix(u.Prev, "set:"); ok { |
| 998 | _, err = t.setSetting(settingProjectHome, prev, person) |
| 999 | } else { |
| 1000 | _, err = t.unsetSetting(settingProjectHome, person) |
| 1001 | } |
| 1002 | if err != nil { |
| 1003 | return wire.Card{}, wire.Card{}, err |
| 1004 | } |
| 1005 | c.State = wire.CardUndone |
| 1006 | case c.State == wire.CardHomeAsk || c.State == wire.CardHomeSet: |
| 1007 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 1008 | default: |
| 1009 | return conflict() |
| 1010 | } |
| 1011 | if err := t.saveCard(&c); err != nil { |
| 1012 | return wire.Card{}, wire.Card{}, err |
| 1013 | } |
| 1014 | v, err := t.cardView(c) |
| 1015 | return v, wire.Card{}, err |
| 1016 | } |
| 1017 | |
| 1018 | // answerPrefix gives the coordinator the question a message answers. |
| 1019 | func (t *txn) answerPrefix(m messageRecord) (string, error) { |
| 1020 | if m.ProjectID != "" { |
| 1021 | p, err := t.messageProject(m) |
| 1022 | if err != nil { |
| 1023 | return "", err |
| 1024 | } |
| 1025 | if p.Repo == "" { |
| 1026 | return t.s.authority.Copy("projects.selection_lost") + "\n" + m.Text, nil |
| 1027 | } |
| 1028 | return fmt.Sprintf(t.s.authority.Copy("projects.selected"), p.Repo) + "\n" + m.Text, nil |
| 1029 | } |
| 1030 | var c cardRecord |
| 1031 | err := t.db.Where("person = ? AND (answer_message = ? OR id IN (SELECT card_id FROM chat_card_threads WHERE message_id = ? AND person = ?))", m.Person, m.ID, m.ID, m.Person).First(&c).Error |
| 1032 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 1033 | return m.Text, nil |
| 1034 | } |
| 1035 | if err != nil { |
| 1036 | return "", err |
| 1037 | } |
| 1038 | if c.Kind == wire.CardTask { |
| 1039 | return t.reportPrefix(c.TaskID, m.Text) |
| 1040 | } |
| 1041 | if c.Kind == wire.CardProject { |
| 1042 | v, err := t.cardView(c) |
| 1043 | if err != nil { |
| 1044 | return "", err |
| 1045 | } |
| 1046 | return "(Use this repository instead of " + v.Name + " for that work) " + m.Text, nil |
| 1047 | } |
| 1048 | if c.Placement != "" { |
| 1049 | var p placementData |
| 1050 | if err := json.Unmarshal([]byte(c.Placement), &p); err != nil { |
| 1051 | return "", err |
| 1052 | } |
| 1053 | if p.MoveTask != "" { |
| 1054 | return "Project correction for existing task " + p.MoveTask + ". Create " + p.NewRepo + " now. Equipo holds the task and will move and restart it once creation and old termination are confirmed. Do not record another task or call start_task.", nil |
| 1055 | } |
| 1056 | repo := p.NewRepo |
| 1057 | offset := 0 |
| 1058 | if p.NewFirst && p.NewRepo != "" { |
| 1059 | offset = 1 |
| 1060 | } |
| 1061 | for i, label := range p.Labels { |
| 1062 | if label == m.Text && i >= offset && i-offset < len(p.Repos) { |
| 1063 | repo = p.Repos[i-offset] |
| 1064 | } |
| 1065 | } |
| 1066 | var original []messageRecord |
| 1067 | if err := t.db.Where("turn_id = ? AND person = ? AND role = ?", c.TurnID, m.Person, wire.RolePerson).Order("seq").Find(&original).Error; err != nil { |
| 1068 | return "", err |
| 1069 | } |
| 1070 | texts := []string{} |
| 1071 | for _, v := range original { |
| 1072 | texts = append(texts, v.Text) |
| 1073 | } |
| 1074 | raw, _ := json.Marshal(texts) |
| 1075 | return "Placement confirmed for " + repo + ". Continue the original request (quoted reference): " + string(raw) + ". Answer: " + m.Text, nil |
| 1076 | } |
| 1077 | q, _ := json.Marshal(c.Question) |
| 1078 | return "(My answer to your question " + string(q) + ") " + m.Text, nil |
| 1079 | } |
| 1080 | |
| 1081 | // projectChoices are the names a project card's Change may pick: the |
| 1082 | // team's projects and the person's allowlist. |
| 1083 | func (t *txn) projectChoices(person string) ([]string, error) { |
| 1084 | allowed, err := t.allowed(person) |
| 1085 | if err != nil { |
| 1086 | return nil, err |
| 1087 | } |
| 1088 | projects, err := t.activeProjects() |
| 1089 | if err != nil { |
| 1090 | return nil, err |
| 1091 | } |
| 1092 | out := []string{} |
| 1093 | for _, r := range allowed { |
| 1094 | out = append(out, ProjectName(r)) |
| 1095 | } |
| 1096 | for _, p := range projects { |
| 1097 | if !slices.Contains(out, p.Name) { |
| 1098 | out = append(out, p.Name) |
| 1099 | } |
| 1100 | } |
| 1101 | slices.Sort(out) |
| 1102 | return out, nil |
| 1103 | } |
| 1104 | |
| 1105 | // ProjectChoices is projectChoices for the page's Change list. |
| 1106 | func (s *Store) ProjectChoices(ctx context.Context, person string) (out []string, err error) { |
| 1107 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 1108 | out, err = (&txn{s: s, db: tx}).projectChoices(person) |
| 1109 | return err |
| 1110 | }) |
| 1111 | return out, err |
| 1112 | } |
| 1113 | |
| 1114 | // snapshotCards are the person's newest Coordinator cards, oldest first. |
| 1115 | func (t *txn) snapshotCards(person string) ([]wire.Card, error) { |
| 1116 | rows, err := t.laneCards(person, wire.LaneCoordinator) |
| 1117 | if err != nil { |
| 1118 | return nil, err |
| 1119 | } |
| 1120 | out := make([]wire.Card, 0, len(rows)) |
| 1121 | for i := len(rows) - 1; i >= 0; i-- { |
| 1122 | v, err := t.cardView(rows[i]) |
| 1123 | if err != nil { |
| 1124 | return nil, err |
| 1125 | } |
| 1126 | out = append(out, v) |
| 1127 | } |
| 1128 | return out, nil |
| 1129 | } |
| 1130 | |
| 1131 | // laneCards are the person's newest visible cards in lane, newest first. |
| 1132 | func (t *txn) laneCards(person, lane string) ([]cardRecord, error) { |
| 1133 | var rows []cardRecord |
| 1134 | err := t.db.Where("person = ? AND (held IS NULL OR held = ?) AND coalesce(lane, '') = ?", person, false, lane).Order("created_at DESC, id DESC").Limit(wire.MaxProjectCards).Find(&rows).Error |
| 1135 | return rows, err |
| 1136 | } |
| 1137 | |
| 1138 | func (t *txn) activeProjects() ([]wire.Project, error) { |
| 1139 | var rows []projectRecord |
| 1140 | if err := t.db.Where("state = ?", wire.ProjectActive).Order("repo").Find(&rows).Error; err != nil { |
| 1141 | return nil, err |
| 1142 | } |
| 1143 | out := make([]wire.Project, 0, len(rows)) |
| 1144 | for _, p := range rows { |
| 1145 | v, err := t.projectView(p) |
| 1146 | if err != nil { |
| 1147 | return nil, err |
| 1148 | } |
| 1149 | out = append(out, v) |
| 1150 | } |
| 1151 | return out, nil |
| 1152 | } |
| 1153 | |