feat: whatsapp send, templates and media proxy

- MetaClient: text and template sends, approved templates with bounded paging, streamed media with a 100 MB cap.
- Send endpoint: 24-hour window, template params and supported checks before Meta; pending then sent or failed with Meta's code and title.
- Template sync per company and nightly at 03:30 KL; a failed fetch keeps existing rows.
- Media proxy: 404 without access, 410 when Meta no longer holds the file.
- Mock: Graph send, templates, media and bearer checks; /simulate/inbound and /simulate/status sign with the company secret.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 11:03:56 +08:00
1 parent e6c3a488cf
commit 9f1b8de04d
13 files changed
+1570 -11

No files matched your search

@@ -217,7 +217,7 @@ public class InboxService {
return companyId == null && !admin;
}
private WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) {
WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) {
if (failClosed(companyId, admin)) {
throw notFound();
}
@@ -258,7 +258,7 @@ public class InboxService {
c.ownerManual, c.lastInboundAt, c.lastMessageAt, withPreview ? c.lastMessagePreview : null, open, unread);
}
private static MessageView message(WaMessage m) {
static MessageView message(WaMessage m) {
return new MessageView(m.uuid, m.direction, m.type, m.body, m.templateName, m.mediaMime, m.mediaFilename, m.locationLat,
m.locationLng, m.locationName, m.status, m.errorCode, m.errorTitle, m.sentByUserId, m.createdAt, m.statusAt);
}
@@ -0,0 +1,68 @@
package com.solvway.services.whatsapp.inbox;
import com.solvway.services.whatsapp.dto.MessageView;
import com.solvway.services.whatsapp.dto.SendMessageRequest;
import com.solvway.services.whatsapp.dto.TemplateView;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
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;
/** Sending, templates and media. Caller context arrives as trusted query params from mobile-api, like {@link InboxController}. */
@RestController
@RequestMapping("/whatsapp")
public class OutboundController {
private final OutboundService service;
private final TemplateService templates;
public OutboundController(OutboundService service, TemplateService templates) {
this.service = service;
this.templates = templates;
}
@PostMapping("/conversations/{uuid}/messages")
public MessageView send(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId,
@RequestParam boolean admin, @RequestBody SendMessageRequest request) {
return service.send(uuid, companyId, userId, admin, request);
}
@GetMapping("/templates")
public List<TemplateView> templates(@RequestParam(required = false) Long companyId) {
return templates.list(companyId);
}
@PostMapping("/templates/sync")
public List<TemplateView> sync(@RequestParam(required = false) Long companyId, @RequestParam boolean admin) {
return templates.sync(companyId, admin);
}
/** Streams straight from Meta into the response; errors are decided before the first byte so they still get a ProblemDetail. */
@GetMapping("/media/{messageUuid}")
public void media(@PathVariable String messageUuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId,
@RequestParam boolean admin, HttpServletResponse response) {
service.media(messageUuid, companyId, userId, admin, (mime, disposition, length) -> {
MediaType type;
try {
type = mime == null ? MediaType.APPLICATION_OCTET_STREAM : MediaType.parseMediaType(mime);
} catch (IllegalArgumentException e) {
type = MediaType.APPLICATION_OCTET_STREAM;
}
response.setContentType(type.toString());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition);
response.setHeader("X-Content-Type-Options", "nosniff");
if (length >= 0) {
response.setContentLengthLong(length);
}
return response.getOutputStream();
});
}
}
@@ -0,0 +1,185 @@
package com.solvway.services.whatsapp.inbox;
import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig;
import com.solvway.services.whatsapp.dto.MessageView;
import com.solvway.services.whatsapp.dto.SendMessageRequest;
import com.solvway.services.whatsapp.meta.MetaClient;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.model.WaMessage;
import com.solvway.services.whatsapp.model.WaTemplate;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import com.solvway.services.whatsapp.repository.WaMessageRepository;
import com.solvway.services.whatsapp.repository.WaTemplateRepository;
import com.solvway.services.whatsapp.service.CompanyDirectory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Sends text (inside the 24-hour window) and templates, and proxies media. The Meta call runs outside any transaction.
* Never logs numbers, message text or tokens.
* ponytail: a delivery webhook that arrives before the wamid is saved is ignored (rare); the message then stays "sent".
*/
@Service
public class OutboundService {
private static final int TEXT_MAX = 4096;
private static final int PREVIEW_MAX = 80;
private static final Pattern PARAM = Pattern.compile("\\{\\{(\\d+)}}");
private static final Set<String> MEDIA_TYPES = Set.of("image", "sticker", "document", "audio", "video");
private static final Set<String> INLINE_MIMES = Set.of("image/jpeg", "image/png", "image/webp", "image/gif");
/** Where the proxied bytes go: called once with the final headers, before any byte is written. */
@FunctionalInterface
public interface MediaOutput {
java.io.OutputStream open(String mime, String disposition, long length) throws java.io.IOException;
}
private final InboxService inbox;
private final WaConversationRepository conversations;
private final WaMessageRepository messages;
private final WaTemplateRepository templates;
private final CompanyDirectory companies;
private final MetaClient meta;
private final Clock clock;
@Autowired
public OutboundService(InboxService inbox, WaConversationRepository conversations, WaMessageRepository messages,
WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta) {
this(inbox, conversations, messages, templates, companies, meta, Clock.systemDefaultZone());
}
OutboundService(InboxService inbox, WaConversationRepository conversations, WaMessageRepository messages,
WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, Clock clock) {
this.inbox = inbox;
this.conversations = conversations;
this.messages = messages;
this.templates = templates;
this.companies = companies;
this.meta = meta;
this.clock = clock;
}
public MessageView send(String uuid, Long companyId, Long userId, boolean admin, SendMessageRequest request) {
WaConversation c = inbox.visible(uuid, companyId, userId, admin);
boolean isText = request != null && request.text() != null;
boolean isTemplate = request != null && request.template() != null;
if (isText == isTemplate || (isText && (request.text().isBlank() || request.text().length() > TEXT_MAX))
|| (isTemplate && (request.template().isBlank() || request.language() == null || request.language().isBlank()))) {
throw bad("INVALID_PAYLOAD");
}
CompanyConfig cfg = companies.configOf(c.companyId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED"));
LocalDateTime now = LocalDateTime.now(clock);
String type;
String body;
String templateName = null;
List<String> params = null;
if (isText) {
if (c.lastInboundAt == null || !c.lastInboundAt.isAfter(now.minusHours(24))) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "WINDOW_CLOSED");
}
type = "text";
body = request.text();
} else {
WaTemplate t = templates.findByCompanyIdAndNameAndLanguage(c.companyId, request.template(), request.language())
.filter(x -> TemplateService.APPROVED.equals(x.status)).orElseThrow(() -> bad("TEMPLATE_PARAMS"));
params = request.params() == null ? List.of() : request.params();
if (params.size() != t.paramCount || params.stream().anyMatch(p -> p == null || p.isBlank())) {
throw bad("TEMPLATE_PARAMS");
}
type = "template";
templateName = t.name;
body = fill(t.bodyText, params);
}
WaMessage m = new WaMessage();
m.uuid = UUID.randomUUID().toString();
m.conversationId = c.id;
m.direction = "OUT";
m.type = type;
m.body = body;
m.templateName = templateName;
m.status = "pending";
m.sentByUserId = userId;
m.createdAt = now;
m = messages.save(m);
MetaClient.SendResult r = isText ? meta.sendText(cfg, c.contactWaId, body)
: meta.sendTemplate(cfg, c.contactWaId, templateName, request.language(), params);
m.statusAt = LocalDateTime.now(clock);
if (r.failed()) {
m.status = "failed";
m.errorCode = r.errorCode();
m.errorTitle = r.errorTitle();
} else {
m.status = "sent";
m.wamid = r.wamid();
}
m = messages.save(m);
conversations.recordOutbound(c.id, m.createdAt, preview(body));
return InboxService.message(m);
}
/**
* Streams a media message's bytes from Meta (404 when not visible or not media, 410 when Meta no longer has it).
* ponytail: Meta keeps media about 30 days and every view re-fetches it; upgrade by copying to object storage on receipt.
*/
public void media(String messageUuid, Long companyId, Long userId, boolean admin, MediaOutput output) {
WaMessage m = messages.findByUuid(messageUuid).orElseThrow(OutboundService::mediaNotFound);
WaConversation c = conversations.findById(m.conversationId).orElseThrow(OutboundService::mediaNotFound);
inbox.visible(c.uuid, companyId, userId, admin);
if (m.mediaId == null || !MEDIA_TYPES.contains(m.type)) {
throw mediaNotFound();
}
CompanyConfig cfg = companies.configOf(c.companyId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED"));
try {
meta.media(cfg, m.mediaId, (upstreamMime, length) -> {
String mime = m.mediaMime != null ? m.mediaMime : upstreamMime;
// Only plain raster images render inline; anything else (SVG, HTML, PDF...) downloads, so media can never run script here.
boolean inline = ("image".equals(m.type) || "sticker".equals(m.type)) && mime != null && INLINE_MIMES.contains(mime.toLowerCase());
String disposition = inline ? "inline"
: m.mediaFilename == null ? "attachment" : ContentDisposition.attachment().filename(m.mediaFilename).build().toString();
return output.open(mime, disposition, length);
});
} catch (MetaClient.MediaExpiredException e) {
throw new ResponseStatusException(HttpStatus.GONE, "MEDIA_EXPIRED");
} catch (MetaClient.MetaException e) {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "META_UNAVAILABLE");
}
}
private static String fill(String template, List<String> params) {
Matcher m = PARAM.matcher(template == null ? "" : template);
StringBuilder out = new StringBuilder();
while (m.find()) { // one pass over the template, so a parameter that contains {{2}} is not substituted again
int i = Integer.parseInt(m.group(1));
m.appendReplacement(out, Matcher.quoteReplacement(i >= 1 && i <= params.size() ? params.get(i - 1) : m.group()));
}
return m.appendTail(out).toString();
}
private static String preview(String text) {
return text.codePointCount(0, text.length()) <= PREVIEW_MAX ? text : text.substring(0, text.offsetByCodePoints(0, PREVIEW_MAX));
}
private static ResponseStatusException bad(String reason) {
return new ResponseStatusException(HttpStatus.BAD_REQUEST, reason);
}
private static ResponseStatusException mediaNotFound() {
return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND");
}
}
@@ -0,0 +1,187 @@
package com.solvway.services.whatsapp.inbox;
import com.fasterxml.jackson.databind.JsonNode;
import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig;
import com.solvway.services.whatsapp.dto.TemplateView;
import com.solvway.services.whatsapp.meta.MetaClient;
import com.solvway.services.whatsapp.model.WaTemplate;
import com.solvway.services.whatsapp.repository.WaTemplateRepository;
import com.solvway.services.whatsapp.service.CompanyDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Template list and sync from Meta. A template this app cannot fill in (media or parameterised header, parameterised or
* copy-code buttons, named parameters) is stored with status UNSUPPORTED so it shows but cannot be sent; supported ones
* keep status APPROVED (the sync only asks Meta for approved templates).
*/
@Service
public class TemplateService {
private static final Logger log = LoggerFactory.getLogger(TemplateService.class);
private static final Pattern PARAM = Pattern.compile("\\{\\{(\\d+)}}");
private static final Set<String> BUTTONS_OK = Set.of("QUICK_REPLY", "PHONE_NUMBER", "URL");
static final String APPROVED = "APPROVED";
static final String UNSUPPORTED = "UNSUPPORTED";
private final WaTemplateRepository templates;
private final CompanyDirectory companies;
private final MetaClient meta;
private final TransactionTemplate tx;
private final Clock clock;
@Autowired
public TemplateService(WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, TransactionTemplate tx) {
this(templates, companies, meta, tx, Clock.systemDefaultZone());
}
TemplateService(WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, TransactionTemplate tx, Clock clock) {
this.templates = templates;
this.companies = companies;
this.meta = meta;
this.tx = tx;
this.clock = clock;
}
/** ponytail: no company means no list (a super admin picks a company); upgrade to a merged list if needed. */
public List<TemplateView> list(Long companyId) {
if (companyId == null) {
return List.of();
}
return templates.findByCompanyIdOrderByNameAsc(companyId).stream().map(TemplateService::view).toList();
}
/** Admin only (404 otherwise). A super admin without a company syncs every configured company; one failure does not stop the rest. */
public List<TemplateView> sync(Long companyId, boolean admin) {
if (!admin) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "NOT_FOUND");
}
if (companyId == null) {
syncAll();
return List.of();
}
CompanyConfig cfg = companies.configOf(companyId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED"));
return syncOne(companyId, cfg).stream().map(TemplateService::view).toList();
}
@Scheduled(cron = "${whatsapp.templates.cron:0 30 3 * * *}", zone = "Asia/Kuala_Lumpur")
public void nightly() {
syncAll();
}
private void syncAll() {
for (Map.Entry<Long, CompanyConfig> e : companies.configured().entrySet()) {
try {
syncOne(e.getKey(), e.getValue());
} catch (RuntimeException ex) { // per company: log the id and exception type only
log.warn("WhatsApp template sync failed for company {}: {}", e.getKey(), ex.getClass().getSimpleName());
}
}
}
/** Fetch first, so a Meta failure leaves the existing rows alone; then replace them atomically. */
private List<WaTemplate> syncOne(long companyId, CompanyConfig cfg) {
List<JsonNode> fetched;
try {
fetched = meta.templates(cfg);
} catch (MetaClient.MetaException e) {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "META_UNAVAILABLE");
}
LocalDateTime now = LocalDateTime.now(clock);
List<WaTemplate> rows = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (JsonNode t : fetched) {
String name = t.path("name").asText("");
String language = t.path("language").asText("");
if (name.isEmpty() || language.isEmpty() || !seen.add(name + "\0" + language)) {
continue;
}
String body = bodyText(t);
WaTemplate row = new WaTemplate();
row.companyId = companyId;
row.name = name;
row.language = language;
row.category = t.path("category").asText(null);
row.status = supported(t) ? APPROVED : UNSUPPORTED;
row.bodyText = body;
row.paramCount = paramCount(body);
row.syncedAt = now;
rows.add(row);
}
tx.executeWithoutResult(s -> {
templates.deleteByCompanyId(companyId);
templates.saveAll(rows);
});
return rows;
}
/** The one place that decides whether this app can fill a template in: body-only parameters, plain header and buttons. */
static boolean supported(JsonNode template) {
if ("NAMED".equals(template.path("parameter_format").asText())) {
return false;
}
for (JsonNode c : template.path("components")) {
switch (c.path("type").asText()) {
case "BODY", "FOOTER" -> { }
case "HEADER" -> {
if (!"TEXT".equals(c.path("format").asText()) || c.path("text").asText("").contains("{{")) {
return false;
}
}
case "BUTTONS" -> {
for (JsonNode b : c.path("buttons")) {
if (!BUTTONS_OK.contains(b.path("type").asText()) || b.path("url").asText("").contains("{{")) {
return false;
}
}
}
default -> {
return false;
}
}
}
return true;
}
private static String bodyText(JsonNode template) {
for (JsonNode c : template.path("components")) {
if ("BODY".equals(c.path("type").asText())) {
return c.path("text").asText(null);
}
}
return null;
}
static int paramCount(String body) {
Set<String> distinct = new HashSet<>();
if (body != null) {
Matcher m = PARAM.matcher(body);
while (m.find()) {
distinct.add(m.group(1));
}
}
return distinct.size();
}
private static TemplateView view(WaTemplate t) {
return new TemplateView(t.name, t.language, t.category, t.bodyText, t.paramCount, APPROVED.equals(t.status));
}
}
@@ -0,0 +1,210 @@
package com.solvway.services.whatsapp.meta;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.solvway.services.whatsapp.config.WhatsAppSettings;
import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Component;
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.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
/**
* Meta WhatsApp Cloud (Graph) API client. Never logs tokens, URLs, message text or numbers; failures surface as codes only.
* ponytail: the media and paging URLs Meta returns get the bearer token as returned; no host allow-list.
*/
@Component
public class MetaClient {
/** wamid on success; otherwise Meta's error code and title (code NETWORK when Meta was not reached). */
public record SendResult(String wamid, String errorCode, String errorTitle) {
public boolean failed() {
return wamid == null;
}
}
/** Receives the upstream's mime type and length (-1 unknown) once, before the first byte, and returns where to write. */
@FunctionalInterface
public interface MediaSink {
OutputStream open(String mime, long length) throws IOException;
}
public static class MediaExpiredException extends RuntimeException {
public MediaExpiredException() {
super("MEDIA_EXPIRED");
}
}
/** A Graph call that failed; the message is only the error code, never a body. */
public static class MetaException extends RuntimeException {
public MetaException(String code) {
super(code);
}
}
private static final JsonNodeFactory JSON = JsonNodeFactory.instance;
private static final int MAX_PAGES = 50;
/** ponytail: fixed 100 MB ceiling on one proxied media file (WhatsApp's own limit is 100 MB for documents); make it a setting if that changes. */
static final long MAX_MEDIA_BYTES = 100L * 1024 * 1024;
long maxMediaBytes = MAX_MEDIA_BYTES; // not final so a test can use a small cap
private final WhatsAppSettings settings;
private final RestTemplate rest;
@Autowired
public MetaClient(WhatsAppSettings settings, RestTemplateBuilder builder) {
this(settings, builder.setConnectTimeout(Duration.ofSeconds(10)).setReadTimeout(Duration.ofSeconds(10)).build());
}
MetaClient(WhatsAppSettings settings, RestTemplate rest) {
this.settings = settings;
this.rest = rest;
}
public SendResult sendText(CompanyConfig cfg, String to, String body) {
ObjectNode payload = payload(to, "text");
payload.putObject("text").put("body", body);
return send(cfg, payload);
}
public SendResult sendTemplate(CompanyConfig cfg, String to, String name, String language, List<String> params) {
ObjectNode payload = payload(to, "template");
ObjectNode template = payload.putObject("template");
template.put("name", name);
template.putObject("language").put("code", language);
if (!params.isEmpty()) {
ArrayNode parameters = template.putArray("components").addObject().put("type", "body").putArray("parameters");
params.forEach(p -> parameters.addObject().put("type", "text").put("text", p));
}
return send(cfg, payload);
}
/** Every approved template of the business account, following paging.next. Throws MetaException. */
public List<JsonNode> templates(CompanyConfig cfg) {
List<JsonNode> all = new ArrayList<>();
URI next = URI.create(settings.graphBaseUrl() + "/" + cfg.wabaId() + "/message_templates?status=APPROVED&limit=200");
for (int pages = 0; next != null; pages++) {
if (pages == MAX_PAGES) { // fail rather than return a truncated list: sync would delete the missing templates
throw new MetaException("PAGING");
}
JsonNode page = get(cfg, next, JsonNode.class);
JsonNode data = page.path("data");
data.forEach(all::add);
String link = page.path("paging").path("next").asText("");
// a repeated link or an empty page means Meta is not advancing: stop instead of looping
next = link.isEmpty() || data.isEmpty() || link.equals(next.toString()) ? null : URI.create(link);
}
return all;
}
/**
* Short-lived URL lookup, then streams the bytes into the sink (never held whole in memory). The sink opens only after
* Meta answered with success and a length within the cap, so 404/410 and refusals happen before anything is written.
* Throws MediaExpiredException (Meta 404/410) or MetaException.
*/
public void media(CompanyConfig cfg, String mediaId, MediaSink sink) {
try {
JsonNode info = rest.exchange(settings.graphBaseUrl() + "/{id}", HttpMethod.GET, auth(cfg), JsonNode.class, mediaId).getBody();
if (info == null || !info.hasNonNull("url")) {
throw new MetaException("NO_URL");
}
String mime = info.path("mime_type").asText(null);
rest.execute(URI.create(info.get("url").asText()), HttpMethod.GET, request -> request.getHeaders().setBearerAuth(cfg.accessToken()), response -> {
long length = response.getHeaders().getContentLength();
if (length > maxMediaBytes) {
throw new MetaException("TOO_LARGE");
}
try (InputStream in = response.getBody(); OutputStream out = sink.open(mime, length)) {
byte[] buffer = new byte[8192];
long total = 0;
for (int n; (n = in.read(buffer)) != -1; ) {
total += n;
if (total > maxMediaBytes) {
throw new MetaException("TOO_LARGE");
}
out.write(buffer, 0, n);
}
}
return null;
});
} catch (HttpStatusCodeException e) {
HttpStatusCode code = e.getStatusCode();
if (code.isSameCodeAs(HttpStatus.NOT_FOUND) || code.isSameCodeAs(HttpStatus.GONE)) {
throw new MediaExpiredException();
}
throw new MetaException(String.valueOf(code.value()));
} catch (RestClientException e) {
throw new MetaException("NETWORK");
}
}
private SendResult send(CompanyConfig cfg, ObjectNode payload) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(cfg.accessToken());
try {
JsonNode r = rest.exchange(settings.graphBaseUrl() + "/{id}/messages", HttpMethod.POST, new HttpEntity<>(payload, headers),
JsonNode.class, cfg.phoneNumberId()).getBody();
String wamid = r == null ? "" : r.path("messages").path(0).path("id").asText("");
return wamid.isEmpty() ? new SendResult(null, "NO_WAMID", null) : new SendResult(wamid, null, null);
} catch (HttpStatusCodeException e) {
JsonNode error = parse(e);
String title = error.path("title").asText(error.path("message").asText(""));
return new SendResult(null, cut(error.path("code").asText(String.valueOf(e.getStatusCode().value())), 32),
title.isEmpty() ? null : cut(title, 255));
} catch (RestClientException e) {
return new SendResult(null, "NETWORK", null);
}
}
private <T> T get(CompanyConfig cfg, URI uri, Class<T> type) {
try {
return rest.exchange(uri, HttpMethod.GET, auth(cfg), type).getBody();
} catch (HttpStatusCodeException e) {
throw new MetaException(cut(parse(e).path("code").asText(String.valueOf(e.getStatusCode().value())), 32));
} catch (RestClientException e) {
throw new MetaException("NETWORK");
}
}
private static JsonNode parse(HttpStatusCodeException e) {
try {
return new com.fasterxml.jackson.databind.ObjectMapper().readTree(e.getResponseBodyAsString()).path("error");
} catch (Exception ignored) { // not JSON: fall back to the HTTP status
return JSON.missingNode();
}
}
private static ObjectNode payload(String to, String type) {
ObjectNode payload = JSON.objectNode();
payload.put("messaging_product", "whatsapp").put("to", to).put("type", type);
return payload;
}
private static HttpEntity<Void> auth(CompanyConfig cfg) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(cfg.accessToken());
return new HttpEntity<>(headers);
}
private static String cut(String s, int max) {
return s.length() <= max ? s : s.substring(0, max);
}
}
@@ -31,6 +31,14 @@ public interface WaConversationRepository extends JpaRepository<WaConversation,
int recordInbound(@Param("id") Long id, @Param("name") String name, @Param("phoneNumberId") String phoneNumberId,
@Param("at") LocalDateTime at, @Param("preview") String preview);
/** Records an outbound message: only the last-message columns move (forward), never owner fields or last_inbound_at. */
@Transactional
@Modifying
@Query(value = "UPDATE wa_conversation SET "
+ "last_message_preview = CASE WHEN last_message_at IS NULL OR :at >= last_message_at THEN :preview ELSE last_message_preview END, "
+ "last_message_at = GREATEST(COALESCE(last_message_at, :at), :at) WHERE id = :id", nativeQuery = true)
int recordOutbound(@Param("id") Long id, @Param("at") LocalDateTime at, @Param("preview") String preview);
Optional<WaConversation> findByUuid(String uuid);
/** Inbox list: null companyId = all companies, null owner = any owner; q and digits are ready-made LIKE patterns. */
@@ -2,5 +2,20 @@ package com.solvway.services.whatsapp.repository;
import com.solvway.services.whatsapp.model.WaTemplate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface WaTemplateRepository extends JpaRepository<WaTemplate, Long> {}
import java.util.List;
import java.util.Optional;
public interface WaTemplateRepository extends JpaRepository<WaTemplate, Long> {
List<WaTemplate> findByCompanyIdOrderByNameAsc(Long companyId);
Optional<WaTemplate> findByCompanyIdAndNameAndLanguage(Long companyId, String name, String language);
/** Bulk delete (runs at once, so re-inserting the same name+language in the same transaction does not collide). */
@Modifying
@Query("delete from WaTemplate t where t.companyId = :companyId")
void deleteByCompanyId(@Param("companyId") Long companyId);
}
@@ -14,6 +14,7 @@ import org.springframework.web.client.RestTemplate;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -72,6 +73,20 @@ public class CompanyDirectory {
return byPhoneNumberId.entrySet().stream().filter(e -> e.getValue().id() == companyId).map(Map.Entry::getKey).findFirst();
}
/** The company's WhatsApp settings; empty when WhatsApp is not configured for it. */
public Optional<WhatsAppSettings.CompanyConfig> configOf(long companyId) {
return phoneNumberIdOf(companyId).flatMap(settings::findByPhoneNumberId);
}
/** Every configured and resolved company id with its settings. */
public Map<Long, WhatsAppSettings.CompanyConfig> configured() {
Map<Long, WhatsAppSettings.CompanyConfig> all = new LinkedHashMap<>();
for (WhatsAppSettings.CompanyConfig c : settings.companies()) {
byPhoneNumberId(c.phoneNumberId()).ifPresent(company -> all.put(company.id(), c));
}
return all;
}
private boolean coolingDown() {
Instant failed = lastFailure;
return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN));
@@ -0,0 +1,310 @@
package com.solvway.services.whatsapp.inbox;
import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig;
import com.solvway.services.whatsapp.controller.ErrorHandler;
import com.solvway.services.whatsapp.dto.MessageView;
import com.solvway.services.whatsapp.dto.SendMessageRequest;
import com.solvway.services.whatsapp.meta.MetaClient;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.model.WaMessage;
import com.solvway.services.whatsapp.model.WaTemplate;
import com.solvway.services.whatsapp.ownership.OwnershipService;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import com.solvway.services.whatsapp.repository.WaMessageRepository;
import com.solvway.services.whatsapp.repository.WaReadRepository;
import com.solvway.services.whatsapp.repository.WaTemplateRepository;
import com.solvway.services.whatsapp.service.CompanyDirectory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
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.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class OutboundTest {
private static final LocalDateTime NOW = LocalDateTime.of(2026, 12, 2, 12, 0);
private static final long STAFF = 10L;
private static final CompanyConfig CFG = new CompanyConfig("INS", "111", "222", "t", "s");
private WaConversationRepository conversations;
private WaMessageRepository messages;
private WaTemplateRepository templates;
private CompanyDirectory directory;
private MetaClient meta;
private OutboundService service;
private MockMvc mvc;
private final List<String> statuses = new ArrayList<>();
private WaConversation conv;
@BeforeEach
void setUp() {
conversations = mock(WaConversationRepository.class);
messages = mock(WaMessageRepository.class);
templates = mock(WaTemplateRepository.class);
directory = mock(CompanyDirectory.class);
meta = mock(MetaClient.class);
Clock clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
InboxService inbox = new InboxService(conversations, messages, mock(WaReadRepository.class), mock(OwnershipService.class), directory,
mock(RestTemplate.class), clock);
service = new OutboundService(inbox, conversations, messages, templates, directory, meta, clock);
mvc = MockMvcBuilders.standaloneSetup(new OutboundController(service, mock(TemplateService.class))).setControllerAdvice(new ErrorHandler()).build();
conv = new WaConversation();
conv.id = 5L;
conv.uuid = "c-5";
conv.companyId = 1L;
conv.contactWaId = "60123";
conv.ownerUserId = STAFF;
conv.lastInboundAt = NOW.minusHours(1);
when(conversations.findByUuid("c-5")).thenReturn(Optional.of(conv));
when(conversations.findById(5L)).thenReturn(Optional.of(conv));
when(directory.configOf(1L)).thenReturn(Optional.of(CFG));
when(messages.save(any(WaMessage.class))).thenAnswer(i -> {
WaMessage m = i.getArgument(0);
if (m.id == null) {
m.id = 77L;
}
statuses.add(m.status);
return m;
});
}
private void template(String status, int params) {
WaTemplate t = new WaTemplate();
t.companyId = 1L;
t.name = "expo_followup";
t.language = "en";
t.status = status;
t.paramCount = params;
t.bodyText = "Hi {{1}}, thanks for visiting us at {{2}}.";
when(templates.findByCompanyIdAndNameAndLanguage(1L, "expo_followup", "en")).thenReturn(Optional.of(t));
}
private static void assertStatus(Runnable call, HttpStatus status, String reason) {
assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(status);
assertThat(e.getReason()).isEqualTo(reason);
});
}
private MessageView sendText(String text) {
return service.send("c-5", 1L, STAFF, false, new SendMessageRequest(text, null, null, null));
}
private MessageView sendTemplate(String... params) {
return service.send("c-5", 1L, STAFF, false, new SendMessageRequest(null, "expo_followup", "en", List.of(params)));
}
// ---- sending
@Test
void windowClosedRefusesTextAndSendsNothing() {
conv.lastInboundAt = NOW.minusHours(25);
assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED");
conv.lastInboundAt = NOW.minusHours(24);
assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED");
conv.lastInboundAt = null;
assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED");
verifyNoInteractions(meta);
verify(messages, never()).save(any());
}
@Test
void openWindowTextIsPendingThenSentWithWamid() {
when(meta.sendText(CFG, "60123", "hi")).thenReturn(new MetaClient.SendResult("wamid.A", null, null));
MessageView view = sendText("hi");
assertThat(statuses).containsExactly("pending", "sent");
assertThat(view.status()).isEqualTo("sent");
assertThat(view.direction()).isEqualTo("OUT");
assertThat(view.type()).isEqualTo("text");
assertThat(view.body()).isEqualTo("hi");
assertThat(view.sentByUserId()).isEqualTo(STAFF);
assertThat(view.statusAt()).isEqualTo(NOW);
verify(messages, never()).findByWamidAndDirection(anyString(), anyString());
verify(conversations).recordOutbound(5L, NOW, "hi");
verify(conversations, never()).updateOwnership(any(), any(), any(Boolean.class), any());
}
@Test
void metaErrorStoresFailedWithCodeAndTitle() {
when(meta.sendText(CFG, "60123", "hi")).thenReturn(new MetaClient.SendResult(null, "131026", "Message undeliverable"));
MessageView view = sendText("hi");
assertThat(statuses).containsExactly("pending", "failed");
assertThat(view.status()).isEqualTo("failed");
assertThat(view.errorCode()).isEqualTo("131026");
assertThat(view.errorTitle()).isEqualTo("Message undeliverable");
}
@Test
void templateSendSubstitutesBodyAndWorksOutsideWindow() {
conv.lastInboundAt = null;
template("APPROVED", 2);
when(meta.sendTemplate(CFG, "60123", "expo_followup", "en", List.of("Ann", "Expo")))
.thenReturn(new MetaClient.SendResult("wamid.T", null, null));
MessageView view = sendTemplate("Ann", "Expo");
assertThat(view.type()).isEqualTo("template");
assertThat(view.templateName()).isEqualTo("expo_followup");
assertThat(view.body()).isEqualTo("Hi Ann, thanks for visiting us at Expo.");
assertThat(view.status()).isEqualTo("sent");
}
@Test
void templateParamProblemsAreRefusedBeforeMeta() {
template("APPROVED", 2);
assertStatus(() -> sendTemplate("Ann", " "), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS");
assertStatus(() -> sendTemplate("Ann"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS");
assertStatus(() -> sendTemplate("a", "b", "c"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS");
assertStatus(() -> service.send("c-5", 1L, STAFF, false, new SendMessageRequest(null, "expo_followup", "en", null)),
HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS");
verifyNoInteractions(meta);
verify(messages, never()).save(any());
}
@Test
void unknownOrUnsupportedTemplateIsRefused() {
assertStatus(() -> sendTemplate("a", "b"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS");
template("UNSUPPORTED", 0);
assertStatus(() -> sendTemplate(), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS");
verifyNoInteractions(meta);
}
@Test
void notConfiguredIs409() {
when(directory.configOf(1L)).thenReturn(Optional.empty());
assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED");
verifyNoInteractions(meta);
}
@Test
void staffOnAnotherUsersChatOrCompanyGets404() {
conv.ownerUserId = 99L;
assertStatus(() -> sendText("hi"), HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND");
conv.ownerUserId = STAFF;
assertStatus(() -> service.send("c-5", 2L, STAFF, false, new SendMessageRequest("hi", null, null, null)),
HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND");
assertStatus(() -> service.send("c-5", null, STAFF, false, new SendMessageRequest("hi", null, null, null)),
HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND");
verifyNoInteractions(meta);
}
@Test
void emptyOrBothBodiesAreInvalid() {
assertStatus(() -> sendText(" "), HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD");
assertStatus(() -> service.send("c-5", 1L, STAFF, false, new SendMessageRequest("x", "expo_followup", "en", List.of())),
HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD");
verifyNoInteractions(meta);
}
// ---- media
private WaMessage media(String type, String mime, String filename) {
WaMessage m = new WaMessage();
m.id = 3L;
m.uuid = "m-3";
m.conversationId = 5L;
m.direction = "IN";
m.type = type;
m.mediaId = "media-1";
m.mediaMime = mime;
m.mediaFilename = filename;
when(messages.findByUuid("m-3")).thenReturn(Optional.of(m));
return m;
}
/** Meta stand-in: announces the mime to the sink, then writes the bytes. */
private void streams(String mime, byte[] bytes) throws Exception {
doAnswer(inv -> {
try (java.io.OutputStream out = inv.<MetaClient.MediaSink>getArgument(2).open(mime, bytes.length)) {
out.write(bytes);
}
return null;
}).when(meta).media(eq(CFG), eq("media-1"), any());
}
@Test
void mediaImageIsInlineWithMime() throws Exception {
media("image", "image/jpeg", null);
streams("image/jpeg", new byte[] {1, 2});
mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(status().isOk()).andExpect(header().string("Content-Type", "image/jpeg"))
.andExpect(header().string("Content-Disposition", "inline")).andExpect(content().bytes(new byte[] {1, 2}));
}
@Test
void mediaDocumentIsAttachmentWithFilename() throws Exception {
media("document", "application/pdf", "Quote 1.pdf");
streams("application/pdf", new byte[] {1});
mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(status().isOk()).andExpect(header().string("Content-Type", "application/pdf"))
.andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("attachment; filename=\"Quote 1.pdf\"")));
}
@Test
void mediaActiveContentIsNeverInline() throws Exception {
media("image", "image/svg+xml", null);
streams("image/svg+xml", new byte[] {1});
mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("attachment")))
.andExpect(header().string("X-Content-Type-Options", "nosniff"));
}
@Test
void mediaExpiredIs410() throws Exception {
media("image", "image/jpeg", null);
doThrow(new MetaClient.MediaExpiredException()).when(meta).media(eq(CFG), eq("media-1"), any());
mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(status().isGone()).andExpect(jsonPath("$.detail").value("MEDIA_EXPIRED"));
}
@Test
void mediaNotVisibleOrNotMediaIs404() throws Exception {
WaMessage m = media("image", "image/jpeg", null);
conv.ownerUserId = 99L;
mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND"));
conv.ownerUserId = STAFF;
m.mediaId = null;
m.type = "text";
mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(status().isNotFound());
mvc.perform(get("/whatsapp/media/nope").param("companyId", "1").param("userId", "10").param("admin", "false"))
.andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND"));
verifyNoInteractions(meta);
}
}
@@ -0,0 +1,175 @@
package com.solvway.services.whatsapp.inbox;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig;
import com.solvway.services.whatsapp.dto.TemplateView;
import com.solvway.services.whatsapp.meta.MetaClient;
import com.solvway.services.whatsapp.model.WaTemplate;
import com.solvway.services.whatsapp.repository.WaTemplateRepository;
import com.solvway.services.whatsapp.service.CompanyDirectory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
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.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TemplateServiceTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final CompanyConfig INS = new CompanyConfig("INS", "111", "222", "t", "s");
private static final CompanyConfig CV = new CompanyConfig("CV", "112", "223", "t", "s");
private WaTemplateRepository repo;
private CompanyDirectory directory;
private MetaClient meta;
private TemplateService service;
@BeforeEach
void setUp() {
repo = mock(WaTemplateRepository.class);
directory = mock(CompanyDirectory.class);
meta = mock(MetaClient.class);
when(directory.configOf(1L)).thenReturn(Optional.of(INS));
when(directory.configOf(2L)).thenReturn(Optional.of(CV));
service = new TemplateService(repo, directory, meta, new TransactionTemplate(mock(PlatformTransactionManager.class)),
Clock.fixed(Instant.parse("2026-12-02T04:00:00Z"), ZoneOffset.UTC));
}
private static JsonNode json(String s) {
try {
return JSON.readTree(s);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static final String EXPO = "{\"name\":\"expo_followup\",\"language\":\"en\",\"category\":\"MARKETING\",\"status\":\"APPROVED\","
+ "\"components\":[{\"type\":\"BODY\",\"text\":\"Hi {{1}}, thanks for visiting us at {{2}}. {{1}} again.\"}]}";
private static final String PROMO = "{\"name\":\"promo_header\",\"language\":\"en\",\"category\":\"MARKETING\",\"status\":\"APPROVED\","
+ "\"components\":[{\"type\":\"HEADER\",\"format\":\"IMAGE\"},{\"type\":\"BODY\",\"text\":\"Big sale\"}]}";
@SuppressWarnings("unchecked")
private List<WaTemplate> savedRows() {
ArgumentCaptor<List<WaTemplate>> captor = ArgumentCaptor.forClass(List.class);
verify(repo).saveAll(captor.capture());
return captor.getValue();
}
@Test
void syncReplacesRowsWithBodyTextParamCountAndUnsupported() {
when(meta.templates(INS)).thenReturn(List.of(json(EXPO), json(PROMO)));
service.sync(1L, true);
verify(repo).deleteByCompanyId(1L);
List<WaTemplate> rows = savedRows();
assertThat(rows).hasSize(2);
WaTemplate expo = rows.get(0);
assertThat(expo.companyId).isEqualTo(1L);
assertThat(expo.name).isEqualTo("expo_followup");
assertThat(expo.language).isEqualTo("en");
assertThat(expo.category).isEqualTo("MARKETING");
assertThat(expo.status).isEqualTo("APPROVED");
assertThat(expo.paramCount).isEqualTo(2); // {{1}} twice counts once
assertThat(expo.bodyText).startsWith("Hi {{1}}");
assertThat(rows.get(1).status).isEqualTo("UNSUPPORTED");
}
@Test
void metaFailureKeepsExistingRows() {
when(meta.templates(INS)).thenThrow(new MetaClient.MetaException("NETWORK"));
assertThatThrownBy(() -> service.sync(1L, true)).isInstanceOfSatisfying(ResponseStatusException.class,
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY));
verify(repo, never()).deleteByCompanyId(any(Long.class));
}
@Test
void staffCannotSyncAndUnconfiguredCompanyIs409() {
assertThatThrownBy(() -> service.sync(1L, false)).isInstanceOfSatisfying(ResponseStatusException.class,
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
assertThatThrownBy(() -> service.sync(9L, true)).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getReason()).isEqualTo("WHATSAPP_NOT_CONFIGURED");
});
verify(meta, never()).templates(any());
}
@Test
void superAdminWithoutCompanySyncsEveryConfiguredCompanyAndSurvivesOneFailure() {
LinkedHashMap<Long, CompanyConfig> all = new LinkedHashMap<>();
all.put(1L, INS);
all.put(2L, CV);
when(directory.configured()).thenReturn(all);
when(meta.templates(INS)).thenThrow(new MetaClient.MetaException("190"));
when(meta.templates(CV)).thenReturn(List.of(json(EXPO)));
service.sync(null, true);
verify(repo).deleteByCompanyId(2L);
verify(repo, never()).deleteByCompanyId(1L);
}
@Test
void nightlySyncsEveryCompany() {
LinkedHashMap<Long, CompanyConfig> all = new LinkedHashMap<>();
all.put(1L, INS);
when(directory.configured()).thenReturn(all);
when(meta.templates(INS)).thenReturn(List.of(json(EXPO)));
service.nightly();
verify(repo).deleteByCompanyId(1L);
}
@Test
void listShowsSupportedFlagFromStatus() {
WaTemplate ok = row("a", "APPROVED");
WaTemplate bad = row("b", "UNSUPPORTED");
when(repo.findByCompanyIdOrderByNameAsc(1L)).thenReturn(List.of(ok, bad));
List<TemplateView> views = service.list(1L);
assertThat(views).extracting(TemplateView::name).containsExactly("a", "b");
assertThat(views).extracting(TemplateView::supported).containsExactly(true, false);
assertThat(service.list(null)).isEmpty();
}
private static WaTemplate row(String name, String status) {
WaTemplate t = new WaTemplate();
t.name = name;
t.language = "en";
t.status = status;
return t;
}
@Test
void supportedRule() {
assertThat(TemplateService.supported(json(EXPO))).isTrue();
assertThat(TemplateService.supported(json(PROMO))).isFalse();
assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"HEADER\",\"format\":\"TEXT\",\"text\":\"Hello\"},{\"type\":\"BODY\",\"text\":\"x\"}]}"))).isTrue();
assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"HEADER\",\"format\":\"TEXT\",\"text\":\"Hello {{1}}\"}]}"))).isFalse();
assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"QUICK_REPLY\"},{\"type\":\"URL\",\"url\":\"https://a.com\"}]}]}"))).isTrue();
assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"URL\",\"url\":\"https://a.com/{{1}}\"}]}]}"))).isFalse();
assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"COPY_CODE\"}]}]}"))).isFalse();
assertThat(TemplateService.supported(json("{\"parameter_format\":\"NAMED\",\"components\":[{\"type\":\"BODY\",\"text\":\"Hi {{name}}\"}]}"))).isFalse();
}
}
@@ -0,0 +1,263 @@
package com.solvway.services.whatsapp.meta;
import com.fasterxml.jackson.databind.JsonNode;
import com.solvway.services.whatsapp.config.WhatsAppSettings;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withException;
class MetaClientTest {
private WhatsAppSettings.CompanyConfig cfg;
private MockRestServiceServer server;
private MetaClient client;
@BeforeEach
void setUp() {
MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS")
.withProperty("WHATSAPP_INS_PHONE_NUMBER_ID", "111").withProperty("WHATSAPP_INS_WABA_ID", "222")
.withProperty("WHATSAPP_INS_ACCESS_TOKEN", "tok").withProperty("WHATSAPP_INS_APP_SECRET", "s")
.withProperty("WHATSAPP_GRAPH_BASE_URL", "http://graph.test/v1");
WhatsAppSettings settings = new WhatsAppSettings(env);
cfg = settings.companies().get(0);
RestTemplate rest = new RestTemplate();
server = MockRestServiceServer.bindTo(rest).build();
client = new MetaClient(settings, rest);
}
@Test
void sendsTextWithBearerAndReturnsWamid() {
server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(method(HttpMethod.POST))
.andExpect(header("Authorization", "Bearer tok"))
.andExpect(jsonPath("$.messaging_product").value("whatsapp")).andExpect(jsonPath("$.to").value("60123"))
.andExpect(jsonPath("$.type").value("text")).andExpect(jsonPath("$.text.body").value("hello"))
.andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.X\"}]}", MediaType.APPLICATION_JSON));
MetaClient.SendResult r = client.sendText(cfg, "60123", "hello");
assertThat(r.wamid()).isEqualTo("wamid.X");
assertThat(r.failed()).isFalse();
server.verify();
}
@Test
void sendsTemplateWithBodyParametersAndOmitsComponentsWithoutParams() {
server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(jsonPath("$.type").value("template"))
.andExpect(jsonPath("$.template.name").value("expo_followup")).andExpect(jsonPath("$.template.language.code").value("en"))
.andExpect(jsonPath("$.template.components[0].type").value("body"))
.andExpect(jsonPath("$.template.components[0].parameters[1].text").value("Expo"))
.andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.T\"}]}", MediaType.APPLICATION_JSON));
server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(jsonPath("$.template.components").doesNotExist())
.andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.U\"}]}", MediaType.APPLICATION_JSON));
assertThat(client.sendTemplate(cfg, "60123", "expo_followup", "en", List.of("Ann", "Expo")).wamid()).isEqualTo("wamid.T");
assertThat(client.sendTemplate(cfg, "60123", "plain", "en", List.of()).wamid()).isEqualTo("wamid.U");
}
@Test
void metaErrorGivesCodeAndTitleOrMessage() {
server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withStatus(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON).body("{\"error\":{\"code\":131026,\"title\":\"Message undeliverable\",\"message\":\"m\"}}"));
server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withStatus(HttpStatus.UNAUTHORIZED)
.contentType(MediaType.APPLICATION_JSON).body("{\"error\":{\"code\":190,\"message\":\"Invalid token\"}}"));
MetaClient.SendResult first = client.sendText(cfg, "60123", "x");
MetaClient.SendResult second = client.sendText(cfg, "60123", "x");
assertThat(first.failed()).isTrue();
assertThat(first.errorCode()).isEqualTo("131026");
assertThat(first.errorTitle()).isEqualTo("Message undeliverable");
assertThat(second.errorCode()).isEqualTo("190");
assertThat(second.errorTitle()).isEqualTo("Invalid token");
}
@Test
void networkErrorGivesNetworkCode() {
server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withException(new IOException("down")));
MetaClient.SendResult r = client.sendText(cfg, "60123", "x");
assertThat(r.failed()).isTrue();
assertThat(r.errorCode()).isEqualTo("NETWORK");
}
@Test
void templatesFollowPagingNext() {
server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200"))
.andExpect(header("Authorization", "Bearer tok"))
.andRespond(withSuccess("{\"data\":[{\"name\":\"a\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}",
MediaType.APPLICATION_JSON));
server.expect(requestTo("http://graph.test/v1/222/message_templates?after=X"))
.andExpect(header("Authorization", "Bearer tok"))
.andRespond(withSuccess("{\"data\":[{\"name\":\"b\"}],\"paging\":{}}", MediaType.APPLICATION_JSON));
List<JsonNode> all = client.templates(cfg);
assertThat(all).extracting(n -> n.get("name").asText()).containsExactly("a", "b");
server.verify();
}
@Test
void templatePagingStopsWhenNextRepeatsTheRequestedUrl() {
server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200"))
.andRespond(withSuccess("{\"data\":[{\"name\":\"a\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}",
MediaType.APPLICATION_JSON));
server.expect(requestTo("http://graph.test/v1/222/message_templates?after=X"))
.andRespond(withSuccess("{\"data\":[{\"name\":\"b\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}",
MediaType.APPLICATION_JSON));
assertThat(client.templates(cfg)).hasSize(2);
server.verify();
}
@Test
void templatePagingStopsOnAnEmptyPage() {
server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200"))
.andRespond(withSuccess("{\"data\":[],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=Y\"}}",
MediaType.APPLICATION_JSON));
assertThat(client.templates(cfg)).isEmpty();
server.verify();
}
@Test
void templatePagingIsCappedAtFiftyPages() {
int[] n = {0};
server.expect(ExpectedCount.manyTimes(), requestTo(org.hamcrest.Matchers.startsWith("http://graph.test/v1/222/message_templates")))
.andRespond(request -> withSuccess("{\"data\":[{\"name\":\"t\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=p"
+ (++n[0]) + "\"}}", MediaType.APPLICATION_JSON).createResponse(request));
assertThatThrownBy(() -> client.templates(cfg)).isInstanceOf(MetaClient.MetaException.class);
assertThat(n[0]).isEqualTo(50);
}
/** Sink that records what was announced and written, and how much of the upstream had been read at the first write. */
private static class Sink implements MetaClient.MediaSink {
String mime;
long length = -2;
boolean opened;
final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
long upstreamReadAtFirstWrite = -1;
java.util.function.LongSupplier upstreamRead = () -> -1;
@Override
public java.io.OutputStream open(String mime, long length) {
this.mime = mime;
this.length = length;
opened = true;
return new java.io.OutputStream() {
@Override
public void write(int b) {
write(new byte[] {(byte) b}, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) {
if (upstreamReadAtFirstWrite < 0) {
upstreamReadAtFirstWrite = upstreamRead.getAsLong();
}
out.write(b, off, len);
}
};
}
}
private void expectMediaLookup(String url) {
server.expect(requestTo("http://graph.test/v1/m1")).andExpect(header("Authorization", "Bearer tok"))
.andRespond(withSuccess("{\"url\":\"" + url + "\",\"mime_type\":\"image/png\"}", MediaType.APPLICATION_JSON));
}
@Test
void mediaFetchesUrlThenStreamsBytes() {
expectMediaLookup("http://cdn.test/file");
server.expect(requestTo("http://cdn.test/file")).andExpect(header("Authorization", "Bearer tok"))
.andRespond(withSuccess(new byte[] {1, 2, 3}, MediaType.APPLICATION_OCTET_STREAM));
Sink sink = new Sink();
client.media(cfg, "m1", sink);
assertThat(sink.out.toByteArray()).containsExactly(1, 2, 3);
assertThat(sink.mime).isEqualTo("image/png");
}
@Test
void mediaIsPassedThroughNotBufferedWhole() {
expectMediaLookup("http://cdn.test/big");
byte[] data = new byte[64 * 1024];
long[] read = {0};
java.io.InputStream upstream = new java.io.ByteArrayInputStream(data) {
@Override
public synchronized int read(byte[] b, int off, int len) {
int n = super.read(b, off, len);
if (n > 0) {
read[0] += n;
}
return n;
}
};
server.expect(requestTo("http://cdn.test/big")).andRespond(request ->
new org.springframework.mock.http.client.MockClientHttpResponse(upstream, HttpStatus.OK));
Sink sink = new Sink();
sink.upstreamRead = () -> read[0];
client.media(cfg, "m1", sink);
assertThat(sink.out.size()).isEqualTo(data.length);
assertThat(sink.upstreamReadAtFirstWrite).isGreaterThan(0).isLessThan(data.length);
}
@Test
void mediaOverTheCapIsRefusedByContentLengthBeforeAnyByte() {
expectMediaLookup("http://cdn.test/huge");
server.expect(requestTo("http://cdn.test/huge")).andRespond(withSuccess(new byte[] {1}, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Length", String.valueOf(MetaClient.MAX_MEDIA_BYTES + 1)));
Sink sink = new Sink();
assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MetaException.class);
assertThat(sink.opened).isFalse();
}
@Test
void mediaCopyStopsAtTheCapWhenLengthIsUnknown() {
expectMediaLookup("http://cdn.test/chunked");
server.expect(requestTo("http://cdn.test/chunked")).andRespond(withSuccess(new byte[100], MediaType.APPLICATION_OCTET_STREAM));
client.maxMediaBytes = 10;
Sink sink = new Sink();
assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MetaException.class);
assertThat(sink.out.size()).isLessThanOrEqualTo(10);
}
@Test
void mediaGoneIsExpiredAndNothingIsOpened() {
server.expect(requestTo("http://graph.test/v1/m1")).andRespond(withStatus(HttpStatus.NOT_FOUND));
server.expect(requestTo("http://graph.test/v1/m2"))
.andRespond(withSuccess("{\"url\":\"http://cdn.test/f\",\"mime_type\":\"image/png\"}", MediaType.APPLICATION_JSON));
server.expect(requestTo("http://cdn.test/f")).andRespond(withStatus(HttpStatus.GONE));
Sink sink = new Sink();
assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MediaExpiredException.class);
assertThatThrownBy(() -> client.media(cfg, "m2", sink)).isInstanceOf(MetaClient.MediaExpiredException.class);
assertThat(sink.opened).isFalse();
}
}