From 755ee7b2ea798cbda9377b2c561367e3354eb732 Mon Sep 17 00:00:00 2001 From: Rainnny7 Date: Wed, 18 Sep 2024 00:07:26 -0400 Subject: [PATCH] org creation --- .../api/service/OrganizationService.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/main/java/cc/pulseapp/api/service/OrganizationService.java diff --git a/src/main/java/cc/pulseapp/api/service/OrganizationService.java b/src/main/java/cc/pulseapp/api/service/OrganizationService.java new file mode 100644 index 0000000..02e31e6 --- /dev/null +++ b/src/main/java/cc/pulseapp/api/service/OrganizationService.java @@ -0,0 +1,62 @@ +package cc.pulseapp.api.service; + +import cc.pulseapp.api.exception.impl.BadRequestException; +import cc.pulseapp.api.model.Feature; +import cc.pulseapp.api.model.IGenericResponse; +import cc.pulseapp.api.model.org.Organization; +import cc.pulseapp.api.model.user.User; +import cc.pulseapp.api.repository.OrganizationRepository; +import jakarta.annotation.Nonnull; +import lombok.NonNull; +import org.springframework.stereotype.Service; + +/** + * @author Braydon + */ +@Service +public final class OrganizationService { + /** + * The service to use for snowflake generation. + */ + @NonNull private final SnowflakeService snowflakeService; + + /** + * The repository to store and retrieve organizations. + */ + @NonNull private final OrganizationRepository orgRepository; + + private OrganizationService(@NonNull SnowflakeService snowflakeService, @NonNull OrganizationRepository orgRepository) { + this.snowflakeService = snowflakeService; + this.orgRepository = orgRepository; + } + + /** + * Create a new organization. + * + * @param name the org name + * @param owner the owner of the org + * @return the created org + * @throws BadRequestException if the org creation fails + */ + @NonNull + public Organization createOrganization(@Nonnull String name, @NonNull User owner) throws BadRequestException { + // Ensure org creation is enabled + if (!Feature.ORG_CREATION_ENABLED.isEnabled()) { + throw new BadRequestException(Error.ORG_CREATION_DISABLED); + } + // Ensure the org name isn't taken + if (orgRepository.findByNameIgnoreCase(name) != null) { + throw new BadRequestException(Error.ORG_NAME_TAKEN); + } + // Create the org and return it + return orgRepository.save(new Organization(snowflakeService.generateSnowflake(), name, owner.getSnowflake())); + } + + /** + * Organization errors. + */ + private enum Error implements IGenericResponse { + ORG_CREATION_DISABLED, + ORG_NAME_TAKEN + } +} \ No newline at end of file