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
@@ -53,7 +53,7 @@ Verify commands:
|
||||
- Depends on: 3.2
|
||||
- Scope: `solvway-services-whatsapp/**`, `local/whatsapp-mock/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-whatsapp verify`
|
||||
- [ ] 4.2 mobile-api admin API: every endpoint in design decision 9, module checks, company scoping (fail closed), audit, and the `userChanged` call from the user save path.
|
||||
- [x] 4.2 mobile-api admin API: every endpoint in design decision 9, module checks, company scoping (fail closed), audit, and the `userChanged` call from the user save path.
|
||||
- Depends on: 4.1
|
||||
- Scope: `solvway-mobile-api/**` (security code: also read the whole diff in the controller check)
|
||||
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
|
||||
|
||||
+1
@@ -7,6 +7,7 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}";
|
||||
public static final String API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE = "/user/activeWithModule?companyId={companyId}&module={module}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}";
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
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.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.TemplateView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ThreadView;
|
||||
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 jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The WhatsApp inbox (design decision 9). Staff with BO_WHATSAPP see their own chats; BO_WHATSAPP_ADMIN sees the
|
||||
* company's. companyId is honoured for a super admin only (AdminCompanyScope). Must stay under {@code controller..}.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/whatsapp")
|
||||
@RequiredArgsConstructor
|
||||
@AdminModule({AdminWhatsAppService.MODULE, AdminWhatsAppService.MODULE_ADMIN})
|
||||
public class AdminWhatsAppController {
|
||||
private final AdminWhatsAppService whatsapp;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/conversations")
|
||||
public ResponseEntity<ConversationPage> list(@RequestParam(defaultValue = "mine") String tab, @RequestParam(required = false) String q,
|
||||
@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "30") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.list(companyId, tab, q, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/conversations/{uuid}")
|
||||
public ResponseEntity<ThreadView> thread(@PathVariable String uuid, @RequestParam(required = false) String before,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.thread(uuid, companyId, before));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@Audited(action = "WHATSAPP_SEND")
|
||||
@PostMapping("/conversations/{uuid}/messages")
|
||||
public ResponseEntity<MessageView> send(@PathVariable String uuid, @RequestBody SendMessageRequest request,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.send(uuid, companyId, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@Audited(skip = true)
|
||||
@PostMapping("/conversations/{uuid}/read")
|
||||
public ResponseEntity<Void> read(@PathVariable String uuid, @RequestParam(required = false) Long companyId) {
|
||||
whatsapp.read(uuid, companyId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminWhatsAppService.MODULE_ADMIN)
|
||||
@Audited(action = "WHATSAPP_ASSIGN")
|
||||
@PostMapping("/conversations/{uuid}/assign")
|
||||
public ResponseEntity<ConversationView> assign(@PathVariable String uuid, @RequestBody AssignRequest request,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.assign(uuid, companyId, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@Audited(action = "WHATSAPP_START")
|
||||
@PostMapping("/start")
|
||||
public ResponseEntity<ConversationView> start(@RequestBody StartChatRequest request, @RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.start(companyId, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/templates")
|
||||
public ResponseEntity<List<TemplateView>> templates(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.templates(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminWhatsAppService.MODULE_ADMIN)
|
||||
@Audited(action = "WHATSAPP_TEMPLATE_SYNC")
|
||||
@PostMapping("/templates/sync")
|
||||
public ResponseEntity<List<TemplateView>> syncTemplates(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.syncTemplates(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/media/{messageUuid}")
|
||||
public void media(@PathVariable String messageUuid, @RequestParam(required = false) Long companyId, HttpServletResponse response) {
|
||||
whatsapp.media(messageUuid, companyId, (type, length) -> {
|
||||
response.setContentType(type);
|
||||
if (length >= 0) response.setContentLengthLong(length);
|
||||
response.setHeader("Cache-Control", "private, no-store");
|
||||
// The type is whatever the sender declared: never let it run as a page on this origin.
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.setHeader("Content-Security-Policy", "sandbox");
|
||||
if (!type.startsWith("image/") && !type.startsWith("audio/") && !type.startsWith("video/")) {
|
||||
response.setHeader("Content-Disposition", "attachment");
|
||||
}
|
||||
return response.getOutputStream();
|
||||
});
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/unread-count")
|
||||
public ResponseEntity<UnreadCount> unreadCount(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.unreadCount(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminWhatsAppService.MODULE_ADMIN)
|
||||
@GetMapping("/assignees")
|
||||
public ResponseEntity<List<Map<String, Object>>> assignees(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.assignees(companyId));
|
||||
}
|
||||
}
|
||||
@@ -178,6 +178,10 @@ public class AdminUserService {
|
||||
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
||||
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
|
||||
if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled());
|
||||
if (Boolean.FALSE.equals(r.enabled()) && !Boolean.FALSE.equals(enabledBefore)
|
||||
|| r.roles() != null && !rolesBefore.equals(rolesAfter)) {
|
||||
AdminWhatsAppService.userChanged(restTemplateUtil, id); // they may have lost WhatsApp: free their chats
|
||||
}
|
||||
return present(clean(saved));
|
||||
}
|
||||
|
||||
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiWhatsappServiceConstants;
|
||||
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.TemplateView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ThreadView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.UnreadCount;
|
||||
import com.solvway.mobile.api.dto.whatsapp.UserChangedRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.useraccess.AdminModuleAccess;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpStatusCodeException;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The WhatsApp inbox for the admin portal. Resolves the caller's context (company, user, admin) from the token and
|
||||
* passes it to the WhatsApp service, which enforces who may see what (RestApiWhatsappServiceConstants).
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AdminWhatsAppService {
|
||||
public static final String MODULE = "BO_WHATSAPP";
|
||||
public static final String MODULE_ADMIN = "BO_WHATSAPP_ADMIN";
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final java.util.regex.Pattern UUID_LIKE = java.util.regex.Pattern.compile("[A-Za-z0-9-]{1,64}");
|
||||
private static final ParameterizedTypeReference<List<Long>> IDS = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<TemplateView>> TEMPLATES = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
/** Messages the portal shows for the service's reason codes; anything else keeps the code. */
|
||||
private static final Map<String, String> MESSAGES = Map.of(
|
||||
"WINDOW_CLOSED", "The 24-hour window has closed. Send a template.",
|
||||
"TEMPLATE_PARAMS", "Fill in every template parameter.",
|
||||
"MEDIA_EXPIRED", "Media expired",
|
||||
"WHATSAPP_NOT_CONFIGURED", "WhatsApp is not configured",
|
||||
"ASSIGNEE_NOT_ALLOWED", "This user cannot take WhatsApp chats.",
|
||||
"LEAD_NOT_FOUND", "This lead has no mobile number.",
|
||||
"USERS_UNAVAILABLE", "Users could not be loaded. Try again.");
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final RestTemplate restTemplate;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
// a field initializer: the scope holds no state
|
||||
private final AdminCompanyScope scope = new AdminCompanyScope();
|
||||
|
||||
public AdminWhatsAppService(RestTemplateCustomUtil rest, RestTemplate restTemplate,
|
||||
AdminAuthenticationService adminAuthenticationService) {
|
||||
this.rest = rest;
|
||||
this.restTemplate = restTemplate;
|
||||
this.adminAuthenticationService = adminAuthenticationService;
|
||||
}
|
||||
|
||||
/** Who is asking: the company they may see (null = super admin, all companies), their id, and admin rights. */
|
||||
record Context(Long companyId, long userId, boolean admin) {}
|
||||
|
||||
Context context(Long requestedCompanyId) {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null || caller.getId() == null) throw coded(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
Long company = scope.scope(caller, requestedCompanyId); // staff without a company: 403, fail closed
|
||||
boolean admin = AdminCompanyScope.isSuper(caller) || AdminModuleAccess.holds(rest, caller, MODULE_ADMIN);
|
||||
return new Context(company, caller.getId(), admin);
|
||||
}
|
||||
|
||||
public ConversationPage list(Long companyId, String tab, String q, int page, int size) {
|
||||
Context c = context(companyId);
|
||||
ConversationPage p = call(() -> rest.getForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATIONS, null, c)
|
||||
+ "&tab={tab}&q={q}&page={page}&size={size}",
|
||||
ConversationPage.class, tab, q == null ? "" : q.trim(), page, size).getBody());
|
||||
Function<Long, String> names = names();
|
||||
return new ConversationPage(p.items().stream().map(v -> named(v, names)).toList(), p.total(), p.page(), p.size());
|
||||
}
|
||||
|
||||
public ThreadView thread(String uuid, Long companyId, String before) {
|
||||
Context c = context(companyId);
|
||||
String u = url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION, uuid, c);
|
||||
ThreadView t = call(() -> before == null
|
||||
? rest.getForEntity(u, ThreadView.class).getBody()
|
||||
: rest.getForEntity(u + "&before={before}", ThreadView.class, before).getBody());
|
||||
return new ThreadView(named(t.conversation(), names()), t.messages(), t.hasOlder());
|
||||
}
|
||||
|
||||
public MessageView send(String uuid, Long companyId, SendMessageRequest r) {
|
||||
boolean text = r != null && StringUtils.hasText(r.text());
|
||||
boolean template = r != null && StringUtils.hasText(r.template());
|
||||
if (text == template) throw coded(HttpStatus.BAD_REQUEST, "Send a text or a template.", "INVALID_PAYLOAD");
|
||||
Context c = context(companyId);
|
||||
// the template name only: never the message text or the filled-in parameters
|
||||
AuditChanges.put("conversation", null, uuid);
|
||||
if (template) AuditChanges.put("template", null, r.template());
|
||||
return call(() -> rest.postForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_SEND, uuid, c),
|
||||
MessageView.class, r).getBody());
|
||||
}
|
||||
|
||||
public void read(String uuid, Long companyId) {
|
||||
Context c = context(companyId);
|
||||
call(() -> rest.postForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_READ, uuid, c),
|
||||
Void.class, null));
|
||||
}
|
||||
|
||||
public ConversationView assign(String uuid, Long companyId, AssignRequest r) {
|
||||
boolean manual = r != null && r.userId() != null;
|
||||
boolean automatic = r != null && Boolean.TRUE.equals(r.automatic());
|
||||
if (manual == automatic) throw coded(HttpStatus.BAD_REQUEST, "Choose a user or automatic.", "INVALID_PAYLOAD");
|
||||
Context c = context(companyId);
|
||||
if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN");
|
||||
// ponytail: reads the thread for the owner before the change (audit); a light conversation GET if it shows up in latency.
|
||||
ConversationView before = call(() -> rest.getForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION, uuid, c), ThreadView.class).getBody()).conversation();
|
||||
ConversationView after = call(() -> rest.postForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_ASSIGN, uuid, c),
|
||||
ConversationView.class, r).getBody());
|
||||
AuditChanges.put("ownerUserId", before.ownerUserId(), after.ownerUserId());
|
||||
AuditChanges.put("ownerManual", before.ownerManual(), after.ownerManual());
|
||||
return named(after, names());
|
||||
}
|
||||
|
||||
public ConversationView start(Long companyId, StartChatRequest r) {
|
||||
if (r == null || (r.leadUuid() == null) == (r.eventLeadUuid() == null)) {
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Choose a lead or an event lead.", "INVALID_PAYLOAD");
|
||||
}
|
||||
Context c = context(companyId);
|
||||
ConversationView v = call(() -> rest.postForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_START, null, c), ConversationView.class, r).getBody());
|
||||
AuditChanges.put("conversation", null, v.uuid());
|
||||
return named(v, names());
|
||||
}
|
||||
|
||||
public List<TemplateView> templates(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
List<TemplateView> t = call(() -> rest.getForEntity(
|
||||
rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_TEMPLATES) + "?companyId={companyId}",
|
||||
TEMPLATES, c.companyId() == null ? "" : c.companyId()).getBody());
|
||||
return t == null ? List.of() : t;
|
||||
}
|
||||
|
||||
public List<TemplateView> syncTemplates(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN");
|
||||
AuditChanges.put("companyId", null, c.companyId());
|
||||
List<TemplateView> t = call(() -> rest.postForEntity(
|
||||
rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_TEMPLATES_SYNC)
|
||||
+ "?companyId=" + (c.companyId() == null ? "" : c.companyId()) + "&admin=true",
|
||||
TEMPLATES, null).getBody());
|
||||
return t == null ? List.of() : t;
|
||||
}
|
||||
|
||||
public UnreadCount unreadCount(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
return call(() -> rest.getForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_UNREAD_COUNT, null, c),
|
||||
UnreadCount.class).getBody());
|
||||
}
|
||||
|
||||
/** Active users of the company who hold BO_WHATSAPP: the people a WhatsApp Admin may assign a chat to. */
|
||||
public List<Map<String, Object>> assignees(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN");
|
||||
if (c.companyId() == null) throw coded(HttpStatus.BAD_REQUEST, "Choose a company.", "COMPANY_REQUIRED");
|
||||
List<Long> ids = call(() -> rest.getForEntity(rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE),
|
||||
IDS, c.companyId(), MODULE).getBody());
|
||||
Function<Long, String> names = names();
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Long id : ids == null ? List.<Long>of() : ids) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("id", id);
|
||||
row.put("name", names.apply(id));
|
||||
out.add(row);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Where the media bytes go: called once with the type and length, before any byte is written. */
|
||||
public interface MediaOutput {
|
||||
OutputStream open(String contentType, long contentLength) throws IOException;
|
||||
}
|
||||
|
||||
/** Streams an incoming image or document through; 404 without access, 410 when Meta no longer holds it. */
|
||||
public void media(String messageUuid, Long companyId, MediaOutput out) {
|
||||
Context c = context(companyId);
|
||||
String url = url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_MEDIA, messageUuid, c);
|
||||
call(() -> restTemplate.execute(url, HttpMethod.GET,
|
||||
req -> req.getHeaders().addAll(rest.getCommonHeaders()),
|
||||
resp -> {
|
||||
HttpHeaders h = resp.getHeaders();
|
||||
String type = h.getContentType() == null ? "application/octet-stream" : h.getContentType().toString();
|
||||
try (InputStream in = resp.getBody(); OutputStream o = out.open(type, h.getContentLength())) {
|
||||
in.transferTo(o);
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
|
||||
/** Best effort after a user is disabled or their roles change: the service unassigns chats they may no longer own. */
|
||||
public static void userChanged(RestTemplateCustomUtil rest, Long userId) {
|
||||
try {
|
||||
rest.postForEntity(rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_OWNERSHIP_USER_CHANGED),
|
||||
Void.class, new UserChangedRequest(userId));
|
||||
} catch (RuntimeException e) { // the nightly job repairs a missed call
|
||||
log.warn("WhatsApp ownership update for user {} failed: {}", userId, e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
/** The service URL with the path id filled in and the caller context as query params. Ids are uuids only, so nothing else reaches the path. */
|
||||
private String url(String api, String id, Context c) {
|
||||
String path = api;
|
||||
if (id != null) {
|
||||
if (!UUID_LIKE.matcher(id).matches()) throw coded(HttpStatus.NOT_FOUND, "Not found", "CONVERSATION_NOT_FOUND");
|
||||
path = api.replaceFirst("\\{[^}]+}", id);
|
||||
}
|
||||
return rest.getURLforApiService(path) + "?companyId=" + (c.companyId() == null ? "" : c.companyId())
|
||||
+ "&userId=" + c.userId() + "&admin=" + c.admin();
|
||||
}
|
||||
|
||||
/** User names by id, one lookup per distinct id per request. */
|
||||
// ponytail: N lookups for N distinct owners on a page (usually a handful); add a system findByIds if pages grow.
|
||||
private Function<Long, String> names() {
|
||||
Map<Long, String> cache = new HashMap<>();
|
||||
return id -> id == null ? null : cache.computeIfAbsent(id, k -> {
|
||||
try {
|
||||
ResponseEntity<Map<String, Object>> found = rest.getForEntity(
|
||||
rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, k);
|
||||
Map<String, Object> u = found == null ? null : found.getBody();
|
||||
if (u == null) return null;
|
||||
String name = (String.valueOf(u.getOrDefault("name", "")) + " "
|
||||
+ (u.get("surname") == null ? "" : u.get("surname"))).trim();
|
||||
return name.isEmpty() ? String.valueOf(u.get("username")) : name;
|
||||
} catch (RestClientException e) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static ConversationView named(ConversationView v, Function<Long, String> names) {
|
||||
if (v == null) return null;
|
||||
return new ConversationView(v.uuid(), v.companyId(), v.contactWaId(), v.contactName(), v.leadUuid(), v.leadName(),
|
||||
v.ownerUserId(), names.apply(v.ownerUserId()), v.ownerManual(), v.lastInboundAt(), v.lastMessageAt(),
|
||||
v.lastMessagePreview(), v.windowOpen(), v.unreadCount());
|
||||
}
|
||||
|
||||
/** Runs a service call; a 4xx from the service becomes the same status with its reason code and a message. */
|
||||
private static <T> T call(java.util.function.Supplier<T> s) {
|
||||
try {
|
||||
return s.get();
|
||||
} catch (HttpStatusCodeException e) {
|
||||
HttpStatusCode status = e.getStatusCode();
|
||||
if (!status.is4xxClientError()) throw coded(HttpStatus.BAD_GATEWAY, "WhatsApp is unavailable. Try again.", "WHATSAPP_UNAVAILABLE");
|
||||
String code = detail(e);
|
||||
return throwCoded(status, MESSAGES.getOrDefault(code, code), code);
|
||||
} catch (RestClientException | UncheckedIOException e) {
|
||||
throw coded(HttpStatus.BAD_GATEWAY, "WhatsApp is unavailable. Try again.", "WHATSAPP_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> T throwCoded(HttpStatusCode status, String message, String code) {
|
||||
CodedResponseStatusException ex = new CodedResponseStatusException(status, message, code);
|
||||
ex.getBody().setProperty("message", message);
|
||||
throw ex;
|
||||
}
|
||||
|
||||
private static String detail(HttpStatusCodeException e) {
|
||||
try {
|
||||
JsonNode body = JSON.readTree(e.getResponseBodyAsString());
|
||||
String d = body == null ? "" : body.path("detail").asText("");
|
||||
return d.isEmpty() ? "NOT_FOUND" : d;
|
||||
} catch (IOException ex) {
|
||||
return "NOT_FOUND";
|
||||
}
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException coded(HttpStatusCode status, String message, String code) {
|
||||
CodedResponseStatusException ex = new CodedResponseStatusException(status, message, code);
|
||||
ex.getBody().setProperty("message", message);
|
||||
return ex;
|
||||
}
|
||||
|
||||
}
|
||||
+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