| 1 | package planning |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "gorm.io/gorm" |
| 8 | "strconv" |
| 9 | "unicode/utf8" |
| 10 | ) |
| 11 | |
| 12 | type ProjectRules struct { |
| 13 | ProjectID int64 `gorm:"primaryKey;autoIncrement:false"` |
| 14 | Text string |
| 15 | Revision int64 |
| 16 | } |
| 17 | |
| 18 | func (ProjectRules) TableName() string { return "project_rules" } |
| 19 | func (s *Application) SaveProjectRules(ctx context.Context, a kernel.Actor, id int64, text string, m kernel.Mutation) error { |
| 20 | return s.Write(ctx, func(tx *gorm.DB) error { return s.At(tx).SetProjectRules(a, id, text, m) }) |
| 21 | } |
| 22 | func (s *Store) SetProjectRules(a kernel.Actor, id int64, text string, m kernel.Mutation) error { |
| 23 | if err := s.deps.Member(s.tx, a, true); err != nil { |
| 24 | return err |
| 25 | } |
| 26 | if err := s.deps.Project(s.tx, id); err != nil { |
| 27 | return err |
| 28 | } |
| 29 | if !utf8.ValidString(text) || len(text) > 16384 { |
| 30 | return s.deps.Invalid |
| 31 | } |
| 32 | var result bool |
| 33 | q, replay, err := s.request(a, "project.rules", strconv.FormatInt(id, 10), m, struct { |
| 34 | Text string |
| 35 | Revision int64 |
| 36 | }{text, m.Revision}, &result) |
| 37 | if err != nil || replay { |
| 38 | return err |
| 39 | } |
| 40 | var row ProjectRules |
| 41 | err = s.tx.First(&row, "project_id=?", id).Error |
| 42 | fresh := errors.Is(err, gorm.ErrRecordNotFound) |
| 43 | if err != nil && !fresh { |
| 44 | return err |
| 45 | } |
| 46 | if row.Revision != m.Revision { |
| 47 | return s.deps.Conflict |
| 48 | } |
| 49 | row.ProjectID = id |
| 50 | row.Text = text |
| 51 | row.Revision++ |
| 52 | if fresh { |
| 53 | err = s.tx.Create(&row).Error |
| 54 | } else { |
| 55 | err = s.tx.Model(&ProjectRules{}).Where("project_id=?", id).Select("text", "revision").Updates(&row).Error |
| 56 | } |
| 57 | if err != nil { |
| 58 | return err |
| 59 | } |
| 60 | if err = s.deps.Audit(s.tx, a, "project.rules", strconv.FormatInt(id, 10)); err != nil { |
| 61 | return err |
| 62 | } |
| 63 | return s.save(q, true) |
| 64 | } |
| 65 | |