Normalize users #55

Merged
RecentRunner merged 8 commits from backend-normalize-users-payments into main 2026-03-29 22:40:13 -06:00
2 changed files with 38 additions and 11 deletions
Showing only changes of commit 2cacf1f852 - Show all commits

View File

@@ -60,15 +60,7 @@ public class CustomerService {
customer.setEmail(request.getEmail());
customer = customerRepository.save(customer);
Customer savedCustomer = customer;
User user = userRepository.findByEmail(savedCustomer.getEmail())
.map(existing -> {
if (existing.getRole() != User.Role.CUSTOMER) {
throw new ResponseStatusException(CONFLICT, "Email already exists for a different account type");
}
return existing;
})
.orElseGet(() -> createLinkedUser(savedCustomer));
User user = createLinkedUser(customer);
Customer linkedCustomer = userBusinessLinkageService.ensureLinkedCustomer(user);
syncLinkedUser(linkedCustomer);
@@ -93,9 +85,14 @@ public class CustomerService {
@Transactional
public void deleteCustomer(Long id) {
if (!customerRepository.existsById(id)) {
throw new ResourceNotFoundException("Customer not found with id: " + id);
Customer customer = customerRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Customer not found with id: " + id));
if (customer.getUserId() != null && userRepository.existsById(customer.getUserId())) {
userRepository.deleteById(customer.getUserId());
return;
}
customerRepository.deleteById(id);
}

View File

@@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -147,4 +148,33 @@ class CustomerServiceTest {
assertThrows(ResponseStatusException.class, () -> customerService.updateCustomer(7L, request));
}
@Test
void deleteCustomerDeletesLinkedUser() {
Customer customer = new Customer();
customer.setCustomerId(7L);
customer.setUserId(11L);
when(customerRepository.findById(7L)).thenReturn(Optional.of(customer));
when(userRepository.existsById(11L)).thenReturn(true);
customerService.deleteCustomer(7L);
verify(userRepository).deleteById(11L);
verify(customerRepository, never()).deleteById(7L);
}
@Test
void deleteCustomerDeletesCustomerWhenNoLinkedUserExists() {
Customer customer = new Customer();
customer.setCustomerId(7L);
customer.setUserId(11L);
when(customerRepository.findById(7L)).thenReturn(Optional.of(customer));
when(userRepository.existsById(11L)).thenReturn(false);
customerService.deleteCustomer(7L);
verify(customerRepository).deleteById(7L);
}
}