| 1 | package store |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | |
| 8 | "gitlab.com/Timfa/bluegit/internal/access" |
| 9 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 10 | ) |
| 11 | |
| 12 | // TransferGroupOwner maakt toID de eigenaar. De vorige eigenaar blijft beheerder. |
| 13 | // toID moet al lid zijn. |
| 14 | func (s *Store) TransferGroupOwner(ctx context.Context, groupID, fromID, toID int64) error { |
| 15 | if fromID == 0 || toID == 0 || fromID == toID { |
| 16 | return i18n.E("err.ownerSame") |
| 17 | } |
| 18 | g, err := s.GroupByID(ctx, groupID) |
| 19 | if err != nil { |
| 20 | return err |
| 21 | } |
| 22 | if g.OwnerID != fromID { |
| 23 | return i18n.E("err.ownerOnly") |
| 24 | } |
| 25 | var role string |
| 26 | err = s.db.QueryRowContext(ctx, `SELECT role FROM group_members WHERE group_id = ? AND user_id = ?`, groupID, toID).Scan(&role) |
| 27 | if errors.Is(err, sql.ErrNoRows) { |
| 28 | return i18n.E("err.ownerMember") |
| 29 | } |
| 30 | if err != nil { |
| 31 | return err |
| 32 | } |
| 33 | tx, err := s.db.BeginTx(ctx, nil) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | defer func() { _ = tx.Rollback() }() |
| 38 | if _, err := tx.ExecContext(ctx, `UPDATE groups SET owner_id = ? WHERE id = ?`, toID, groupID); err != nil { |
| 39 | return err |
| 40 | } |
| 41 | if _, err := tx.ExecContext(ctx, `INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, ?) |
| 42 | ON CONFLICT(group_id, user_id) DO UPDATE SET role = ?`, groupID, fromID, string(access.RoleMaintainer), string(access.RoleMaintainer)); err != nil { |
| 43 | return err |
| 44 | } |
| 45 | if _, err := tx.ExecContext(ctx, `UPDATE group_members SET role = ? WHERE group_id = ? AND user_id = ?`, string(access.RoleMaintainer), groupID, toID); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | return tx.Commit() |
| 49 | } |