1package board
2
3import (
4 "fmt"
5
6 "github.com/git-bug/git-bug/entities/identity"
7 "github.com/git-bug/git-bug/entity"
8 "github.com/git-bug/git-bug/entity/dag"
9 "github.com/git-bug/git-bug/util/text"
10 "github.com/git-bug/git-bug/util/timestamp"
11)
12
13var _ Operation = &AddItemDraftOperation{}
14
15type AddItemDraftOperation struct {
16 dag.OpBase
17 ColumnId entity.Id `json:"column"`
18 Title string `json:"title"`
19}
20
21func (op *AddItemDraftOperation) Id() entity.Id {
22 return dag.IdOperation(op, &op.OpBase)
23}
24
25func (op *AddItemDraftOperation) Validate() error {
26 if err := op.OpBase.Validate(op, AddItemDraftOp); err != nil {
27 return err
28 }
29
30 if err := op.ColumnId.Validate(); err != nil {
31 return err
32 }
33
34 if text.Empty(op.Title) {
35 return fmt.Errorf("title is empty")
36 }
37 if !text.SafeOneLine(op.Title) {
38 return fmt.Errorf("title has unsafe characters")
39 }
40
41 return nil
42}
43
44func (op *AddItemDraftOperation) Apply(snapshot *Snapshot) {
45 // Recreate the combined Id to match on
46 combinedId := entity.CombineIds(snapshot.Id(), op.ColumnId)
47
48 // search the column
49 for _, column := range snapshot.Columns {
50 if column.CombinedId == combinedId {
51 column.Items = append(column.Items, &Draft{
52 combinedId: entity.CombineIds(snapshot.id, op.Id()),
53 author: op.Author(),
54 title: op.Title,
55 unixTime: timestamp.Timestamp(op.UnixTime),
56 })
57
58 snapshot.addActor(op.Author())
59 return
60 }
61 }
62}
63
64func NewAddItemDraftOp(author identity.Interface, unixTime int64, columnId entity.Id, title string) *AddItemDraftOperation {
65 return &AddItemDraftOperation{
66 OpBase: dag.NewOpBase(AddItemDraftOp, author, unixTime),
67 ColumnId: columnId,
68 Title: title,
69 }
70}
71
72// AddItemDraft is a convenience function to add a draft item to a Board
73func AddItemDraft(b ReadWrite, author identity.Interface, unixTime int64, columnId entity.Id, title string, metadata map[string]string) (entity.CombinedId, *AddItemDraftOperation, error) {
74 op := NewAddItemDraftOp(author, unixTime, columnId, title)
75 for key, val := range metadata {
76 op.SetMetadata(key, val)
77 }
78 if err := op.Validate(); err != nil {
79 return entity.UnsetCombinedId, nil, err
80 }
81 b.Append(op)
82 return entity.CombineIds(b.Id(), op.Id()), op, nil
83}