fix: issues found in the invitations live check

- guest list failed when no guest was linked yet (Map.of().get(null))
- counter errors arrive as ProblemDetail: read the reason code from detail;
  drop the counter error advice the core handler always overrode
- emails published with a null sender failed the NOT NULL column

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:27:22 +08:00
1 parent aed9473aba
commit fbbc5d0980
10 files changed
+115 -87

No files matched your search

@@ -278,7 +278,9 @@ public class AdminEventService {
private static String counterField(HttpClientErrorException e, String field, String fallback) {
try {
String v = new ObjectMapper().readTree(e.getResponseBodyAsString()).path(field).asText();
// The counter's core error handler sends a ProblemDetail whose "detail" is the reason code.
com.fasterxml.jackson.databind.JsonNode body = new ObjectMapper().readTree(e.getResponseBodyAsString());
String v = body.path(field).asText("code".equals(field) ? body.path("detail").asText() : "");
return v.isEmpty() ? fallback : v;
} catch (Exception ex) {
return fallback;
@@ -184,7 +184,9 @@ public class PublicInviteService {
private static String counterCode(HttpClientErrorException e) {
try {
String v = new ObjectMapper().readTree(e.getResponseBodyAsString()).path("code").asText();
// The counter's core error handler sends a ProblemDetail whose "detail" is the reason code.
com.fasterxml.jackson.databind.JsonNode body = new ObjectMapper().readTree(e.getResponseBodyAsString());
String v = body.path("code").asText(body.path("detail").asText());
return v.isEmpty() ? "CONFLICT" : v;
} catch (Exception ex) {
return "CONFLICT";
@@ -146,6 +146,16 @@ class AdminEventServiceCapacityTest {
});
}
@Test
void update_capBelowGuests_fromTheCountersProblemDetailBody() {
grantGuestsModuleToRole(3L);
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null,
"{\"type\":\"about:blank\",\"title\":\"Conflict\",\"status\":409,\"detail\":\"CAP_BELOW_GUESTS\"}".getBytes(), null));
assertThatThrownBy(() -> service.update(String.valueOf(UUID), req(800, 1)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("CAP_BELOW_GUESTS"));
}
@Test
void update_failedModuleLookup_failsClosedAndKeepsLimits() {
when(rest.getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"))).thenThrow(new IllegalStateException("down"));
@@ -301,6 +301,18 @@ class PublicInviteServiceTest {
});
}
@Test
void inviteRegister_eventFull_fromTheCountersProblemDetailBody() {
// The counter's core handler renders ResponseStatusException as a ProblemDetail: the reason is in "detail".
when(rest.postForEntity(eq(GUEST_REGISTER), any(ParameterizedTypeReference.class), any())).thenThrow(
HttpClientErrorException.create(HttpStatus.CONFLICT, "c", null,
"{\"type\":\"about:blank\",\"title\":\"Conflict\",\"status\":409,\"detail\":\"EVENT_FULL\"}".getBytes(), null));
assertThatThrownBy(() -> service.inviteRegister(GT, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getReason()).isEqualTo("This event is full");
assertThat(e.getBody().getProperties()).containsEntry("code", "EVENT_FULL");
});
}
// --- invite check-in ---
@Test
@@ -1,18 +0,0 @@
package com.solvway.services.counter.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;
import java.util.Map;
/** Puts the reason of a ResponseStatusException into the body as `code`, which mobile-api reads. Limited to the invitation feature. */
@RestControllerAdvice(assignableTypes = {EventGuestController.class, EventCheckInController.class, EventController.class})
public class ApiErrorAdvice {
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<Map<String, String>> handle(ResponseStatusException e) {
String reason = e.getReason() == null ? "" : e.getReason();
return ResponseEntity.status(e.getStatusCode()).body(Map.of("code", reason, "message", reason));
}
}
@@ -78,7 +78,7 @@ public class EventGuestService {
List<Long> leadIds = guests.stream().map(EventGuest::getEventLeadId).filter(Objects::nonNull).toList();
Map<Long, EventLead> leads = leadIds.isEmpty() ? Map.of()
: eventLeadRepository.findAllById(leadIds).stream().collect(Collectors.toMap(EventLead::getId, l -> l));
return guests.stream().map(g -> row(g, leads.get(g.getEventLeadId()))).toList();
return guests.stream().map(g -> row(g, g.getEventLeadId() == null ? null : leads.get(g.getEventLeadId()))).toList();
}
private static GuestRow row(EventGuest g, EventLead lead) {
@@ -1,66 +0,0 @@
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,44 @@
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.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.Test;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Found live: a guest list where nobody has registered yet must list, not fail. */
class EventGuestListUnlinkedTest {
@Test
void listsGuestsWhenNoneIsLinkedYet() {
EventRepository events = mock(EventRepository.class);
EventGuestRepository guests = mock(EventGuestRepository.class);
EventGuestService service = new EventGuestService(events, guests, mock(EventLeadRepository.class),
mock(EventSalespersonRepository.class), mock(RegistrationService.class));
Event event = new Event();
event.setCompanyId(42L);
when(events.findByUuid(1000L)).thenReturn(Optional.of(event));
EventGuest g = new EventGuest();
g.setId(1L);
g.setCompanyId(42L);
g.setEventUuid(1000L);
g.setName("Tan Mei Ling");
g.setToken("t1");
when(guests.findByEventUuidOrderByNameAsc(1000L)).thenReturn(List.of(g));
List<EventGuestService.GuestRow> rows = service.list(new EventGuestService.ListRequest(42L, 1000L));
assertThat(rows).hasSize(1);
assertThat(rows.get(0).attended()).isFalse();
assertThat(rows.get(0).eventLeadUuid()).isNull();
}
}
@@ -36,6 +36,8 @@ public class EmailService {
}
@Transactional
public Email save(Email email) {
// A published email may carry "sender": null, which overrides the entity default; keep the column filled.
if (email.getSender() == null) email.setSender(com.solvway.services.email.constants.EmailConstant.EMAIL_SENDER);
return emailRepository.save(email);
}
@Transactional
@@ -0,0 +1,40 @@
package com.solvway.services.email.service;
import com.solvway.services.email.constants.EmailConstant;
import com.solvway.services.email.model.Email;
import com.solvway.services.email.repo.EmailRepository;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/** Found live: a published email whose JSON carries "sender": null overwrote the entity default and failed the NOT NULL column. */
@ExtendWith(MockitoExtension.class)
class EmailServiceSenderTest {
@Mock private EmailRepository emailRepository;
@InjectMocks private EmailService service;
@Test
void missingSenderGetsTheDefault() {
when(emailRepository.save(any(Email.class))).thenAnswer(i -> i.getArgument(0));
Email email = new Email();
email.setSender(null);
assertThat(service.save(email).getSender()).isEqualTo(EmailConstant.EMAIL_SENDER);
}
@Test
void givenSenderIsKept() {
when(emailRepository.save(any(Email.class))).thenAnswer(i -> i.getArgument(0));
Email email = new Email();
email.setSender("events@example.test");
assertThat(service.save(email).getSender()).isEqualTo("events@example.test");
}
}