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:
ngqileandClaude Opus 5.5 committed 2026-12-02 02:08:28 +08:00
1 parent 0f83e9cc08
commit 0b201a51ca
25 files changed
+765 -9

No files matched your search

@@ -10,7 +10,7 @@ Verify commands:
- Depends on: none
- Scope: `openspec/changes/polish-e2e-followups/sql/**`, `local/seed/**`
- Verify: seed load in a throwaway MySQL with the compose flags; `SHOW COLUMNS` lists `deleted_at` on both tables.
- [ ] 2. Soft delete backend:
- [x] 2. Soft delete backend:
- Interest delete in counter. Lists, capture options and filters exclude deleted rows. Lead views keep the name. The deleted-name duplicate error is a distinct reason.
- Role delete in system, refused with `ROLE_IN_USE` and a count while any user holds the role. The role list and user role picker exclude deleted rows. Deleted-name reason.
- mobile-api admin endpoints `DELETE /api/admin/interests/{id}` and `DELETE /api/admin/roles/{id}`, super admin only, audited.
@@ -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";
@@ -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}";
@@ -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();
}
}
@@ -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));
@@ -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;
}
@@ -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(
@@ -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");
@@ -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");
@@ -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);
}
}
@@ -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");
}
}
@@ -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");
}
}
@@ -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");
}
}
@@ -24,6 +24,11 @@ public class InterestController {
return interestService.save(interest);
}
@PostMapping("/delete")
public void delete(@RequestBody Long id) {
interestService.delete(id);
}
@PostMapping("/findByIds")
public List<Interest> findByIds(@RequestBody InterestFindByIdsRequest body) {
return interestService.findByIds(body.companyId(), body.ids());
@@ -4,6 +4,8 @@ import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@@ -21,4 +23,7 @@ public class Interest {
private boolean active = true;
private int sortOrder;
/** Soft delete: the row stays so tagged leads keep resolving the name, and the name stays reserved. */
private LocalDateTime deletedAt;
}
@@ -13,5 +13,7 @@ public interface InterestRepository extends JpaRepository<Interest, Long> {
boolean existsByNameIgnoreCase(String name);
boolean existsByNameIgnoreCaseAndDeletedAtIsNotNull(String name);
List<Interest> findByIdIn(Collection<Long> ids);
}
@@ -9,6 +9,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
@Service
@@ -16,6 +17,7 @@ import java.util.List;
public class InterestService {
private final InterestRepository interestRepository;
/** Every row, deleted ones included (flagged by deletedAt): lead views resolve a deleted interest's name through this list. Consumers filter what they offer. */
public List<Interest> findByCompany(long companyId) {
return interestRepository.findAllByOrderBySortOrderAscNameAsc();
}
@@ -39,7 +41,7 @@ public class InterestService {
// Create: names are unique across the one shared list
interest.setCompanyId(null);
if (interestRepository.existsByNameIgnoreCase(trimmedName)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME");
throw nameTaken(trimmedName);
}
return interestRepository.saveAndFlush(interest);
} else {
@@ -48,7 +50,7 @@ public class InterestService {
interest.setCompanyId(existing.getCompanyId());
if (!existing.getName().equalsIgnoreCase(trimmedName)
&& interestRepository.existsByNameIgnoreCase(trimmedName)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME");
throw nameTaken(trimmedName);
}
return interestRepository.saveAndFlush(interest);
}
@@ -57,6 +59,20 @@ public class InterestService {
}
}
@Transactional
public void delete(Long id) {
Interest interest = interestRepository.findById(id)
.filter(i -> i.getDeletedAt() == null)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
interest.setDeletedAt(LocalDateTime.now());
interestRepository.save(interest);
}
private ResponseStatusException nameTaken(String name) {
return new ResponseStatusException(HttpStatus.CONFLICT,
interestRepository.existsByNameIgnoreCaseAndDeletedAtIsNotNull(name) ? "INTEREST_NAME_DELETED" : "DUPLICATE_NAME");
}
public List<Interest> findByIds(long companyId, List<Long> ids) {
if (ids == null || ids.isEmpty()) {
return List.of();
@@ -0,0 +1,23 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.service.InterestService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class InterestControllerDeleteTest {
@Mock
private InterestService interestService;
@Test
void deleteDelegatesToService() {
new InterestController(interestService).delete(7L);
verify(interestService).delete(7L);
}
}
@@ -0,0 +1,109 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Interest;
import com.solvway.services.counter.repo.InterestRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.Optional;
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.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Soft delete of interests: delete, 404s, and names of deleted interests staying reserved. */
@ExtendWith(MockitoExtension.class)
class InterestServiceDeleteTest {
@Mock
private InterestRepository repository;
private InterestService service;
@BeforeEach
void setUp() {
service = new InterestService(repository);
}
@Test
void deleteStampsDeletedAt() {
Interest row = interest(5L, "Cookware");
when(repository.findById(5L)).thenReturn(Optional.of(row));
service.delete(5L);
assertThat(row.getDeletedAt()).isNotNull();
verify(repository).save(row);
}
@Test
void deleteUnknownIs404() {
when(repository.findById(9L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.delete(9L))
.isInstanceOf(ResponseStatusException.class)
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND);
verify(repository, never()).save(any());
}
@Test
void deleteAlreadyDeletedIs404() {
Interest row = interest(5L, "Cookware");
LocalDateTime when = LocalDateTime.of(2026, 1, 1, 0, 0);
row.setDeletedAt(when);
when(repository.findById(5L)).thenReturn(Optional.of(row));
assertThatThrownBy(() -> service.delete(5L))
.isInstanceOf(ResponseStatusException.class)
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND);
assertThat(row.getDeletedAt()).isEqualTo(when);
verify(repository, never()).save(any());
}
@Test
void createWithDeletedNameIsRefusedAsNameDeleted() {
when(repository.existsByNameIgnoreCase("Cookware")).thenReturn(true);
when(repository.existsByNameIgnoreCaseAndDeletedAtIsNotNull("Cookware")).thenReturn(true);
assertThatThrownBy(() -> service.save(interest(null, "Cookware")))
.isInstanceOf(ResponseStatusException.class)
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT)
.hasMessageContaining("INTEREST_NAME_DELETED");
}
@Test
void renameToDeletedNameIsRefusedAsNameDeleted() {
when(repository.findById(10L)).thenReturn(Optional.of(interest(10L, "Old")));
when(repository.existsByNameIgnoreCase("Cookware")).thenReturn(true);
when(repository.existsByNameIgnoreCaseAndDeletedAtIsNotNull("Cookware")).thenReturn(true);
assertThatThrownBy(() -> service.save(interest(10L, "Cookware")))
.isInstanceOf(ResponseStatusException.class)
.hasMessageContaining("INTEREST_NAME_DELETED");
}
@Test
void liveDuplicateStaysDuplicateName() {
when(repository.existsByNameIgnoreCase("Cookware")).thenReturn(true);
assertThatThrownBy(() -> service.save(interest(null, "Cookware")))
.isInstanceOf(ResponseStatusException.class)
.hasMessageContaining("DUPLICATE_NAME");
}
private static Interest interest(Long id, String name) {
Interest i = new Interest();
i.setId(id);
i.setName(name);
return i;
}
}
@@ -6,6 +6,7 @@ import com.solvway.services.system.service.RoleService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -43,8 +44,14 @@ public class RoleController {
return role.get();
}
@PostMapping("/delete")
public void delete(@RequestBody Long id) {
roleService.delete(id);
}
@RequestMapping("/save")
public Role save(@RequestBody Role role) {
roleService.requireNameNotDeleted(role);
try {
RoleParent roleParent= modelMapper.map(findById(role.getParent().getId()),RoleParent.class);
role.setParent(roleParent);
@@ -41,4 +41,7 @@ public class Role {
private String doneBy;
private Timestamp createDate;
/** Soft delete: the row stays and its name stays reserved. */
private Timestamp deletedAt;
}
@@ -8,6 +8,11 @@ import java.util.List;
public interface RoleRepository extends JpaRepository<Role, Long> {
Role findByName(String name);
List<Role> findByDeletedAtIsNull();
boolean existsByNameIgnoreCaseAndDeletedAtIsNotNull(String name);
@Query("SELECT r FROM Role r where parent.id = :parentId")
List<Role> findByParent(String parentId);
}
@@ -110,4 +110,7 @@ public interface UserRepository extends JpaRepository<User, Long>, JpaRepository
@Query("select u from User u join u.roles r where r.name= :roleName")
List<User> findUserByRoleName(@Param("roleName")String roleName);
@Query("select count(u) from User u join u.roles r where r.id = :roleId")
long countByRoleId(@Param("roleId") Long roleId);
}
@@ -4,10 +4,14 @@ import com.solvway.services.system.model.Role;
import com.solvway.services.system.model.RoleParent;
import com.solvway.services.system.repo.ModuleRepository;
import com.solvway.services.system.repo.RoleRepository;
import com.solvway.services.system.repo.UserRepository;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
@@ -21,9 +25,35 @@ public class RoleService {
@Autowired
private ModelMapper modelMapper;
@Autowired
private UserRepository userRepository;
/** Live roles only: deleted ones leave the role list and the user role picker. */
public List<Role> findAll() {
return roleRepository.findAll();
return roleRepository.findByDeletedAtIsNull();
}
public void delete(Long id) {
Role role = roleRepository.findById(id).filter(r -> r.getDeletedAt() == null)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
if (id == 1L || List.of("ROLE_ADMIN", "ROLE_MEMBER").contains(role.getName())) { // 1 = ROLE_SUPER_ADMIN, seeded
throw new ResponseStatusException(HttpStatus.CONFLICT, "ROLE_PROTECTED");
}
long users = userRepository.countByRoleId(id);
if (users > 0) {
ResponseStatusException e = new ResponseStatusException(HttpStatus.CONFLICT, "ROLE_IN_USE");
e.getBody().setProperty("users", users);
throw e;
}
role.setDeletedAt(new Timestamp(System.currentTimeMillis()));
roleRepository.save(role);
}
public void requireNameNotDeleted(Role role) {
if (role.getName() != null && roleRepository.existsByNameIgnoreCaseAndDeletedAtIsNotNull(role.getName())) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "ROLE_NAME_DELETED");
}
}
public Role findByName(String name) {
@@ -0,0 +1,135 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.Role;
import com.solvway.services.system.repo.RoleRepository;
import com.solvway.services.system.repo.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
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.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Soft delete of roles: list exclusion, in-use and protected refusals, 404s, reserved names. */
@ExtendWith(MockitoExtension.class)
class RoleServiceDeleteTest {
@Mock
private RoleRepository roleRepository;
@Mock
private UserRepository userRepository;
@InjectMocks
private RoleService service;
@Test
void findAllExcludesDeletedRoles() {
Role live = role(5L, "ROLE_SALES");
when(roleRepository.findByDeletedAtIsNull()).thenReturn(List.of(live));
assertThat(service.findAll()).containsExactly(live);
}
@Test
void deleteUnusedRoleStampsDeletedAt() {
Role r = role(5L, "ROLE_TEMP");
when(roleRepository.findById(5L)).thenReturn(Optional.of(r));
when(userRepository.countByRoleId(5L)).thenReturn(0L);
service.delete(5L);
assertThat(r.getDeletedAt()).isNotNull();
verify(roleRepository).save(r);
}
@Test
void deleteRoleInUseIsRefusedWithUserCount() {
Role r = role(5L, "ROLE_SALES");
when(roleRepository.findById(5L)).thenReturn(Optional.of(r));
when(userRepository.countByRoleId(5L)).thenReturn(3L);
assertThatThrownBy(() -> service.delete(5L))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getBody().getDetail()).isEqualTo("ROLE_IN_USE");
assertThat(e.getBody().getProperties()).containsEntry("users", 3L);
});
assertThat(r.getDeletedAt()).isNull();
verify(roleRepository, never()).save(any());
}
@Test
void superAdminAndRoleAdminAreProtected() {
when(roleRepository.findById(1L)).thenReturn(Optional.of(role(1L, "ROLE_SUPER_ADMIN")));
when(roleRepository.findById(2L)).thenReturn(Optional.of(role(2L, "ROLE_ADMIN")));
for (long id : new long[]{1L, 2L}) {
assertThatThrownBy(() -> service.delete(id))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getBody().getDetail()).isEqualTo("ROLE_PROTECTED");
});
}
verify(roleRepository, never()).save(any());
}
@Test
void roleMemberIsProtected() {
when(roleRepository.findById(3L)).thenReturn(Optional.of(role(3L, "ROLE_MEMBER")));
assertThatThrownBy(() -> service.delete(3L))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getBody().getDetail()).isEqualTo("ROLE_PROTECTED");
});
verify(roleRepository, never()).save(any());
}
@Test
void unknownOrDeletedRoleIs404() {
Role gone = role(6L, "ROLE_OLD");
gone.setDeletedAt(new Timestamp(1L));
when(roleRepository.findById(9L)).thenReturn(Optional.empty());
when(roleRepository.findById(6L)).thenReturn(Optional.of(gone));
for (long id : new long[]{9L, 6L}) {
assertThatThrownBy(() -> service.delete(id))
.isInstanceOf(ResponseStatusException.class)
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND);
}
verify(roleRepository, never()).save(any());
}
@Test
void savingADeletedRolesNameIsRefused() {
when(roleRepository.existsByNameIgnoreCaseAndDeletedAtIsNotNull("ROLE_TEMP")).thenReturn(true);
assertThatThrownBy(() -> service.requireNameNotDeleted(role(null, "ROLE_TEMP")))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getBody().getDetail()).isEqualTo("ROLE_NAME_DELETED");
});
}
@Test
void savingALiveNameIsAllowed() {
service.requireNameNotDeleted(role(null, "ROLE_NEW"));
}
private static Role role(Long id, String name) {
Role r = new Role();
r.setId(id);
r.setName(name);
return r;
}
}