feat(mobile-api): admin interests API
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
48507979bd
commit
5d768b1566
7 files changed
+387
-1
No files matched your search
@@ -57,7 +57,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [ ] 3.1 Add the interests admin API (design decision 8). `AdminInterestController` with `GET`, `POST` and `PUT /api/admin/interests`, all `@AppAuth @AdminModule("BO_INTERESTS")`. The company id comes from the caller.
|
||||
- [x] 3.1 Add the interests admin API (design decision 8). `AdminInterestController` with `GET`, `POST` and `PUT /api/admin/interests`, all `@AppAuth @AdminModule("BO_INTERESTS")`. The company id comes from the caller.
|
||||
|
||||
Validation:
|
||||
- Name is required, else `REQUIRED_FIELD`.
|
||||
|
||||
+3
@@ -37,6 +37,9 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_EVENT_SAVE="/counter/event/save";
|
||||
public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
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_FIND_BY_IDS="/counter/interest/findByIds";
|
||||
|
||||
//Event Product
|
||||
public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}";
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
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.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Admin interest list. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminInterestController {
|
||||
private final AdminInterestService adminInterestService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@GetMapping("/interests")
|
||||
public ResponseEntity<List<Map<String, Object>>> list() {
|
||||
return ResponseEntity.ok(adminInterestService.list());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@PostMapping("/interests")
|
||||
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.create(request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_INTERESTS")
|
||||
@PutMapping("/interests/{id}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable long id, @RequestBody AdminInterestRequest request) {
|
||||
return ResponseEntity.ok(adminInterestService.update(id, request));
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
/** Create (name) or update (any field; omitted fields keep their stored value) an interest. */
|
||||
public record AdminInterestRequest(String name, Boolean active, Integer sortOrder) {}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** The company's interest list (tags for leads). Company comes from the logged-in admin, never the request. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminInterestService {
|
||||
private static final int NAME_MAX = 100;
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> LIST = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public List<Map<String, Object>> list() {
|
||||
return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList();
|
||||
}
|
||||
|
||||
public Map<String, Object> create(AdminInterestRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("name", checkedName(r.name()));
|
||||
body.put("active", r.active() == null || r.active());
|
||||
body.put("sortOrder", r.sortOrder() == null ? 0 : r.sortOrder());
|
||||
return save(body);
|
||||
}
|
||||
|
||||
public Map<String, Object> update(long id, AdminInterestRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> stored = load(caller.getCompanyId()).stream()
|
||||
.filter(m -> 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);
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("name", r.name() == null ? stored.get("name") : checkedName(r.name()));
|
||||
body.put("active", r.active() == null ? stored.get("active") : r.active());
|
||||
body.put("sortOrder", r.sortOrder() == null ? stored.get("sortOrder") : r.sortOrder());
|
||||
return save(body);
|
||||
}
|
||||
|
||||
private Map<String, Object> save(Map<String, Object> body) {
|
||||
try {
|
||||
return row(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_SAVE), MAP, body).getBody());
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
throw error(HttpStatus.CONFLICT, "An interest with this name already exists", "DUPLICATE_NAME", "name");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> load(long companyId) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, companyId).getBody();
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
private static String checkedName(String name) {
|
||||
String n = name == null ? "" : name.trim();
|
||||
if (n.isEmpty()) {
|
||||
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: name", "REQUIRED_FIELD", "name");
|
||||
e.getBody().setProperty("errors", List.of("name"));
|
||||
throw e;
|
||||
}
|
||||
if (n.length() > NAME_MAX) throw error(HttpStatus.BAD_REQUEST, "Name is too long", "TOO_LONG", "name");
|
||||
return n;
|
||||
}
|
||||
|
||||
private static Map<String, Object> row(Map<String, Object> m) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("id", m.get("id"));
|
||||
out.put("name", m.get("name"));
|
||||
out.put("active", m.get("active"));
|
||||
out.put("sortOrder", m.get("sortOrder"));
|
||||
return out;
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
|
||||
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
|
||||
if (field != null) e.getBody().setProperty("details", Map.of("field", field));
|
||||
return e;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||
import com.solvway.mobile.api.service.AdminInterestService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminInterestControllerTest {
|
||||
|
||||
@Mock private AdminInterestService interests;
|
||||
@InjectMocks private AdminInterestController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHandlerIsAuthenticatedAndGuardedByBoInterests() {
|
||||
List<Method> handlers = Arrays.stream(AdminInterestController.class.getDeclaredMethods())
|
||||
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
|
||||
assertThat(handlers).hasSize(3);
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsTheInterests() throws Exception {
|
||||
when(interests.list()).thenReturn(List.of(Map.of("id", 1, "name", "Cookware")));
|
||||
mvc.perform(get("/api/admin/interests")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"id\":1,\"name\":\"Cookware\"}]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndUpdateBindTheBody() throws Exception {
|
||||
when(interests.create(new AdminInterestRequest("Cookware", null, null))).thenReturn(Map.of("id", 1));
|
||||
mvc.perform(post("/api/admin/interests").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"Cookware\"}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(interests).create(new AdminInterestRequest("Cookware", null, null));
|
||||
|
||||
when(interests.update(2L, new AdminInterestRequest(null, false, null))).thenReturn(Map.of("id", 2));
|
||||
mvc.perform(put("/api/admin/interests/2").contentType(MediaType.APPLICATION_JSON).content("{\"active\":false}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(interests).update(2L, new AdminInterestRequest(null, false, null));
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
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.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
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 AdminInterestServiceTest {
|
||||
|
||||
private static final String LIST = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String SAVE = "/counter/interest/save";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminInterestService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService 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");
|
||||
User caller = new User();
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private static Map<String, Object> row(long id, String name, boolean active, int sort) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("companyId", 5);
|
||||
m.put("name", name);
|
||||
m.put("active", active);
|
||||
m.put("sortOrder", sort);
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stubList(Map<String, Object>... rows) {
|
||||
when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(5L))).thenReturn(ResponseEntity.ok(List.of(rows)));
|
||||
}
|
||||
|
||||
private Map<String, Object> saved() {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
private static void assertCoded(Runnable r, HttpStatus status, String code, String field) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getCode()).isEqualTo(code);
|
||||
if (field != null) assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", field);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIsTheCallersCompanyInterests() {
|
||||
stubList(row(1, "Cookware", true, 0), row(2, "Old", false, 1));
|
||||
|
||||
assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("Cookware", "Old");
|
||||
assertThat(service.list().get(1)).containsEntry("active", false).doesNotContainKey("companyId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSendsTrimmedActiveInterestForTheCallersCompany() {
|
||||
service.create(new AdminInterestRequest(" Kitchen appliances ", null, null));
|
||||
|
||||
assertThat(saved()).containsEntry("companyId", 5L).containsEntry("name", "Kitchen appliances")
|
||||
.containsEntry("active", true).containsEntry("sortOrder", 0).doesNotContainKey("id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameIsRequired() {
|
||||
assertCoded(() -> service.create(new AdminInterestRequest(" ", null, null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD", "name");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameAtMostHundredCharacters() {
|
||||
assertCoded(() -> service.create(new AdminInterestRequest("x".repeat(101), null, null)), HttpStatus.BAD_REQUEST, "TOO_LONG", "name");
|
||||
service.create(new AdminInterestRequest("x".repeat(100), null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateNameIsAConflictOnTheNameField() {
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, null, null));
|
||||
|
||||
assertCoded(() -> service.create(new AdminInterestRequest("kitchen APPLIANCES", null, null)), HttpStatus.CONFLICT, "DUPLICATE_NAME", "name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateDeactivatesKeepingNameAndOrder() {
|
||||
stubList(row(2, "Cookware", true, 3));
|
||||
|
||||
service.update(2L, new AdminInterestRequest(null, false, null));
|
||||
|
||||
assertThat(saved()).containsEntry("id", 2L).containsEntry("companyId", 5L).containsEntry("name", "Cookware")
|
||||
.containsEntry("active", false).containsEntry("sortOrder", 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRenamesAndReorders() {
|
||||
stubList(row(2, "Cookware", true, 3));
|
||||
|
||||
service.update(2L, new AdminInterestRequest(" Pots ", null, 1));
|
||||
|
||||
assertThat(saved()).containsEntry("name", "Pots").containsEntry("sortOrder", 1).containsEntry("active", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfAnInterestNotInTheCallersCompanyIsNotFound() {
|
||||
stubList(row(2, "Cookware", true, 3));
|
||||
|
||||
assertCoded(() -> service.update(99L, new AdminInterestRequest("X", true, 0)), HttpStatus.NOT_FOUND, "INTEREST_NOT_FOUND", null);
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user