| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/setup" |
| 6 | "context" |
| 7 | "net/mail" |
| 8 | "strings" |
| 9 | |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | func normalizeAddress(address string) string { return strings.ToLower(strings.TrimSpace(address)) } |
| 14 | |
| 15 | func validAddress(address string) bool { |
| 16 | parsed, err := mail.ParseAddress(address) |
| 17 | return err == nil && parsed.Address == address && strings.Contains(address, "@") |
| 18 | } |
| 19 | |
| 20 | func (s *Store) Bootstrap(ctx context.Context, owners []string) error { |
| 21 | return s.write(ctx, func(tx *gorm.DB) error { |
| 22 | return s.invitationsAt(tx).Bootstrap(owners) |
| 23 | }) |
| 24 | } |
| 25 | |
| 26 | func memberAt(tx *gorm.DB, address string) (Member, error) { |
| 27 | var member Member |
| 28 | err := tx.Where("address = ?", normalizeAddress(address)).First(&member).Error |
| 29 | return member, storeError(err) |
| 30 | } |
| 31 | |
| 32 | func (s *Store) Member(ctx context.Context, address string) (Member, error) { |
| 33 | if s == nil || s.db == nil { |
| 34 | return Member{}, ErrUnavailable |
| 35 | } |
| 36 | return memberAt(s.db.G.WithContext(ctx), address) |
| 37 | } |
| 38 | |
| 39 | func requireOwner(tx *gorm.DB, actor Actor) error { |
| 40 | return setup.CurrentOwner(tx, actor, memberAt, ErrNotFound, ErrForbidden) |
| 41 | } |
| 42 | |
| 43 | func (s *Store) SetMember(ctx context.Context, actor Actor, address string, role Role, active bool, revision int64) error { |
| 44 | address = normalizeAddress(address) |
| 45 | if !validAddress(address) || (role != RoleOwner && role != RoleMember) || revision < 0 { |
| 46 | return ErrInvalid |
| 47 | } |
| 48 | return s.write(ctx, func(tx *gorm.DB) error { |
| 49 | if err := requireOwner(tx, actor); err != nil { |
| 50 | return err |
| 51 | } |
| 52 | var ack personapi.Ack |
| 53 | if replay, err := personapi.Replay(tx, ctx, &ack, ErrConflict); err != nil || replay { |
| 54 | return err |
| 55 | } |
| 56 | if err := s.invitationsAt(tx).SetMember(actor, address, role, active, revision); err != nil { |
| 57 | return err |
| 58 | } |
| 59 | return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: revision + 1}, ErrConflict) |
| 60 | }) |
| 61 | } |
| 62 | |