feat: WhatsApp webhook ingest for messages and delivery statuses

Stores inbound messages once per wamid in the conversation of the company
that owns the receiving number (only companies whose app secret matched),
keeps INS and CV apart, moves statuses only forward (failed always), and
updates conversations in place without touching ownership. Company codes
resolve through the system service with a 30 s retry cooldown.

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 6d63cc74d1
commit b13e39ac75
24 files changed
+1067

No files matched your search

@@ -0,0 +1,23 @@
package com.solvway.services.whatsapp.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/** Errors are ProblemDetail with the reason in {@code detail}; ResponseStatusException(status, reason) already maps so. */
@RestControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
return handleExceptionInternal(ex, ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"),
headers, HttpStatus.BAD_REQUEST, request);
}
}
@@ -0,0 +1,25 @@
package com.solvway.services.whatsapp.controller;
import com.solvway.services.whatsapp.dto.WebhookIngestRequest;
import com.solvway.services.whatsapp.service.IngestResult;
import com.solvway.services.whatsapp.service.WebhookIngestService;
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.RestController;
@RestController
@RequestMapping("/whatsapp/webhook")
public class WebhookController {
private final WebhookIngestService service;
public WebhookController(WebhookIngestService service) {
this.service = service;
}
@PostMapping("/ingest")
public IngestResult ingest(@RequestBody WebhookIngestRequest request) {
return service.ingest(request);
}
}
@@ -0,0 +1,26 @@
package com.solvway.services.whatsapp.model;
import jakarta.persistence.*;
import java.time.LocalDateTime;
// ponytail: public fields instead of getters/setters (no Lombok in this module); switch if a mapper needs bean accessors.
@Entity
@Table(name = "wa_conversation")
public class WaConversation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
public String uuid;
public Long companyId;
public String phoneNumberId;
public String contactWaId;
public String contactName;
public Long leadUuid;
public Long ownerUserId;
public boolean ownerManual;
public LocalDateTime lastInboundAt;
public LocalDateTime lastMessageAt;
public String lastMessagePreview;
public LocalDateTime createdAt;
}
@@ -0,0 +1,34 @@
package com.solvway.services.whatsapp.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "wa_message")
public class WaMessage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
public String uuid;
public Long conversationId;
public String direction;
public String wamid;
public String type;
@Column(columnDefinition = "text")
public String body;
public String templateName;
public String mediaId;
public String mediaMime;
public String mediaFilename;
public BigDecimal locationLat;
public BigDecimal locationLng;
public String locationName;
public String status;
public String errorCode;
public String errorTitle;
public Long sentByUserId;
public LocalDateTime createdAt;
public LocalDateTime statusAt;
}
@@ -0,0 +1,14 @@
package com.solvway.services.whatsapp.model;
import jakarta.persistence.*;
@Entity
@Table(name = "wa_read")
@IdClass(WaReadId.class)
public class WaRead {
@Id
public Long conversationId;
@Id
public Long userId;
public Long lastReadMessageId;
}
@@ -0,0 +1,5 @@
package com.solvway.services.whatsapp.model;
import java.io.Serializable;
public record WaReadId(Long conversationId, Long userId) implements Serializable {}
@@ -0,0 +1,22 @@
package com.solvway.services.whatsapp.model;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "wa_template")
public class WaTemplate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
public Long companyId;
public String name;
public String language;
public String category;
public String status;
@Column(columnDefinition = "text")
public String bodyText;
public int paramCount;
public LocalDateTime syncedAt;
}
@@ -0,0 +1,30 @@
package com.solvway.services.whatsapp.repository;
import com.solvway.services.whatsapp.model.WaConversation;
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;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Optional;
public interface WaConversationRepository extends JpaRepository<WaConversation, Long> {
Optional<WaConversation> findByCompanyIdAndContactWaId(Long companyId, String contactWaId);
/**
* Records an inbound message on the conversation. Touches only the inbound columns, never owner_user_id,
* owner_manual or lead_uuid, which linking and manual reassignment write concurrently. Timestamps only move
* forward and an older message never replaces a newer preview (MySQL applies SET left to right, so the preview
* is decided before last_message_at moves). A null name keeps the stored one.
*/
@Transactional
@Modifying
@Query(value = "UPDATE wa_conversation SET contact_name = COALESCE(:name, contact_name), phone_number_id = :phoneNumberId, "
+ "last_inbound_at = GREATEST(COALESCE(last_inbound_at, :at), :at), "
+ "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 recordInbound(@Param("id") Long id, @Param("name") String name, @Param("phoneNumberId") String phoneNumberId,
@Param("at") LocalDateTime at, @Param("preview") String preview);
}
@@ -0,0 +1,12 @@
package com.solvway.services.whatsapp.repository;
import com.solvway.services.whatsapp.model.WaMessage;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface WaMessageRepository extends JpaRepository<WaMessage, Long> {
boolean existsByWamid(String wamid);
Optional<WaMessage> findByWamidAndDirection(String wamid, String direction);
}
@@ -0,0 +1,7 @@
package com.solvway.services.whatsapp.repository;
import com.solvway.services.whatsapp.model.WaRead;
import com.solvway.services.whatsapp.model.WaReadId;
import org.springframework.data.jpa.repository.JpaRepository;
public interface WaReadRepository extends JpaRepository<WaRead, WaReadId> {}
@@ -0,0 +1,6 @@
package com.solvway.services.whatsapp.repository;
import com.solvway.services.whatsapp.model.WaTemplate;
import org.springframework.data.jpa.repository.JpaRepository;
public interface WaTemplateRepository extends JpaRepository<WaTemplate, Long> {}
@@ -0,0 +1,92 @@
package com.solvway.services.whatsapp.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.solvway.services.whatsapp.config.WhatsAppSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Maps each configured WhatsApp number to its company id, resolved through the system service's
* {@code GET /company/findByCode/{code}} (service id address, like the other services' SystemService).
* A code with no company is skipped for good; a code whose lookup failed is retried on the next use.
*/
@Component
public class CompanyDirectory {
public record Company(long id, String code) {}
private static final Logger log = LoggerFactory.getLogger(CompanyDirectory.class);
private static final Duration RETRY_COOLDOWN = Duration.ofSeconds(30);
private static final String FIND_BY_CODE = "http://service-system/company/findByCode/{code}";
private final WhatsAppSettings settings;
private final RestTemplate rest;
private final Clock clock;
private volatile Instant lastFailure;
private final Map<String, Company> byPhoneNumberId = new ConcurrentHashMap<>();
private final Set<String> unresolved = ConcurrentHashMap.newKeySet();
@Autowired
public CompanyDirectory(WhatsAppSettings settings, RestTemplateBuilder builder) {
this(settings, builder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(5)).build(), Clock.systemUTC());
}
CompanyDirectory(WhatsAppSettings settings, RestTemplate rest, Clock clock) {
this.settings = settings;
this.rest = rest;
this.clock = clock;
settings.companies().forEach(c -> unresolved.add(c.code()));
}
@EventListener(ApplicationReadyEvent.class)
void resolveAtStartup() {
resolve();
}
public Optional<Company> byPhoneNumberId(String phoneNumberId) {
if (!unresolved.isEmpty() && !coolingDown()) {
resolve();
}
return Optional.ofNullable(byPhoneNumberId.get(phoneNumberId));
}
private boolean coolingDown() {
Instant failed = lastFailure;
return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN));
}
// ponytail: unreachable system service is retried at most every 30 s (flat cooldown); exponential backoff if that is ever noisy.
private synchronized void resolve() {
for (WhatsAppSettings.CompanyConfig c : settings.companies()) {
if (!unresolved.contains(c.code())) {
continue;
}
try {
JsonNode company = rest.getForObject(FIND_BY_CODE, JsonNode.class, c.code());
if (company != null && company.hasNonNull("id")) {
byPhoneNumberId.put(c.phoneNumberId(), new Company(company.get("id").asLong(), c.code()));
} else {
log.warn("WhatsApp company {} skipped: no company with that code", c.code());
}
unresolved.remove(c.code());
} catch (RuntimeException e) {
lastFailure = clock.instant();
log.warn("WhatsApp company {} not resolved yet, system service unreachable; will retry after the cooldown", c.code());
}
}
}
}
@@ -0,0 +1,4 @@
package com.solvway.services.whatsapp.service;
/** Counts only: messages stored, redeliveries skipped, items dropped (number not matched), statuses applied or ignored. */
public record IngestResult(int accepted, int duplicates, int dropped, int statusesApplied, int statusesIgnored) {}
@@ -0,0 +1,209 @@
package com.solvway.services.whatsapp.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.solvway.services.whatsapp.dto.WebhookIngestRequest;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.model.WaMessage;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import com.solvway.services.whatsapp.repository.WaMessageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Stores Meta webhook messages and delivery statuses. Deliberately not transactional: each repository call is its own
* transaction, so a unique-wamid violation on a redelivery cannot poison the rest of the batch. The conversation is
* updated through a targeted UPDATE, never a whole-entity save, so it cannot overwrite owner or lead columns that
* linking and manual reassignment write concurrently.
* Logs ids and counts only, never message text, numbers or names.
*/
@Service
public class WebhookIngestService {
private static final Logger log = LoggerFactory.getLogger(WebhookIngestService.class);
private static final Set<String> MEDIA = Set.of("image", "document", "audio", "video", "sticker");
private static final List<String> STATUS_RANK = List.of("pending", "sent", "delivered", "read");
private static final int PREVIEW_MAX = 80;
private static final class Counts {
int accepted, duplicates, dropped, applied, ignored;
}
private final CompanyDirectory companies;
private final WaConversationRepository conversations;
private final WaMessageRepository messages;
public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages) {
this.companies = companies;
this.conversations = conversations;
this.messages = messages;
}
public IngestResult ingest(WebhookIngestRequest request) {
JsonNode entries = request.payload() == null ? null : request.payload().get("entry");
if (entries == null || !entries.isArray()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD");
}
Set<String> matched = request.matchedCompanyCodes() == null ? Set.of()
: request.matchedCompanyCodes().stream().map(String::toUpperCase).collect(Collectors.toSet());
Counts c = new Counts();
for (JsonNode entry : entries) {
for (JsonNode change : entry.path("changes")) {
if (!"messages".equals(change.path("field").asText())) {
continue;
}
JsonNode value = change.path("value");
String phoneNumberId = value.path("metadata").path("phone_number_id").asText("");
CompanyDirectory.Company company = companies.byPhoneNumberId(phoneNumberId)
.filter(co -> matched.contains(co.code().toUpperCase())).orElse(null);
if (company == null) {
c.dropped += value.path("messages").size() + value.path("statuses").size();
continue;
}
value.path("messages").forEach(m -> message(company, phoneNumberId, value, m, c));
value.path("statuses").forEach(s -> status(s, c));
}
}
log.info("WhatsApp webhook: accepted={} duplicates={} dropped={} statusesApplied={} statusesIgnored={}",
c.accepted, c.duplicates, c.dropped, c.applied, c.ignored);
return new IngestResult(c.accepted, c.duplicates, c.dropped, c.applied, c.ignored);
}
private void message(CompanyDirectory.Company company, String phoneNumberId, JsonNode value, JsonNode m, Counts c) {
String wamid = text(m, "id");
String from = text(m, "from");
if (wamid == null || from == null) {
c.dropped++;
return;
}
if (messages.existsByWamid(wamid)) {
c.duplicates++;
return;
}
LocalDateTime at = time(text(m, "timestamp"));
WaMessage msg = toMessage(m, wamid, at);
WaConversation conv = conversations.findByCompanyIdAndContactWaId(company.id(), from)
.orElseGet(() -> newConversation(company.id(), from));
msg.conversationId = conv.id;
try {
messages.save(msg);
} catch (DataIntegrityViolationException e) { // a concurrent delivery of the same wamid won the unique key
c.duplicates++;
return;
}
conversations.recordInbound(conv.id, cut(contactName(value, from), 255), phoneNumberId, at, preview(msg));
c.accepted++;
}
/** The one place a conversation is first created; lead and owner linking hooks in here. */
private WaConversation newConversation(Long companyId, String contactWaId) {
WaConversation conv = new WaConversation();
conv.uuid = UUID.randomUUID().toString();
conv.companyId = companyId;
conv.contactWaId = contactWaId;
conv.phoneNumberId = "";
conv.createdAt = LocalDateTime.now();
try {
return conversations.save(conv);
} catch (DataIntegrityViolationException e) { // a concurrent first message created it
return conversations.findByCompanyIdAndContactWaId(companyId, contactWaId).orElseThrow(() -> e);
}
}
private WaMessage toMessage(JsonNode m, String wamid, LocalDateTime at) {
WaMessage msg = new WaMessage();
msg.uuid = UUID.randomUUID().toString();
msg.direction = "IN";
msg.wamid = wamid;
msg.createdAt = at;
String type = text(m, "type");
if ("text".equals(type)) {
msg.type = "text";
msg.body = text(m.path("text"), "body");
} else if (type != null && MEDIA.contains(type)) {
JsonNode media = m.path(type);
msg.type = type;
msg.mediaId = text(media, "id");
msg.mediaMime = text(media, "mime_type");
msg.mediaFilename = text(media, "filename");
msg.body = text(media, "caption");
} else if ("location".equals(type) && m.path("location").hasNonNull("latitude") && m.path("location").hasNonNull("longitude")) {
JsonNode loc = m.path("location");
msg.type = "location";
msg.locationLat = loc.get("latitude").decimalValue();
msg.locationLng = loc.get("longitude").decimalValue();
msg.locationName = text(loc, "name");
} else {
msg.type = "unsupported";
}
return msg;
}
private void status(JsonNode s, Counts c) {
WaMessage msg = messages.findByWamidAndDirection(text(s, "id") == null ? "" : text(s, "id"), "OUT").orElse(null);
String next = s.path("status").asText();
if (msg == null) {
c.ignored++;
return;
}
String current = msg.status == null ? "pending" : msg.status;
boolean failed = "failed".equals(next);
// ponytail: read-modify-write, a racing older status could win; a conditional UPDATE on rank if that ever shows up.
boolean apply = !"failed".equals(current)
&& (failed || STATUS_RANK.indexOf(next) > STATUS_RANK.indexOf(current));
if (!apply) {
c.ignored++;
return;
}
msg.status = next;
msg.statusAt = time(text(s, "timestamp"));
if (failed) {
JsonNode error = s.path("errors").path(0);
msg.errorCode = cut(text(error, "code"), 32);
msg.errorTitle = cut(text(error, "title"), 255);
}
messages.save(msg);
c.applied++;
}
private static String contactName(JsonNode value, String from) {
for (JsonNode contact : value.path("contacts")) {
if (from.equals(text(contact, "wa_id"))) {
return text(contact.path("profile"), "name");
}
}
return null;
}
private static String preview(WaMessage msg) {
String text = "text".equals(msg.type) && msg.body != null ? msg.body : "[" + msg.type + "]";
return text.codePointCount(0, text.length()) <= PREVIEW_MAX ? text : text.substring(0, text.offsetByCodePoints(0, PREVIEW_MAX));
}
private static String cut(String s, int max) {
return s == null || s.length() <= max ? s : s.substring(0, max);
}
private static String text(JsonNode node, String field) {
return node.hasNonNull(field) ? node.get(field).asText() : null;
}
private static LocalDateTime time(String epochSeconds) {
try {
return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(epochSeconds)), ZoneId.systemDefault());
} catch (RuntimeException e) { // missing or malformed timestamp: use arrival time
return LocalDateTime.now();
}
}
}
@@ -0,0 +1,60 @@
package com.solvway.services.whatsapp.controller;
import com.solvway.services.whatsapp.dto.WebhookIngestRequest;
import com.solvway.services.whatsapp.service.IngestResult;
import com.solvway.services.whatsapp.service.WebhookIngestService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.server.ResponseStatusException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class WebhookControllerTest {
private WebhookIngestService service;
private MockMvc mvc;
@BeforeEach
void setUp() {
service = mock(WebhookIngestService.class);
mvc = MockMvcBuilders.standaloneSetup(new WebhookController(service)).setControllerAdvice(new ErrorHandler()).build();
}
@Test
void answersWithTheCounts() throws Exception {
when(service.ingest(any(WebhookIngestRequest.class))).thenReturn(new IngestResult(2, 1, 3, 0, 0));
mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON)
.content("{\"matchedCompanyCodes\":[\"INS\"],\"payload\":{\"entry\":[]}}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accepted").value(2))
.andExpect(jsonPath("$.duplicates").value(1))
.andExpect(jsonPath("$.dropped").value(3));
}
@Test
void anUnreadableBodyIsInvalidPayload() throws Exception {
mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{not json"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD"));
}
@Test
void aPayloadTheServiceRejectsIsInvalidPayload() throws Exception {
when(service.ingest(any(WebhookIngestRequest.class)))
.thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"));
mvc.perform(post("/whatsapp/webhook/ingest").contentType(MediaType.APPLICATION_JSON).content("{\"payload\":{}}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD"));
}
}
@@ -0,0 +1,129 @@
package com.solvway.services.whatsapp.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.whatsapp.config.WhatsAppSettings;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class CompanyDirectoryTest {
private static final ObjectMapper JSON = new ObjectMapper();
private RestTemplate rest;
private WhatsAppSettings settings;
private final MutableClock clock = new MutableClock();
@BeforeEach
void setUp() {
rest = mock(RestTemplate.class);
MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS,CV");
for (String[] c : new String[][] {{"INS", "111"}, {"CV", "222"}}) {
env.withProperty("WHATSAPP_" + c[0] + "_PHONE_NUMBER_ID", c[1])
.withProperty("WHATSAPP_" + c[0] + "_WABA_ID", "w")
.withProperty("WHATSAPP_" + c[0] + "_ACCESS_TOKEN", "t")
.withProperty("WHATSAPP_" + c[0] + "_APP_SECRET", "s");
}
settings = new WhatsAppSettings(env);
}
private static JsonNode company(long id) throws Exception {
return JSON.readTree("{\"id\":" + id + ",\"code\":\"X\",\"name\":\"Co\",\"status\":\"A\"}");
}
@Test
void mapsPhoneNumberIdToCompanyAtStartup() throws Exception {
when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS"))).thenReturn(company(1));
when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenReturn(company(2));
CompanyDirectory d = new CompanyDirectory(settings, rest, clock);
d.resolveAtStartup();
assertThat(d.byPhoneNumberId("111")).contains(new CompanyDirectory.Company(1, "INS"));
assertThat(d.byPhoneNumberId("222")).contains(new CompanyDirectory.Company(2, "CV"));
assertThat(d.byPhoneNumberId("999")).isEmpty();
}
@Test
void skipsACodeWithNoCompany() throws Exception {
when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS"))).thenReturn(company(1));
when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenReturn(null);
CompanyDirectory d = new CompanyDirectory(settings, rest, clock);
d.resolveAtStartup();
assertThat(d.byPhoneNumberId("111")).isPresent();
assertThat(d.byPhoneNumberId("222")).isEmpty();
}
@Test
void retriesLazilyWhenTheSystemServiceWasDownAtStartup() throws Exception {
when(rest.getForObject(anyString(), eq(JsonNode.class), eq("INS")))
.thenThrow(new ResourceAccessException("down"))
.thenReturn(company(1));
when(rest.getForObject(anyString(), eq(JsonNode.class), eq("CV"))).thenThrow(new ResourceAccessException("down"))
.thenReturn(company(2));
CompanyDirectory d = new CompanyDirectory(settings, rest, clock);
d.resolveAtStartup(); // must not throw
clock.advance(Duration.ofSeconds(30));
assertThat(d.byPhoneNumberId("111")).contains(new CompanyDirectory.Company(1, "INS"));
assertThat(d.byPhoneNumberId("222")).contains(new CompanyDirectory.Company(2, "CV"));
}
@Test
void waitsThirtySecondsAfterAFailedResolveBeforeTryingAgain() {
when(rest.getForObject(anyString(), eq(JsonNode.class), anyString())).thenThrow(new ResourceAccessException("down"));
CompanyDirectory d = new CompanyDirectory(settings, rest, clock);
d.resolveAtStartup();
clock.advance(Duration.ofSeconds(29));
d.byPhoneNumberId("111");
d.byPhoneNumberId("111");
verify(rest, times(2)).getForObject(anyString(), eq(JsonNode.class), anyString()); // startup only: INS and CV
clock.advance(Duration.ofSeconds(1));
d.byPhoneNumberId("111");
verify(rest, times(4)).getForObject(anyString(), eq(JsonNode.class), anyString()); // one more round
}
private static final class MutableClock extends Clock {
private Instant now = Instant.parse("2026-12-02T00:00:00Z");
void advance(Duration d) {
now = now.plus(d);
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
return this;
}
@Override
public Instant instant() {
return now;
}
}
}
@@ -0,0 +1,362 @@
package com.solvway.services.whatsapp.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.whatsapp.dto.WebhookIngestRequest;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.model.WaMessage;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import com.solvway.services.whatsapp.repository.WaMessageRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class WebhookIngestServiceTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final String INS_PHONE = "111";
private static final String CV_PHONE = "222";
private final Map<String, WaConversation> conversations = new LinkedHashMap<>();
private final List<WaMessage> messages = new ArrayList<>();
private boolean existsAlwaysFalse;
private long seq;
private WaConversationRepository convRepo;
private WebhookIngestService service;
@BeforeEach
void setUp() {
CompanyDirectory companies = mock(CompanyDirectory.class);
when(companies.byPhoneNumberId(INS_PHONE)).thenReturn(Optional.of(new CompanyDirectory.Company(1, "INS")));
when(companies.byPhoneNumberId(CV_PHONE)).thenReturn(Optional.of(new CompanyDirectory.Company(2, "CV")));
when(companies.byPhoneNumberId("999")).thenReturn(Optional.empty());
convRepo = mock(WaConversationRepository.class);
when(convRepo.findByCompanyIdAndContactWaId(any(), any()))
.thenAnswer(i -> Optional.ofNullable(conversations.get(i.getArgument(0) + "/" + i.getArgument(1))));
when(convRepo.save(any())).thenAnswer(i -> {
WaConversation c = i.getArgument(0);
if (c.id == null) {
c.id = ++seq;
}
conversations.put(c.companyId + "/" + c.contactWaId, c);
return c;
});
// mirrors the SQL of WaConversationRepository.recordInbound
when(convRepo.recordInbound(any(), any(), any(), any(), any())).thenAnswer(i -> {
WaConversation c = conversations.values().stream().filter(x -> i.getArgument(0).equals(x.id)).findFirst().orElseThrow();
LocalDateTime at = i.getArgument(3);
if (i.getArgument(1) != null) {
c.contactName = i.getArgument(1);
}
c.phoneNumberId = i.getArgument(2);
c.lastInboundAt = c.lastInboundAt == null || at.isAfter(c.lastInboundAt) ? at : c.lastInboundAt;
if (c.lastMessageAt == null || !at.isBefore(c.lastMessageAt)) {
c.lastMessagePreview = i.getArgument(4);
c.lastMessageAt = at;
}
return 1;
});
WaMessageRepository msgRepo = mock(WaMessageRepository.class);
when(msgRepo.existsByWamid(any())).thenAnswer(i -> !existsAlwaysFalse && byWamid(i.getArgument(0)).isPresent());
when(msgRepo.findByWamidAndDirection(any(), any())).thenAnswer(i -> byWamid(i.getArgument(0))
.filter(m -> m.direction.equals(i.getArgument(1))));
when(msgRepo.save(any())).thenAnswer(i -> {
WaMessage m = i.getArgument(0);
if (m.id == null) {
if (m.wamid != null && byWamid(m.wamid).isPresent()) {
throw new DataIntegrityViolationException("uk_wa_message_wamid");
}
m.id = ++seq;
messages.add(m);
}
return m;
});
service = new WebhookIngestService(companies, convRepo, msgRepo);
}
private Optional<WaMessage> byWamid(String wamid) {
return messages.stream().filter(m -> wamid.equals(m.wamid)).findFirst();
}
private static JsonNode payload(String file, String... kv) throws IOException {
String text = new String(WebhookIngestServiceTest.class.getResourceAsStream("/whatsapp/" + file).readAllBytes(),
StandardCharsets.UTF_8);
Map<String, String> v = new HashMap<>(Map.of("PHONE_ID", INS_PHONE, "FROM", "60111222333", "WAMID", "wamid.1",
"TS", "1764662400", "NAME", "Aisyah", "BODY", "hello", "STATUS", "sent"));
for (int i = 0; i < kv.length; i += 2) {
v.put(kv[i], kv[i + 1]);
}
for (Map.Entry<String, String> e : v.entrySet()) {
text = text.replace("${" + e.getKey() + "}", e.getValue());
}
return JSON.readTree(text);
}
private IngestResult ingest(JsonNode payload, String... codes) {
return service.ingest(new WebhookIngestRequest(List.of(codes), payload));
}
private WaMessage seedOut(String wamid, String status) {
WaMessage m = new WaMessage();
m.id = ++seq;
m.direction = "OUT";
m.wamid = wamid;
m.type = "text";
m.status = status;
messages.add(m);
return m;
}
@Test
void truncatesAContactNameTo255() throws Exception {
ingest(payload("text.json", "NAME", "N".repeat(300)), "INS");
assertThat(conversations.get("1/60111222333").contactName).hasSize(255);
}
@Test
void anExistingConversationIsUpdatedInPlaceNeverRewrittenWhole() throws Exception {
ingest(payload("text.json"), "INS");
ingest(payload("text.json", "WAMID", "wamid.2", "TS", "1764662500"), "INS");
verify(convRepo, times(1)).save(any()); // only the insert of the new conversation
verify(convRepo, times(2)).recordInbound(any(), any(), any(), any(), any());
}
@Test
void anOlderMessageNeverOverwritesANewerPreview() throws Exception {
ingest(payload("text.json", "WAMID", "wamid.2", "TS", "1764662500", "BODY", "newer"), "INS");
ingest(payload("text.json", "WAMID", "wamid.1", "TS", "1764662400", "BODY", "older"), "INS");
WaConversation c = conversations.get("1/60111222333");
assertThat(c.lastMessagePreview).isEqualTo("newer");
assertThat(c.lastMessageAt).isEqualTo(LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662500L), ZoneId.systemDefault()));
}
@Test
void ingestIsNotTransactionalSoEachRepositoryCallIsItsOwnTransaction() throws Exception {
assertThat(WebhookIngestService.class.getAnnotation(org.springframework.transaction.annotation.Transactional.class)).isNull();
assertThat(WebhookIngestService.class.getAnnotation(jakarta.transaction.Transactional.class)).isNull();
var ingest = WebhookIngestService.class.getMethod("ingest", WebhookIngestRequest.class);
assertThat(ingest.getAnnotation(org.springframework.transaction.annotation.Transactional.class)).isNull();
assertThat(ingest.getAnnotation(jakarta.transaction.Transactional.class)).isNull();
}
@Test
void acceptsOnlyTheMatchedCompanysNumber() throws Exception {
IngestResult own = ingest(payload("text.json"), "INS");
IngestResult other = ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "INS");
assertThat(own.accepted()).isEqualTo(1);
assertThat(other.accepted()).isZero();
assertThat(other.dropped()).isEqualTo(1);
assertThat(conversations).containsOnlyKeys("1/60111222333");
assertThat(messages).hasSize(1);
}
@Test
void dropsAnUnknownNumber() throws Exception {
IngestResult r = ingest(payload("text.json", "PHONE_ID", "999"), "INS", "CV");
assertThat(r.dropped()).isEqualTo(1);
assertThat(conversations).isEmpty();
assertThat(messages).isEmpty();
}
@Test
void keepsInsAndCvApart() throws Exception {
ingest(payload("text.json"), "INS", "CV");
ingest(payload("text.json", "PHONE_ID", CV_PHONE, "WAMID", "wamid.2"), "INS", "CV");
assertThat(conversations).containsOnlyKeys("1/60111222333", "2/60111222333");
assertThat(conversations.get("1/60111222333").phoneNumberId).isEqualTo(INS_PHONE);
assertThat(conversations.get("2/60111222333").phoneNumberId).isEqualTo(CV_PHONE);
assertThat(messages).extracting(m -> m.conversationId).doesNotHaveDuplicates();
}
@Test
void storesARedeliveredMessageOnce() throws Exception {
ingest(payload("text.json"), "INS");
IngestResult again = ingest(payload("text.json"), "INS");
assertThat(messages).hasSize(1);
assertThat(again.accepted()).isZero();
assertThat(again.duplicates()).isEqualTo(1);
}
@Test
void survivesAConcurrentDuplicateRacingPastTheExistsCheck() throws Exception {
ingest(payload("text.json"), "INS");
existsAlwaysFalse = true; // the other delivery inserted between our check and our insert
IngestResult r = ingest(payload("text.json"), "INS");
assertThat(r.duplicates()).isEqualTo(1);
assertThat(messages).hasSize(1);
}
@Test
void createsTheConversationFromTheFirstMessage() throws Exception {
ingest(payload("text.json"), "INS");
WaConversation c = conversations.get("1/60111222333");
LocalDateTime at = LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662400L), ZoneId.systemDefault());
assertThat(c.contactName).isEqualTo("Aisyah");
assertThat(c.uuid).isNotBlank();
assertThat(c.leadUuid).isNull();
assertThat(c.ownerUserId).isNull();
assertThat(c.lastInboundAt).isEqualTo(at);
assertThat(c.lastMessageAt).isEqualTo(at);
assertThat(c.lastMessagePreview).isEqualTo("hello");
WaMessage m = messages.get(0);
assertThat(m.direction).isEqualTo("IN");
assertThat(m.type).isEqualTo("text");
assertThat(m.body).isEqualTo("hello");
assertThat(m.conversationId).isEqualTo(c.id);
}
@Test
void updatesAnExistingConversationAndTakesTheLatestContactName() throws Exception {
ingest(payload("text.json"), "INS");
ingest(payload("text.json", "WAMID", "wamid.2", "TS", "1764662500", "NAME", "Aisyah R", "BODY", "again"), "INS");
assertThat(conversations).hasSize(1);
WaConversation c = conversations.get("1/60111222333");
assertThat(c.contactName).isEqualTo("Aisyah R");
assertThat(c.lastMessagePreview).isEqualTo("again");
assertThat(c.lastMessageAt).isEqualTo(LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662500L), ZoneId.systemDefault()));
}
@Test
void truncatesThePreviewAtEightyCharactersButKeepsTheFullBody() throws Exception {
String body = "x".repeat(100);
ingest(payload("text.json", "BODY", body), "INS");
assertThat(conversations.get("1/60111222333").lastMessagePreview).hasSize(80);
assertThat(messages.get(0).body).isEqualTo(body);
}
@Test
void storesAnImageWithItsCaption() throws Exception {
ingest(payload("image.json"), "INS");
WaMessage m = messages.get(0);
assertThat(m.type).isEqualTo("image");
assertThat(m.mediaId).isEqualTo("MEDIA-IMG-1");
assertThat(m.mediaMime).isEqualTo("image/jpeg");
assertThat(m.body).isEqualTo("BRIDAL");
assertThat(conversations.get("1/60111222333").lastMessagePreview).isEqualTo("[image]");
}
@Test
void storesADocumentWithItsFilename() throws Exception {
ingest(payload("document.json"), "INS");
WaMessage m = messages.get(0);
assertThat(m.type).isEqualTo("document");
assertThat(m.mediaFilename).isEqualTo("quote.pdf");
assertThat(m.mediaMime).isEqualTo("application/pdf");
assertThat(m.body).isNull();
}
@Test
void storesALocation() throws Exception {
ingest(payload("location.json"), "INS");
WaMessage m = messages.get(0);
assertThat(m.type).isEqualTo("location");
assertThat(m.locationLat).isEqualByComparingTo(new BigDecimal("3.139"));
assertThat(m.locationLng).isEqualByComparingTo(new BigDecimal("101.6869"));
assertThat(m.locationName).isEqualTo("KLCC");
}
@Test
void storesAnUnsupportedType() throws Exception {
ingest(payload("reaction.json"), "INS");
assertThat(messages.get(0).type).isEqualTo("unsupported");
assertThat(conversations.get("1/60111222333").lastMessagePreview).isEqualTo("[unsupported]");
}
@Test
void readThenDeliveredStaysRead() throws Exception {
WaMessage out = seedOut("wamid.out", "sent");
ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", "read", "TS", "1764662500"), "INS");
IngestResult late = ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", "delivered", "TS", "1764662600"), "INS");
assertThat(out.status).isEqualTo("read");
assertThat(out.statusAt).isEqualTo(LocalDateTime.ofInstant(Instant.ofEpochSecond(1764662500L), ZoneId.systemDefault()));
assertThat(late.statusesIgnored()).isEqualTo(1);
}
@Test
void movesForwardThroughSentDeliveredRead() throws Exception {
WaMessage out = seedOut("wamid.out", "pending");
for (String s : List.of("sent", "delivered", "read")) {
ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", s), "INS");
assertThat(out.status).isEqualTo(s);
}
}
@Test
void failedAfterDeliveredRecordsTheError() throws Exception {
WaMessage out = seedOut("wamid.out", "delivered");
IngestResult r = ingest(payload("status-failed.json", "WAMID", "wamid.out"), "INS");
assertThat(out.status).isEqualTo("failed");
assertThat(out.errorCode).isEqualTo("131047");
assertThat(out.errorTitle).isEqualTo("Re-engagement message");
assertThat(r.statusesApplied()).isEqualTo(1);
}
@Test
void ignoresAStatusForAnUnknownWamid() throws Exception {
IngestResult r = ingest(payload("status.json", "WAMID", "wamid.nope"), "INS");
assertThat(r.statusesIgnored()).isEqualTo(1);
assertThat(messages).isEmpty();
}
@Test
void dropsAStatusFromAnUnmatchedNumber() throws Exception {
WaMessage out = seedOut("wamid.out", "sent");
IngestResult r = ingest(payload("status.json", "WAMID", "wamid.out", "STATUS", "read", "PHONE_ID", CV_PHONE), "INS");
assertThat(r.dropped()).isEqualTo(1);
assertThat(out.status).isEqualTo("sent");
}
@Test
void rejectsAMalformedPayload() {
assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), null)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode().value()).isEqualTo(400);
assertThat(e.getReason()).isEqualTo("INVALID_PAYLOAD");
});
assertThatThrownBy(() -> service.ingest(new WebhookIngestRequest(List.of("INS"), JSON.createObjectNode())))
.isInstanceOf(ResponseStatusException.class);
}
}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"document","document":{"filename":"quote.pdf","mime_type":"application/pdf","sha256":"abc","id":"MEDIA-DOC-1"}}]}}]}]}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"image","image":{"caption":"BRIDAL","mime_type":"image/jpeg","sha256":"abc","id":"MEDIA-IMG-1"}}]}}]}]}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"location","location":{"latitude":3.139,"longitude":101.6869,"name":"KLCC"}}]}}]}]}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"reaction","reaction":{"message_id":"wamid.X","emoji":"👍"}}]}}]}]}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"statuses":[{"id":"${WAMID}","status":"failed","timestamp":"${TS}","recipient_id":"60111222333","errors":[{"code":131047,"title":"Re-engagement message","message":"x","error_data":{"details":"d"}}]}]}}]}]}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"statuses":[{"id":"${WAMID}","status":"${STATUS}","timestamp":"${TS}","recipient_id":"60111222333"}]}}]}]}
@@ -0,0 +1 @@
{"object":"whatsapp_business_account","entry":[{"id":"WABA","changes":[{"field":"messages","value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"60123456789","phone_number_id":"${PHONE_ID}"},"contacts":[{"profile":{"name":"${NAME}"},"wa_id":"${FROM}"}],"messages":[{"from":"${FROM}","id":"${WAMID}","timestamp":"${TS}","type":"text","text":{"body":"${BODY}"}}]}}]}]}