Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: create default organisation for signup user #617

Merged
merged 5 commits into from
Aug 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 12 additions & 115 deletions src/main/java/hng_java_boilerplate/organisation/entity/Organisation.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
import hng_java_boilerplate.util.UUIDGenarator;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.List;
Expand All @@ -15,6 +18,7 @@
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "organisations")
@Data
public class Organisation {
@Id
private String id;
Expand All @@ -29,12 +33,17 @@ public class Organisation {
private String country;
private String address;
private String state;

@CreationTimestamp
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;

@UpdateTimestamp
@Column(name = "updated_at")
private LocalDateTime updatedAt;

@ManyToOne
@JoinColumn(name = "owner_id")
private User owner;
@Column(name = "owner_id")
private String owner;

@ManyToMany(mappedBy = "organisations")
@JsonIgnore
Expand All @@ -46,116 +55,4 @@ public void prePersist() {
this.id = UUID.randomUUID().toString();
}
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public List<User> getUsers() {
return users;
}

public void setUsers(List<User> users) {
this.users = users;
}

public String getSlug() {
return slug;
}

public void setSlug(String slug) {
this.slug = slug;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getIndustry() {
return industry;
}

public void setIndustry(String industry) {
this.industry = industry;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public LocalDateTime getCreatedAt() {
return createdAt;
}

public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}

public LocalDateTime getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}

public User getOwner() {
return owner;
}

public void setOwner(User owner) {
this.owner = owner;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,9 @@ public CreateOrganisationResponseDto create(
organisation.setCountry(orgRequest.country());
organisation.setAddress(orgRequest.address());
organisation.setState(orgRequest.state());
organisation.setCreatedAt(LocalDateTime.now());
organisation.setUpdatedAt(null);
organisation.setUsers(List.of(user));
// set the user that owns the organisation.
organisation.setOwner(user);
organisation.setOwner(user.getId());

organisationRepository.save(organisation);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package hng_java_boilerplate.user.dto.response;

import hng_java_boilerplate.organisation.entity.Organisation;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.List;

@Data
@AllArgsConstructor
Expand All @@ -18,5 +20,6 @@ public class UserResponse {
private String email;
private String role;
private String imr_url;
private List<Organisation> organisations;
private LocalDateTime created_at;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import hng_java_boilerplate.exception.BadRequestException;
import hng_java_boilerplate.exception.NotFoundException;
import hng_java_boilerplate.exception.UnAuthorizedException;
import hng_java_boilerplate.organisation.entity.Organisation;
import hng_java_boilerplate.organisation.repository.OrganisationRepository;
import hng_java_boilerplate.user.dto.request.GetUserDto;
import hng_java_boilerplate.user.dto.request.LoginDto;
import hng_java_boilerplate.user.dto.request.SignupDto;
Expand All @@ -30,9 +32,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import java.util.*;

@Service
@RequiredArgsConstructor
Expand All @@ -44,6 +44,7 @@ public class UserServiceImpl implements UserDetailsService, UserService {
private final ActivityLogService activityLogService;
private final VerificationTokenRepository verificationTokenRepository;
private final EmailServiceImpl emailService;
private final OrganisationRepository organisationRepository;


@Override
Expand All @@ -67,8 +68,8 @@ public ResponseEntity<ApiResponse> registerUser(SignupDto signupDto) {
user.setUserRole(Role.ROLE_USER);
user.setEmail(signupDto.getEmail());
user.setPassword(passwordEncoder.encode(signupDto.getPassword()));

User savedUser = userRepository.save(user);
createDefaultOrganisation(savedUser);

Optional<User> createdUserCheck = userRepository.findByEmail(user.getEmail());
if (createdUserCheck.isEmpty()) {
Expand Down Expand Up @@ -160,21 +161,41 @@ public User findUser(String id) {
return userRepository.findById(id).orElseThrow(() -> new NotFoundException("User not found"));
}

// GetUserResponse method that combines both branches
public UserResponse getUserResponse(User user) {
private Map<String, String> splitName(User user){
String[] nameParts = user.getName().split(" ", 2);
String firstName = nameParts.length > 0 ? nameParts[0] : "";
String lastName = nameParts.length > 1 ? nameParts[1] : "";

Map<String, String> nameDict = new HashMap<>();
nameDict.put("firstName", firstName);
nameDict.put("lastName", lastName);
return nameDict;
}

// GetUserResponse method that combines both branches
public UserResponse getUserResponse(User user) {
Map<String, String> splitName = splitName(user);

UserResponse userResponse = new UserResponse();
userResponse.setId(user.getId());
userResponse.setFirst_name(firstName);
userResponse.setLast_name(lastName);
userResponse.setFirst_name(splitName.get("firstName"));
userResponse.setLast_name(splitName.get("lastName"));
userResponse.setEmail(user.getEmail());
userResponse.setOrganisations(user.getOrganisations());
userResponse.setCreated_at(user.getCreatedAt());
return userResponse;
}

private void createDefaultOrganisation(User user){
Organisation organisation = new Organisation();
organisation.setName(splitName(user).get("firstName") + "'s Organisation");
organisation.setOwner(user.getId());
organisation.setDescription("Default organisation for " + splitName(user).get("firstName"));
organisation.setUsers(Collections.singletonList(user));
user.setOrganisations(Collections.singletonList(organisation));
organisationRepository.save(organisation);
}

// Validate email method to check if the email already exists
private void validateEmail(String email) {
if (userRepository.existsByEmail(email)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ALTER TABLE organisations
DROP CONSTRAINT IF EXISTS organisations_owner_id_fkey, -- Drop the foreign key constraint if it exists
ALTER COLUMN owner_id TYPE VARCHAR(255);
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package hng_java_boilerplate.user.signup_unit_test;

import hng_java_boilerplate.exception.BadRequestException;
import hng_java_boilerplate.organisation.entity.Organisation;
import hng_java_boilerplate.organisation.repository.OrganisationRepository;
import hng_java_boilerplate.user.dto.request.SignupDto;
import hng_java_boilerplate.user.dto.response.ApiResponse;
import hng_java_boilerplate.user.dto.response.ResponseData;
Expand All @@ -21,6 +23,7 @@

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
Expand All @@ -38,6 +41,9 @@ class UserServiceImplTest {
@Mock
UserRepository userRepository;

@Mock
OrganisationRepository organisationRepository;

@Mock
PasswordEncoder passwordEncoder;

Expand All @@ -53,15 +59,19 @@ void setUp() {
@Test
void testRegisterUser_Success() {
SignupDto signupDto = new SignupDto("John", "Doe", "john.doe@example.com", "password123");

Organisation organisation = new Organisation();
User user = new User();
user.setId("someUserId");
user.setName(signupDto.getFirstName() + " " + signupDto.getLastName());
user.setEmail(signupDto.getEmail());
user.setPassword("encodedPassword");
user.setCreatedAt(LocalDateTime.now());
user.setOrganisations(Collections.singletonList(organisation));


when(passwordEncoder.encode(signupDto.getPassword())).thenReturn("encodedPassword");
when(organisationRepository.save(any(Organisation.class))).thenReturn(organisation);
when(userRepository.save(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0));
when(userRepository.findByEmail("john.doe@example.com")).thenReturn(Optional.of(new User()));
when(jwtUtils.createJwt.apply(any(User.class))).thenReturn("someToken");
Expand Down