feat: counter guest, invite registration and check-in endpoints

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-01 17:08:54 +08:00
1 parent d039cbc1e1
commit c700e12865
16 files changed
+1335 -6

No files matched your search

@@ -0,0 +1,66 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.service.EventCheckInService;
import com.solvway.services.counter.service.EventGuestService;
import com.solvway.services.counter.service.EventHeadcountService;
import com.solvway.services.counter.service.EventService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.modelmapper.ModelMapper;
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.server.ResponseStatusException;
import static org.mockito.ArgumentMatchers.any;
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;
/** mobile-api reads the JSON `code` of counter 4xx bodies, so the reason must reach the body. */
@ExtendWith(MockitoExtension.class)
class ApiErrorAdviceTest {
@Mock private EventGuestService guestService;
@Mock private EventCheckInService checkInService;
@Mock private EventService eventService;
@Mock private ModelMapper modelMapper;
@Mock private EventHeadcountService headcountService;
private MockMvc mvc() {
return MockMvcBuilders.standaloneSetup(new EventGuestController(guestService),
new EventCheckInController(checkInService), new EventController(eventService, modelMapper, headcountService))
.setControllerAdvice(new ApiErrorAdvice()).build();
}
@Test
void guestRegisterEventFullIs409WithCode() throws Exception {
when(guestService.register(any())).thenThrow(new ResponseStatusException(HttpStatus.CONFLICT, "EVENT_FULL"));
mvc().perform(post("/counter/eventGuest/register").contentType(MediaType.APPLICATION_JSON)
.content("{\"companyId\":42,\"guestToken\":\"t\"}"))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.code").value("EVENT_FULL"))
.andExpect(jsonPath("$.message").value("EVENT_FULL"));
}
@Test
void checkinCompanyRequiredIs400WithCode() throws Exception {
when(checkInService.ensureToken(any())).thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"));
mvc().perform(post("/counter/checkin/ensureToken").contentType(MediaType.APPLICATION_JSON)
.content("{\"eventUuid\":1}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value("COMPANY_REQUIRED"));
}
@Test
void eventSaveCapBelowGuestsIs409WithCode() throws Exception {
when(eventService.save(any(Event.class))).thenThrow(new ResponseStatusException(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS"));
mvc().perform(post("/counter/event/save").contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.code").value("CAP_BELOW_GUESTS"));
}
}
@@ -0,0 +1,264 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventGuest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Collections;
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.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class EventCheckInServiceTest {
private static final long COMPANY = 42L;
private static final long EVENT = 1000L;
@Mock private EventRepository eventRepository;
@Mock private EventGuestRepository guestRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private LeadRepository leadRepository;
private EventCheckInService service;
private Event event;
@BeforeEach
void setUp() {
service = new EventCheckInService(eventRepository, guestRepository, eventLeadRepository, leadRepository);
event = new Event();
event.setCompanyId(COMPANY);
event.setDateStart(LocalDateTime.now().minusDays(1));
event.setDateEnd(LocalDateTime.now().plusDays(1));
lenient().when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event));
lenient().when(eventRepository.save(any(Event.class))).then(i -> i.getArgument(0));
}
private static void assertStatus(Throwable t, HttpStatus status, String reason) {
assertThat(t).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(status);
if (reason != null) assertThat(e.getReason()).isEqualTo(reason);
});
}
// ---- token / findEvent
@Test
void ensureTokenWritesThroughTheAtomicUpdateAndReturnsTheStoredValue() {
when(eventRepository.setCheckinTokenIfAbsent(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.anyString()))
.then(i -> {
event.setCheckinToken(i.getArgument(1));
return 1;
});
String token = service.ensureToken(new EventCheckInService.EnsureRequest(COMPANY, EVENT)).token();
assertThat(token).hasSize(22).isEqualTo(event.getCheckinToken());
verify(eventRepository).setCheckinTokenIfAbsent(org.mockito.ArgumentMatchers.eq(EVENT), org.mockito.ArgumentMatchers.eq(token));
verify(eventRepository, never()).save(any());
}
@Test
void ensureTokenKeepsAnExistingToken() {
event.setCheckinToken("existing");
assertThat(service.ensureToken(new EventCheckInService.EnsureRequest(COMPANY, EVENT)).token()).isEqualTo("existing");
verify(eventRepository, never()).setCheckinTokenIfAbsent(org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString());
}
@Test
void checkinTokenStaysOutOfEntityUpdatesSoEventServiceSaveCannotWipeIt() throws Exception {
assertThat(Event.class.getDeclaredField("checkinToken").getAnnotation(jakarta.persistence.Column.class).updatable()).isFalse();
}
@Test
void lookupIsNotEventDayOutsideTheEventDays() {
event.setDateStart(LocalDateTime.now().plusDays(5));
event.setDateEnd(LocalDateTime.now().plusDays(6));
assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null)))
.satisfies(t -> assertStatus(t, HttpStatus.CONFLICT, "NOT_EVENT_DAY"));
verify(eventLeadRepository, never()).save(any());
}
@Test
void lookupIs404ForADisabledEvent() {
event.setEnabled(com.solvway.core.enums.GeneralEnum.FlagYesNo.N);
assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null)))
.satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null));
}
@Test
void companyIsRequiredOnEnsureTokenLookupAndByGuest() {
assertThatThrownBy(() -> service.ensureToken(new EventCheckInService.EnsureRequest(null, EVENT)))
.satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"));
assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(null, EVENT, "+601", null)))
.satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"));
assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(null, "gt")))
.satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"));
}
@Test
void ensureTokenIs404ForAnotherCompanysEvent() {
event.setCompanyId(COMPANY + 1);
assertThatThrownBy(() -> service.ensureToken(new EventCheckInService.EnsureRequest(COMPANY, EVENT)))
.satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null));
}
@Test
void findEventReturnsTheEvent() {
event.setCheckinToken("abc");
when(eventRepository.findByCheckinToken("abc")).thenReturn(Optional.of(event));
assertThat(service.findEvent("abc")).isEqualTo(new EventCheckInService.EventRef(COMPANY, event.getUuid()));
}
@Test
void findEventIs404WhenUnknown() {
when(eventRepository.findByCheckinToken("nope")).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.findEvent("nope")).satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null));
}
// ---- lookup
private EventLead leadRow(String name, String mobile, String email, LocalDateTime attendedAt) {
EventLead el = new EventLead();
el.setAttendedAt(attendedAt);
Lead l = new Lead();
l.setName(name);
List<Object[]> rows = Collections.singletonList(new Object[]{el, l});
lenient().when(eventLeadRepository.findByEventAndMobile(EVENT, mobile)).thenReturn(mobile == null ? List.of() : rows);
lenient().when(eventLeadRepository.findByEventAndEmail(EVENT, email)).thenReturn(email == null ? List.of() : rows);
return el;
}
@Test
void lookupByMobileChecksInAndGivesTheFirstName() {
EventLead el = leadRow("Aisyah binti Ali", "+601", null, null);
EventCheckInService.LookupResult r = service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null));
assertThat(r).isEqualTo(new EventCheckInService.LookupResult("CHECKED_IN", "Aisyah"));
assertThat(el.getAttendedAt()).isNotNull();
verify(eventLeadRepository).save(el);
}
@Test
void lookupByEmailWorksAndKeepsAnEarlierAttendanceTime() {
LocalDateTime earlier = LocalDateTime.of(2026, 12, 1, 9, 0);
EventLead el = leadRow("Ben", null, "b@x.com", earlier);
EventCheckInService.LookupResult r = service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, null, "b@x.com"));
assertThat(r).isEqualTo(new EventCheckInService.LookupResult("CHECKED_IN", "Ben"));
assertThat(el.getAttendedAt()).isEqualTo(earlier);
verify(eventLeadRepository, never()).save(any());
}
@Test
void lookupGivesFormForAnInvitedGuestWhoHasNotRegisteredOrAnUnknownPerson() {
lenient().when(eventLeadRepository.findByEventAndMobile(EVENT, "+699")).thenReturn(List.of());
lenient().when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of());
EventCheckInService.LookupResult r = service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+699", null));
assertThat(r.result()).isEqualTo("FORM");
assertThat(r.firstName()).isNull();
verify(eventLeadRepository, never()).save(any());
}
@Test
void lookupNeedsExactlyOneOfMobileAndEmail() {
assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", "a@x.com")))
.satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, null));
assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, null, " ")))
.satisfies(t -> assertStatus(t, HttpStatus.BAD_REQUEST, null));
}
@Test
void lookupIs404ForAnotherCompanysEvent() {
event.setCompanyId(COMPANY + 1);
assertThatThrownBy(() -> service.lookup(new EventCheckInService.LookupRequest(COMPANY, EVENT, "+601", null)))
.satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null));
}
// ---- byGuest
private EventGuest guest(Long eventLeadId) {
EventGuest g = new EventGuest();
g.setCompanyId(COMPANY);
g.setEventUuid(EVENT);
g.setEventLeadId(eventLeadId);
when(guestRepository.findByToken("gt")).thenReturn(Optional.of(g));
return g;
}
@Test
void byGuestChecksInARegisteredGuestOnAnEventDay() {
guest(9L);
EventLead el = new EventLead();
el.setId(9L);
Lead l = new Lead();
l.setName("Aisyah binti Ali");
el.setLeadUuid(l.getUuid());
when(eventLeadRepository.findById(9L)).thenReturn(Optional.of(el));
when(leadRepository.findByUuid(l.getUuid())).thenReturn(Optional.of(l));
EventCheckInService.NameView n = service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt"));
assertThat(n.firstName()).isEqualTo("Aisyah");
assertThat(el.getAttendedAt()).isNotNull();
verify(eventLeadRepository).save(el);
}
@Test
void byGuestRefusesAGuestWhoHasNotRegistered() {
guest(null);
assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt")))
.satisfies(t -> assertStatus(t, HttpStatus.CONFLICT, "NOT_REGISTERED"));
}
@Test
void byGuestRefusesOutsideTheEventDays() {
guest(9L);
event.setDateStart(LocalDateTime.now().plusDays(5));
event.setDateEnd(LocalDateTime.now().plusDays(6));
assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt")))
.satisfies(t -> assertStatus(t, HttpStatus.CONFLICT, "NOT_EVENT_DAY"));
verify(eventLeadRepository, never()).save(any());
}
@Test
void byGuestIs404ForAnUnknownOrForeignGuest() {
EventGuest g = guest(9L);
g.setCompanyId(COMPANY + 1);
assertThatThrownBy(() -> service.byGuest(new EventCheckInService.ByGuestRequest(COMPANY, "gt")))
.satisfies(t -> assertStatus(t, HttpStatus.NOT_FOUND, null));
}
}
@@ -0,0 +1,417 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventGuest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class EventGuestServiceTest {
private static final long COMPANY = 42L;
private static final long EVENT = 1000L;
private static final String TOKEN = "tok-1";
@Mock private EventRepository eventRepository;
@Mock private EventGuestRepository guestRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventSalespersonRepository eventSalespersonRepository;
@Mock private RegistrationService registrationService;
private EventGuestService service;
private Event event;
@BeforeEach
void setUp() {
service = new EventGuestService(eventRepository, guestRepository, eventLeadRepository, eventSalespersonRepository,
registrationService);
event = new Event();
event.setCompanyId(COMPANY);
event.setDateStart(LocalDateTime.now().plusDays(10));
event.setDateEnd(LocalDateTime.now().plusDays(11));
lenient().when(eventRepository.findByUuid(EVENT)).thenReturn(Optional.of(event));
lenient().when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of());
lenient().when(guestRepository.save(any(EventGuest.class))).then(i -> {
EventGuest g = i.getArgument(0);
if (g.getId() == null) g.setId(100L + g.getName().length());
return g;
});
lenient().when(guestRepository.saveAndFlush(any(EventGuest.class))).then(i -> guestRepository.save(i.getArgument(0)));
EventSalesperson sp = new EventSalesperson();
sp.setUserId(7L);
lenient().when(eventSalespersonRepository.findByEventUuid(EVENT)).thenReturn(List.of(sp));
}
private static EventGuestService.GuestInput in(String name, String mobile, String email, Long sp) {
return new EventGuestService.GuestInput(name, mobile, email, "Acme", sp);
}
private static EventGuest guest(long id, String name, String mobile, String email) {
EventGuest g = new EventGuest();
g.setId(id);
g.setCompanyId(COMPANY);
g.setEventUuid(EVENT);
g.setName(name);
g.setMobileE164(mobile);
g.setEmail(email);
g.setToken("t" + id);
return g;
}
private EventGuestService.AddResult add(EventGuestService.GuestInput... guests) {
return service.add(new EventGuestService.AddRequest(COMPANY, EVENT, List.of(guests), "admin"));
}
// ---- add
@Test
void addSavesInOrderWithFreshTokens() {
EventGuestService.AddResult r = add(in("Bee", "+601", "b@x.com", 7L), in("Aaa", "+602", "a@x.com", null));
assertThat(r.rejected()).isEmpty();
assertThat(r.added()).extracting(EventGuestService.GuestRow::name).containsExactly("Bee", "Aaa");
ArgumentCaptor<EventGuest> c = ArgumentCaptor.forClass(EventGuest.class);
verify(guestRepository, times(2)).saveAndFlush(c.capture());
EventGuest first = c.getAllValues().get(0);
assertThat(first.getCompanyId()).isEqualTo(COMPANY);
assertThat(first.getEventUuid()).isEqualTo(EVENT);
assertThat(first.getSalespersonUserId()).isEqualTo(7L);
assertThat(first.getCreatedBy()).isEqualTo("admin");
assertThat(first.getToken()).hasSize(22);
assertThat(first.getToken()).isNotEqualTo(c.getAllValues().get(1).getToken());
assertThat(r.added().get(0).token()).isEqualTo(first.getToken());
}
@Test
void addRejectsDuplicateNamingTheExistingGuest() {
when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of(guest(1, "Existing Eve", "+601", "e@x.com")));
EventGuestService.AddResult r = add(in("New", "+601", "n@x.com", null), in("New2", "+609", "e@x.com", null));
assertThat(r.added()).isEmpty();
assertThat(r.rejected()).extracting(EventGuestService.Rejection::index, EventGuestService.Rejection::code,
EventGuestService.Rejection::field).containsExactly(
org.assertj.core.groups.Tuple.tuple(0, "DUPLICATE", "mobile"),
org.assertj.core.groups.Tuple.tuple(1, "DUPLICATE", "email"));
assertThat(r.rejected().get(0).message()).contains("Existing Eve");
verify(guestRepository, never()).saveAndFlush(any());
}
@Test
void addRejectsDuplicateEarlierInTheSameRequest() {
EventGuestService.AddResult r = add(in("First One", "+601", "a@x.com", null), in("Second", "+601", "b@x.com", null));
assertThat(r.added()).hasSize(1);
assertThat(r.rejected()).hasSize(1);
assertThat(r.rejected().get(0).index()).isEqualTo(1);
assertThat(r.rejected().get(0).code()).isEqualTo("DUPLICATE");
assertThat(r.rejected().get(0).message()).contains("First One");
}
@Test
void addTreatsUniqueKeyRaceAsDuplicate() {
when(guestRepository.saveAndFlush(any(EventGuest.class)))
.thenThrow(new DataIntegrityViolationException("Duplicate entry for key 'event_guest.uk_event_guest_mobile'"));
EventGuestService.AddResult r = add(in("Racer", "+601", "r@x.com", null));
assertThat(r.added()).isEmpty();
assertThat(r.rejected()).extracting(EventGuestService.Rejection::code).containsExactly("DUPLICATE");
}
@Test
void addRethrowsOtherIntegrityViolations() {
when(guestRepository.saveAndFlush(any(EventGuest.class)))
.thenThrow(new DataIntegrityViolationException("Data too long for column 'name'"));
assertThatThrownBy(() -> add(in("Racer", "+601", "r@x.com", null))).isInstanceOf(DataIntegrityViolationException.class);
}
@Test
void companyIsRequiredOnEveryEndpoint() {
List<org.junit.jupiter.api.function.Executable> calls = List.of(
() -> service.list(new EventGuestService.ListRequest(null, EVENT)),
() -> service.add(new EventGuestService.AddRequest(null, EVENT, List.of(), "a")),
() -> service.remove(new EventGuestService.RemoveRequest(null, EVENT, 1L, "a")),
() -> service.markSent(new EventGuestService.MarkSentRequest(null, EVENT, List.of(1L), "a")),
() -> service.register(new EventGuestService.GuestRegisterRequest(null, TOKEN, "n", "+601", null, null, null, null, null, null)));
for (var c : calls) {
assertThatThrownBy(c::execute).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo("COMPANY_REQUIRED");
});
}
}
@Test
void addStopsAtTheInvitationCap() {
event.setInvitationCap(2);
when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of(guest(1, "Old", "+600", "o@x.com")));
EventGuestService.AddResult r = add(in("A", "+601", "a@x.com", null), in("B", "+602", "b@x.com", null));
assertThat(r.added()).extracting(EventGuestService.GuestRow::name).containsExactly("A");
assertThat(r.rejected()).extracting(EventGuestService.Rejection::index, EventGuestService.Rejection::code)
.containsExactly(org.assertj.core.groups.Tuple.tuple(1, "CAP_REACHED"));
assertThat(r.rejected().get(0).message()).isEqualTo("Invitation cap reached (2)");
}
@Test
void addRejectsSalespersonNotOnTheTeam() {
EventGuestService.AddResult r = add(in("A", "+601", "a@x.com", 99L));
assertThat(r.added()).isEmpty();
assertThat(r.rejected()).extracting(EventGuestService.Rejection::code, EventGuestService.Rejection::field)
.containsExactly(org.assertj.core.groups.Tuple.tuple("NOT_ON_TEAM", "salespersonUserId"));
}
@Test
void addIs404ForAnotherCompanysEvent() {
event.setCompanyId(COMPANY + 1);
assertThatThrownBy(() -> add(in("A", "+601", "a@x.com", null)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
verify(guestRepository, never()).saveAndFlush(any());
}
// ---- remove / markSent
@Test
void removeRefusesALinkedGuest() {
EventGuest g = guest(5, "Linked", "+601", null);
g.setEventLeadId(9L);
when(guestRepository.findByIdAndEventUuidAndCompanyId(5L, EVENT, COMPANY)).thenReturn(Optional.of(g));
assertThatThrownBy(() -> service.remove(new EventGuestService.RemoveRequest(COMPANY, EVENT, 5L, "admin")))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getReason()).isEqualTo("GUEST_REGISTERED");
});
verify(guestRepository, never()).delete(any());
}
@Test
void removeDeletesAnUnlinkedGuest() {
EventGuest g = guest(5, "Free", "+601", null);
when(guestRepository.findByIdAndEventUuidAndCompanyId(5L, EVENT, COMPANY)).thenReturn(Optional.of(g));
service.remove(new EventGuestService.RemoveRequest(COMPANY, EVENT, 5L, "admin"));
verify(guestRepository).delete(g);
}
@Test
void removeIs404WhenTheGuestIsNotOfThisEvent() {
when(guestRepository.findByIdAndEventUuidAndCompanyId(5L, EVENT, COMPANY)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.remove(new EventGuestService.RemoveRequest(COMPANY, EVENT, 5L, "admin")))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
}
@Test
void markSentSetsInvitedAtOnceAndCountsEverySend() {
EventGuest fresh = guest(1, "Fresh", "+601", null);
EventGuest resent = guest(2, "Resent", "+602", null);
LocalDateTime first = LocalDateTime.of(2026, 11, 1, 9, 0);
resent.setInvitedAt(first);
resent.setInviteSentCount(1);
when(guestRepository.findByEventUuidAndCompanyIdAndIdIn(anyLong(), anyLong(), anyCollection())).thenReturn(List.of(fresh, resent));
service.markSent(new EventGuestService.MarkSentRequest(COMPANY, EVENT, List.of(1L, 2L, 3L), "admin"));
assertThat(fresh.getInvitedAt()).isNotNull();
assertThat(fresh.getInviteSentCount()).isEqualTo(1);
assertThat(resent.getInvitedAt()).isEqualTo(first);
assertThat(resent.getInviteSentCount()).isEqualTo(2);
}
// ---- findByToken
@Test
void findByTokenReturnsTheGuest() {
EventGuest g = guest(5, "Aisyah", "+601", "a@x.com");
g.setSalespersonUserId(7L);
g.setEventLeadId(9L);
EventLead lead = new EventLead();
lead.setAttendedAt(LocalDateTime.now());
when(guestRepository.findByToken(TOKEN)).thenReturn(Optional.of(g));
when(eventLeadRepository.findById(9L)).thenReturn(Optional.of(lead));
EventGuestService.GuestLookup l = service.findByToken(TOKEN);
assertThat(l).isEqualTo(new EventGuestService.GuestLookup(COMPANY, EVENT, 5L, "Aisyah", "+601", "a@x.com", "Acme"
.equals(g.getCompanyName()) ? "Acme" : null, 7L, true, true));
}
@Test
void findByTokenIs404WhenUnknown() {
when(guestRepository.findByToken(TOKEN)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.findByToken(TOKEN))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
}
// ---- list
@Test
void listDerivesAttendedAndEventLeadWithOneLeadQuery() {
EventGuest a = guest(1, "Aaa", "+601", null);
a.setEventLeadId(10L);
EventGuest b = guest(2, "Bbb", "+602", null);
b.setEventLeadId(11L);
EventGuest c = guest(3, "Ccc", "+603", null);
EventLead l10 = new EventLead();
l10.setId(10L);
l10.setAttendedAt(LocalDateTime.now());
EventLead l11 = new EventLead();
l11.setId(11L);
when(guestRepository.findByEventUuidOrderByNameAsc(EVENT)).thenReturn(List.of(a, b, c));
when(eventLeadRepository.findAllById(anyCollection())).thenReturn(List.of(l10, l11));
List<EventGuestService.GuestRow> rows = service.list(new EventGuestService.ListRequest(COMPANY, EVENT));
assertThat(rows).extracting(EventGuestService.GuestRow::name).containsExactly("Aaa", "Bbb", "Ccc");
assertThat(rows).extracting(EventGuestService.GuestRow::attended).containsExactly(true, false, false);
assertThat(rows.get(0).eventLeadUuid()).isEqualTo(String.valueOf(l10.getUuid()));
assertThat(rows.get(1).eventLeadUuid()).isEqualTo(String.valueOf(l11.getUuid()));
assertThat(rows.get(2).eventLeadUuid()).isNull();
verify(eventLeadRepository, times(1)).findAllById(anyCollection());
verify(eventLeadRepository, never()).findById(any());
}
@Test
void listIs404ForAnotherCompanysEvent() {
event.setCompanyId(COMPANY + 1);
assertThatThrownBy(() -> service.list(new EventGuestService.ListRequest(COMPANY, EVENT)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
}
// ---- register
private EventGuestService.GuestRegisterRequest reg() {
return new EventGuestService.GuestRegisterRequest(COMPANY, TOKEN, "Aisyah", "+601", "a@x.com", "Acme", "CEO",
List.of(3L), 5L, LocalDateTime.of(2026, 12, 1, 10, 0));
}
private EventGuest registrable() {
EventGuest g = guest(5, "Aisyah", "+601", "a@x.com");
g.setSalespersonUserId(7L);
when(guestRepository.findByToken(TOKEN)).thenReturn(Optional.of(g));
return g;
}
@Test
void registerUsesSourceInviteTheGuestsSalespersonAndLinksTheTokenGuest() {
registrable();
when(registrationService.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "555"));
EventGuestService.GuestRegisterRequest r = reg();
RegistrationService.RegisterResult out = service.register(r);
assertThat(out).isEqualTo(new RegistrationService.RegisterResult("CREATED", "555"));
ArgumentCaptor<RegistrationService.RegisterRequest> c = ArgumentCaptor.forClass(RegistrationService.RegisterRequest.class);
verify(registrationService).register(c.capture());
RegistrationService.RegisterRequest q = c.getValue();
assertThat(q.source()).isEqualTo("INVITE");
assertThat(q.guestId()).isEqualTo(5L);
assertThat(q.salespersonUserId()).isEqualTo(7L);
assertThat(q.attend()).isFalse();
assertThat(q.eventUuid()).isEqualTo(EVENT);
assertThat(q.companyId()).isEqualTo(COMPANY);
assertThat(q.name()).isEqualTo("Aisyah");
assertThat(q.interestIds()).containsExactly(3L);
}
@Test
void registerIs404ForAnotherCompanysGuest() {
EventGuest g = registrable();
g.setCompanyId(COMPANY + 1);
assertThatThrownBy(() -> service.register(reg()))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
verify(registrationService, never()).register(any());
}
@Test
void registerAgainReportsAlreadyRegisteredAndChangesNothing() {
EventGuest g = registrable();
g.setEventLeadId(9L);
EventLead lead = new EventLead();
lead.setId(9L);
when(eventLeadRepository.findById(9L)).thenReturn(Optional.of(lead));
RegistrationService.RegisterResult out = service.register(reg());
assertThat(out).isEqualTo(new RegistrationService.RegisterResult("ALREADY_REGISTERED", String.valueOf(lead.getUuid())));
verify(registrationService, never()).register(any());
}
@Test
void registerIsEventFullBeforeTheEventDaysAtCapacity() {
registrable();
event.setCapacity(10);
when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(7L);
when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(3L);
assertThatThrownBy(() -> service.register(reg()))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getReason()).isEqualTo("EVENT_FULL");
});
verify(registrationService, never()).register(any());
}
@Test
void registerBelowCapacityGoesThrough() {
registrable();
event.setCapacity(10);
when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(7L);
when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(2L);
when(registrationService.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "1"));
assertThat(service.register(reg()).outcome()).isEqualTo("CREATED");
}
@Test
void registerIsNeverEventFullOnTheEventDays() {
registrable();
event.setDateStart(LocalDateTime.now().minusDays(1));
event.setDateEnd(LocalDateTime.now().plusDays(1));
event.setCapacity(10);
lenient().when(guestRepository.countByEventUuidAndEventLeadIdIsNotNull(EVENT)).thenReturn(10L);
lenient().when(eventLeadRepository.countWalkIns(EVENT)).thenReturn(5L);
when(registrationService.register(any())).thenReturn(new RegistrationService.RegisterResult("CREATED", "1"));
assertThat(service.register(reg()).outcome()).isEqualTo("CREATED");
}
}
@@ -0,0 +1,107 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.EventGuest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventGuestRepository;
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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class RegistrationInviteLinkTest {
private static final long COMPANY = 42L;
private static final long EVENT = 1000L;
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository interestRepository;
@Mock private EventLeadStatusChangeRepository statusChangeRepository;
@Mock private EventGuestRepository guests;
private RegistrationService registration;
@BeforeEach
void setUp() {
EventLeadService eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, interestRepository, statusChangeRepository);
registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)),
leadRepository, eventLeadRepository, eventLeadService, new GuestLinker(guests));
lenient().when(leadRepository.saveAndFlush(any(Lead.class))).then(returnsFirstArg());
lenient().when(eventLeadRepository.saveAndFlush(any(EventLead.class))).then(i -> {
EventLead e = i.getArgument(0);
e.setId(1L);
return e;
});
}
private static RegistrationService.RegisterRequest invite(Long guestId) {
return new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "Aisyah", "+601", "a@x.com", null, null,
List.of(), null, null, false, "INVITE", guestId);
}
@Test
void inviteRegistrationSavesSourceInviteAndLinksOnlyTheTokenGuest() {
EventGuest tokenGuest = new EventGuest();
tokenGuest.setId(5L);
when(guests.findById(5L)).thenReturn(Optional.of(tokenGuest));
registration.register(invite(5L));
ArgumentCaptor<EventLead> c = ArgumentCaptor.forClass(EventLead.class);
verify(eventLeadRepository).saveAndFlush(c.capture());
assertThat(c.getValue().getSource()).isEqualTo("INVITE");
assertThat(tokenGuest.getEventLeadId()).isEqualTo(1L);
assertThat(tokenGuest.getRegisteredAt()).isNotNull();
verify(guests, never()).findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(any(Long.class), any());
verify(guests, never()).findFirstByEventUuidAndEventLeadIdIsNullAndEmail(any(Long.class), any());
}
@Test
void qrRegistrationKeepsSourceQr() {
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", "+601", null, null, null,
List.of(), null, null));
ArgumentCaptor<EventLead> c = ArgumentCaptor.forClass(EventLead.class);
verify(eventLeadRepository).saveAndFlush(c.capture());
assertThat(c.getValue().getSource()).isEqualTo("QR");
}
@Test
void linkGuestDoesNotStealAnEventLeadAlreadyLinkedToAnotherGuest() {
EventGuest tokenGuest = new EventGuest();
tokenGuest.setId(5L);
when(guests.findById(5L)).thenReturn(Optional.of(tokenGuest));
when(guests.existsByEventLeadId(1L)).thenReturn(true);
new GuestLinker(guests).linkGuest(5L, leadWithId(1L));
assertThat(tokenGuest.getEventLeadId()).isNull();
}
private static EventLead leadWithId(long id) {
EventLead e = new EventLead();
e.setId(id);
return e;
}
}