feat: whatsapp admin api in mobile-api
- /api/admin/whatsapp: conversations, thread, send, read, assign, start, templates and sync, media, unread count, assignees. - Caller context from the token: company through AdminCompanyScope (fail closed), admin for BO_WHATSAPP_ADMIN or super admin. - Exactly-one validation for send, assign and start; path ids must look like uuids before they reach the service. - Service reason codes come back with their status and a message; an unreachable service is 502. - Owner and assignee names filled from the system service. - Audit: send (conversation and template name, never text), assign (owner before and after), start, sync; read markers skipped. - Media streams with nosniff and a sandbox CSP; anything but image, audio or video downloads. - Disabling a user or changing their roles tells the service to free their chats (best effort). 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
0d5c3f351a
commit
13b692748c
8 files changed
+1030
-1
No files matched your search
+155
@@ -0,0 +1,155 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.whatsapp.AssignRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.UnreadCount;
|
||||
import com.solvway.mobile.api.service.AdminWhatsAppService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
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.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
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.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminWhatsAppControllerTest {
|
||||
|
||||
@Mock private AdminWhatsAppService whatsapp;
|
||||
@InjectMocks private AdminWhatsAppController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
private static List<String> modules(Method m) {
|
||||
AdminModule a = m.getAnnotation(AdminModule.class);
|
||||
if (a == null) a = AdminWhatsAppController.class.getAnnotation(AdminModule.class);
|
||||
return Arrays.asList(a.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHandlerIsAuthenticatedAndGuardedByTheWhatsappModules() {
|
||||
List<Method> handlers = Arrays.stream(AdminWhatsAppController.class.getDeclaredMethods())
|
||||
.filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList();
|
||||
assertThat(handlers).hasSize(11);
|
||||
for (Method m : handlers) {
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue();
|
||||
if (List.of("assign", "syncTemplates", "assignees").contains(m.getName())) {
|
||||
assertThat(modules(m)).as(m.getName()).containsExactly("BO_WHATSAPP_ADMIN");
|
||||
} else {
|
||||
assertThat(modules(m)).as(m.getName()).containsExactlyInAnyOrder("BO_WHATSAPP", "BO_WHATSAPP_ADMIN");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void readMarkersAreNotAuditedAndWritesNameTheirAction() throws Exception {
|
||||
assertThat(AdminWhatsAppController.class.getMethod("read", String.class, Long.class).getAnnotation(Audited.class).skip()).isTrue();
|
||||
assertThat(AdminWhatsAppController.class.getMethod("send", String.class, SendMessageRequest.class, Long.class)
|
||||
.getAnnotation(Audited.class).action()).isEqualTo("WHATSAPP_SEND");
|
||||
assertThat(AdminWhatsAppController.class.getMethod("assign", String.class, AssignRequest.class, Long.class)
|
||||
.getAnnotation(Audited.class).action()).isEqualTo("WHATSAPP_ASSIGN");
|
||||
assertThat(AdminWhatsAppController.class.getMethod("syncTemplates", Long.class)
|
||||
.getAnnotation(Audited.class).action()).isEqualTo("WHATSAPP_TEMPLATE_SYNC");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendBindsTheBodyAndPath() throws Exception {
|
||||
mvc.perform(post("/api/admin/whatsapp/conversations/c1/messages").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"template\":\"expo_followup\",\"language\":\"en\",\"params\":[\"A\",\"B\"]}"))
|
||||
.andExpect(status().isOk());
|
||||
verify(whatsapp).send("c1", null, new SendMessageRequest(null, "expo_followup", "en", List.of("A", "B")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readAnswers204() throws Exception {
|
||||
mvc.perform(post("/api/admin/whatsapp/conversations/c1/read")).andExpect(status().isNoContent());
|
||||
verify(whatsapp).read("c1", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadCountAndListPassTheirParameters() throws Exception {
|
||||
when(whatsapp.unreadCount(null)).thenReturn(new UnreadCount(3));
|
||||
mvc.perform(get("/api/admin/whatsapp/unread-count")).andExpect(status().isOk()).andExpect(content().json("{\"count\":3}"));
|
||||
mvc.perform(get("/api/admin/whatsapp/conversations").param("tab", "unassigned").param("q", "ais").param("companyId", "2"))
|
||||
.andExpect(status().isOk());
|
||||
verify(whatsapp).list(2L, "unassigned", "ais", 0, 30);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mediaStreamsWithTheTypeAndNoCaching() throws Exception {
|
||||
doAnswer(i -> {
|
||||
AdminWhatsAppService.MediaOutput out = i.getArgument(2);
|
||||
out.open("image/jpeg", 3).write(new byte[]{1, 2, 3});
|
||||
return null;
|
||||
}).when(whatsapp).media(eq("m1"), isNull(), any());
|
||||
|
||||
mvc.perform(get("/api/admin/whatsapp/media/m1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string("Content-Type", "image/jpeg"))
|
||||
.andExpect(header().string("Cache-Control", "private, no-store"))
|
||||
.andExpect(content().bytes(new byte[]{1, 2, 3}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mediaASenderTypedAsHtmlIsADownloadThatCannotRun() throws Exception {
|
||||
doAnswer(i -> {
|
||||
AdminWhatsAppService.MediaOutput out = i.getArgument(2);
|
||||
out.open("text/html", 1).write(new byte[]{1});
|
||||
return null;
|
||||
}).when(whatsapp).media(eq("m2"), isNull(), any());
|
||||
|
||||
mvc.perform(get("/api/admin/whatsapp/media/m2"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string("X-Content-Type-Options", "nosniff"))
|
||||
.andExpect(header().string("Content-Security-Policy", "sandbox"))
|
||||
.andExpect(header().string("Content-Disposition", "attachment"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mediaImagesStayInline() throws Exception {
|
||||
doAnswer(i -> {
|
||||
AdminWhatsAppService.MediaOutput out = i.getArgument(2);
|
||||
out.open("image/png", 1).write(new byte[]{1});
|
||||
return null;
|
||||
}).when(whatsapp).media(eq("m3"), isNull(), any());
|
||||
|
||||
mvc.perform(get("/api/admin/whatsapp/media/m3"))
|
||||
.andExpect(header().doesNotExist("Content-Disposition"))
|
||||
.andExpect(header().string("X-Content-Type-Options", "nosniff"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void assigneesComeFromTheService() throws Exception {
|
||||
when(whatsapp.assignees(null)).thenReturn(List.of(Map.of("id", 21, "name", "Siti")));
|
||||
mvc.perform(get("/api/admin/whatsapp/assignees")).andExpect(status().isOk())
|
||||
.andExpect(content().json("[{\"id\":21,\"name\":\"Siti\"}]", true));
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.LocationHierarchy;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
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.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.when;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminUserServiceWhatsAppTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminUserService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminUserService(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.setId(1L);
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(7L);
|
||||
LocationHierarchy branch = new LocationHierarchy();
|
||||
branch.setId(3L);
|
||||
caller.setBranch(branch);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
||||
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
||||
when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins")));
|
||||
when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(role(4, "ROLE_SALES"), role(5, "ROLE_OPS"), role(6, "ROLE_ACCOUNTS"))));
|
||||
when(rest.getForEntity(eq("/user/findByUsername/{username}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq("/user/findByEmailAndCompanyId/{email}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq("/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> {
|
||||
Map<String, Object> saved = new HashMap<>((Map<String, Object>) i.getArgument(2));
|
||||
saved.put("id", 9L);
|
||||
return ResponseEntity.ok(saved);
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> role(long id, String name) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stored(boolean enabled, Map<String, Object>... roles) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", 9L);
|
||||
u.put("name", "Sam");
|
||||
u.put("username", "sam");
|
||||
u.put("email", "sam@x.com");
|
||||
u.put("enabled", enabled);
|
||||
u.put("type", "A");
|
||||
u.put("companyId", 7L);
|
||||
u.put("roles", List.of(roles));
|
||||
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> change(Object before, Object after) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("before", before);
|
||||
m.put("after", after);
|
||||
return m;
|
||||
}
|
||||
|
||||
private static final String USER_CHANGED = "/whatsapp/ownership/userChanged";
|
||||
|
||||
private void verifyUserChanged(int times) {
|
||||
verify(rest, org.mockito.Mockito.times(times)).postForEntity(eq(USER_CHANGED), eq(Void.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disablingAUserFreesTheirWhatsappChats() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
service.update(9L, new AdminUserRequest(null, null, null, null, false, null));
|
||||
verifyUserChanged(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingRolesFreesTheirWhatsappChats() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
service.update(9L, new AdminUserRequest(null, null, null, null, null, List.of(new AdminRoleRef(5L, null))));
|
||||
verifyUserChanged(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherEditsLeaveWhatsappAlone() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
service.update(9L, new AdminUserRequest("Renamed", null, null, null, true, List.of(new AdminRoleRef(4L, null))));
|
||||
verifyUserChanged(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWhatsappFailureDoesNotFailTheSave() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
when(rest.postForEntity(eq(USER_CHANGED), eq(Void.class), any())).thenThrow(new org.springframework.web.client.ResourceAccessException("down"));
|
||||
service.update(9L, new AdminUserRequest(null, null, null, null, false, null));
|
||||
verifyUserChanged(1);
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
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.dto.whatsapp.AssignRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ConversationPage;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ConversationView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.MessageView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.StartChatRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ThreadView;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
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.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
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.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.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminWhatsAppServiceTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminWhatsAppService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminWhatsAppService(rest, mock(RestTemplate.class), auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> "http://gw/" + i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static User user(long id, Long companyId, long... roleIds) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setUsername("u" + id);
|
||||
u.setCompanyId(companyId);
|
||||
List<Role> roles = new ArrayList<>();
|
||||
for (long r : roleIds) {
|
||||
Role role = new Role();
|
||||
role.setId(r);
|
||||
roles.add(role);
|
||||
}
|
||||
u.setRoles(roles);
|
||||
return u;
|
||||
}
|
||||
|
||||
/** BO module list where role 7 holds BO_WHATSAPP and role 8 holds BO_WHATSAPP_ADMIN. */
|
||||
private void modules() {
|
||||
when(rest.getForEntity(eq("http://gw//module/findAllByArea/{area}"), any(ParameterizedTypeReference.class), eq("BO")))
|
||||
.thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("name", "BO_WHATSAPP", "roles", List.of(Map.of("id", 7))),
|
||||
Map.of("name", "BO_WHATSAPP_ADMIN", "roles", List.of(Map.of("id", 8))))));
|
||||
}
|
||||
|
||||
private static ConversationView conv(Long owner, boolean manual) {
|
||||
return new ConversationView("c1", 5L, "60123", "Aisyah", 9L, "Aisyah", owner, null, manual, null, null, null, true, 0);
|
||||
}
|
||||
|
||||
private String lastGetUrl() {
|
||||
ArgumentCaptor<String> url = ArgumentCaptor.forClass(String.class);
|
||||
verify(rest).getForEntity(url.capture(), eq(ConversationPage.class), any(Object[].class));
|
||||
return url.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffAreScopedToTheirCompanyAsNonAdmin() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class)))
|
||||
.thenReturn(ResponseEntity.ok(new ConversationPage(List.of(), 0, 0, 30)));
|
||||
|
||||
service.list(99L, "mine", null, 0, 30); // a requested company is ignored for staff
|
||||
|
||||
assertThat(lastGetUrl()).contains("companyId=5&userId=11&admin=false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whatsappAdminsAndSuperAdminsActAsAdmin() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8));
|
||||
modules();
|
||||
when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class)))
|
||||
.thenReturn(ResponseEntity.ok(new ConversationPage(List.of(), 0, 0, 30)));
|
||||
service.list(null, "all", null, 0, 30);
|
||||
assertThat(lastGetUrl()).contains("companyId=5&userId=12&admin=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminSeesTheRequestedCompanyOrAll() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(1, null, 1));
|
||||
when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class)))
|
||||
.thenReturn(ResponseEntity.ok(new ConversationPage(List.of(), 0, 0, 30)));
|
||||
service.list(null, "all", null, 0, 30);
|
||||
assertThat(lastGetUrl()).contains("companyId=&userId=1&admin=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffWithoutACompanyFailClosed() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(13, null, 7));
|
||||
assertThatThrownBy(() -> service.list(null, "mine", null, 0, 30))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403));
|
||||
verify(rest, never()).getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listFillsOwnerNamesWithOneLookupPerOwner() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(1, null, 1));
|
||||
when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class)))
|
||||
.thenReturn(ResponseEntity.ok(new ConversationPage(List.of(conv(21L, false), conv(21L, true), conv(null, false)), 3, 0, 30)));
|
||||
when(rest.getForEntity(eq("http://gw//user/findById/{id}"), any(ParameterizedTypeReference.class), eq(21L)))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("name", "Siti", "surname", "Rahman", "username", "sales1")));
|
||||
|
||||
ConversationPage page = service.list(null, "all", null, 0, 30);
|
||||
|
||||
assertThat(page.items()).extracting(ConversationView::ownerName).containsExactly("Siti Rahman", "Siti Rahman", null);
|
||||
verify(rest, times(1)).getForEntity(eq("http://gw//user/findById/{id}"), any(ParameterizedTypeReference.class), eq(21L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendNeedsExactlyOneOfTextOrTemplate() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
for (SendMessageRequest bad : new SendMessageRequest[]{
|
||||
new SendMessageRequest("hi", "expo_followup", "en", List.of()),
|
||||
new SendMessageRequest(" ", null, null, null), null}) {
|
||||
assertThatThrownBy(() -> service.send("c1", null, bad))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(400));
|
||||
}
|
||||
verify(rest, never()).postForEntity(anyString(), eq(MessageView.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateSendIsAuditedWithTheTemplateNameButNotTheText() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
when(rest.postForEntity(anyString(), eq(MessageView.class), any())).thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
service.send("c1", null, new SendMessageRequest(null, "expo_followup", "en", List.of("Aisyah", "Expo")));
|
||||
|
||||
verify(rest).postForEntity(eq("http://gw//whatsapp/conversations/c1/messages?companyId=5&userId=11&admin=false"),
|
||||
eq(MessageView.class), any());
|
||||
assertThat(AuditChanges.current()).containsKeys("conversation", "template");
|
||||
assertThat(AuditChanges.current().toString()).contains("expo_followup").doesNotContain("Aisyah").doesNotContain("Expo");
|
||||
}
|
||||
|
||||
@Test
|
||||
void textSendAuditsNoText() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
when(rest.postForEntity(anyString(), eq(MessageView.class), any())).thenReturn(ResponseEntity.ok(null));
|
||||
service.send("c1", null, new SendMessageRequest("my secret text", null, null, null));
|
||||
assertThat(AuditChanges.current().toString()).doesNotContain("secret");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPathIdThatIsNotAUuidNeverReachesTheService() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
assertThatThrownBy(() -> service.send("../templates/sync", null, new SendMessageRequest("x", null, null, null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404));
|
||||
verify(rest, never()).postForEntity(anyString(), eq(MessageView.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceReasonsComeBackWithTheirStatusCodeAndMessage() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
when(rest.postForEntity(anyString(), eq(MessageView.class), any())).thenThrow(HttpClientErrorException.create(
|
||||
HttpStatus.CONFLICT, "Conflict", HttpHeaders.EMPTY,
|
||||
"{\"status\":409,\"detail\":\"WINDOW_CLOSED\"}".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
|
||||
|
||||
assertThatThrownBy(() -> service.send("c1", null, new SendMessageRequest("hi", null, null, null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode().value()).isEqualTo(409);
|
||||
assertThat(e.getCode()).isEqualTo("WINDOW_CLOSED");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("message", "The 24-hour window has closed. Send a template.");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreachableServiceIs502() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
when(rest.getForEntity(anyString(), eq(ConversationPage.class), any(Object[].class))).thenThrow(new ResourceAccessException("down"));
|
||||
assertThatThrownBy(() -> service.list(null, "mine", null, 0, 30))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(502));
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignNeedsExactlyOneOfUserOrAutomaticAndAnAdmin() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8));
|
||||
modules();
|
||||
for (AssignRequest bad : new AssignRequest[]{new AssignRequest(21L, true), new AssignRequest(null, false), null}) {
|
||||
assertThatThrownBy(() -> service.assign("c1", null, bad))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(400));
|
||||
}
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7)); // staff
|
||||
assertThatThrownBy(() -> service.assign("c1", null, new AssignRequest(21L, null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403));
|
||||
verify(rest, never()).postForEntity(anyString(), eq(ConversationView.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignIsAuditedFromAndToOwner() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8));
|
||||
modules();
|
||||
when(rest.getForEntity(anyString(), eq(ThreadView.class))).thenReturn(ResponseEntity.ok(new ThreadView(conv(21L, false), List.of(), false)));
|
||||
when(rest.postForEntity(anyString(), eq(ConversationView.class), any())).thenReturn(ResponseEntity.ok(conv(22L, true)));
|
||||
|
||||
service.assign("c1", null, new AssignRequest(22L, null));
|
||||
|
||||
Map<String, Object> owner = (Map<String, Object>) AuditChanges.current().get("ownerUserId");
|
||||
assertThat(owner).containsEntry("before", 21L).containsEntry("after", 22L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startNeedsExactlyOneOfLeadOrEventLead() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
for (StartChatRequest bad : new StartChatRequest[]{new StartChatRequest(1L, 2L), new StartChatRequest(null, null), null}) {
|
||||
assertThatThrownBy(() -> service.start(null, bad))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(400));
|
||||
}
|
||||
verifyNoInteractions(rest);
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncAndAssigneesAreForAdminsOnly() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(11, 5L, 7));
|
||||
modules();
|
||||
assertThatThrownBy(() -> service.syncTemplates(null))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403));
|
||||
assertThatThrownBy(() -> service.assignees(null))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(403));
|
||||
}
|
||||
|
||||
@Test
|
||||
void assigneesAreTheCompanysActiveWhatsappUsersWithNames() {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(user(12, 5L, 8));
|
||||
modules();
|
||||
when(rest.getForEntity(eq("http://gw//user/activeWithModule?companyId={companyId}&module={module}"),
|
||||
any(ParameterizedTypeReference.class), eq(5L), eq("BO_WHATSAPP"))).thenReturn(ResponseEntity.ok(List.of(21L)));
|
||||
when(rest.getForEntity(eq("http://gw//user/findById/{id}"), any(ParameterizedTypeReference.class), eq(21L)))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("name", "Siti", "username", "sales1")));
|
||||
|
||||
assertThat(service.assignees(null)).containsExactly(Map.of("id", 21L, "name", "Siti"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void userChangedIsBestEffort() {
|
||||
when(rest.postForEntity(anyString(), eq(Void.class), any())).thenThrow(new ResourceAccessException("down"));
|
||||
AdminWhatsAppService.userChanged(rest, 21L); // no exception
|
||||
verify(rest).postForEntity(eq("http://gw//whatsapp/ownership/userChanged"), eq(Void.class), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user