diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 4fa0862..6e99652 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -118,3 +118,7 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic (40400000, 'BO_LEADS', 'Leads', 'BO', 'M', 40000000, '/leads', 'Users'), (40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'M', 40000000, NULL, NULL), (40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'M', 40000000, NULL, NULL); + +-- add-admin-email-listing/sql/01-email-module.sql +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40900000, 'BO_EMAILS', 'Emails', 'BO', 'M', 40000000, '/emails', 'Mail'); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiEmailServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiEmailServiceConstants.java index 3fe85bf..224dd80 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiEmailServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiEmailServiceConstants.java @@ -5,4 +5,6 @@ public class RestApiEmailServiceConstants { private RestApiEmailServiceConstants() {} public static final String API_REST_EMAIL_SEND = "/email/send"; + public static final String API_REST_EMAIL_FIND_BY_PROPERTY_AND_PAGEABLE = "/email/findByPropertyAndPageable"; + public static final String API_REST_EMAIL_FIND_BY_ID = "/email/findById/{id}"; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEmailController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEmailController.java new file mode 100644 index 0000000..8aa368f --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEmailController.java @@ -0,0 +1,42 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.AdminEmailService; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** Read-only listing of saved emails for the portal. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +@AdminModule("BO_EMAILS") +public class AdminEmailController { + + private final AdminEmailService adminEmailService; + + @AppAuth + @GetMapping("/emails") + public ResponseEntity> list( + @RequestParam(required = false) String recipient, + @RequestParam(required = false) String subject, + @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)); + } + + @AppAuth + @GetMapping("/emails/{id}") + public ResponseEntity> detail(@PathVariable Long id) { + return ResponseEntity.ok(adminEmailService.detail(id)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEmailService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEmailService.java new file mode 100644 index 0000000..2352163 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEmailService.java @@ -0,0 +1,135 @@ +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.RestApiEmailServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Read-only view of the emails service-email has saved, so a temporary password can be passed on while no + * email provider is configured. The list never carries a body; the detail does, except that an email to a + * super admin is refused to a caller who is not one. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AdminEmailService { + + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final int MAX_PAGE_SIZE = 100; + private static final DateTimeFormatter UPSTREAM_DATE = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + public Map list(String recipient, String subject, String from, String to, int page, int size) { + Map property = new LinkedHashMap<>(); + 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)); + if (StringUtils.hasText(to)) property.put("endDate", upstreamDate(to)); + Map pageable = Map.of("number", Math.max(page, 0), "size", Math.min(Math.max(size, 1), MAX_PAGE_SIZE), + "sorts", List.of(Map.of("property", "datetime", "direction", "DESC"))); + Map result = restTemplateUtil.postForEntity( + url(RestApiEmailServiceConstants.API_REST_EMAIL_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, + Map.of("property", property, "pageableRest", pageable)).getBody(); + Map out = new LinkedHashMap<>(result == null ? Map.of() : result); + List> rows = new ArrayList<>(); + if (out.get("content") instanceof List content) { + for (Object item : content) if (item instanceof Map row) rows.add(listRow(row)); + } + out.put("content", rows); + return out; + } + + public Map detail(Long id) { + Map row = restTemplateUtil.getForEntity(url(RestApiEmailServiceConstants.API_REST_EMAIL_FIND_BY_ID), MAP, id).getBody(); + if (row == null || row.isEmpty()) { + throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Email not found", "EMAIL_NOT_FOUND"); + } + User caller = caller(); + List> recipients = new ArrayList<>(); + if (row.get("recipients") instanceof List list) { + for (Object item : list) { + if (item instanceof Map r && r.get("recipient") != null) { + Map ref = new LinkedHashMap<>(); + ref.put("recipient", String.valueOf(r.get("recipient"))); + ref.put("type", r.get("type") == null ? null : String.valueOf(r.get("type"))); + recipients.add(ref); + } + } + } + if (!isSuper(caller) && recipients.stream().anyMatch(r -> isSuperAdminAddress((String) r.get("recipient")))) { + throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Only a super admin can read this email", "SUPER_ADMIN_REQUIRED"); + } + Map out = new LinkedHashMap<>(); + out.put("id", row.get("id")); + out.put("datetime", row.get("datetime")); + out.put("sender", row.get("sender")); + out.put("subject", row.get("subject")); + out.put("status", row.get("status")); + out.put("recipients", recipients); + out.put("body", row.get("body")); + log.info("email {} viewed by {}", id, caller.getUsername()); + return out; + } + + private static Map listRow(Map row) { + List to = new ArrayList<>(); + if (row.get("recipients") instanceof List list) { + for (Object item : list) if (item instanceof Map r && r.get("recipient") != null) to.add(String.valueOf(r.get("recipient"))); + } + Map out = new LinkedHashMap<>(); + out.put("id", row.get("id") instanceof Number n ? n.longValue() : null); + out.put("datetime", row.get("datetime")); + out.put("recipients", to); + out.put("subject", row.get("subject")); + out.put("status", row.get("status")); + return out; + } + + /** An admin user holding the super admin role; services-system may send a role as a bare id. */ + private boolean isSuperAdminAddress(String address) { + Map user = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL), MAP, address).getBody(); + return user != null && "A".equals(user.get("type")) && user.get("roles") instanceof List roles + && roles.stream().anyMatch(r -> Long.valueOf(SUPER_ADMIN_ROLE_ID).equals(AdminRoleService.idOf(r))); + } + + private static boolean isSuper(User caller) { + return caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID); + } + + private static String upstreamDate(String isoDate) { + try { + return LocalDate.parse(isoDate.trim()).format(UPSTREAM_DATE); + } catch (java.time.format.DateTimeParseException e) { + throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "Dates must be yyyy-MM-dd", "INVALID_DATE"); + } + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + return caller; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEmailControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEmailControllerTest.java new file mode 100644 index 0000000..35589ed --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEmailControllerTest.java @@ -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", "

hi

")); + mvc.perform(get("/api/admin/emails/7")).andExpect(status().isOk()).andExpect(jsonPath("$.body").value("

hi

")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEmailServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEmailServiceTest.java new file mode 100644 index 0000000..52a2422 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEmailServiceTest.java @@ -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 = "

Hi sales1,

Your temporary password: Xy7kPq2m

"; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminEmailService service; + private MockedStatic 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 emailRow(long id, String to) { + Map 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 row) { + when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(row)); + } + + private void stubUserByEmail(String email, Map user) { + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq(email))).thenReturn(ResponseEntity.ok(user)); + } + + private static Map adminUser(long... roleIds) { + Map 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 body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + Map sent = (Map) body.getValue(); + assertThat((Map) sent.get("property")) + .containsOnly(Map.entry("recipient", "sales1"), Map.entry("startDate", "01-11-2026"), Map.entry("endDate", "30-11-2026")); + Map pageable = (Map) sent.get("pageableRest"); + assertThat(pageable).containsEntry("number", 2).containsEntry("size", 10); + assertThat((List>) 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 out = service.list(null, null, null, null, 0, 20); + + List> rows = (List>) 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 out = service.detail(7L); + + assertThat(out).containsEntry("body", BODY).containsEntry("subject", "Reset Admin Password"); + assertThat((List>) 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 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 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 body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) ((Map) body.getValue()).get("pageableRest")).containsEntry("size", 100); + } +}