feat: company-scoped emails and audit log, company on admin password emails
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
b7d9da8ec0
commit
00ce47bc49
13 files changed
+435
-25
No files matched your search
@@ -30,6 +30,9 @@ public class Email {
|
||||
|
||||
private List<Long> attachmentId;
|
||||
|
||||
/** Set for an admin user's email; member and system emails stay null. */
|
||||
private Long companyId;
|
||||
|
||||
public Email() {
|
||||
super();
|
||||
// TODO Auto-generated constructor stub
|
||||
|
||||
+3
-2
@@ -32,8 +32,9 @@ public class AdminAuditLogController {
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(auditLog.search(actor, module, action, outcome, from, to, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(auditLog.search(actor, module, action, outcome, from, to, page, size, companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
|
||||
+3
-2
@@ -31,8 +31,9 @@ public class AdminEmailController {
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size, companyId));
|
||||
}
|
||||
|
||||
@Audited(action = "EMAIL_VIEW")
|
||||
|
||||
+23
-3
@@ -3,7 +3,10 @@ package com.solvway.mobile.api.service;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.mobile.api.constant.api.RestApiLogServiceConstants;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -24,9 +27,13 @@ public class AdminAuditLogService {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AdminCompanyScope companyScope;
|
||||
|
||||
public Map<String, Object> search(String actor, String module, String action, String outcome, String from, String to, int page, int size) {
|
||||
public Map<String, Object> search(String actor, String module, String action, String outcome, String from, String to, int page, int size, Long companyId) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
Long scope = companyScope.scope(caller(), companyId);
|
||||
if (scope != null) body.put("companyId", scope);
|
||||
put(body, "actor", actor);
|
||||
put(body, "module", module);
|
||||
put(body, "action", action);
|
||||
@@ -44,12 +51,25 @@ public class AdminAuditLogService {
|
||||
|
||||
public Map<String, Object> get(Long id) {
|
||||
try {
|
||||
return restTemplateUtil.getForEntity(url(RestApiLogServiceConstants.API_REST_LOG_AUDIT_DETAIL), MAP, id).getBody();
|
||||
Map<String, Object> row = restTemplateUtil.getForEntity(url(RestApiLogServiceConstants.API_REST_LOG_AUDIT_DETAIL), MAP, id).getBody();
|
||||
Long scope = companyScope.scope(caller(), null);
|
||||
if (scope != null && row != null && !(row.get("companyId") instanceof Number n && n.longValue() == scope)) throw notFound();
|
||||
return row;
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Audit event not found", "NOT_FOUND");
|
||||
throw notFound();
|
||||
}
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException notFound() {
|
||||
return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Audit event not found", "NOT_FOUND");
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
return caller;
|
||||
}
|
||||
|
||||
private static void put(Map<String, Object> body, String key, String value) {
|
||||
if (StringUtils.hasText(value)) body.put(key, value.trim());
|
||||
}
|
||||
|
||||
+11
-1
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiEmailServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -39,9 +40,12 @@ public class AdminEmailService {
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AdminCompanyScope companyScope;
|
||||
|
||||
public Map<String, Object> list(String recipient, String subject, String from, String to, int page, int size) {
|
||||
public Map<String, Object> list(String recipient, String subject, String from, String to, int page, int size, Long companyId) {
|
||||
Map<String, Object> property = new LinkedHashMap<>();
|
||||
Long scope = companyScope.scope(caller(), companyId);
|
||||
if (scope != null) property.put("companyId", String.valueOf(scope));
|
||||
if (StringUtils.hasText(recipient)) property.put("recipient", recipient.trim());
|
||||
if (StringUtils.hasText(subject)) property.put("subject", subject.trim());
|
||||
if (StringUtils.hasText(from)) property.put("startDate", upstreamDate(from));
|
||||
@@ -68,6 +72,10 @@ public class AdminEmailService {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Email not found", "EMAIL_NOT_FOUND");
|
||||
}
|
||||
User caller = caller();
|
||||
Long scope = companyScope.scope(caller, null);
|
||||
if (scope != null && !(row.get("companyId") instanceof Number n && n.longValue() == scope)) {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Email not found", "EMAIL_NOT_FOUND");
|
||||
}
|
||||
List<Map<String, Object>> recipients = new ArrayList<>();
|
||||
if (row.get("recipients") instanceof List<?> list) {
|
||||
for (Object item : list) {
|
||||
@@ -84,6 +92,7 @@ public class AdminEmailService {
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("id", row.get("id"));
|
||||
out.put("companyId", row.get("companyId"));
|
||||
out.put("datetime", row.get("datetime"));
|
||||
out.put("sender", row.get("sender"));
|
||||
out.put("subject", row.get("subject"));
|
||||
@@ -101,6 +110,7 @@ public class AdminEmailService {
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("id", row.get("id") instanceof Number n ? n.longValue() : null);
|
||||
out.put("companyId", row.get("companyId"));
|
||||
out.put("datetime", row.get("datetime"));
|
||||
out.put("recipients", to);
|
||||
out.put("subject", row.get("subject"));
|
||||
|
||||
+3
-3
@@ -46,7 +46,7 @@ class AdminAuditLogControllerTest {
|
||||
|
||||
@Test
|
||||
void list_passesEveryParam() throws Exception {
|
||||
when(audit.search("boss", "LEADS", "UPDATE", "SUCCESS", "2026-11-01", "2026-11-30", 1, 5))
|
||||
when(audit.search("boss", "LEADS", "UPDATE", "SUCCESS", "2026-11-01", "2026-11-30", 1, 5, null))
|
||||
.thenReturn(Map.of("content", List.of(Map.of("id", 7))));
|
||||
mvc.perform(get("/api/admin/audit-log").param("actor", "boss").param("module", "LEADS").param("action", "UPDATE")
|
||||
.param("outcome", "SUCCESS").param("from", "2026-11-01").param("to", "2026-11-30")
|
||||
@@ -56,9 +56,9 @@ class AdminAuditLogControllerTest {
|
||||
|
||||
@Test
|
||||
void list_defaultsToFirstPageOfTwenty() throws Exception {
|
||||
when(audit.search(null, null, null, null, null, null, 0, 20)).thenReturn(Map.of());
|
||||
when(audit.search(null, null, null, null, null, null, 0, 20, null)).thenReturn(Map.of());
|
||||
mvc.perform(get("/api/admin/audit-log")).andExpect(status().isOk());
|
||||
verify(audit).search(null, null, null, null, null, null, 0, 20);
|
||||
verify(audit).search(null, null, null, null, null, null, 0, 20, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -40,7 +40,7 @@ class AdminEmailControllerTest {
|
||||
|
||||
@Test
|
||||
void list_passesFiltersAndPaging() throws Exception {
|
||||
when(emails.list("sales1", "Reset", "2026-11-01", "2026-11-30", 1, 5))
|
||||
when(emails.list("sales1", "Reset", "2026-11-01", "2026-11-30", 1, 5, null))
|
||||
.thenReturn(Map.of("content", List.of(Map.of("id", 7)), "totalElements", 6));
|
||||
mvc.perform(get("/api/admin/emails").param("recipient", "sales1").param("subject", "Reset")
|
||||
.param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5"))
|
||||
@@ -51,9 +51,9 @@ class AdminEmailControllerTest {
|
||||
|
||||
@Test
|
||||
void list_defaultsToFirstPageOfTwenty() throws Exception {
|
||||
when(emails.list(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
|
||||
when(emails.list(null, null, null, null, 0, 20, null)).thenReturn(Map.of("content", List.of()));
|
||||
mvc.perform(get("/api/admin/emails")).andExpect(status().isOk());
|
||||
verify(emails).list(null, null, null, null, 0, 20);
|
||||
verify(emails).list(null, null, null, null, 0, 20, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
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.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminAuditLogServiceCompanyTest {
|
||||
|
||||
private static final String SEARCH = "/log/audit/search";
|
||||
private static final String DETAIL = "/log/audit/{id}";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminAuditLogService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminAuditLogService(rest, auth, new AdminCompanyScope());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void caller(Long companyId, long roleId) {
|
||||
User caller = new User();
|
||||
caller.setId(1L);
|
||||
caller.setCompanyId(companyId);
|
||||
Role r = new Role();
|
||||
r.setId(roleId);
|
||||
caller.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
}
|
||||
|
||||
private Map<String, Object> searched() {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture());
|
||||
return (Map<String, Object>) body.getValue();
|
||||
}
|
||||
|
||||
private void stubDetail(Long companyId) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("id", 3L);
|
||||
row.put("companyId", companyId);
|
||||
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(3L))).thenReturn(ResponseEntity.ok(row));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffSearchIgnoresRequestedCompany() {
|
||||
caller(7L, 4L);
|
||||
service.search(null, null, null, null, null, null, 0, 20, 9L);
|
||||
assertThat(searched()).containsEntry("companyId", 7L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superSearchPassesRequestedCompanyOrAll() {
|
||||
caller(null, 1L);
|
||||
service.search(null, null, null, null, null, null, 0, 20, 9L);
|
||||
assertThat(searched()).containsEntry("companyId", 9L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superSearchWithoutCompanyMeansAll() {
|
||||
caller(null, 1L);
|
||||
service.search(null, null, null, null, null, null, 0, 20, null);
|
||||
assertThat(searched()).doesNotContainKey("companyId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffDetailOfOtherCompanyOrNullCompanyIs404() {
|
||||
caller(7L, 4L);
|
||||
stubDetail(8L);
|
||||
assertThatThrownBy(() -> service.get(3L)).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
stubDetail(null);
|
||||
assertThatThrownBy(() -> service.get(3L)).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffDetailOfOwnCompanyAndSuperDetailOfAnyWork() {
|
||||
caller(7L, 4L);
|
||||
stubDetail(7L);
|
||||
assertThat(service.get(3L)).containsEntry("companyId", 7L);
|
||||
caller(null, 1L);
|
||||
stubDetail(null);
|
||||
assertThat(service.get(3L)).containsKey("id");
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -1,5 +1,10 @@
|
||||
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 org.junit.jupiter.api.AfterEach;
|
||||
import org.mockito.MockedStatic;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -20,6 +25,7 @@ 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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -31,14 +37,22 @@ class AdminAuditLogServiceTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuditLogService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
service = new AdminAuditLogService(rest);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminAuditLogService(rest, auth, new AdminCompanyScope());
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(auth.loadUserByToken("tok")).thenReturn(new User());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private static HttpClientErrorException clientError(HttpStatus status, String body) {
|
||||
return HttpClientErrorException.create(status, status.getReasonPhrase(), new HttpHeaders(), body.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
@@ -46,7 +60,7 @@ class AdminAuditLogServiceTest {
|
||||
@Test
|
||||
void search_forwardsOnlyGivenFiltersWithPaging() {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
|
||||
service.search(" boss ", null, "", " ", "2026-11-01", null, 0, 20);
|
||||
service.search(" boss ", null, "", " ", "2026-11-01", null, 0, 20, null);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsOnlyKeys("actor", "from", "page", "size")
|
||||
@@ -57,7 +71,7 @@ class AdminAuditLogServiceTest {
|
||||
void search_upstreamBadRequest_becomesInvalidFilterWithDetail() {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(clientError(HttpStatus.BAD_REQUEST, "{\"detail\":\"from must be yyyy-MM-dd\"}"));
|
||||
assertThatThrownBy(() -> service.search(null, null, null, null, "nope", null, 0, 20))
|
||||
assertThatThrownBy(() -> service.search(null, null, null, null, "nope", null, 0, 20, null))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("INVALID_FILTER");
|
||||
@@ -68,7 +82,7 @@ class AdminAuditLogServiceTest {
|
||||
@Test
|
||||
void search_upstreamBadRequestWithoutBody_usesGenericReason() {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenThrow(clientError(HttpStatus.BAD_REQUEST, ""));
|
||||
assertThatThrownBy(() -> service.search(null, null, null, null, "nope", null, 0, 20))
|
||||
assertThatThrownBy(() -> service.search(null, null, null, null, "nope", null, 0, 20, null))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("Invalid request"));
|
||||
}
|
||||
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
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.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEmailServiceCompanyTest {
|
||||
|
||||
private static final String PAGE = "/email/findByPropertyAndPageable";
|
||||
private static final String FIND = "/email/findById/{id}";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminEmailService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEmailService(rest, auth, new AdminCompanyScope());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void caller(Long companyId, long roleId) {
|
||||
User caller = new User();
|
||||
caller.setId(1L);
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(companyId);
|
||||
Role r = new Role();
|
||||
r.setId(roleId);
|
||||
caller.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
}
|
||||
|
||||
private Map<String, Object> listedProperty() {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||
return (Map<String, Object>) ((Map<String, Object>) body.getValue()).get("property");
|
||||
}
|
||||
|
||||
private void stubPage() {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("id", 4L);
|
||||
row.put("companyId", 7L);
|
||||
row.put("recipients", List.of());
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(row))));
|
||||
}
|
||||
|
||||
private void stubFind(Long companyId) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("id", 4L);
|
||||
row.put("companyId", companyId);
|
||||
row.put("recipients", List.of());
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(4L))).thenReturn(ResponseEntity.ok(row));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffListIgnoresRequestedCompany() {
|
||||
caller(7L, 4L);
|
||||
stubPage();
|
||||
Map<String, Object> out = service.list(null, null, null, null, 0, 20, 9L);
|
||||
assertThat(listedProperty()).containsEntry("companyId", "7");
|
||||
assertThat(((List<Map<String, Object>>) out.get("content")).get(0)).containsEntry("companyId", 7L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superListPassesRequestedCompany() {
|
||||
caller(null, 1L);
|
||||
stubPage();
|
||||
service.list(null, null, null, null, 0, 20, 9L);
|
||||
assertThat(listedProperty()).containsEntry("companyId", "9");
|
||||
}
|
||||
|
||||
@Test
|
||||
void superListWithoutCompanyMeansAll() {
|
||||
caller(null, 1L);
|
||||
stubPage();
|
||||
service.list(null, null, null, null, 0, 20, null);
|
||||
assertThat(listedProperty()).doesNotContainKey("companyId");
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffDetailOfOtherCompanyOrNullCompanyIs404() {
|
||||
caller(7L, 4L);
|
||||
stubFind(8L);
|
||||
assertThatThrownBy(() -> service.detail(4L)).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
stubFind(null);
|
||||
assertThatThrownBy(() -> service.detail(4L)).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffDetailOfOwnCompanyAndSuperDetailOfAnyWork() {
|
||||
caller(7L, 4L);
|
||||
stubFind(7L);
|
||||
assertThat(service.detail(4L)).containsEntry("companyId", 7L);
|
||||
caller(null, 1L);
|
||||
stubFind(null);
|
||||
assertThat(service.detail(4L)).containsKey("id");
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -50,7 +50,7 @@ class AdminEmailServiceTest {
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEmailService(rest, auth);
|
||||
service = new AdminEmailService(rest, auth, new com.solvway.mobile.api.useraccess.AdminCompanyScope());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
@@ -103,7 +103,7 @@ class AdminEmailServiceTest {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0)));
|
||||
|
||||
service.list("sales1", null, "2026-11-01", "2026-11-30", 2, 10);
|
||||
service.list("sales1", null, "2026-11-01", "2026-11-30", 2, 10, null);
|
||||
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||
@@ -120,11 +120,11 @@ class AdminEmailServiceTest {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(emailRow(7, "sales1@example.com")), "totalElements", 1)));
|
||||
|
||||
Map<String, Object> out = service.list(null, null, null, null, 0, 20);
|
||||
Map<String, Object> out = service.list(null, null, null, null, 0, 20, null);
|
||||
|
||||
List<Map<String, Object>> rows = (List<Map<String, Object>>) out.get("content");
|
||||
assertThat(rows).hasSize(1);
|
||||
assertThat(rows.get(0)).containsOnlyKeys("id", "datetime", "recipients", "subject", "status")
|
||||
assertThat(rows.get(0)).containsOnlyKeys("id", "companyId", "datetime", "recipients", "subject", "status")
|
||||
.containsEntry("id", 7L).containsEntry("subject", "Reset Admin Password")
|
||||
.containsEntry("recipients", List.of("sales1@example.com"));
|
||||
assertThat(out).containsEntry("totalElements", 1);
|
||||
@@ -205,7 +205,7 @@ class AdminEmailServiceTest {
|
||||
|
||||
@Test
|
||||
void list_badDate_is400InvalidDate() {
|
||||
assertThatThrownBy(() -> service.list(null, null, "30/11/2026", null, 0, 20))
|
||||
assertThatThrownBy(() -> service.list(null, null, "30/11/2026", null, 0, 20, null))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("INVALID_DATE");
|
||||
@@ -217,7 +217,7 @@ class AdminEmailServiceTest {
|
||||
void list_pageSizeIsCappedAtOneHundred() {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
|
||||
service.list(null, null, null, null, 0, 100000);
|
||||
service.list(null, null, null, null, 0, 100000, null);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) ((Map<String, Object>) body.getValue()).get("pageableRest")).containsEntry("size", 100);
|
||||
@@ -227,7 +227,7 @@ class AdminEmailServiceTest {
|
||||
void list_sameEmailTwiceFromTheRecipientJoin_isListedOnce() {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(emailRow(7, "a@example.com"), emailRow(7, "a@example.com"), emailRow(6, "b@example.com")))));
|
||||
List<Map<String, Object>> rows = (List<Map<String, Object>>) service.list("example.com", null, null, null, 0, 20).get("content");
|
||||
List<Map<String, Object>> rows = (List<Map<String, Object>>) service.list("example.com", null, null, null, 0, 20, null).get("content");
|
||||
assertThat(rows).extracting(r -> r.get("id")).containsExactly(7L, 6L);
|
||||
}
|
||||
}
|
||||
+1
@@ -927,6 +927,7 @@ public class UserController {
|
||||
recipientslist.add(new Recipient(null, emailAddress, RecipientType.R, RecipientStatusType.Y));
|
||||
Email email = new Email();
|
||||
email.setSubject("Reset Admin Password");
|
||||
email.setCompanyId(user.getCompanyId());
|
||||
email.setBody("<p>Hi "+username+",</p><p>Your temporary password: "+ randPassword+"</p>");
|
||||
email.setDatetime(LocalDateTime.now());
|
||||
email.setRecipients(recipientslist);
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.solvway.services.system.controller;
|
||||
|
||||
import com.solvway.core.enums.UserEnum.UserType;
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.services.system.model.Member;
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.service.EmailService;
|
||||
import com.solvway.services.system.service.MemberService;
|
||||
import com.solvway.services.system.service.UserService;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserControllerEmailCompanyTest {
|
||||
|
||||
@Mock
|
||||
private UserService userService;
|
||||
@Mock
|
||||
private MemberService memberService;
|
||||
@Mock
|
||||
private EmailService emailService;
|
||||
@Mock
|
||||
private ValidateUtil validateUtil;
|
||||
@Mock
|
||||
private BCryptPasswordEncoder bCryptPasswordEncoder;
|
||||
@InjectMocks
|
||||
private UserController controller;
|
||||
|
||||
@Test
|
||||
void adminPasswordEmailCarriesTheAdminsCompany() {
|
||||
User user = new User();
|
||||
user.setId(5L);
|
||||
user.setUsername("sales1@ins");
|
||||
user.setEmail("sales1@example.com");
|
||||
user.setType(UserType.A);
|
||||
user.setEnabled(true);
|
||||
user.setCompanyId(7L);
|
||||
when(userService.findByUsername("sales1@ins")).thenReturn(user);
|
||||
when(validateUtil.getRandomPasswordString(8)).thenReturn("Xy7kPq2m");
|
||||
when(bCryptPasswordEncoder.encode(anyString())).thenReturn("hash");
|
||||
when(userService.resetPassword(anyLong(), anyString(), any())).thenReturn(1);
|
||||
|
||||
controller.resetAdminPassword(new HashMap<>(Map.of("username", "sales1@ins", "email", "sales1@example.com")));
|
||||
|
||||
ArgumentCaptor<Email> sent = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(sent.capture());
|
||||
assertThat(sent.getValue().getCompanyId()).isEqualTo(7L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminPasswordEmailHasNoCompany() {
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
user.setUsername("boss");
|
||||
user.setEmail("boss@example.com");
|
||||
user.setType(UserType.A);
|
||||
user.setEnabled(true);
|
||||
when(userService.findByUsername("boss")).thenReturn(user);
|
||||
when(validateUtil.getRandomPasswordString(8)).thenReturn("Xy7kPq2m");
|
||||
when(bCryptPasswordEncoder.encode(anyString())).thenReturn("hash");
|
||||
when(userService.resetPassword(anyLong(), anyString(), any())).thenReturn(1);
|
||||
|
||||
controller.resetAdminPassword(new HashMap<>(Map.of("username", "boss", "email", "boss@example.com")));
|
||||
|
||||
ArgumentCaptor<Email> sent = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(sent.capture());
|
||||
assertThat(sent.getValue().getCompanyId()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberPasswordEmailHasNoCompany() {
|
||||
User user = new User();
|
||||
user.setId(9L);
|
||||
user.setUsername("m1");
|
||||
user.setCompanyId(7L);
|
||||
Member member = new Member();
|
||||
member.setPhoneNo("0123456789");
|
||||
when(userService.findByUsername("m1")).thenReturn(user);
|
||||
when(memberService.findByUsername("m1")).thenReturn(Optional.of(member));
|
||||
when(bCryptPasswordEncoder.encode(anyString())).thenReturn("hash");
|
||||
when(userService.resetPasswordSecondary(anyLong(), anyString())).thenReturn(1);
|
||||
|
||||
controller.resetMemberPasswordSecondary(new HashMap<>(Map.of("username", "m1", "email", "m1@example.com")), null);
|
||||
|
||||
ArgumentCaptor<Email> sent = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(sent.capture());
|
||||
assertThat(sent.getValue().getCompanyId()).isNull();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user