feat: counter WhatsApp contact lookup and lead-changed notify

GET /counter/lead/whatsappContact returns the company's newest lead for a
mobile with its latest salesperson (the Leads list's definition). Event
lead capture, registration and salesperson changes notify the WhatsApp
service after commit, best effort, never logging the mobile.

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 b13e39ac75
commit ae96e316ec
11 files changed
+434 -5

No files matched your search

@@ -0,0 +1,6 @@
package com.solvway.services.counter.constant;
public class RestApiWhatsappServiceConstant {
public static final String SERVICE_ID_WHATSAPP = "service-whatsapp";
public static final String API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED = "/whatsapp/ownership/leadChanged";
}
@@ -23,6 +23,12 @@ public class LeadController {
@GetMapping("/lead/detail/{leadUuid}")
public LeadDetail detail(@PathVariable("leadUuid") long leadUuid) { return leadService.detail(null, leadUuid); }
@GetMapping("/lead/whatsappContact")
public WhatsappContact whatsappContact(@RequestParam("companyId") long companyId,
@RequestParam("mobileE164") String mobileE164) {
return leadService.whatsappContact(companyId, mobileE164);
}
@PostMapping("/lead/update")
public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); }
}
@@ -46,13 +46,16 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
String SEARCH_WHERE = " WHERE (:companyId IS NULL OR l.company_id = :companyId) AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'"
+ " OR l.email_normalised LIKE :q ESCAPE '\\\\' OR (:digits IS NOT NULL AND l.mobile_e164 LIKE :digits))";
/** The most recently captured event lead that has a salesperson, per lead; alias sp. Shared by search and the WhatsApp lookup. */
String LATEST_SALESPERSON_JOIN = " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn"
+ " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1";
String SEARCH_FROM = " FROM `lead` l"
+ " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid"
+ " LEFT JOIN (SELECT lead_uuid, event_uuid, captured_at, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn"
+ " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId)) last ON last.lead_uuid = l.uuid AND last.rn = 1"
+ " LEFT JOIN `event` ev ON ev.uuid = last.event_uuid"
+ " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn"
+ " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1"
+ LATEST_SALESPERSON_JOIN
+ SEARCH_WHERE;
/**
@@ -69,4 +72,9 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE)
Page<SummaryRow> search(@Param("companyId") Long companyId, @Param("q") String q,
@Param("digits") String digits, Pageable pageable);
/** Salesperson of the lead's most recently captured event lead that has one; null when none. */
@Query(nativeQuery = true, value = "SELECT sp.salesperson_user_id FROM `lead` l" + LATEST_SALESPERSON_JOIN
+ " WHERE l.company_id = :companyId AND l.uuid = :leadUuid")
Long latestSalespersonUserId(@Param("companyId") long companyId, @Param("leadUuid") long leadUuid);
}
@@ -53,12 +53,28 @@ public class EventLeadService {
private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private final EventRepository eventRepository;
private final GuestLinker guestLinker;
private final WhatsappNotifier whatsappNotifier;
// ponytail: null event repository and linker keep the pre-invitation wiring working; drop once callers pass both.
// ponytail: null event repository, linker and notifier keep older wiring working; drop once callers pass all.
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
EventLeadInterestRepository eventLeadInterestRepository,
EventLeadStatusChangeRepository eventLeadStatusChangeRepository) {
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null);
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null, null);
}
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
EventLeadInterestRepository eventLeadInterestRepository,
EventLeadStatusChangeRepository eventLeadStatusChangeRepository,
EventRepository eventRepository, GuestLinker guestLinker) {
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository,
eventRepository, guestLinker, null);
}
/** The one place every capture or salesperson change tells the WhatsApp service; skipped for a lead with no mobile. */
public void notifyLeadChanged(Lead lead) {
if (whatsappNotifier != null && lead.getMobileE164() != null) {
whatsappNotifier.leadChanged(lead.getCompanyId(), lead.getMobileE164(), lead.getUuid());
}
}
/** True when today is one of the event's days. */
@@ -144,6 +160,7 @@ public class EventLeadService {
recordStatusChange(eventLead, null, eventLead.getStatus(), eventLead.getCapturedAt(), req.doneBy());
linkGuest(req.eventUuid(), eventLead, lead);
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
notifyLeadChanged(lead);
return detail(eventLead, lead, interestIds);
}
@@ -180,6 +197,7 @@ public class EventLeadService {
requireCompany(req.companyId());
EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
boolean salespersonChanged = !Objects.equals(eventLead.getSalespersonUserId(), req.salespersonUserId());
eventLead.setSalespersonUserId(req.salespersonUserId());
eventLead.setTemperature(blankToNull(req.temperature()));
String oldStatus = eventLead.getStatus();
@@ -201,6 +219,7 @@ public class EventLeadService {
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
if (salespersonChanged) notifyLeadChanged(lead);
return detail(eventLead, lead, interestIds);
}
@@ -6,6 +6,7 @@ import com.solvway.services.counter.dto.LeadSearchRequest;
import com.solvway.services.counter.dto.LeadSummary;
import com.solvway.services.counter.dto.LeadUpdateRequest;
import com.solvway.services.counter.dto.SharedContact;
import com.solvway.services.counter.dto.WhatsappContact;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
@@ -51,6 +52,13 @@ public class LeadService {
: find(companyId, leadUuid));
}
/** The newest lead of the company with this mobile and its latest salesperson; 404 when there is none. */
public WhatsappContact whatsappContact(long companyId, String mobileE164) {
Lead l = leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(companyId, mobileE164)
.orElseThrow(LeadService::notFound);
return new WhatsappContact(l.getUuid(), l.getName(), leadRepository.latestSalespersonUserId(companyId, l.getUuid()));
}
@Transactional
public LeadDetail update(LeadUpdateRequest req) {
if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
@@ -119,6 +119,7 @@ public class RegistrationService {
eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR);
eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds());
link(req, e, lead);
eventLeadService.notifyLeadChanged(lead);
return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid()));
}
@@ -133,6 +134,7 @@ public class RegistrationService {
eventLeadRepository.save(e);
}
link(req, e, lead);
if (assign) eventLeadService.notifyLeadChanged(lead);
return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid()));
}
@@ -0,0 +1,58 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.constant.RestApiWhatsappServiceConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* Tells the WhatsApp service an event lead was captured or its salesperson changed, so it can re-run ownership
* (a lead's mobile edit does not notify; the nightly repair covers it). Best effort: it runs
* after the surrounding transaction commits, never throws, and logs the lead uuid only (never the mobile).
*/
@Component
@Slf4j
public class WhatsappNotifier {
private static final int TIMEOUT_MS = 2000;
private static final String URL = "http://" + RestApiWhatsappServiceConstant.SERVICE_ID_WHATSAPP
+ RestApiWhatsappServiceConstant.API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED;
private final RestTemplate restTemplate;
@Autowired
public WhatsappNotifier() {
// The shared RestTemplate bean has 5 s timeouts; this call must never hold a request thread that long.
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(TIMEOUT_MS);
f.setReadTimeout(TIMEOUT_MS);
this.restTemplate = new RestTemplate(f);
}
WhatsappNotifier(RestTemplate restTemplate) { this.restTemplate = restTemplate; }
public void leadChanged(long companyId, String mobileE164, long leadUuid) {
if (mobileE164 == null || mobileE164.isBlank()) return;
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
send(companyId, mobileE164, leadUuid);
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { send(companyId, mobileE164, leadUuid); }
});
}
private void send(long companyId, String mobileE164, long leadUuid) {
try {
restTemplate.postForLocation(URL, Map.of("companyId", companyId, "mobileE164", mobileE164));
} catch (Exception e) {
// ponytail: no retry; the WhatsApp service also re-resolves ownership when it next sees the contact.
log.warn("WhatsApp ownership notify failed for lead {}: {}", leadUuid, e.getClass().getSimpleName());
}
}
}
@@ -29,7 +29,7 @@ class InvitationWiringTest {
RedisUtil.class, TransactionTemplate.class}) {
mockBean(ctx, c);
}
ctx.register(GuestLinker.class, EventLeadService.class, RegistrationService.class, EventService.class,
ctx.register(GuestLinker.class, WhatsappNotifier.class, EventLeadService.class, RegistrationService.class, EventService.class,
EventHeadcountService.class);
ctx.refresh();
@@ -0,0 +1,94 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.controller.LeadController;
import com.solvway.services.counter.dto.WhatsappContact;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.Test;
import org.springframework.data.jpa.repository.Query;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.server.ResponseStatusException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** GET /counter/lead/whatsappContact: newest lead for the mobile in one company, with its latest salesperson. */
class WhatsappLookupTest {
private static final long COMPANY = 42L;
private static final String MOBILE = "+60123456789";
private final LeadRepository leads = mock(LeadRepository.class);
private final LeadService service = new LeadService(leads, mock(EventLeadRepository.class));
private static Lead lead(String name) {
Lead l = new Lead();
l.setCompanyId(COMPANY);
l.setName(name);
l.setMobileE164(MOBILE);
return l;
}
@Test
void newestLeadOfTheCompanyWinsAndCarriesTheLatestSalesperson() {
Lead newest = lead("Newest");
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(newest));
when(leads.latestSalespersonUserId(COMPANY, newest.getUuid())).thenReturn(7L);
assertThat(service.whatsappContact(COMPANY, MOBILE))
.isEqualTo(new WhatsappContact(newest.getUuid(), "Newest", 7L));
}
@Test
void noSalespersonYieldsNullNotAnError() {
Lead l = lead("A");
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l));
when(leads.latestSalespersonUserId(COMPANY, l.getUuid())).thenReturn(null);
assertThat(service.whatsappContact(COMPANY, MOBILE).latestSalespersonUserId()).isNull();
}
@Test
void otherCompanyOrUnknownMobileIs404() {
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.whatsappContact(COMPANY, MOBILE))
.isInstanceOfSatisfying(ResponseStatusException.class,
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
}
@Test
void latestSalespersonQueryReusesTheSearchWindowAndSkipsEventLeadsWithoutOne() throws Exception {
String sql = LeadRepository.class.getMethod("latestSalespersonUserId", long.class, long.class)
.getAnnotation(Query.class).value();
assertThat(sql).contains(LeadRepository.LATEST_SALESPERSON_JOIN)
.contains("salesperson_user_id IS NOT NULL").contains("ORDER BY captured_at DESC, id DESC");
assertThat(LeadRepository.SEARCH_FROM).contains(LeadRepository.LATEST_SALESPERSON_JOIN);
}
@Test
void httpMapsFoundNotFoundAndMissingCompany() throws Exception {
LeadService svc = mock(LeadService.class);
when(svc.whatsappContact(COMPANY, MOBILE)).thenReturn(new WhatsappContact(9L, "A", 7L));
when(svc.whatsappContact(1L, MOBILE)).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND));
MockMvc mvc = MockMvcBuilders.standaloneSetup(new LeadController(svc)).build();
mvc.perform(get("/counter/lead/whatsappContact").param("companyId", "42").param("mobileE164", MOBILE))
.andExpect(status().isOk()).andExpect(jsonPath("$.leadUuid").value(9))
.andExpect(jsonPath("$.latestSalespersonUserId").value(7));
mvc.perform(get("/counter/lead/whatsappContact").param("companyId", "1").param("mobileE164", MOBILE))
.andExpect(status().isNotFound());
mvc.perform(get("/counter/lead/whatsappContact").param("mobileE164", MOBILE))
.andExpect(status().isBadRequest());
}
}
@@ -0,0 +1,80 @@
package com.solvway.services.counter.service;
import org.junit.jupiter.api.AfterEach;
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.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.client.RestTemplate;
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;
import static org.assertj.core.api.Assertions.assertThatCode;
class WhatsappNotifierTest {
private static final String URL = "http://service-whatsapp/whatsapp/ownership/leadChanged";
private final RestTemplate rest = new RestTemplate();
private final MockRestServiceServer server = MockRestServiceServer.bindTo(rest).build();
private final WhatsappNotifier notifier = new WhatsappNotifier(rest);
@AfterEach
void clear() {
if (TransactionSynchronizationManager.isSynchronizationActive()) TransactionSynchronizationManager.clearSynchronization();
}
@Test
void postsCompanyAndMobile() {
server.expect(requestTo(URL)).andExpect(method(HttpMethod.POST))
.andExpect(content().json("{\"companyId\":42,\"mobileE164\":\"+60123456789\"}"))
.andRespond(withSuccess());
notifier.leadChanged(42L, "+60123456789", 9L);
server.verify();
}
@Test
void noMobileMeansNoCall() {
notifier.leadChanged(42L, null, 9L);
notifier.leadChanged(42L, " ", 9L);
server.verify(); // no expectation set: any call would have failed
}
@Test
void serverErrorAndConnectionFailureAreSwallowed() {
server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
server.expect(requestTo(URL)).andRespond(r -> { throw new java.net.ConnectException("refused"); });
assertThatCode(() -> notifier.leadChanged(42L, "+60123456789", 9L)).doesNotThrowAnyException();
assertThatCode(() -> notifier.leadChanged(42L, "+60123456789", 9L)).doesNotThrowAnyException();
}
@Test
void insideATransactionTheCallWaitsForCommit() {
server.expect(requestTo(URL)).andRespond(withSuccess());
TransactionSynchronizationManager.initSynchronization();
notifier.leadChanged(42L, "+60123456789", 9L);
TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit);
server.verify();
}
@Test
void aRolledBackTransactionNotifiesNobody() {
TransactionSynchronizationManager.initSynchronization();
notifier.leadChanged(42L, "+60123456789", 9L);
TransactionSynchronizationManager.getSynchronizations()
.forEach(s -> s.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK));
server.verify(); // no expectation set: any call would have failed
}
}
@@ -0,0 +1,148 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.EventLeadCaptureRequest;
import com.solvway.services.counter.dto.EventLeadUpdateRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.Optional;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
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.verify;
import static org.mockito.Mockito.when;
/** Every save path that creates an event lead or changes its salesperson tells the WhatsApp service, best effort. */
class WhatsappNotifyOnSaveTest {
private static final long COMPANY = 42L;
private static final long EVENT = 1000L;
private static final String MOBILE = "+60123456789";
private final LeadRepository leads = mock(LeadRepository.class);
private final EventLeadRepository eventLeads = mock(EventLeadRepository.class);
private final WhatsappNotifier notifier = mock(WhatsappNotifier.class);
private EventLeadService service;
private RegistrationService registration;
@BeforeEach
void setUp() {
service = new EventLeadService(leads, eventLeads, mock(EventLeadInterestRepository.class),
mock(EventLeadStatusChangeRepository.class), null, null, notifier);
registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)),
leads, eventLeads, service);
when(leads.saveAndFlush(any(Lead.class))).then(returnsFirstArg());
when(eventLeads.saveAndFlush(any(EventLead.class))).then(i -> {
EventLead e = i.getArgument(0);
e.setId(1L);
return e;
});
}
private static Lead lead(String mobile) {
Lead l = new Lead();
l.setCompanyId(COMPANY);
l.setMobileE164(mobile);
return l;
}
private static EventLeadCaptureRequest capture(String mobile) {
return new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", mobile, null, null, null, 7L, null, null, null, null, null, "staff");
}
@Test
void staffCaptureNotifiesWithTheLeadMobile() {
service.capture(capture(MOBILE));
verify(notifier).leadChanged(eq(COMPANY), eq(MOBILE), anyLong());
}
@Test
void captureWithoutMobileDoesNotNotify() {
service.capture(capture(null));
verify(notifier, never()).leadChanged(anyLong(), any(), anyLong());
}
@Test
void qrRegistrationNotifies() {
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null));
verify(notifier).leadChanged(eq(COMPANY), eq(MOBILE), anyLong());
}
@Test
void qrRegistrationAssigningASalespersonToAnExistingCaptureNotifies() {
Lead l = lead(MOBILE);
EventLead existing = new EventLead();
existing.setLeadUuid(l.getUuid());
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l));
when(eventLeads.findByEventUuidAndLeadUuid(EVENT, l.getUuid())).thenReturn(Optional.of(existing));
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null));
verify(notifier).leadChanged(COMPANY, MOBILE, l.getUuid());
}
@Test
void qrRegistrationOfAnAlreadyOwnedCaptureDoesNotNotify() {
Lead l = lead(MOBILE);
EventLead existing = new EventLead();
existing.setSalespersonUserId(5L);
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l));
when(eventLeads.findByEventUuidAndLeadUuid(EVENT, l.getUuid())).thenReturn(Optional.of(existing));
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null));
verify(notifier, never()).leadChanged(anyLong(), any(), anyLong());
}
private EventLeadUpdateRequest update(Long salesperson) {
return new EventLeadUpdateRequest(COMPANY, 555L, salesperson, null, null, null, null, null, "bo");
}
private EventLead stubUpdate(Long currentSalesperson) {
Lead l = lead(MOBILE);
EventLead e = new EventLead();
e.setCompanyId(COMPANY);
e.setLeadUuid(l.getUuid());
e.setId(1L);
e.setSalespersonUserId(currentSalesperson);
when(eventLeads.findByUuidAndCompanyId(555L, COMPANY)).thenReturn(Optional.of(e));
when(eventLeads.saveAndFlush(any(EventLead.class))).then(returnsFirstArg());
when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l));
return e;
}
@Test
void salespersonChangeNotifies() {
stubUpdate(5L);
service.update(update(7L));
verify(notifier).leadChanged(eq(COMPANY), eq(MOBILE), anyLong());
}
@Test
void updateKeepingTheSameSalespersonDoesNotNotify() {
stubUpdate(5L);
service.update(update(5L));
verify(notifier, never()).leadChanged(anyLong(), any(), anyLong());
}
}