feat: WhatsApp chat ownership, manual assignment and nightly repair

Conversations follow the lead's latest salesperson who is active with
BO_WHATSAPP, keep the current owner otherwise, and go unassigned when
nobody qualifies. Automatic writes are compare-and-set so they never
overwrite a WhatsApp Admin's manual assignment. leadChanged, userChanged
and assign endpoints, a 03:00 nightly job, and a system-service read of
the users of a company holding a module.

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 73d06795aa
commit 846c22697e
13 files changed
+1031 -3

No files matched your search

@@ -51,6 +51,7 @@ 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.lang.reflect.Type;
@@ -233,6 +234,13 @@ public class UserController {
.isPresent();
}
/** Ids of the company's enabled admins whose roles grant the module (used by the WhatsApp service for chat ownership). */
@GetMapping("/activeWithModule")
public List<Long> activeWithModule(@RequestParam("companyId") Long companyId,
@RequestParam("module") String module) {
return userService.findActiveAdminIdsWithModule(companyId, module);
}
@RequestMapping("/findByEmail/{email}")
public User findByEmail(@PathVariable("email") String email) {
User user = userService.findByEmail(email);
@@ -2,9 +2,12 @@ package com.solvway.services.system.service;
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
import com.solvway.core.enums.UserEnum.UserType;
import com.solvway.services.system.constant.SystemConstants.Area;
import com.solvway.services.system.constant.SystemConstants.LoginStatus;
import com.solvway.services.system.model.User;
import com.solvway.services.system.model.User.UserStatus;
import com.solvway.services.system.model.Role;
import com.solvway.services.system.repo.ModuleRepository;
import com.solvway.services.system.repo.UserRepository;
import com.solvway.services.system.util.paging.PageableRest;
import org.springframework.beans.factory.annotation.Autowired;
@@ -20,12 +23,18 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private ModuleRepository moduleRepository;
public List<User> findAll() {
return userRepository.findAll();
}
@@ -165,4 +174,17 @@ public class UserService {
public List<User> findUserByRoleName(String roleName){
return userRepository.findUserByRoleName(roleName);
}
/** Ids of the company's enabled admins whose roles grant the module; no company (super admins) means none. */
public List<Long> findActiveAdminIdsWithModule(Long companyId, String module) {
if (companyId == null) {
return List.of();
}
// ROLE_ADMIN (id 2) is injected into every admin and grants no modules; only back office modules count
Set<Long> roleIds = moduleRepository.findByName(module).filter(m -> m.getArea() == Area.BO)
.map(m -> m.getRoles().stream().map(Role::getId).filter(id -> !Long.valueOf(2L).equals(id)).collect(Collectors.toSet())).orElse(Set.of());
return userRepository.findByCompanyIdAndType(companyId, UserType.A).stream()
.filter(u -> u.isEnabled() && u.getRoles().stream().anyMatch(r -> roleIds.contains(r.getId())))
.map(User::getId).toList();
}
}
@@ -0,0 +1,35 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserControllerActiveWithModuleTest {
@Mock private UserService userService;
@InjectMocks private UserController controller;
@Test
void returnsTheIdsTheServiceFindsForTheCompanyAndModule() {
when(userService.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).thenReturn(List.of(10L, 11L));
assertThat(controller.activeWithModule(2L, "BO_WHATSAPP")).containsExactly(10L, 11L);
}
@Test
void noMatchingUsersIsAnEmptyList() {
assertThat(controller.activeWithModule(3L, "BO_WHATSAPP")).isEmpty();
}
}
@@ -0,0 +1,122 @@
package com.solvway.services.system.service;
import com.solvway.core.enums.UserEnum.UserType;
import com.solvway.services.system.constant.SystemConstants.Area;
import com.solvway.services.system.model.Module;
import com.solvway.services.system.model.Role;
import com.solvway.services.system.model.User;
import com.solvway.services.system.repo.ModuleRepository;
import com.solvway.services.system.repo.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserServiceActiveWithModuleTest {
@Mock private UserRepository userRepository;
@Mock private ModuleRepository moduleRepository;
@InjectMocks private UserService service;
private final Role withModule = role(1L);
private final Role withoutModule = role(3L);
private final Role injectedAdmin = role(2L); // ROLE_ADMIN, added to every admin, never a module grant
@BeforeEach
void setUp() {
Module m = new Module();
m.setName("BO_WHATSAPP");
m.setArea(Area.BO);
m.setRoles(List.of(withModule, injectedAdmin));
when(moduleRepository.findByName("BO_WHATSAPP")).thenReturn(Optional.of(m));
}
private static Role role(long id) {
Role r = new Role();
r.setId(id);
return r;
}
private static User user(long id, boolean enabled, Role... roles) {
User u = new User();
u.setId(id);
u.setEnabled(enabled);
u.setRoles(List.of(roles));
return u;
}
@Test
void enabledAdminWhoseRoleGrantsTheModuleIsIncluded() {
when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withoutModule, withModule)));
assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).containsExactly(10L);
}
@Test
void disabledAdminIsExcluded() {
when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, false, withModule)));
assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).isEmpty();
}
@Test
void roleWithoutTheModuleIsExcluded() {
when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withoutModule)));
assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).isEmpty();
}
@Test
void usersOfAnotherCompanyAreNeverLoaded() {
when(userRepository.findByCompanyIdAndType(3L, UserType.A)).thenReturn(List.of());
assertThat(service.findActiveAdminIdsWithModule(3L, "BO_WHATSAPP")).isEmpty();
verify(userRepository).findByCompanyIdAndType(3L, UserType.A);
}
@Test
void noCompanyMeansNoUsersNotTheCompanylessSuperAdmins() {
assertThat(service.findActiveAdminIdsWithModule(null, "BO_WHATSAPP")).isEmpty();
verifyNoInteractions(userRepository);
}
@Test
void unknownModuleMeansNoUsers() {
when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withModule)));
assertThat(service.findActiveAdminIdsWithModule(2L, "NOPE")).isEmpty();
}
@Test
void injectedRoleAdminNeverGrantsTheModule() {
when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, injectedAdmin)));
assertThat(service.findActiveAdminIdsWithModule(2L, "BO_WHATSAPP")).isEmpty();
}
@Test
void moduleOutsideTheBackOfficeAreaMeansNoUsers() {
Module m = new Module();
m.setName("MEMBER_WHATSAPP");
m.setArea(Area.M);
m.setRoles(List.of(withModule));
when(moduleRepository.findByName("MEMBER_WHATSAPP")).thenReturn(Optional.of(m));
when(userRepository.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(user(10L, true, withModule)));
assertThat(service.findActiveAdminIdsWithModule(2L, "MEMBER_WHATSAPP")).isEmpty();
}
}
@@ -2,8 +2,10 @@ package com.solvway.services.whatsapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SolvwayServicesWhatsappApplication {
public static void main(String[] args) {
@@ -0,0 +1,72 @@
package com.solvway.services.whatsapp.job;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.ownership.OwnershipService;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Set;
/** Nightly repair: drops owners who lost access, then recomputes every automatic conversation, company by company. */
@Component
public class OwnershipJob {
public record Counts(int scanned, int unassigned, int recomputed, int changed, int failed) {}
private static final Logger log = LoggerFactory.getLogger(OwnershipJob.class);
private static final int PAGE = 200;
private final WaConversationRepository conversations;
private final OwnershipService ownership;
public OwnershipJob(WaConversationRepository conversations, OwnershipService ownership) {
this.conversations = conversations;
this.ownership = ownership;
}
@Scheduled(cron = "${whatsapp.ownership.cron:0 0 3 * * *}", zone = "Asia/Kuala_Lumpur")
public void nightly() {
run();
}
Counts run() {
int scanned = 0, unassigned = 0, recomputed = 0, changed = 0, failed = 0, skipped = 0;
for (Long companyId : conversations.companyIds()) {
Set<Long> active = ownership.activeUsers(companyId);
if (active == null) {
skipped++;
continue;
}
long after = 0;
List<WaConversation> page;
while (!(page = conversations.findByCompanyIdAndIdGreaterThanOrderByIdAsc(companyId, after, PageRequest.of(0, PAGE))).isEmpty()) {
for (WaConversation c : page) {
scanned++;
after = c.id;
try {
if (ownership.dropIfNoAccess(c, active)) {
unassigned++;
}
if (!c.ownerManual) {
recomputed++;
if (ownership.recompute(c, active)) {
changed++;
}
}
} catch (RuntimeException e) {
failed++;
log.warn("WhatsApp ownership job: conversation {} failed ({})", c.uuid, e.getClass().getSimpleName());
}
}
}
}
log.info("WhatsApp ownership job: scanned={} unassigned={} recomputed={} changed={} failed={} companiesSkipped={}",
scanned, unassigned, recomputed, changed, failed, skipped);
return new Counts(scanned, unassigned, recomputed, changed, failed);
}
}
@@ -0,0 +1,40 @@
package com.solvway.services.whatsapp.ownership;
import com.solvway.services.whatsapp.dto.AssignRequest;
import com.solvway.services.whatsapp.dto.ConversationView;
import com.solvway.services.whatsapp.dto.LeadChangedRequest;
import com.solvway.services.whatsapp.dto.UserChangedRequest;
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;
@RestController
@RequestMapping("/whatsapp")
public class OwnershipController {
private final OwnershipService service;
public OwnershipController(OwnershipService service) {
this.service = service;
}
@PostMapping("/ownership/leadChanged")
public void leadChanged(@RequestBody LeadChangedRequest request) {
service.leadChanged(request);
}
@PostMapping("/ownership/userChanged")
public void userChanged(@RequestBody UserChangedRequest request) {
service.userChanged(request.userId());
}
@PostMapping("/conversations/{uuid}/assign")
public ConversationView assign(@PathVariable String uuid, @RequestParam(required = false) Long companyId,
@RequestParam(required = false) Long userId, @RequestParam boolean admin,
@RequestBody AssignRequest request) {
return service.assign(uuid, companyId, admin, request);
}
}
@@ -0,0 +1,179 @@
package com.solvway.services.whatsapp.ownership;
import com.solvway.services.whatsapp.constants.CounterApi;
import com.solvway.services.whatsapp.dto.AssignRequest;
import com.solvway.services.whatsapp.dto.ConversationView;
import com.solvway.services.whatsapp.dto.LeadChangedRequest;
import com.solvway.services.whatsapp.dto.WhatsappContact;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
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.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Decides who owns each chat. Writes only owner_user_id, owner_manual and lead_uuid through a targeted UPDATE, never a
* whole-entity save, because ingest updates the other columns of the same row concurrently. When the counter or system
* service is unreachable the conversation is left unchanged. Logs conversation ids only, never numbers or names,
* and never exception messages (they can carry the request URL).
*/
@Service
public class OwnershipService {
static final String MODULE = "BO_WHATSAPP";
private static final Logger log = LoggerFactory.getLogger(OwnershipService.class);
private final WaConversationRepository conversations;
private final RestTemplate rest;
@Autowired
public OwnershipService(WaConversationRepository conversations, RestTemplateBuilder builder) {
this(conversations, builder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(10)).build());
}
OwnershipService(WaConversationRepository conversations, RestTemplate rest) {
this.conversations = conversations;
this.rest = rest;
}
/** Users of the company who are enabled admins with BO_WHATSAPP; null when the system service is unreachable. */
public Set<Long> activeUsers(Long companyId) {
try {
Long[] ids = rest.getForObject(
URI.create("http://service-system/user/activeWithModule?companyId=" + companyId + "&module=" + MODULE), Long[].class);
return ids == null ? Set.of() : new HashSet<>(Arrays.asList(ids));
} catch (RuntimeException e) {
log.warn("WhatsApp ownership: active users of company {} unavailable ({})", companyId, e.getClass().getSimpleName());
return null;
}
}
/** Automatic owner for one conversation; a manual owner is never touched. */
public void recompute(WaConversation c) {
if (c.ownerManual) {
return;
}
Set<Long> active = activeUsers(c.companyId);
if (active != null) {
recompute(c, active);
}
}
/** Latest salesperson if they have access, else the current owner if they still do, else nobody. Returns true when it changed. */
public boolean recompute(WaConversation c, Set<Long> active) {
WhatsappContact contact;
try {
contact = lookup(c);
} catch (RuntimeException e) {
log.warn("WhatsApp ownership: counter lookup failed for conversation {} ({})", c.uuid, e.getClass().getSimpleName());
return false;
}
Long salesperson = contact == null ? null : contact.latestSalespersonUserId();
Long owner = salesperson != null && active.contains(salesperson) ? salesperson
: c.ownerUserId != null && active.contains(c.ownerUserId) ? c.ownerUserId : null;
return cas(c, owner, contact == null ? null : contact.leadUuid());
}
/** The userChanged rule: an owner without access loses the chat and the manual flag. Returns true when it did. */
public boolean dropIfNoAccess(WaConversation c, Set<Long> active) {
return c.ownerUserId != null && !active.contains(c.ownerUserId) && cas(c, null, c.leadUuid);
}
public void leadChanged(LeadChangedRequest request) {
if (request.companyId() == null || request.mobileE164() == null) {
return;
}
conversations.findByCompanyIdAndContactWaId(request.companyId(), request.mobileE164().replace("+", ""))
.ifPresent(this::recompute);
}
public void userChanged(Long userId) {
if (userId == null) {
return;
}
conversations.findByOwnerUserId(userId).stream().collect(Collectors.groupingBy(c -> c.companyId)).forEach((companyId, owned) -> {
Set<Long> active = activeUsers(companyId);
if (active != null) {
owned.forEach(c -> dropIfNoAccess(c, active));
}
});
}
public ConversationView assign(String uuid, Long companyId, boolean admin, AssignRequest request) {
if (!admin) {
throw notFound();
}
WaConversation c = conversations.findByUuid(uuid).filter(x -> companyId == null || companyId.equals(x.companyId))
.orElseThrow(OwnershipService::notFound);
if (request == null || (request.userId() == null && !Boolean.TRUE.equals(request.automatic()))) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD");
}
if (Boolean.TRUE.equals(request.automatic())) {
conversations.updateOwnership(c.id, c.ownerUserId, false, c.leadUuid);
c.ownerManual = false;
recompute(c);
} else {
Set<Long> active = activeUsers(c.companyId);
if (active == null) {
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "USERS_UNAVAILABLE");
}
if (!active.contains(request.userId())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ASSIGNEE_NOT_ALLOWED");
}
conversations.updateOwnership(c.id, request.userId(), true, c.leadUuid);
c.ownerUserId = request.userId();
c.ownerManual = true;
}
// ponytail: minimal view (no leadName, unreadCount 0) until the read task; the mobile-api layer fills ownerName.
return new ConversationView(c.uuid, c.companyId, c.contactWaId, c.contactName, c.leadUuid, null, c.ownerUserId, null,
c.ownerManual, c.lastInboundAt, c.lastMessageAt, c.lastMessagePreview,
c.lastInboundAt != null && c.lastInboundAt.isAfter(LocalDateTime.now().minusHours(24)), 0);
}
private WhatsappContact lookup(WaConversation c) {
String mobile = URLEncoder.encode("+" + c.contactWaId, StandardCharsets.UTF_8);
try {
return rest.getForObject(URI.create("http://service-counter" + CounterApi.WHATSAPP_CONTACT
+ "?companyId=" + c.companyId + "&mobileE164=" + mobile), WhatsappContact.class);
} catch (HttpClientErrorException.NotFound e) {
return null; // no lead for this number
}
}
/** Automatic write, compare-and-set on what was read; 0 rows means someone changed it meanwhile, so leave it. */
private boolean cas(WaConversation c, Long owner, Long lead) {
if (Objects.equals(c.ownerUserId, owner) && !c.ownerManual && Objects.equals(c.leadUuid, lead)) {
return false;
}
if (conversations.casOwnership(c.id, owner, lead, c.ownerManual, c.ownerUserId) == 0) {
log.info("WhatsApp ownership: conversation {} changed concurrently, left as is", c.uuid);
return false;
}
c.ownerUserId = owner;
c.ownerManual = false;
c.leadUuid = lead;
return true;
}
private static ResponseStatusException notFound() {
return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND");
}
}
@@ -1,6 +1,7 @@
package com.solvway.services.whatsapp.repository;
import com.solvway.services.whatsapp.model.WaConversation;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
@@ -8,6 +9,7 @@ import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface WaConversationRepository extends JpaRepository<WaConversation, Long> {
@@ -27,4 +29,28 @@ public interface WaConversationRepository extends JpaRepository<WaConversation,
+ "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);
Optional<WaConversation> findByUuid(String uuid);
List<WaConversation> findByOwnerUserId(Long ownerUserId);
/** Keyset paging (stable while rows are updated underneath), used by the nightly job. */
List<WaConversation> findByCompanyIdAndIdGreaterThanOrderByIdAsc(Long companyId, Long afterId, Pageable page);
@Query("select distinct c.companyId from WaConversation c")
List<Long> companyIds();
/** Writes only the ownership columns, never the inbound ones that ingest updates concurrently. */
@Transactional
@Modifying
@Query(value = "UPDATE wa_conversation SET owner_user_id = :owner, owner_manual = :manual, lead_uuid = :lead WHERE id = :id", nativeQuery = true)
int updateOwnership(@Param("id") Long id, @Param("owner") Long owner, @Param("manual") boolean manual, @Param("lead") Long lead);
/** Compare-and-set for automatic writes: applies only if the row still has the flag and owner that recompute read. */
@Transactional
@Modifying
@Query(value = "UPDATE wa_conversation SET owner_user_id = :owner, owner_manual = false, lead_uuid = :lead "
+ "WHERE id = :id AND owner_manual = :prevManual AND owner_user_id <=> :prevOwner", nativeQuery = true)
int casOwnership(@Param("id") Long id, @Param("owner") Long owner, @Param("lead") Long lead,
@Param("prevManual") boolean prevManual, @Param("prevOwner") Long prevOwner);
}
@@ -4,6 +4,7 @@ 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.ownership.OwnershipService;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import com.solvway.services.whatsapp.repository.WaMessageRepository;
import org.slf4j.Logger;
@@ -43,11 +44,14 @@ public class WebhookIngestService {
private final CompanyDirectory companies;
private final WaConversationRepository conversations;
private final WaMessageRepository messages;
private final OwnershipService ownership;
public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages) {
public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages,
OwnershipService ownership) {
this.companies = companies;
this.conversations = conversations;
this.messages = messages;
this.ownership = ownership;
}
public IngestResult ingest(WebhookIngestRequest request) {
@@ -115,7 +119,13 @@ public class WebhookIngestService {
conv.phoneNumberId = "";
conv.createdAt = LocalDateTime.now();
try {
return conversations.save(conv);
WaConversation saved = conversations.save(conv);
try {
ownership.recompute(saved);
} catch (RuntimeException e) { // ownership must never fail ingest; the nightly job repairs it
log.warn("WhatsApp ownership: recompute failed for new conversation {} ({})", saved.uuid, e.getClass().getSimpleName());
}
return saved;
} catch (DataIntegrityViolationException e) { // a concurrent first message created it
return conversations.findByCompanyIdAndContactWaId(companyId, contactWaId).orElseThrow(() -> e);
}
@@ -0,0 +1,122 @@
package com.solvway.services.whatsapp.job;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.ownership.OwnershipService;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class OwnershipJobTest {
private WaConversationRepository repo;
private OwnershipService ownership;
private OwnershipJob job;
private static WaConversation conv(long id, long company, Long owner, boolean manual) {
WaConversation c = new WaConversation();
c.id = id;
c.companyId = company;
c.ownerUserId = owner;
c.ownerManual = manual;
return c;
}
@BeforeEach
void setUp() {
repo = mock(WaConversationRepository.class);
ownership = mock(OwnershipService.class);
job = new OwnershipJob(repo, ownership);
when(repo.companyIds()).thenReturn(List.of(1L, 2L));
}
@Test
void walksEveryCompanyInPagesOf200AndRecomputesNonManualOnes() {
List<WaConversation> first = new ArrayList<>();
for (long i = 1; i <= 200; i++) {
first.add(conv(i, 1, null, false));
}
List<WaConversation> second = List.of(conv(201, 1, null, false), conv(202, 1, 55L, true));
when(ownership.activeUsers(1L)).thenReturn(Set.of(10L));
when(ownership.activeUsers(2L)).thenReturn(Set.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), any(Pageable.class))).thenReturn(first);
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(200L), any(Pageable.class))).thenReturn(second);
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(202L), any(Pageable.class))).thenReturn(List.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of());
when(ownership.dropIfNoAccess(any(), any())).thenReturn(false);
when(ownership.recompute(any(), any())).thenReturn(true);
OwnershipJob.Counts counts = job.run();
assertThat(counts.scanned()).isEqualTo(202);
assertThat(counts.recomputed()).isEqualTo(201); // the manual one is not recomputed
verify(ownership, times(201)).recompute(any(), eq(Set.of(10L)));
verify(repo).findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), eq(org.springframework.data.domain.PageRequest.of(0, 200)));
}
@Test
void ownerWhoLostAccessIsUnassignedThenRecomputedWhenAutomatic() {
WaConversation lostManual = conv(1, 1, 55L, true);
WaConversation lostAuto = conv(2, 1, 56L, false);
when(ownership.activeUsers(1L)).thenReturn(Set.of(10L));
when(ownership.activeUsers(2L)).thenReturn(Set.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), any(Pageable.class))).thenReturn(List.of(lostManual, lostAuto));
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(2L), any(Pageable.class))).thenReturn(List.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of());
when(ownership.dropIfNoAccess(any(), any())).thenAnswer(i -> {
WaConversation c = i.getArgument(0);
c.ownerUserId = null;
c.ownerManual = false;
return true;
});
OwnershipJob.Counts counts = job.run();
assertThat(counts.unassigned()).isEqualTo(2);
verify(ownership, times(2)).recompute(any(), any()); // both were reset to automatic by the drop
}
@Test
void companyWhoseUserListIsUnavailableIsSkipped() {
when(ownership.activeUsers(1L)).thenReturn(null);
when(ownership.activeUsers(2L)).thenReturn(Set.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of());
job.run();
verify(repo, never()).findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), anyLong(), any(Pageable.class));
}
@Test
void oneFailingConversationDoesNotAbortTheRun() {
WaConversation bad = conv(1, 1, null, false);
WaConversation good = conv(2, 1, null, false);
when(ownership.activeUsers(1L)).thenReturn(Set.of(10L));
when(ownership.activeUsers(2L)).thenReturn(Set.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(0L), any(Pageable.class))).thenReturn(List.of(bad, good));
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(1L), eq(2L), any(Pageable.class))).thenReturn(List.of());
when(repo.findByCompanyIdAndIdGreaterThanOrderByIdAsc(eq(2L), anyLong(), any(Pageable.class))).thenReturn(List.of());
when(ownership.recompute(eq(bad), any())).thenThrow(new IllegalStateException("boom"));
when(ownership.recompute(eq(good), any())).thenReturn(true);
OwnershipJob.Counts counts = job.run();
assertThat(counts.scanned()).isEqualTo(2);
assertThat(counts.failed()).isEqualTo(1);
assertThat(counts.changed()).isEqualTo(1);
}
}
@@ -0,0 +1,369 @@
package com.solvway.services.whatsapp.ownership;
import com.solvway.services.whatsapp.dto.WhatsappContact;
import com.solvway.services.whatsapp.controller.ErrorHandler;
import com.solvway.services.whatsapp.model.WaConversation;
import com.solvway.services.whatsapp.repository.WaConversationRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
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 OwnershipTest {
private WaConversationRepository repo;
private RestTemplate rest;
private OwnershipService service;
private MockMvc mvc;
private WhatsappContact contact; // null = counter answers 404
private boolean counterDown;
private Set<Long> active = Set.of(10L, 11L); // users of company 1 with BO_WHATSAPP
private boolean systemDown;
@BeforeEach
void setUp() {
repo = mock(WaConversationRepository.class);
rest = mock(RestTemplate.class);
when(rest.getForObject(any(URI.class), eq(WhatsappContact.class))).thenAnswer(i -> {
if (counterDown) {
throw new ResourceAccessException("down");
}
if (contact == null) {
throw HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null);
}
return contact;
});
when(rest.getForObject(any(URI.class), eq(Long[].class))).thenAnswer(i -> {
if (systemDown) {
throw new ResourceAccessException("down");
}
return active.toArray(new Long[0]);
});
when(repo.casOwnership(anyLong(), any(), any(), anyBoolean(), any())).thenReturn(1);
service = new OwnershipService(repo, rest);
mvc = MockMvcBuilders.standaloneSetup(new OwnershipController(service)).setControllerAdvice(new ErrorHandler()).build();
}
private static WaConversation conv(Long owner, boolean manual) {
WaConversation c = new WaConversation();
c.id = 5L;
c.uuid = "u-1";
c.companyId = 1L;
c.contactWaId = "60111222333";
c.ownerUserId = owner;
c.ownerManual = manual;
c.lastInboundAt = LocalDateTime.now().minusHours(1);
return c;
}
// ---- automatic ownership
@Test
void newConversationGoesToTheLatestSalespersonAndLinksTheLead() {
contact = new WhatsappContact(77L, "Aisyah", 10L);
WaConversation c = conv(null, false);
service.recompute(c);
assertThat(c.ownerUserId).isEqualTo(10L);
assertThat(c.leadUuid).isEqualTo(77L);
assertThat(c.ownerManual).isFalse();
verify(repo).casOwnership(5L, 10L, 77L, false, null);
verify(repo, never()).save(any());
}
@Test
void salespersonWithoutAccessLeavesItUnassignedButLinked() {
contact = new WhatsappContact(77L, "Aisyah", 99L);
WaConversation c = conv(null, false);
service.recompute(c);
assertThat(c.ownerUserId).isNull();
assertThat(c.leadUuid).isEqualTo(77L);
}
@Test
void salespersonWithoutAccessKeepsACurrentOwnerWhoStillHasAccess() {
contact = new WhatsappContact(77L, "Aisyah", 99L);
WaConversation c = conv(11L, false);
service.recompute(c);
assertThat(c.ownerUserId).isEqualTo(11L);
}
@Test
void ownerWhoLostAccessIsDroppedWhenNoSalespersonCanTakeOver() {
contact = new WhatsappContact(77L, "Aisyah", null);
WaConversation c = conv(55L, false);
service.recompute(c);
assertThat(c.ownerUserId).isNull();
}
@Test
void manualOwnerIsLeftAloneWithoutAnyLookup() {
WaConversation c = conv(55L, true);
service.recompute(c);
assertThat(c.ownerUserId).isEqualTo(55L);
verify(rest, never()).getForObject(any(URI.class), eq(WhatsappContact.class));
verify(repo, never()).casOwnership(anyLong(), any(), any(), anyBoolean(), any());
}
@Test
void unknownSenderStaysUnassignedAndUnlinked() {
contact = null;
WaConversation c = conv(null, false);
service.recompute(c);
assertThat(c.ownerUserId).isNull();
assertThat(c.leadUuid).isNull();
}
@Test
void counterDownLeavesTheConversationUnchanged() {
counterDown = true;
WaConversation c = conv(10L, false);
service.recompute(c);
assertThat(c.ownerUserId).isEqualTo(10L);
verify(repo, never()).casOwnership(anyLong(), any(), any(), anyBoolean(), any());
}
@Test
void systemDownLeavesTheConversationUnchanged() {
systemDown = true;
contact = new WhatsappContact(77L, "Aisyah", 10L);
WaConversation c = conv(null, false);
service.recompute(c);
assertThat(c.ownerUserId).isNull();
verify(repo, never()).casOwnership(anyLong(), any(), any(), anyBoolean(), any());
}
@Test
void counterLookupAddsAndEncodesThePlus() {
contact = null;
service.recompute(conv(null, false));
ArgumentCaptor<URI> uri = ArgumentCaptor.forClass(URI.class);
verify(rest).getForObject(uri.capture(), eq(WhatsappContact.class));
assertThat(uri.getValue().toString())
.isEqualTo("http://service-counter/counter/lead/whatsappContact?companyId=1&mobileE164=%2B60111222333");
}
@Test
void systemLookupAsksForTheCompanyAndModule() {
contact = null;
service.recompute(conv(null, false));
ArgumentCaptor<URI> uri = ArgumentCaptor.forClass(URI.class);
verify(rest).getForObject(uri.capture(), eq(Long[].class));
assertThat(uri.getValue().toString())
.isEqualTo("http://service-system/user/activeWithModule?companyId=1&module=BO_WHATSAPP");
}
// ---- leadChanged
@Test
void leadChangedRecomputesTheContactsConversation() throws Exception {
contact = new WhatsappContact(77L, "Aisyah", 11L);
WaConversation c = conv(null, false);
when(repo.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c));
mvc.perform(post("/whatsapp/ownership/leadChanged").contentType(MediaType.APPLICATION_JSON)
.content("{\"companyId\":1,\"mobileE164\":\"+60111222333\"}")).andExpect(status().isOk());
assertThat(c.ownerUserId).isEqualTo(11L);
}
@Test
void leadChangedLeavesAManualOwner() throws Exception {
WaConversation c = conv(55L, true);
when(repo.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c));
mvc.perform(post("/whatsapp/ownership/leadChanged").contentType(MediaType.APPLICATION_JSON)
.content("{\"companyId\":1,\"mobileE164\":\"+60111222333\"}")).andExpect(status().isOk());
assertThat(c.ownerUserId).isEqualTo(55L);
}
@Test
void leadChangedForAnUnknownContactIsStill200() throws Exception {
when(repo.findByCompanyIdAndContactWaId(any(), any())).thenReturn(Optional.empty());
mvc.perform(post("/whatsapp/ownership/leadChanged").contentType(MediaType.APPLICATION_JSON)
.content("{\"companyId\":1,\"mobileE164\":\"+60999\"}")).andExpect(status().isOk());
}
// ---- userChanged
@Test
void userChangedUnassignsConversationsOfAUserWhoLostAccessAndClearsManual() throws Exception {
WaConversation lost = conv(55L, true);
WaConversation kept = conv(10L, true);
kept.id = 6L;
when(repo.findByOwnerUserId(55L)).thenReturn(List.of(lost));
when(repo.findByOwnerUserId(10L)).thenReturn(List.of(kept));
mvc.perform(post("/whatsapp/ownership/userChanged").contentType(MediaType.APPLICATION_JSON)
.content("{\"userId\":55}")).andExpect(status().isOk());
mvc.perform(post("/whatsapp/ownership/userChanged").contentType(MediaType.APPLICATION_JSON)
.content("{\"userId\":10}")).andExpect(status().isOk());
assertThat(lost.ownerUserId).isNull();
assertThat(lost.ownerManual).isFalse();
verify(repo).casOwnership(5L, null, null, true, 55L);
assertThat(kept.ownerUserId).isEqualTo(10L);
assertThat(kept.ownerManual).isTrue();
}
@Test
void latestEventWithoutSalespersonKeepsTheCurrentOwner() {
contact = new WhatsappContact(77L, "Aisyah", null);
WaConversation c = conv(11L, false);
service.recompute(c);
assertThat(c.ownerUserId).isEqualTo(11L);
assertThat(c.leadUuid).isEqualTo(77L);
}
@Test
void recomputeWhoseCompareAndSetLosesIsNotRetriedNorOverwritten() {
contact = new WhatsappContact(77L, "Aisyah", 10L);
when(repo.casOwnership(anyLong(), any(), any(), anyBoolean(), any())).thenReturn(0);
WaConversation c = conv(null, false);
assertThat(service.recompute(c, active)).isFalse();
verify(repo, times(1)).casOwnership(5L, 10L, 77L, false, null);
verify(repo, never()).updateOwnership(anyLong(), any(), anyBoolean(), any());
assertThat(c.ownerUserId).isNull();
}
@Test
void dropWhoseCompareAndSetLosesLeavesTheConversationAlone() {
when(repo.casOwnership(anyLong(), any(), any(), anyBoolean(), any())).thenReturn(0);
WaConversation c = conv(55L, false);
assertThat(service.dropIfNoAccess(c, active)).isFalse();
assertThat(c.ownerUserId).isEqualTo(55L);
}
// ---- assign
private org.springframework.test.web.servlet.ResultActions assign(String query, String body) throws Exception {
return mvc.perform(post("/whatsapp/conversations/u-1/assign?" + query).contentType(MediaType.APPLICATION_JSON).content(body));
}
@Test
void adminAssignsManuallyAndGetsTheView() throws Exception {
WaConversation c = conv(null, false);
when(repo.findByUuid("u-1")).thenReturn(Optional.of(c));
assign("companyId=1&userId=9&admin=true", "{\"userId\":11}")
.andExpect(status().isOk())
.andExpect(jsonPath("$.ownerUserId").value(11))
.andExpect(jsonPath("$.ownerManual").value(true))
.andExpect(jsonPath("$.windowOpen").value(true));
verify(repo).updateOwnership(5L, 11L, true, null);
}
@Test
void superAdminWithNoCompanyScopeMayAssign() throws Exception {
when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false)));
assign("userId=9&admin=true", "{\"userId\":11}").andExpect(status().isOk());
}
@Test
void staffCannotAssign() throws Exception {
when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(9L, false)));
assign("companyId=1&userId=9&admin=false", "{\"userId\":11}").andExpect(status().isNotFound());
verify(repo, never()).updateOwnership(anyLong(), any(), anyBoolean(), any());
}
@Test
void conversationOfAnotherCompanyIs404() throws Exception {
when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false)));
assign("companyId=2&userId=9&admin=true", "{\"userId\":11}").andExpect(status().isNotFound());
}
@Test
void unknownConversationIs404() throws Exception {
when(repo.findByUuid("u-1")).thenReturn(Optional.empty());
assign("companyId=1&userId=9&admin=true", "{\"userId\":11}").andExpect(status().isNotFound());
}
@Test
void assigneeWithoutAccessIs400() throws Exception {
when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false)));
assign("companyId=1&userId=9&admin=true", "{\"userId\":99}")
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("ASSIGNEE_NOT_ALLOWED"));
verify(repo, never()).updateOwnership(anyLong(), any(), anyBoolean(), any());
}
@Test
void automaticClearsManualAndRecomputes() throws Exception {
contact = new WhatsappContact(77L, "Aisyah", 10L);
WaConversation c = conv(11L, true);
when(repo.findByUuid("u-1")).thenReturn(Optional.of(c));
assign("companyId=1&userId=9&admin=true", "{\"automatic\":true}")
.andExpect(status().isOk())
.andExpect(jsonPath("$.ownerUserId").value(10))
.andExpect(jsonPath("$.ownerManual").value(false))
.andExpect(jsonPath("$.leadUuid").value(77));
}
@Test
void assignWithNeitherFieldIs400() throws Exception {
when(repo.findByUuid("u-1")).thenReturn(Optional.of(conv(null, false)));
assign("companyId=1&userId=9&admin=true", "{}")
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("INVALID_PAYLOAD"));
}
}
@@ -6,6 +6,7 @@ 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.ownership.OwnershipService;
import com.solvway.services.whatsapp.repository.WaMessageRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -24,6 +25,7 @@ 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.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -39,6 +41,7 @@ class WebhookIngestServiceTest {
private boolean existsAlwaysFalse;
private long seq;
private WaConversationRepository convRepo;
private OwnershipService ownership;
private WebhookIngestService service;
@BeforeEach
@@ -91,7 +94,8 @@ class WebhookIngestServiceTest {
}
return m;
});
service = new WebhookIngestService(companies, convRepo, msgRepo);
ownership = mock(OwnershipService.class);
service = new WebhookIngestService(companies, convRepo, msgRepo, ownership);
}
private Optional<WaMessage> byWamid(String wamid) {
@@ -127,6 +131,23 @@ class WebhookIngestServiceTest {
return m;
}
@Test
void recomputesOwnershipOnlyWhenTheConversationIsFirstCreated() throws Exception {
ingest(payload("text.json", "WAMID", "wamid.a"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b"), "INS");
verify(ownership, times(1)).recompute(any(WaConversation.class));
}
@Test
void ownershipFailureNeverFailsIngest() throws Exception {
doThrow(new IllegalStateException("boom")).when(ownership).recompute(any(WaConversation.class));
ingest(payload("text.json"), "INS");
assertThat(conversations).containsKey("1/60111222333");
}
@Test
void truncatesAContactNameTo255() throws Exception {
ingest(payload("text.json", "NAME", "N".repeat(300)), "INS");