feat(notifications): bell alerts for assigned leads and web sign-ups

InvitationWiringTest registers StaffNotifier and asserts it is wired.

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 19:54:57 +08:00
1 parent 66e2e488d9
commit e3f08bc6cf
12 files changed
+495 -8

No files matched your search

@@ -12,7 +12,7 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-de
## 2. Triggers
- [ ] 2.1 services-counter `StaffNotifier` (after commit, 2 s timeout, never throws, ids-only logs).
- [x] 2.1 services-counter `StaffNotifier` (after commit, 2 s timeout, never throws, ids-only logs).
- Lead assigned at capture and on update, not on self-assignment or clearing.
- Web sign-up to the salesperson, else the event's sales team; one notification when assigned at capture.
- [ ] 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.
@@ -163,6 +163,7 @@ public class AdminEventLeadService {
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
body.put("notes", trimmed(r.notes()));
body.put("doneBy", caller.getUsername());
body.put("doneByUserId", caller.getId()); // add-lead-notifications: self-assignment is silent
try {
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_CAPTURE), MAP, body).getBody(),
known, new HashMap<>());
@@ -281,6 +282,7 @@ public class AdminEventLeadService {
body.put("notes", trimmed(r.notes()));
body.put("attended", r.attended());
body.put("doneBy", caller.getUsername());
body.put("doneByUserId", caller.getId()); // add-lead-notifications: self-assignment is silent
Map<String, Object> saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody();
// field names only: follow-up values are personal data
List<String> changed = new ArrayList<>();
@@ -302,6 +302,16 @@ class AdminEventLeadServiceTest {
.containsEntry("eventUuid", String.valueOf(EV)).containsEntry("leadType", "NEW").containsEntry("mobile", "+60123456789");
}
@Test
void captureAndUpdateSendTheActingUsersIdSoSelfAssignmentIsSilent() {
// add-lead-notifications: the counter skips the bell when the actor is the new salesperson.
service.capture(String.valueOf(EV), capture(null, "Aisyah", "+60 12-345 6789", null));
assertThat(sent(CAPTURE)).containsEntry("doneByUserId", 21L);
stubStored(EV, 23L, List.of());
service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "CONTACTED", List.of(), null, null));
assertThat(sent(UPDATE)).containsEntry("doneByUserId", 21L);
}
@Test
void neitherMobileNorEmailIsRefusedNamingBoth() {
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "", " ")))
@@ -1,6 +1,8 @@
package com.solvway.services.counter.constant;
public class RestApiSystemServiceConstant {
// add-lead-notifications: the staff bell
public static final String API_REST_SYSTEM_NOTIFICATION_SEND = "/notification/send";
//Message
public static final String API_REST_SYSTEM_MESSAGE_FIND_BY_CODE = "/message/getMessagesByCode/{code}";
public static final String API_REST_SYSTEM_MESSAGE_FIND_BY_CODE_AND_AREA = "/message/getMessagesByCodeAndArea/{code}/{Area}";
@@ -19,5 +19,14 @@ public record EventLeadCaptureRequest(
List<Long> interestIds,
LocalDate nextFollowUpDate,
String notes,
String doneBy
) {}
String doneBy,
/* add-lead-notifications: the acting staff user's id, so assigning a lead to yourself is silent. */
Long doneByUserId
) {
public EventLeadCaptureRequest(Long companyId, long eventUuid, Long leadUuid, String name, String mobileE164, String email,
String companyName, String jobTitle, Long salespersonUserId, String temperature, String status,
List<Long> interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) {
this(companyId, eventUuid, leadUuid, name, mobileE164, email, companyName, jobTitle, salespersonUserId, temperature, status,
interestIds, nextFollowUpDate, notes, doneBy, null);
}
}
@@ -6,9 +6,15 @@ import java.util.List;
/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. attended: true stamps now if empty, false clears, null leaves it. */
public record EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy, Boolean attended) {
String doneBy, Boolean attended, Long doneByUserId) {
/** doneByUserId (add-lead-notifications): the acting staff user's id, so assigning a lead to yourself is silent. */
public EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy, Boolean attended) {
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, attended, null);
}
public EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) {
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, null);
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, null, null);
}
}
@@ -54,6 +54,7 @@ public class EventLeadService {
private final EventRepository eventRepository;
private final GuestLinker guestLinker;
private final WhatsappNotifier whatsappNotifier;
private final StaffNotifier staffNotifier;
// ponytail: null event repository, linker and notifier keep older wiring working; drop once callers pass all.
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
@@ -70,6 +71,24 @@ public class EventLeadService {
eventRepository, guestLinker, null);
}
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
EventLeadInterestRepository eventLeadInterestRepository,
EventLeadStatusChangeRepository eventLeadStatusChangeRepository,
EventRepository eventRepository, GuestLinker guestLinker, WhatsappNotifier whatsappNotifier) {
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository,
eventRepository, guestLinker, whatsappNotifier, null);
}
/**
* add-lead-notifications: the staff bell for a capture or a registration. A landing-page sign-up is a sign-up;
* anything else tells the salesperson the lead is theirs (silent when they assigned it to themselves).
*/
public void notifyStaff(EventLead e, Lead lead, String source, Long actorUserId) {
if (staffNotifier == null) return;
if ("WEB".equals(source)) staffNotifier.webSignup(e, lead);
else staffNotifier.leadAssigned(e, lead, actorUserId);
}
/** 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) {
@@ -161,6 +180,7 @@ public class EventLeadService {
linkGuest(req.eventUuid(), eventLead, lead);
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
notifyLeadChanged(lead);
notifyStaff(eventLead, lead, null, req.doneByUserId());
return detail(eventLead, lead, interestIds);
}
@@ -219,7 +239,10 @@ 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);
if (salespersonChanged) {
notifyLeadChanged(lead);
notifyStaff(eventLead, lead, null, req.doneByUserId());
}
return detail(eventLead, lead, interestIds);
}
@@ -134,6 +134,7 @@ public class RegistrationService {
eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds());
link(req, e, lead);
eventLeadService.notifyLeadChanged(lead);
eventLeadService.notifyStaff(e, lead, req.source(), null);
return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid()));
}
@@ -149,6 +150,8 @@ public class RegistrationService {
}
link(req, e, lead);
if (assign) eventLeadService.notifyLeadChanged(lead);
// add-lead-notifications: a repeat landing-page sign-up is news to the team; a QR scan only when it assigns.
if (WEB.equals(req.source()) || assign) eventLeadService.notifyStaff(e, lead, req.source(), null);
return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid()));
}
@@ -0,0 +1,128 @@
package com.solvway.services.counter.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.core.constant.SystemConstants;
import com.solvway.services.counter.constant.RestApiSystemServiceConstant;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
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.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* add-lead-notifications: tells staff about their leads through the bell in service-system. Resolves who hears
* about it, then sends after the surrounding transaction commits. Best effort: never throws, no retry, and logs ids
* only. Parameters carry the lead's and event's names, never a phone number or email address.
*/
@Component
@Slf4j
public class StaffNotifier {
private static final int TIMEOUT_MS = 2000;
private static final String URL = "http://" + SystemConstants.SERVICE_ID_SYSTEM
+ RestApiSystemServiceConstant.API_REST_SYSTEM_NOTIFICATION_SEND;
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplate restTemplate;
private final EventRepository events;
private final EventSalespersonRepository team;
@Autowired
public StaffNotifier(EventRepository events, EventSalespersonRepository team) {
// 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);
this.events = events;
this.team = team;
}
StaffNotifier(RestTemplate restTemplate, EventRepository events, EventSalespersonRepository team) {
this.restTemplate = restTemplate;
this.events = events;
this.team = team;
}
/** The event lead's salesperson hears about it, unless nobody is assigned or they assigned it to themselves. */
public void leadAssigned(EventLead e, Lead lead, Long actorUserId) {
Long to = e.getSalespersonUserId();
if (to == null || to.equals(actorUserId)) return;
send(List.of(row(to, e, lead, "LEAD_ASSIGNED", "NoticeLeadAssigned")));
}
/** A landing-page sign-up: its salesperson, else everyone on the event's sales team, else nobody. */
public void webSignup(EventLead e, Lead lead) {
Set<Long> to = new LinkedHashSet<>();
if (e.getSalespersonUserId() != null) {
to.add(e.getSalespersonUserId());
} else {
team.findByEventUuid(e.getEventUuid()).stream().map(EventSalesperson::getUserId).forEach(to::add);
}
if (to.isEmpty()) return;
List<Map<String, Object>> rows = new ArrayList<>();
for (Long userId : to) rows.add(row(userId, e, lead, "WEB_SIGNUP", "NoticeWebSignup"));
send(rows);
}
private Map<String, Object> row(long userId, EventLead e, Lead lead, String type, String title) {
Map<String, Object> params = new LinkedHashMap<>();
params.put("lead", Objects.toString(lead.getName(), ""));
params.put("event", events.findByUuid(e.getEventUuid()).map(Event::getName).orElse(""));
return row(userId, e.getCompanyId(), type, title, Map.of("code", "NoticeLeadBody", "params", params),
"/leads/" + lead.getUuid(), null);
}
/** One bell row; {@code message} is a code and its parameters, rendered in the reader's language. */
static Map<String, Object> row(long userId, Long companyId, String type, String title, Map<String, Object> message,
String link, String collapseKey) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("receiver", String.valueOf(userId));
r.put("companyId", companyId);
r.put("type", type);
r.put("title", title);
try {
r.put("message", JSON.writeValueAsString(message));
} catch (JsonProcessingException ex) {
throw new IllegalStateException(ex);
}
r.put("link", link);
r.put("collapseKey", collapseKey);
return r;
}
void send(List<Map<String, Object>> rows) {
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
post(rows);
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { post(rows); }
});
}
private void post(List<Map<String, Object>> rows) {
try {
restTemplate.postForLocation(URL, rows);
} catch (Exception e) {
// ponytail: no retry; the lead, chat and follow-up date are still there. Pub/Sub if losses show up.
log.warn("Staff notification ({} rows, type {}) failed: {}", rows.size(), rows.get(0).get("type"), e.getClass().getSimpleName());
}
}
}
@@ -5,6 +5,7 @@ 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.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import com.solvway.services.counter.repo.LeadRepository;
import com.solvway.services.counter.util.redis.RedisUtil;
import org.junit.jupiter.api.Test;
@@ -26,15 +27,16 @@ class InvitationWiringTest {
try (var ctx = new AnnotationConfigApplicationContext()) {
for (Class<?> c : new Class<?>[]{LeadRepository.class, EventLeadRepository.class, EventLeadInterestRepository.class,
EventLeadStatusChangeRepository.class, EventRepository.class, EventGuestRepository.class,
RedisUtil.class, TransactionTemplate.class}) {
RedisUtil.class, TransactionTemplate.class, EventSalespersonRepository.class}) {
mockBean(ctx, c);
}
ctx.register(GuestLinker.class, WhatsappNotifier.class, EventLeadService.class, RegistrationService.class, EventService.class,
ctx.register(GuestLinker.class, WhatsappNotifier.class, StaffNotifier.class, EventLeadService.class, RegistrationService.class, EventService.class,
EventHeadcountService.class);
ctx.refresh();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "guestLinker")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "eventRepository")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "staffNotifier")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(RegistrationService.class), "guestLinker")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventService.class), "guestRepository")).isNotNull();
assertThat(ctx.getBean(EventHeadcountService.class)).isNotNull();
@@ -0,0 +1,158 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
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 java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
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: who hears about a lead, sent best effort to service-system after commit.
class StaffNotifierTest {
private static final String URL = "http://service-system/notification/send";
private static final long COMPANY = 2L;
private static final long EVENT = 1000L;
private final RestTemplate rest = new RestTemplate();
private final MockRestServiceServer server = MockRestServiceServer.bindTo(rest).build();
private final EventRepository events = mock(EventRepository.class);
private final EventSalespersonRepository team = mock(EventSalespersonRepository.class);
private final StaffNotifier notifier = new StaffNotifier(rest, events, team);
private Lead lead;
@BeforeEach
void setUp() {
Event e = new Event();
e.setName("Hotel Expo");
when(events.findByUuid(EVENT)).thenReturn(Optional.of(e));
lead = new Lead();
lead.setCompanyId(COMPANY);
lead.setName("Tan Mei Ling");
lead.setMobileE164("+60123456789");
lead.setEmailNormalised("tan@example.com");
}
@AfterEach
void clear() {
if (TransactionSynchronizationManager.isSynchronizationActive()) TransactionSynchronizationManager.clearSynchronization();
}
private EventLead eventLead(Long salesperson) {
EventLead e = new EventLead();
e.setCompanyId(COMPANY);
e.setEventUuid(EVENT);
e.setLeadUuid(lead.getUuid());
e.setSalespersonUserId(salesperson);
return e;
}
private static EventSalesperson member(long userId) {
EventSalesperson s = new EventSalesperson();
s.setUserId(userId);
return s;
}
@Test
void anAssignedLeadNotifiesTheSalespersonWithNamesOnly() {
server.expect(requestTo(URL)).andExpect(method(HttpMethod.POST))
.andExpect(content().json("[{\"receiver\":\"7\",\"companyId\":2,\"type\":\"LEAD_ASSIGNED\",\"title\":\"NoticeLeadAssigned\","
+ "\"link\":\"/leads/" + lead.getUuid() + "\",\"collapseKey\":null}]"))
.andExpect(r -> {
String body = r.getBody().toString();
assertThat(body).contains("Tan Mei Ling").contains("Hotel Expo").contains("NoticeLeadBody");
assertThat(body).doesNotContain("+60123456789").doesNotContain("tan@example.com");
})
.andRespond(withSuccess());
notifier.leadAssigned(eventLead(7L), lead, 3L);
server.verify();
}
@Test
void selfAssignmentAndClearingNotifyNobody() {
notifier.leadAssigned(eventLead(7L), lead, 7L);
notifier.leadAssigned(eventLead(null), lead, 3L);
server.verify(); // no expectation set: any call would have failed
}
@Test
void aWebSignUpGoesToItsSalesperson() {
server.expect(requestTo(URL))
.andExpect(content().json("[{\"receiver\":\"7\",\"type\":\"WEB_SIGNUP\",\"title\":\"NoticeWebSignup\"}]"))
.andRespond(withSuccess());
notifier.webSignup(eventLead(7L), lead);
server.verify();
}
@Test
void anUnassignedWebSignUpGoesToTheEventsSalesTeamOnceEach() {
when(team.findByEventUuid(EVENT)).thenReturn(List.of(member(7L), member(8L), member(7L)));
server.expect(requestTo(URL))
.andExpect(content().json("[{\"receiver\":\"7\",\"type\":\"WEB_SIGNUP\"},{\"receiver\":\"8\",\"type\":\"WEB_SIGNUP\"}]"))
.andRespond(withSuccess());
notifier.webSignup(eventLead(null), lead);
server.verify();
}
@Test
void anUnassignedWebSignUpWithNoTeamNotifiesNobody() {
when(team.findByEventUuid(EVENT)).thenReturn(List.of());
notifier.webSignup(eventLead(null), lead);
server.verify();
}
@Test
void failuresAreSwallowed() {
server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
server.expect(requestTo(URL)).andRespond(r -> { throw new java.net.ConnectException("refused"); });
assertThatCode(() -> notifier.leadAssigned(eventLead(7L), lead, null)).doesNotThrowAnyException();
assertThatCode(() -> notifier.leadAssigned(eventLead(7L), lead, null)).doesNotThrowAnyException();
}
@Test
void insideATransactionTheCallWaitsForCommitAndARollbackSendsNothing() {
TransactionSynchronizationManager.initSynchronization();
notifier.leadAssigned(eventLead(7L), lead, null);
TransactionSynchronizationManager.getSynchronizations()
.forEach(s -> s.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK));
server.verify();
TransactionSynchronizationManager.clearSynchronization();
server.expect(requestTo(URL)).andRespond(withSuccess());
TransactionSynchronizationManager.initSynchronization();
notifier.leadAssigned(eventLead(7L), lead, null);
TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit);
server.verify();
}
}
@@ -0,0 +1,144 @@
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.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
// add-lead-notifications: every path that assigns an event lead, and every landing-page sign-up, tells the bell.
class StaffNotifyOnSaveTest {
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 StaffNotifier staff = mock(StaffNotifier.class);
private EventLeadService service;
private RegistrationService registration;
@BeforeEach
void setUp() {
service = new EventLeadService(leads, eventLeads, mock(EventLeadInterestRepository.class),
mock(EventLeadStatusChangeRepository.class), null, null, null, staff);
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);
if (e.getId() == null) e.setId(1L);
return e;
});
}
private static Lead lead() {
Lead l = new Lead();
l.setCompanyId(COMPANY);
l.setMobileE164(MOBILE);
return l;
}
@Test
void staffCaptureTellsTheSalespersonWithTheActingUser() {
service.capture(new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", MOBILE, null, null, null, 7L,
null, null, null, null, null, "staff", 3L));
verify(staff).leadAssigned(any(EventLead.class), any(Lead.class), eq(3L));
verify(staff, never()).webSignup(any(), any());
}
@Test
void qrRegistrationWithAPersonalCodeIsAnAssignment() {
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null));
verify(staff).leadAssigned(any(EventLead.class), any(Lead.class), eq(null));
}
@Test
void aWebSignUpIsASignUpNotAnAssignment() {
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null, false, "WEB", null));
verify(staff).webSignup(any(EventLead.class), any(Lead.class));
verify(staff, never()).leadAssigned(any(), any(), any());
}
@Test
void aRepeatWebSignUpOfACapturedPersonIsASignUpAgain() {
Lead l = lead();
EventLead existing = new EventLead();
existing.setLeadUuid(l.getUuid());
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, null, "A", MOBILE, null, null, null,
null, null, null, false, "WEB", null));
verify(staff).webSignup(existing, l);
}
@Test
void qrAssigningAnUnownedCaptureIsAnAssignmentAndAnOwnedOneIsSilent() {
Lead l = lead();
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(staff).leadAssigned(existing, l, null);
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 9L, "A", MOBILE, null, null, null, null, null, null));
verify(staff, org.mockito.Mockito.times(1)).leadAssigned(any(), any(), any());
}
private void stubUpdate(Long currentSalesperson) {
Lead l = lead();
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(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l));
}
private static EventLeadUpdateRequest update(Long salesperson) {
return new EventLeadUpdateRequest(COMPANY, 555L, salesperson, null, null, null, null, null, "bo", null, 3L);
}
@Test
void reassignmentTellsTheNewSalespersonWithTheActingUser() {
stubUpdate(5L);
service.update(update(7L));
verify(staff).leadAssigned(any(EventLead.class), any(Lead.class), eq(3L));
}
@Test
void anUpdateKeepingTheSalespersonIsSilent() {
stubUpdate(5L);
service.update(update(5L));
verifyNoInteractions(staff);
}
}