feat: WhatsApp contract between mobile-api, the service and the counter

Shared DTOs on both sides with identical JSON keys, the service API
constants with the access convention (the service enforces company,
owner and admin), Snowflake ids as strings towards the portal, and the
counter's WhatsApp contact type.

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 3ac3e108ff
commit 6d63cc74d1
32 files changed
+332 -1

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ Verify commands:
- Depends on: 1.1
- Scope: `solvway-services-whatsapp/**`, `pom.xml`, `solvway-api-gateway/src/main/resources/application.yml`, `local/docker-compose.yml`, `local/whatsapp-mock/**`, `local/.env.example`
- Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-api-gateway verify`
- [ ] 1.3 Shared DTOs and API constants: the webhook ingest body, conversation and message views, and `RestApiWhatsappServiceConstants` in mobile-api.
- [x] 1.3 Shared DTOs and API constants: the webhook ingest body, conversation and message views, and `RestApiWhatsappServiceConstants` in mobile-api.
- Depends on: 1.2
- Scope: `solvway-services-whatsapp/src/main/java/**/dto/**`, `solvway-mobile-api/src/main/java/**/constant/api/RestApiWhatsappServiceConstants.java`, `solvway-mobile-api/src/main/java/**/dto/whatsapp/**`
- Verify: `mvn -T 1C -q -pl solvway-services-whatsapp,solvway-mobile-api verify`
@@ -0,0 +1,36 @@
package com.solvway.mobile.api.constant.api;
/**
* Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values):
* - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params
* companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and
* admin (true when the caller holds BO_WHATSAPP_ADMIN or is a super admin).
* - mobile-api resolves companyId through AdminCompanyScope.scope and admin from the caller's modules, never from
* the request; it does NOT re-check conversation ownership.
* - the service answers 404 for a conversation of another company, always; with admin=false also for a conversation
* not owned by userId. Exception: start returns the conversation's ConversationView (owner fields set, no
* messages) even when owned by someone else, so the UI can say who owns it.
* Response contracts: unreadCount returns UnreadCount {"count": long}; start returns ConversationView; media answers
* 410 ProblemDetail detail MEDIA_EXPIRED when Meta no longer has it, 404 when not visible; send answers 409 detail
* WINDOW_CLOSED (text outside the 24 h window) or 400 detail TEMPLATE_PARAMS (missing template parameters);
* WhatsApp not configured for the company answers 409 detail WHATSAPP_NOT_CONFIGURED.
* "Exactly one of" request validation is done by the mobile-api admin layer, not the DTOs.
*/
public class RestApiWhatsappServiceConstants {
private RestApiWhatsappServiceConstants() {}
public static final String API_REST_WHATSAPP_WEBHOOK_INGEST = "/whatsapp/webhook/ingest";
public static final String API_REST_WHATSAPP_CONVERSATIONS = "/whatsapp/conversations";
public static final String API_REST_WHATSAPP_CONVERSATION = "/whatsapp/conversations/{uuid}";
public static final String API_REST_WHATSAPP_CONVERSATION_SEND = "/whatsapp/conversations/{uuid}/messages";
public static final String API_REST_WHATSAPP_CONVERSATION_READ = "/whatsapp/conversations/{uuid}/read";
public static final String API_REST_WHATSAPP_CONVERSATION_ASSIGN = "/whatsapp/conversations/{uuid}/assign";
public static final String API_REST_WHATSAPP_CONVERSATION_START = "/whatsapp/conversations/start";
public static final String API_REST_WHATSAPP_TEMPLATES = "/whatsapp/templates";
public static final String API_REST_WHATSAPP_TEMPLATES_SYNC = "/whatsapp/templates/sync";
public static final String API_REST_WHATSAPP_MEDIA = "/whatsapp/media/{messageUuid}";
public static final String API_REST_WHATSAPP_UNREAD_COUNT = "/whatsapp/unreadCount";
public static final String API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED = "/whatsapp/ownership/leadChanged";
public static final String API_REST_WHATSAPP_OWNERSHIP_USER_CHANGED = "/whatsapp/ownership/userChanged";
}
@@ -0,0 +1,4 @@
package com.solvway.mobile.api.dto.whatsapp;
/** userId assigns manually; automatic=true returns the chat to automatic ownership. */
public record AssignRequest(Long userId, Boolean automatic) {}
@@ -0,0 +1,5 @@
package com.solvway.mobile.api.dto.whatsapp;
import java.util.List;
public record ConversationPage(List<ConversationView> items, long total, int page, int size) {}
@@ -0,0 +1,10 @@
package com.solvway.mobile.api.dto.whatsapp;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import java.time.LocalDateTime;
/** leadUuid is a Snowflake id, written as a JSON string toward the portal (reads accept the service number). Caller context (companyId, userId) travels as query params, never in this body. ownerName is filled by mobile-api. */
public record ConversationView(String uuid, Long companyId, String contactWaId, String contactName, @JsonSerialize(using = ToStringSerializer.class) Long leadUuid, String leadName,
Long ownerUserId, String ownerName, boolean ownerManual, LocalDateTime lastInboundAt,
LocalDateTime lastMessageAt, String lastMessagePreview, boolean windowOpen, long unreadCount) {}
@@ -0,0 +1,3 @@
package com.solvway.mobile.api.dto.whatsapp;
public record LeadChangedRequest(Long companyId, String mobileE164) {}
@@ -0,0 +1,10 @@
package com.solvway.mobile.api.dto.whatsapp;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** Never carries media_id or wamid. */
public record MessageView(String uuid, String direction, String type, String body, String templateName, String mediaMime,
String mediaFilename, BigDecimal locationLat, BigDecimal locationLng, String locationName,
String status, String errorCode, String errorTitle, Long sentByUserId, LocalDateTime createdAt,
LocalDateTime statusAt) {}
@@ -0,0 +1,6 @@
package com.solvway.mobile.api.dto.whatsapp;
import java.util.List;
/** Exactly one of text or template (with language and params). */
public record SendMessageRequest(String text, String template, String language, List<String> params) {}
@@ -0,0 +1,8 @@
package com.solvway.mobile.api.dto.whatsapp;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
/** Exactly one of leadUuid or eventLeadUuid. */
public record StartChatRequest(@JsonSerialize(using = ToStringSerializer.class) Long leadUuid,
@JsonSerialize(using = ToStringSerializer.class) Long eventLeadUuid) {}
@@ -0,0 +1,3 @@
package com.solvway.mobile.api.dto.whatsapp;
public record TemplateView(String name, String language, String category, String bodyText, int paramCount, boolean supported) {}
@@ -0,0 +1,5 @@
package com.solvway.mobile.api.dto.whatsapp;
import java.util.List;
public record ThreadView(ConversationView conversation, List<MessageView> messages, boolean hasOlder) {}
@@ -0,0 +1,4 @@
package com.solvway.mobile.api.dto.whatsapp;
/** GET /whatsapp/unreadCount response. */
public record UnreadCount(long count) {}
@@ -0,0 +1,3 @@
package com.solvway.mobile.api.dto.whatsapp;
public record UserChangedRequest(Long userId) {}
@@ -0,0 +1,7 @@
package com.solvway.mobile.api.dto.whatsapp;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */
public record WebhookIngestRequest(List<String> matchedCompanyCodes, JsonNode payload) {}
@@ -0,0 +1,70 @@
package com.solvway.mobile.api.dto.whatsapp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** The service and mobile-api sides must serialise to the same key sets. */
class DtoJsonTest {
// same shape as Spring Boot's default mapper: java.time as ISO strings
private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
private Set<String> keys(Object o) {
JsonNode n = mapper.valueToTree(o);
Set<String> k = new TreeSet<>();
n.fieldNames().forEachRemaining(k::add);
return k;
}
@Test
void conversationViewKeys() throws Exception {
LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0);
ConversationView v = new ConversationView("u", 1L, "27820000000", "Ann", 2L, "Lead Ann", 3L, "Bob", true, t, t, "hi", true, 4);
assertEquals(new TreeSet<>(List.of("uuid", "companyId", "contactWaId", "contactName", "leadUuid", "leadName", "ownerUserId",
"ownerName", "ownerManual", "lastInboundAt", "lastMessageAt", "lastMessagePreview", "windowOpen",
"unreadCount")), keys(v));
assertEquals("2026-12-01T10:00:00", mapper.valueToTree(v).get("lastInboundAt").asText());
assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), ConversationView.class));
}
@Test
void snowflakeIdsAreWrittenAsStrings() throws Exception {
ConversationView v = new ConversationView("u", 1L, "w", "n", 1234567890123456789L, "l", null, null, false, null, null, null, false, 0);
assertEquals("1234567890123456789", mapper.valueToTree(v).get("leadUuid").asText());
assertEquals(true, mapper.valueToTree(v).get("leadUuid").isTextual());
assertEquals(true, mapper.valueToTree(new StartChatRequest(1L, 2L)).get("eventLeadUuid").isTextual());
assertEquals(1234567890123456789L, mapper.readValue("{\"leadUuid\":1234567890123456789}", ConversationView.class).leadUuid());
assertEquals(1L, mapper.readValue("{\"leadUuid\":\"1\"}", StartChatRequest.class).leadUuid());
}
@Test
void messageViewKeys() throws Exception {
LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0);
MessageView v = new MessageView("u", "in", "text", "hi", "tpl", "image/png", "a.png", new BigDecimal("1.5"),
new BigDecimal("2.5"), "Spot", "sent", "131047", "Re-engagement", 3L, t, t);
assertEquals(new TreeSet<>(List.of("uuid", "direction", "type", "body", "templateName", "mediaMime",
"mediaFilename", "locationLat", "locationLng", "locationName", "status", "errorCode", "errorTitle",
"sentByUserId", "createdAt", "statusAt")), keys(v));
assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), MessageView.class));
}
@Test
void webhookIngestRequestKeys() throws Exception {
WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}"));
assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r));
assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class));
}
}
@@ -0,0 +1,4 @@
package com.solvway.services.counter.dto;
/** Counter GET /counter/lead/whatsappContact response; the newest lead for the mobile. */
public record WhatsappContact(Long leadUuid, String name, Long latestSalespersonUserId) {}
@@ -0,0 +1,9 @@
package com.solvway.services.whatsapp.constants;
public final class CounterApi {
private CounterApi() {}
/** GET, query params companyId and mobileE164; returns WhatsappContact. */
public static final String WHATSAPP_CONTACT = "/counter/lead/whatsappContact";
}
@@ -0,0 +1,4 @@
package com.solvway.services.whatsapp.dto;
/** userId assigns manually; automatic=true returns the chat to automatic ownership. */
public record AssignRequest(Long userId, Boolean automatic) {}
@@ -0,0 +1,5 @@
package com.solvway.services.whatsapp.dto;
import java.util.List;
public record ConversationPage(List<ConversationView> items, long total, int page, int size) {}
@@ -0,0 +1,8 @@
package com.solvway.services.whatsapp.dto;
import java.time.LocalDateTime;
/** Caller context (companyId, userId) travels as query params, never in this body. ownerName is filled by mobile-api. */
public record ConversationView(String uuid, Long companyId, String contactWaId, String contactName, Long leadUuid, String leadName,
Long ownerUserId, String ownerName, boolean ownerManual, LocalDateTime lastInboundAt,
LocalDateTime lastMessageAt, String lastMessagePreview, boolean windowOpen, long unreadCount) {}
@@ -0,0 +1,3 @@
package com.solvway.services.whatsapp.dto;
public record LeadChangedRequest(Long companyId, String mobileE164) {}
@@ -0,0 +1,10 @@
package com.solvway.services.whatsapp.dto;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** Never carries media_id or wamid. */
public record MessageView(String uuid, String direction, String type, String body, String templateName, String mediaMime,
String mediaFilename, BigDecimal locationLat, BigDecimal locationLng, String locationName,
String status, String errorCode, String errorTitle, Long sentByUserId, LocalDateTime createdAt,
LocalDateTime statusAt) {}
@@ -0,0 +1,6 @@
package com.solvway.services.whatsapp.dto;
import java.util.List;
/** Exactly one of text or template (with language and params). */
public record SendMessageRequest(String text, String template, String language, List<String> params) {}
@@ -0,0 +1,4 @@
package com.solvway.services.whatsapp.dto;
/** Exactly one of leadUuid or eventLeadUuid. */
public record StartChatRequest(Long leadUuid, Long eventLeadUuid) {}
@@ -0,0 +1,3 @@
package com.solvway.services.whatsapp.dto;
public record TemplateView(String name, String language, String category, String bodyText, int paramCount, boolean supported) {}
@@ -0,0 +1,5 @@
package com.solvway.services.whatsapp.dto;
import java.util.List;
public record ThreadView(ConversationView conversation, List<MessageView> messages, boolean hasOlder) {}
@@ -0,0 +1,4 @@
package com.solvway.services.whatsapp.dto;
/** GET /whatsapp/unreadCount response. */
public record UnreadCount(long count) {}
@@ -0,0 +1,3 @@
package com.solvway.services.whatsapp.dto;
public record UserChangedRequest(Long userId) {}
@@ -0,0 +1,7 @@
package com.solvway.services.whatsapp.dto;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
/** mobile-api to service, POST /whatsapp/webhook/ingest: the signature-matched company codes and the raw Meta payload. */
public record WebhookIngestRequest(List<String> matchedCompanyCodes, JsonNode payload) {}
@@ -0,0 +1,4 @@
package com.solvway.services.whatsapp.dto;
/** Counter GET /counter/lead/whatsappContact response; the newest lead for the mobile. */
public record WhatsappContact(Long leadUuid, String name, Long latestSalespersonUserId) {}
@@ -0,0 +1,18 @@
/**
* Caller context and access (the SERVICE enforces it; mobile-api only supplies trusted values):
* - per-conversation calls (thread, send, read, media, assign, start) and the list carry query params
* companyId (null ONLY for a super admin = all companies), userId (the acting staff user) and
* admin (true when the caller holds BO_WHATSAPP_ADMIN or is a super admin).
* - mobile-api resolves companyId through AdminCompanyScope.scope and admin from the caller's modules, never from
* the request; it does NOT re-check conversation ownership.
* - the service answers 404 for a conversation of another company, always; with admin=false also for a conversation
* not owned by userId. Exception: start returns the conversation's ConversationView (owner fields set, no
* messages) even when owned by someone else, so the UI can say who owns it.
* Response contracts: unreadCount returns UnreadCount {"count": long}; start returns ConversationView; media answers
* 410 ProblemDetail detail MEDIA_EXPIRED when Meta no longer has it, 404 when not visible; send answers 409 detail
* WINDOW_CLOSED (text outside the 24 h window) or 400 detail TEMPLATE_PARAMS (missing template parameters);
* WhatsApp not configured for the company answers 409 detail WHATSAPP_NOT_CONFIGURED.
* "Exactly one of" request validation is done by the mobile-api admin layer, not the DTOs.
* Same contract as mobile-api RestApiWhatsappServiceConstants (keep in sync).
*/
package com.solvway.services.whatsapp.dto;
@@ -0,0 +1,60 @@
package com.solvway.services.whatsapp.dto;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** The service and mobile-api sides must serialise to the same key sets. */
class DtoJsonTest {
// same shape as Spring Boot's default mapper: java.time as ISO strings
private final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
private Set<String> keys(Object o) {
JsonNode n = mapper.valueToTree(o);
Set<String> k = new TreeSet<>();
n.fieldNames().forEachRemaining(k::add);
return k;
}
@Test
void conversationViewKeys() throws Exception {
LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0);
ConversationView v = new ConversationView("u", 1L, "27820000000", "Ann", 2L, "Lead Ann", 3L, "Bob", true, t, t, "hi", true, 4);
assertEquals(new TreeSet<>(List.of("uuid", "companyId", "contactWaId", "contactName", "leadUuid", "leadName", "ownerUserId",
"ownerName", "ownerManual", "lastInboundAt", "lastMessageAt", "lastMessagePreview", "windowOpen",
"unreadCount")), keys(v));
assertEquals("2026-12-01T10:00:00", mapper.valueToTree(v).get("lastInboundAt").asText());
assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), ConversationView.class));
}
@Test
void messageViewKeys() throws Exception {
LocalDateTime t = LocalDateTime.of(2026, 12, 1, 10, 0);
MessageView v = new MessageView("u", "in", "text", "hi", "tpl", "image/png", "a.png", new BigDecimal("1.5"),
new BigDecimal("2.5"), "Spot", "sent", "131047", "Re-engagement", 3L, t, t);
assertEquals(new TreeSet<>(List.of("uuid", "direction", "type", "body", "templateName", "mediaMime",
"mediaFilename", "locationLat", "locationLng", "locationName", "status", "errorCode", "errorTitle",
"sentByUserId", "createdAt", "statusAt")), keys(v));
assertEquals(v, mapper.readValue(mapper.writeValueAsString(v), MessageView.class));
}
@Test
void webhookIngestRequestKeys() throws Exception {
WebhookIngestRequest r = new WebhookIngestRequest(List.of("INS"), mapper.readTree("{\"entry\":[]}"));
assertEquals(new TreeSet<>(List.of("matchedCompanyCodes", "payload")), keys(r));
assertEquals(r, mapper.readValue(mapper.writeValueAsString(r), WebhookIngestRequest.class));
}
}