| 1 | package library |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | |
| 7 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 8 | "gorm.io/gorm" |
| 9 | ) |
| 10 | |
| 11 | type PlaybookSuggestion struct { |
| 12 | ID string `gorm:"primaryKey"` |
| 13 | PlaybookID string |
| 14 | } |
| 15 | |
| 16 | func (s *Store) PlaybookSuggestion(actor kernel.Actor, id string) (string, int64, error) { |
| 17 | a, err := s.deps.Authorize(s.tx, actor) |
| 18 | if err != nil { |
| 19 | return "", 0, err |
| 20 | } |
| 21 | var row struct { |
| 22 | Body string |
| 23 | Revision int64 |
| 24 | } |
| 25 | err = s.tx.Table("conversation_messages m").Select("m.body,m.revision").Joins("JOIN conversations c ON c.id=m.conversation_id").Joins("JOIN conversation_cards card ON card.resource_id=m.id AND card.stream_id=c.id").Where("m.id=? AND c.person=? AND c.team_id=? AND m.author_kind='coordinator' AND card.kind='suggest_playbook'", id, actor.Address, a.TeamID).Take(&row).Error |
| 26 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 27 | err = s.deps.NotFound |
| 28 | } |
| 29 | return row.Body, row.Revision, err |
| 30 | } |
| 31 | func (s *Store) SavePlaybookSuggestion(actor kernel.Actor, id string, in PlaybookInput, m kernel.Mutation) (Playbook, error) { |
| 32 | a, err := s.deps.Authorize(s.tx, actor) |
| 33 | if err != nil { |
| 34 | return Playbook{}, err |
| 35 | } |
| 36 | _, rev, err := s.PlaybookSuggestion(actor, id) |
| 37 | if err != nil { |
| 38 | return Playbook{}, err |
| 39 | } |
| 40 | q, old, replay, err := s.playbookReplay(a, actor, "playbook.suggestion_save", id, m, in) |
| 41 | if err != nil || replay { |
| 42 | return old, err |
| 43 | } |
| 44 | if rev != m.Revision { |
| 45 | return Playbook{}, s.deps.Conflict |
| 46 | } |
| 47 | if in.ID != "" || in.Template != (TemplateRef{}) { |
| 48 | return Playbook{}, s.deps.Invalid |
| 49 | } |
| 50 | var saved PlaybookSuggestion |
| 51 | err = s.tx.Where("id=?", id).First(&saved).Error |
| 52 | if err == nil { |
| 53 | return Playbook{}, s.deps.Conflict |
| 54 | } |
| 55 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 56 | return Playbook{}, err |
| 57 | } |
| 58 | row, err := s.writePlaybook(a, actor, Playbook{}, in, kernel.Mutation{RequestID: m.RequestID}, q) |
| 59 | if err != nil { |
| 60 | return Playbook{}, err |
| 61 | } |
| 62 | return row, s.tx.Create(&PlaybookSuggestion{ID: id, PlaybookID: row.ID}).Error |
| 63 | } |
| 64 | func suggestionDraft(raw string) (name, instructions string) { |
| 65 | var v struct { |
| 66 | Draft struct{ Name, Instructions string } |
| 67 | } |
| 68 | _ = json.Unmarshal([]byte(raw), &v) |
| 69 | return v.Draft.Name, v.Draft.Instructions |
| 70 | } |
| 71 | |