feat: read-only admin email listing for when no email provider is configured

GET /api/admin/emails lists saved emails newest first (no bodies), and
GET /api/admin/emails/{id} returns one with its body, under a new BO_EMAILS
module. A caller who is not a super admin cannot open an email addressed to a
super admin. Each view logs the email id and viewer, never the body.

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-11-30 12:05:21 +08:00
1 parent b18e2e625a
commit 0961a10bb2
6 files changed
+472

No files matched your search

@@ -0,0 +1,64 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.mobile.api.service.AdminEmailService;
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.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
class AdminEmailControllerTest {
@Mock private AdminEmailService emails;
@InjectMocks private AdminEmailController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
void guardedByBackOfficeEmailsModule() {
assertThat(AdminEmailController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_EMAILS");
}
@Test
void list_passesFiltersAndPaging() throws Exception {
when(emails.list("sales1", "Reset", "2026-11-01", "2026-11-30", 1, 5))
.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"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content[0].id").value(7))
.andExpect(jsonPath("$.totalElements").value(6));
}
@Test
void list_defaultsToFirstPageOfTwenty() throws Exception {
when(emails.list(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
mvc.perform(get("/api/admin/emails")).andExpect(status().isOk());
verify(emails).list(null, null, null, null, 0, 20);
}
@Test
void detail_returnsTheEmail() throws Exception {
when(emails.detail(7L)).thenReturn(Map.of("id", 7, "body", "<p>hi</p>"));
mvc.perform(get("/api/admin/emails/7")).andExpect(status().isOk()).andExpect(jsonPath("$.body").value("<p>hi</p>"));
}
}
@@ -0,0 +1,225 @@
package com.solvway.mobile.api.service;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
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.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.slf4j.LoggerFactory;
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.anyString;
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 AdminEmailServiceTest {
private static final String PAGE = "/email/findByPropertyAndPageable";
private static final String FIND = "/email/findById/{id}";
private static final String BY_EMAIL = "/user/findByEmail/{email}";
private static final String BODY = "<p>Hi sales1,</p><p>Your temporary password: Xy7kPq2m</p>";
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);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
callerWithRole(4L);
}
@AfterEach
void close() { http.close(); }
private void callerWithRole(long roleId) {
User caller = new User();
caller.setId(1L);
caller.setUsername("boss");
Role r = new Role();
r.setId(roleId);
caller.setRoles(List.of(r));
when(auth.loadUserByToken("tok")).thenReturn(caller);
}
private static Map<String, Object> emailRow(long id, String to) {
Map<String, Object> m = new HashMap<>();
m.put("id", id);
m.put("sender", "noreply@example.com");
m.put("subject", "Reset Admin Password");
m.put("body", BODY);
m.put("status", "Y");
m.put("resend", 0);
m.put("datetime", "2026-11-30T10:15:00");
m.put("recipients", List.of(Map.of("recipient", to, "type", "R")));
return m;
}
private void stubFind(long id, Map<String, Object> row) {
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(row));
}
private void stubUserByEmail(String email, Map<String, Object> user) {
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq(email))).thenReturn(ResponseEntity.ok(user));
}
private static Map<String, Object> adminUser(long... roleIds) {
Map<String, Object> u = new HashMap<>();
u.put("type", "A");
u.put("roles", java.util.Arrays.stream(roleIds).mapToObj(id -> Map.of("id", id)).toList());
return u;
}
@Test
void list_sendsOnlyGivenFiltersNewestFirstAndConvertsDates() {
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);
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
Map<String, Object> sent = (Map<String, Object>) body.getValue();
assertThat((Map<String, Object>) sent.get("property"))
.containsOnly(Map.entry("recipient", "sales1"), Map.entry("startDate", "01-11-2026"), Map.entry("endDate", "30-11-2026"));
Map<String, Object> pageable = (Map<String, Object>) sent.get("pageableRest");
assertThat(pageable).containsEntry("number", 2).containsEntry("size", 10);
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("property", "datetime", "direction", "DESC"));
}
@Test
void list_rowsCarryMetadataButNeverTheBody() {
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);
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")
.containsEntry("id", 7L).containsEntry("subject", "Reset Admin Password")
.containsEntry("recipients", List.of("sales1@example.com"));
assertThat(out).containsEntry("totalElements", 1);
assertThat(out.toString()).doesNotContain("Xy7kPq2m");
}
@Test
void detail_returnsBodyAndRecipientsForAnOrdinaryRecipient() {
stubFind(7, emailRow(7, "sales1@example.com"));
stubUserByEmail("sales1@example.com", adminUser(4));
Map<String, Object> out = service.detail(7L);
assertThat(out).containsEntry("body", BODY).containsEntry("subject", "Reset Admin Password");
assertThat((List<Map<String, Object>>) out.get("recipients")).containsExactly(Map.of("recipient", "sales1@example.com", "type", "R"));
}
@Test
void detail_unknownEmail_is404() {
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok().build());
assertThatThrownBy(() -> service.detail(9L)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(e.getCode()).isEqualTo("EMAIL_NOT_FOUND");
});
}
@Test
void detail_superAdminRecipientWithNonSuperCaller_is403() {
stubFind(7, emailRow(7, "root@example.com"));
stubUserByEmail("root@example.com", adminUser(1));
assertThatThrownBy(() -> service.detail(7L)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(e.getCode()).isEqualTo("SUPER_ADMIN_REQUIRED");
});
}
@Test
void detail_superAdminRoleSentAsBareId_isStillProtected() {
stubFind(7, emailRow(7, "root@example.com"));
Map<String, Object> u = new HashMap<>(Map.of("type", "A", "roles", List.of(1)));
stubUserByEmail("root@example.com", u);
assertThatThrownBy(() -> service.detail(7L)).isInstanceOf(CodedResponseStatusException.class);
}
@Test
void detail_superCallerSkipsTheRecipientLookup() {
callerWithRole(1L);
stubFind(7, emailRow(7, "root@example.com"));
assertThat(service.detail(7L)).containsEntry("body", BODY);
verify(rest, never()).getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), anyString());
}
@Test
void detail_recipientWhoIsNoUser_isShown() {
stubFind(7, emailRow(7, "visitor@example.com"));
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("visitor@example.com")))
.thenReturn(ResponseEntity.ok().build());
assertThat(service.detail(7L)).containsEntry("body", BODY);
}
@Test
void detail_auditLineNamesEmailAndViewerButNotTheBody() {
stubFind(7, emailRow(7, "sales1@example.com"));
stubUserByEmail("sales1@example.com", adminUser(4));
Logger logger = (Logger) LoggerFactory.getLogger(AdminEmailService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
service.detail(7L);
} finally {
logger.detachAppender(appender);
}
assertThat(appender.list).extracting(ILoggingEvent::getFormattedMessage)
.anySatisfy(m -> assertThat(m).isEqualTo("email 7 viewed by boss"))
.allSatisfy(m -> assertThat(m).doesNotContain("Xy7kPq2m"));
}
@Test
void list_badDate_is400InvalidDate() {
assertThatThrownBy(() -> service.list(null, null, "30/11/2026", null, 0, 20))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getCode()).isEqualTo("INVALID_DATE");
});
verify(rest, never()).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any());
}
@Test
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);
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);
}
}