feat: soft delete for interests and roles
A super admin can delete an interest or a role. Deleted rows leave every list, picker and filter, keep their names on existing leads, and keep their names reserved. A role held by any user, and the protected roles, cannot be deleted. Deletes are audited. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
0f83e9cc08
commit
0b201a51ca
25 files changed
+765
-9
No files matched your search
+1
@@ -50,6 +50,7 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace";
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}";
|
||||
public static final String API_REST_COUNTER_INTEREST_SAVE="/counter/interest/save";
|
||||
public static final String API_REST_COUNTER_INTEREST_DELETE="/counter/interest/delete";
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds";
|
||||
public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches";
|
||||
public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search";
|
||||
|
||||
+1
@@ -14,6 +14,7 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable";
|
||||
public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll";
|
||||
public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save";
|
||||
public static final String API_REST_SYSTEM_ROLE_DELETE = "/role/delete";
|
||||
public static final String API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA = "/module/findAllByArea/{area}";
|
||||
public static final String API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE = "/module/addModuleRole/{moduleId}/{roleId}";
|
||||
public static final String API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE = "/module/deleteModuleRole/{moduleId}/{roleId}";
|
||||
|
||||
+9
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.service.AdminInterestService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
@@ -44,4 +45,12 @@ public class AdminInterestController {
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable long id, @RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.update(id, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@DeleteMapping("/interests/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable long id) {
|
||||
adminInterestService.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+7
@@ -49,6 +49,13 @@ public class AdminRoleController {
|
||||
}
|
||||
@AppAuth
|
||||
@AdminModule("BO_ROLES")
|
||||
@DeleteMapping("/roles/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable Long id) {
|
||||
adminRoleService.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
@AppAuth
|
||||
@AdminModule("BO_ROLES")
|
||||
@GetMapping("/roles/{id}/modules")
|
||||
public ResponseEntity<List<AdminModuleGrant>> getModules(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(adminAclService.getGrantTree(id));
|
||||
|
||||
+1
-1
@@ -386,7 +386,7 @@ public class AdminEventLeadService {
|
||||
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
if (rows != null) for (Map<String, Object> r : rows) {
|
||||
long id = ((Number) r.get("id")).longValue();
|
||||
out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active"))));
|
||||
out.put(id, Map.of("id", id, "name", String.valueOf(r.get("name")), "active", Boolean.TRUE.equals(r.get("active")) && r.get("deletedAt") == null)); // a deleted interest keeps its name but is never offered or accepted
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
+14
-2
@@ -32,7 +32,7 @@ public class AdminInterestService {
|
||||
|
||||
public List<Map<String, Object>> list() {
|
||||
caller();
|
||||
return load().stream().map(AdminInterestService::row).toList();
|
||||
return load().stream().filter(m -> m.get("deletedAt") == null).map(AdminInterestService::row).toList();
|
||||
}
|
||||
|
||||
public Map<String, Object> create(AdminInterestRequest r) {
|
||||
@@ -47,7 +47,7 @@ public class AdminInterestService {
|
||||
public Map<String, Object> update(long id, AdminInterestRequest r) {
|
||||
scope.requireSuper(caller());
|
||||
Map<String, Object> stored = load().stream()
|
||||
.filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst()
|
||||
.filter(m -> m.get("deletedAt") == null && m.get("id") instanceof Number n && n.longValue() == id).findFirst()
|
||||
.orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null));
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("id", id);
|
||||
@@ -61,10 +61,22 @@ public class AdminInterestService {
|
||||
try {
|
||||
return row(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_SAVE), MAP, body).getBody());
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
if (e.getResponseBodyAsString().contains("INTEREST_NAME_DELETED")) {
|
||||
throw error(HttpStatus.CONFLICT, "This name belongs to a deleted interest", "INTEREST_NAME_DELETED", "name");
|
||||
}
|
||||
throw error(HttpStatus.CONFLICT, "An interest with this name already exists", "DUPLICATE_NAME", "name");
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(long id) {
|
||||
scope.requireSuper(caller());
|
||||
try {
|
||||
restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_DELETE), Void.class, id);
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null);
|
||||
}
|
||||
}
|
||||
|
||||
// ponytail: the counter ignores the company id (one shared list); 0 is a placeholder for its path variable.
|
||||
private List<Map<String, Object>> load() {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
|
||||
+32
-1
@@ -1,5 +1,7 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
@@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
@@ -30,6 +33,7 @@ import java.util.Map;
|
||||
public class AdminRoleService {
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final long SUPER_ADMIN_ROLE_ID = 1L;
|
||||
private static final List<String> HIDDEN = List.of("ROLE_MEMBER", "ROLE_ADMIN");
|
||||
private static final List<String> PROTECTED = List.of("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER");
|
||||
@@ -95,6 +99,28 @@ public class AdminRoleService {
|
||||
return clean(reread);
|
||||
}
|
||||
|
||||
public void delete(Long id) {
|
||||
scope.requireSuper(caller());
|
||||
if (isProtected(find(id))) throw error(HttpStatus.CONFLICT, "ROLE_PROTECTED", "ROLE_PROTECTED");
|
||||
try {
|
||||
restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_DELETE), Void.class, id);
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw notFound();
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
// services-system reports ROLE_IN_USE / ROLE_PROTECTED in the ProblemDetail detail; relay it with the user count
|
||||
Map<?, ?> body;
|
||||
try {
|
||||
body = JSON.readValue(e.getResponseBodyAsString(), Map.class);
|
||||
} catch (JsonProcessingException x) {
|
||||
body = Map.of();
|
||||
}
|
||||
String reason = body.get("detail") == null ? "ROLE_DELETE_REFUSED" : String.valueOf(body.get("detail"));
|
||||
CodedResponseStatusException out = error(HttpStatus.CONFLICT, reason, reason);
|
||||
if (body.get("users") != null) out.getBody().setProperty("users", body.get("users"));
|
||||
throw out;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isProtected(Map<String, Object> role) {
|
||||
return PROTECTED.contains(role.get("name"));
|
||||
}
|
||||
@@ -127,7 +153,12 @@ public class AdminRoleService {
|
||||
}
|
||||
|
||||
private Map<String, Object> save(Map<String, Object> role) {
|
||||
ResponseEntity<Map<String, Object>> ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role);
|
||||
ResponseEntity<Map<String, Object>> ent;
|
||||
try {
|
||||
ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role);
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
throw error(HttpStatus.CONFLICT, "This name belongs to a deleted role", "ROLE_NAME_DELETED");
|
||||
}
|
||||
// services-system swallows save errors and returns the unsaved entity, so a missing id means it failed.
|
||||
if (ent.getBody() == null || ent.getBody().get("id") == null) {
|
||||
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED");
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ class AdminInterestControllerTest {
|
||||
void everyHandlerIsAuthenticatedAndGuardedByBoInterests() {
|
||||
List<Method> handlers = Arrays.stream(AdminInterestController.class.getDeclaredMethods())
|
||||
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
|
||||
assertThat(handlers).hasSize(3);
|
||||
assertThat(handlers).hasSize(4);
|
||||
for (Method m : handlers) {
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
|
||||
assertThat(Arrays.asList(m.getAnnotation(AdminModule.class).value())).as(m.getName()).containsExactly("BO_INTERESTS");
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadDeletedInterestTest {
|
||||
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private AdminEventLeadService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(rest, auth, new AdminCompanyScope());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.getForEntity(eq("/counter/interest/findByCompany/{companyId}"), any(ParameterizedTypeReference.class), eq(5L)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("id", 1, "name", "Kitchen", "active", true),
|
||||
Map.of("id", 2, "name", "Old", "active", true, "deletedAt", "2026-12-01T10:00:00"))));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
@Test
|
||||
void deletedInterestIsNotOfferedButItsNameStillResolves() {
|
||||
assertThat(service.interestOptions()).extracting(m -> m.get("name")).containsExactly("Kitchen");
|
||||
assertThat(service.interests(5L).get(2L)).containsEntry("name", "Old").containsEntry("active", false);
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminInterestDeleteTest {
|
||||
|
||||
private static final String LIST = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String SAVE = "/counter/interest/save";
|
||||
private static final String DELETE = "/counter/interest/delete";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminInterestService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private User caller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminInterestService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
caller = new User();
|
||||
caller.setUsername("boss");
|
||||
com.solvway.core.model.Role r = new com.solvway.core.model.Role();
|
||||
r.setId(1L);
|
||||
caller.setRoles(new ArrayList<>(List.of(r)));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private static Map<String, Object> row(long id, String name, String deletedAt) {
|
||||
Map<String, Object> m = new java.util.HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
m.put("active", true);
|
||||
m.put("sortOrder", 0);
|
||||
m.put("deletedAt", deletedAt);
|
||||
return m;
|
||||
}
|
||||
|
||||
private static HttpClientErrorException conflict(String body) {
|
||||
return HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", HttpHeaders.EMPTY,
|
||||
body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static void assertCoded(Runnable call, HttpStatus status, String code) {
|
||||
assertThatThrownBy(call::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", code);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void listSkipsDeletedInterests() {
|
||||
when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(0L)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(row(1, "Kitchen", null), row(2, "Old", "2026-12-01T10:00:00"))));
|
||||
assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("Kitchen");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfDeletedInterestIsNotFound() {
|
||||
when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(0L)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(row(2, "Old", "2026-12-01T10:00:00"))));
|
||||
assertCoded(() -> service.update(2L, new AdminInterestRequest("New", null, null)), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithDeletedNameReportsNameDeleted() {
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(conflict("{\"detail\":\"INTEREST_NAME_DELETED\"}"));
|
||||
assertCoded(() -> service.create(new AdminInterestRequest("Old", null, null)), HttpStatus.CONFLICT, "INTEREST_NAME_DELETED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithDuplicateNameStillReportsDuplicate() {
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(conflict("{\"detail\":\"DUPLICATE_NAME\"}"));
|
||||
assertCoded(() -> service.create(new AdminInterestRequest("Kitchen", null, null)), HttpStatus.CONFLICT, "DUPLICATE_NAME");
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminDeletesThroughTheCounter() {
|
||||
service.delete(5L);
|
||||
verify(rest).postForEntity(eq(DELETE), eq(Void.class), eq(5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void companyUserIsRefusedAndNothingIsPosted() {
|
||||
caller.setCompanyId(7L);
|
||||
com.solvway.core.model.Role staff = new com.solvway.core.model.Role();
|
||||
staff.setId(4L);
|
||||
caller.setRoles(new ArrayList<>(List.of(staff)));
|
||||
assertCoded(() -> service.delete(5L), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrDeletedInterestIsNotFound() {
|
||||
when(rest.postForEntity(eq(DELETE), eq(Void.class), any())).thenThrow(
|
||||
HttpClientErrorException.create(HttpStatus.NOT_FOUND, "Not Found", HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8));
|
||||
assertCoded(() -> service.delete(9L), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND");
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminRoleDeleteTest {
|
||||
|
||||
private static final String DELETE = "/role/delete";
|
||||
private static final String SAVE = "/role/save";
|
||||
private static final String FIND_ALL = "/role/findAll";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminRoleService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private User caller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminRoleService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
caller = new User();
|
||||
caller.setUsername("boss");
|
||||
com.solvway.core.model.Role r = new com.solvway.core.model.Role();
|
||||
r.setId(1L);
|
||||
caller.setRoles(new ArrayList<>(List.of(r)));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))).thenReturn(org.springframework.http.ResponseEntity.ok(
|
||||
List.of(java.util.Map.of("id", 5, "name", "Sales"), java.util.Map.of("id", 9, "name", "Ops"))));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private static HttpClientErrorException http(HttpStatus status, String body) {
|
||||
return HttpClientErrorException.create(status, status.getReasonPhrase(), HttpHeaders.EMPTY,
|
||||
body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException thrown(Runnable call) {
|
||||
assertThatThrownBy(call::run).isInstanceOf(CodedResponseStatusException.class);
|
||||
try {
|
||||
call.run();
|
||||
} catch (CodedResponseStatusException e) {
|
||||
return e;
|
||||
}
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminDeletesThroughSystem() {
|
||||
service.delete(5L);
|
||||
verify(rest).postForEntity(eq(DELETE), eq(Void.class), eq(5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void companyUserIsRefusedAndNothingIsPosted() {
|
||||
caller.setCompanyId(7L);
|
||||
com.solvway.core.model.Role staff = new com.solvway.core.model.Role();
|
||||
staff.setId(4L);
|
||||
caller.setRoles(new ArrayList<>(List.of(staff)));
|
||||
CodedResponseStatusException e = thrown(() -> service.delete(5L));
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "SUPER_ADMIN_REQUIRED");
|
||||
verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrDeletedRoleIsNotFound() {
|
||||
when(rest.postForEntity(eq(DELETE), eq(Void.class), any())).thenThrow(http(HttpStatus.NOT_FOUND, ""));
|
||||
CodedResponseStatusException e = thrown(() -> service.delete(9L));
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_NOT_FOUND");
|
||||
}
|
||||
|
||||
@Test
|
||||
void protectedNamedRolesAreRefusedBeforeCallingSystem() {
|
||||
for (String name : List.of("ROLE_MEMBER", "ROLE_ADMIN", "ROLE_SUPER_ADMIN")) {
|
||||
when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(org.springframework.http.ResponseEntity.ok(List.of(java.util.Map.of("id", 3, "name", name))));
|
||||
CodedResponseStatusException e = thrown(() -> service.delete(3L));
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_PROTECTED");
|
||||
}
|
||||
verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleInUseRelaysReasonAndUserCount() {
|
||||
when(rest.postForEntity(eq(DELETE), eq(Void.class), any()))
|
||||
.thenThrow(http(HttpStatus.CONFLICT, "{\"detail\":\"ROLE_IN_USE\",\"users\":3}"));
|
||||
CodedResponseStatusException e = thrown(() -> service.delete(5L));
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getReason()).isEqualTo("ROLE_IN_USE");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_IN_USE").containsEntry("users", 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void protectedRoleRelaysReason() {
|
||||
when(rest.postForEntity(eq(DELETE), eq(Void.class), any()))
|
||||
.thenThrow(http(HttpStatus.CONFLICT, "{\"detail\":\"ROLE_PROTECTED\"}"));
|
||||
CodedResponseStatusException e = thrown(() -> service.delete(5L));
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_PROTECTED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithDeletedNameReportsNameDeleted() {
|
||||
when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))).thenReturn(org.springframework.http.ResponseEntity.ok(List.of()));
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(http(HttpStatus.CONFLICT, "{\"detail\":\"ROLE_NAME_DELETED\"}"));
|
||||
CodedResponseStatusException e = thrown(() -> service.create(new AdminRoleRequest("Old")));
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "ROLE_NAME_DELETED");
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class DeleteAuditActionTest {
|
||||
@Test
|
||||
void deleteHandlersAuditAsInterestAndRoleDelete() {
|
||||
assertThat(AppAccessAspect.defaultAuditAction("AdminInterestController", "delete")).isEqualTo("INTEREST_DELETE");
|
||||
assertThat(AppAccessAspect.defaultAuditAction("AdminRoleController", "delete")).isEqualTo("ROLE_DELETE");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user