feat(notifications): tell the chat owner about inbound WhatsApp messages

One unread notification per chat (collapse key WA:<conversation uuid>), linking to
/whatsapp?c=<uuid>. Parameters carry the contact name, never the phone number.
Best effort: a failing store never fails ingest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 20:02:37 +08:00
1 parent 909c1754c0
commit 56fb94ab81
5 files changed
+153 -4

No files matched your search

@@ -17,7 +17,7 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-de
- Web sign-up to the salesperson, else the event's sales team; one notification when assigned at capture.
- [x] 2.2 services-counter daily follow-up summary job (08:00 Asia/Kuala_Lumpur, cron property), one per salesperson with open leads due today or overdue.
- Verify (2.1, 2.2): `mvn -T 1C -B -pl solvway-services-counter -am verify`
- [ ] 2.3 services-whatsapp: notify the chat owner after an inbound message is recorded, collapse key `WA:<conversation uuid>`; no owner, no notification.
- [x] 2.3 services-whatsapp: notify the chat owner after an inbound message is recorded, collapse key `WA:<conversation uuid>`; no owner, no notification.
- Verify: `mvn -T 1C -B -pl solvway-services-whatsapp -am verify`
## 3. Portal
@@ -0,0 +1,63 @@
package com.solvway.services.whatsapp.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.whatsapp.model.WaConversation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* add-lead-notifications: tells a chat's owner about an inbound message through service-system's bell. One unread row
* per chat (collapse key), so a busy chat does not flood the bell. Best effort: never throws, logs ids only, and the
* parameters carry the contact name but never the phone number.
*/
@Component
public class StaffNotifier {
private static final Logger log = LoggerFactory.getLogger(StaffNotifier.class);
private static final String URL = "http://service-system/notification/send";
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplate rest;
@Autowired
public StaffNotifier(RestTemplateBuilder builder) {
this(builder.setConnectTimeout(Duration.ofSeconds(2)).setReadTimeout(Duration.ofSeconds(2)).build());
}
StaffNotifier(RestTemplate rest) {
this.rest = rest;
}
public void whatsappMessage(WaConversation c, String contactName) {
if (c.ownerUserId == null) {
return;
}
try {
Map<String, Object> params = new LinkedHashMap<>();
params.put("name", contactName);
Map<String, Object> message = new LinkedHashMap<>();
message.put("code", "NoticeWhatsappBody");
message.put("params", params);
Map<String, Object> row = new LinkedHashMap<>();
row.put("receiver", String.valueOf(c.ownerUserId));
row.put("companyId", c.companyId);
row.put("type", "WHATSAPP_MESSAGE");
row.put("title", "NoticeWhatsappMessage");
row.put("message", JSON.writeValueAsString(message));
row.put("link", "/whatsapp?c=" + c.uuid);
row.put("collapseKey", "WA:" + c.uuid);
rest.postForEntity(URL, List.of(row), Void.class);
} catch (JsonProcessingException | RuntimeException e) {
log.warn("WhatsApp notification: not sent for conversation {} ({})", c.uuid, e.getClass().getSimpleName());
}
}
}
@@ -57,10 +57,12 @@ public class WebhookIngestService {
private final WaMessageRepository messages;
private final OwnershipService ownership;
private final WhatsAppSettings settings;
private final StaffNotifier notifier;
public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages,
OwnershipService ownership, WhatsAppSettings settings) {
OwnershipService ownership, WhatsAppSettings settings, StaffNotifier notifier) {
this.settings = settings;
this.notifier = notifier;
this.companies = companies;
this.conversations = conversations;
this.messages = messages;
@@ -164,7 +166,10 @@ public class WebhookIngestService {
c.duplicates++;
return;
}
conversations.recordInbound(conv.id, cut(contactName(value, from), 255), phoneNumberId, at, preview(msg));
String name = cut(contactName(value, from), 255);
String shownName = name == null || name.isBlank() ? conv.contactName : name; // read before recordInbound moves it
conversations.recordInbound(conv.id, name, phoneNumberId, at, preview(msg));
notifier.whatsappMessage(conv, shownName);
c.accepted++;
}
@@ -0,0 +1,61 @@
package com.solvway.services.whatsapp.service;
import com.solvway.services.whatsapp.model.WaConversation;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
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;
// add-lead-notifications: an inbound message tells the chat owner, one unread row per chat.
class StaffNotifierTest {
private static final String URL = "http://service-system/notification/send";
private final RestTemplate rest = new RestTemplate();
private final MockRestServiceServer server = MockRestServiceServer.bindTo(rest).build();
private final StaffNotifier notifier = new StaffNotifier(rest);
private static WaConversation chat(Long owner) {
WaConversation c = new WaConversation();
c.id = 5L;
c.uuid = "c-uuid";
c.companyId = 2L;
c.contactWaId = "60111222333";
c.ownerUserId = owner;
return c;
}
@Test
void theOwnerGetsOneCollapsedRowLinkingToTheChatWithTheNameButNeverThePhone() {
server.expect(requestTo(URL)).andExpect(method(HttpMethod.POST))
.andExpect(content().json("[{\"receiver\":\"7\",\"companyId\":2,\"type\":\"WHATSAPP_MESSAGE\","
+ "\"title\":\"NoticeWhatsappMessage\",\"link\":\"/whatsapp?c=c-uuid\",\"collapseKey\":\"WA:c-uuid\","
+ "\"message\":\"{\\\"code\\\":\\\"NoticeWhatsappBody\\\",\\\"params\\\":{\\\"name\\\":\\\"Aisyah\\\"}}\"}]", true))
.andRespond(withSuccess());
notifier.whatsappMessage(chat(7L), "Aisyah");
server.verify();
}
@Test
void aChatWithoutAnOwnerNotifiesNobody() {
notifier.whatsappMessage(chat(null), "Aisyah");
server.verify(); // no request expected
}
@Test
void aFailingStoreNeverFailsTheCaller() {
server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.SERVICE_UNAVAILABLE));
assertThatCode(() -> notifier.whatsappMessage(chat(7L), null)).doesNotThrowAnyException();
}
}
@@ -47,6 +47,7 @@ class WebhookIngestServiceTest {
private long seq;
private WaConversationRepository convRepo;
private OwnershipService ownership;
private StaffNotifier notifier;
private WebhookIngestService service;
private CompanyDirectory companies;
@@ -105,7 +106,8 @@ class WebhookIngestServiceTest {
when(settings.companies()).thenReturn(List.of(
new WhatsAppSettings.CompanyConfig("INS", INS_PHONE, "w1", "t1", SECRETS.get("INS")),
new WhatsAppSettings.CompanyConfig("CV", CV_PHONE, "w2", "t2", SECRETS.get("CV"))));
service = new WebhookIngestService(companies, convRepo, msgRepo, ownership, settings);
notifier = mock(StaffNotifier.class);
service = new WebhookIngestService(companies, convRepo, msgRepo, ownership, settings, notifier);
}
private Optional<WaMessage> byWamid(String wamid) {
@@ -182,6 +184,24 @@ class WebhookIngestServiceTest {
assertThat(conversations).containsKey("1/60111222333");
}
@Test
void eachNewInboundMessageTellsTheChatOwnerButARedeliveryDoesNot() throws Exception {
ingest(payload("text.json", "WAMID", "wamid.a"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b", "TS", "1764662500"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b", "TS", "1764662500"), "INS"); // Meta redelivers
WaConversation chat = conversations.get("1/60111222333");
verify(notifier, times(2)).whatsappMessage(chat, "Aisyah");
}
@Test
void withoutANameInThePayloadTheStoredContactNameIsUsed() throws Exception {
ingest(payload("text.json", "WAMID", "wamid.a"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b", "NAME", ""), "INS");
verify(notifier, times(2)).whatsappMessage(conversations.get("1/60111222333"), "Aisyah");
}
@Test
void truncatesAContactNameTo255() throws Exception {
ingest(payload("text.json", "NAME", "N".repeat(300)), "INS");