Create creates a new group in the specified organization.
(ctx context.Context, orgID uuid.UUID, opts *biz.CreateGroupOpts)
| 240 | |
| 241 | // Create creates a new group in the specified organization. |
| 242 | func (g GroupRepo) Create(ctx context.Context, orgID uuid.UUID, opts *biz.CreateGroupOpts) (*biz.Group, error) { |
| 243 | ctx, span := otelx.Start(ctx, groupRepoTracer, "GroupRepo.Create") |
| 244 | defer span.End() |
| 245 | |
| 246 | if opts == nil { |
| 247 | return nil, biz.NewErrValidationStr("create group options cannot be nil") |
| 248 | } |
| 249 | |
| 250 | var entGroup ent.Group |
| 251 | |
| 252 | err := WithTx(ctx, g.data.DB, func(tx *ent.Tx) error { |
| 253 | // Create the group with the provided options |
| 254 | gr, err := tx.Group.Create(). |
| 255 | SetName(opts.Name). |
| 256 | SetDescription(opts.Description). |
| 257 | SetOrganizationID(orgID).Save(ctx) |
| 258 | if err != nil { |
| 259 | if ent.IsConstraintError(err) { |
| 260 | return biz.NewErrAlreadyExistsStr("group with the same name already exists") |
| 261 | } |
| 262 | return err |
| 263 | } |
| 264 | |
| 265 | // Only add memberships if userID is not nil |
| 266 | if opts.UserID != nil { |
| 267 | // Set user as group maintainer |
| 268 | if _, err = tx.GroupMembership.Create(). |
| 269 | SetGroupID(gr.ID). |
| 270 | SetUserID(*opts.UserID). |
| 271 | SetMaintainer(true). |
| 272 | Save(ctx); err != nil { |
| 273 | return err |
| 274 | } |
| 275 | |
| 276 | // Update the user membership with the role of maintainer |
| 277 | _, err = tx.Membership.Create(). |
| 278 | SetUserID(*opts.UserID). |
| 279 | SetOrganizationID(orgID). |
| 280 | SetRole(authz.RoleGroupMaintainer). |
| 281 | SetMembershipType(authz.MembershipTypeUser). |
| 282 | SetMemberID(*opts.UserID). |
| 283 | SetResourceType(authz.ResourceTypeGroup). |
| 284 | SetResourceID(gr.ID). |
| 285 | Save(ctx) |
| 286 | if err != nil { |
| 287 | return fmt.Errorf("failed to create membership for user %s in group %s: %w", *opts.UserID, gr.ID, err) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | entGroup = *gr |
| 292 | |
| 293 | return nil |
| 294 | }) |
| 295 | if err != nil { |
| 296 | return nil, fmt.Errorf("failed to create group: %w", err) |
| 297 | } |
| 298 | |
| 299 | // Update the member count based on actual query |
nothing calls this directly
no test coverage detected