diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index ea6123d..57617ef 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -35,6 +35,12 @@ public class RestApiCounterServiceConstants { //Event admin public static final String API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE="/counter/event/findByPropertyAndPageable"; public static final String API_REST_COUNTER_EVENT_SAVE="/counter/event/save"; + public static final String API_REST_COUNTER_EVENT_GUEST_LIST = "/counter/eventGuest/list"; + public static final String API_REST_COUNTER_EVENT_GUEST_ADD = "/counter/eventGuest/add"; + public static final String API_REST_COUNTER_EVENT_GUEST_REMOVE = "/counter/eventGuest/remove"; + public static final String API_REST_COUNTER_EVENT_GUEST_MARK_SENT = "/counter/eventGuest/markSent"; + public static final String API_REST_COUNTER_CHECKIN_ENSURE_TOKEN = "/counter/checkin/ensureToken"; + public static final String API_REST_COUNTER_EVENT_ATTENDANCE = "/counter/event/attendance"; public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}"; public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace"; public static final String API_REST_COUNTER_INTEREST_FIND_BY_COMPANY="/counter/interest/findByCompany/{companyId}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java new file mode 100644 index 0000000..94dab5c --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminEventGuestController.java @@ -0,0 +1,76 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.service.AdminEventGuestService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Event invitations: guest list, send, check-in token and attendance. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin/events/{uuid}") +@RequiredArgsConstructor +public class AdminEventGuestController { + private final AdminEventGuestService guests; + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/guests") + public ResponseEntity>> list(@PathVariable String uuid) { + return ResponseEntity.ok(guests.list(uuid)); + } + + @AppAuth + @AdminModule(value = "BO_EVENT_GUESTS", also = "BO_EVENTS") + @Audited(targetVariable = "uuid") + @PostMapping("/guests") + public ResponseEntity> add(@PathVariable String uuid, @RequestBody AdminGuestsRequest body, + @RequestParam(defaultValue = "false") boolean preview) { + return ResponseEntity.ok(guests.add(uuid, body, preview)); + } + + @AppAuth + @AdminModule(value = "BO_EVENT_GUESTS", also = "BO_EVENTS") + @Audited(targetVariable = "uuid") + @DeleteMapping("/guests/{guestId}") + public ResponseEntity remove(@PathVariable String uuid, @PathVariable String guestId) { + guests.remove(uuid, guestId); + return ResponseEntity.noContent().build(); + } + + @AppAuth + @AdminModule(value = "BO_EVENT_GUESTS", also = "BO_EVENTS") + @Audited(targetVariable = "uuid") + @PostMapping("/guests/send") + public ResponseEntity> send(@PathVariable String uuid, @RequestBody AdminGuestSendRequest body) { + return ResponseEntity.ok(guests.send(uuid, body)); + } + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/checkin") + public ResponseEntity> checkin(@PathVariable String uuid) { + return ResponseEntity.ok(guests.checkin(uuid)); + } + + @AppAuth + @AdminModule("BO_EVENTS") + @GetMapping("/attendance") + public ResponseEntity> attendance(@PathVariable String uuid) { + return ResponseEntity.ok(guests.attendance(uuid)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java index 42b5a9e..e76833f 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventLeadUpdateRequest.java @@ -2,6 +2,11 @@ package com.solvway.mobile.api.dto.admin; import java.util.List; -/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. */ +/** An event lead's working fields. nextFollowUpDate is YYYY-MM-DD; null clears it. attended null leaves the flag alone. */ public record AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List interestIds, - String nextFollowUpDate, String notes) {} + String nextFollowUpDate, String notes, Boolean attended) { + public AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List interestIds, + String nextFollowUpDate, String notes) { + this(salespersonId, temperature, status, interestIds, nextFollowUpDate, notes, null); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java index d971af9..a9fe2c9 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminEventRequest.java @@ -6,12 +6,17 @@ import java.util.List; /** * Create/update body. Dates are kept as text so a malformed date answers INVALID_DATE, not a bind error. enabled is update-only. - * companyId is read on create only, and only from a super admin; staff get their own company and an edit never moves an event. + * capacity and invitationCap (null = no limit) are read only from a caller holding BO_EVENT_GUESTS. companyId is read on create only, and only from a super admin; staff get their own company and an edit never moves an event. */ @JsonIgnoreProperties(ignoreUnknown = true) public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds, - Long companyId) { + Long companyId, Integer capacity, Integer invitationCap) { + public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds, + Long companyId) { + this(name, location, startDate, endDate, enabled, salespersonIds, companyId, null, null); + } + public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List salespersonIds) { - this(name, location, startDate, endDate, enabled, salespersonIds, null); + this(name, location, startDate, endDate, enabled, salespersonIds, null, null, null); } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java new file mode 100644 index 0000000..08d4183 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestSendRequest.java @@ -0,0 +1,9 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** Which guests to email: the listed ids, or every guest not yet sent when allUnsent is true. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminGuestSendRequest(List guestIds, Boolean allUnsent) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java new file mode 100644 index 0000000..2fc6920 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGuestsRequest.java @@ -0,0 +1,12 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** Guests to invite to an event: one line for a single add, many for a paste. Same shape either way. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminGuestsRequest(List guests) { + @JsonIgnoreProperties(ignoreUnknown = true) + public record Guest(String name, String mobile, String email, String companyName, Long salespersonUserId) {} +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java index d189e20..162afde 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/CompanyEvent.java @@ -9,4 +9,6 @@ import lombok.Setter; @Setter public class CompanyEvent extends Event { private Long companyId; + private Integer capacity; + private Integer invitationCap; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java new file mode 100644 index 0000000..374d3ca --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventGuestService.java @@ -0,0 +1,272 @@ +package com.solvway.mobile.api.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.core.enums.EmailEnum; +import com.solvway.core.model.Email; +import com.solvway.core.model.Recipient; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminModuleAccess; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.util.HtmlUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Invited-guest list of an event for the admin portal. Validates and normalises at this boundary; services-counter stores. + * Every operation resolves the event through AdminEventLeadService.loadEvent, so another company's event is a 404. + * Never log a guest's name, mobile or email. + */ +@Service +@Slf4j +@SuppressWarnings("unchecked") +public class AdminEventGuestService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final RestTemplateCustomUtil rest; + private final AdminEventLeadService leads; + private final EmailService emailService; + private final String portalBase; + + public AdminEventGuestService(RestTemplateCustomUtil rest, AdminEventLeadService leads, EmailService emailService, @Value("${app.admin-portal-base-url}") String portalBase) { + this.rest = rest; + this.leads = leads; + this.emailService = emailService; + this.portalBase = portalBase.replaceAll("/+$", ""); + log.info("Admin portal base URL for invitation links: {}", this.portalBase); + } + + public List> list(String uuid) { + CompanyEvent event = leads.loadEvent(uuid, null); + boolean mayCopyLinks = AdminModuleAccess.holds(rest, leads.caller(), "BO_EVENT_GUESTS"); + Map names = new HashMap<>(); + List> out = new ArrayList<>(); + for (Map g : guests(event)) { + Map row = new LinkedHashMap<>(g); + // Only the guest-list module may copy invitation links, so the token stays with it. + if (!mayCopyLinks) row.remove("token"); + if (g.get("salespersonUserId") instanceof Number n) { + row.put("salespersonName", names.computeIfAbsent(n.longValue(), id -> { + Map user = leads.user(id); + return user == null ? null : user.get("name"); + })); + } + out.add(row); + } + return out; + } + + private List> guests(CompanyEvent event) { + List> guests = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_LIST), MAP_LIST, + eventBody(event)).getBody(); + return guests == null ? List.of() : guests; + } + + /** Valid lines go to the counter (unless previewing); rejections of both kinds come back with the line's original index. */ + public Map add(String uuid, AdminGuestsRequest r, boolean preview) { + CompanyEvent event = leads.loadEvent(uuid, null); + if (r == null || r.guests() == null || r.guests().isEmpty()) throw AdminEventLeadService.required(List.of("guests")); + List> valid = new ArrayList<>(); + List validIndexes = new ArrayList<>(); + List> rejected = new ArrayList<>(); + for (int i = 0; i < r.guests().size(); i++) { + try { + valid.add(normalise(r.guests().get(i))); + validIndexes.add(i); + } catch (CodedResponseStatusException e) { + rejected.add(rejection(i, e.getCode(), field(e), e.getReason())); + } + } + List added = new ArrayList<>(valid); + if (!preview && !valid.isEmpty()) { + Map body = eventBody(event); + body.put("guests", valid); + body.put("doneBy", leads.caller().getUsername()); + Map result; + try { + result = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_ADD), MAP, body).getBody(); + } catch (HttpClientErrorException.NotFound e) { + throw AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null); + } + added = result == null || result.get("added") == null ? new ArrayList<>() : new ArrayList<>((List) result.get("added")); + if (result != null && result.get("rejected") instanceof List counterRejected) { + for (Object o : counterRejected) { + Map m = new LinkedHashMap<>((Map) o); + int at = m.get("index") instanceof Number n ? n.intValue() : -1; + if (at < 0 || at >= validIndexes.size()) { + log.warn("Counter rejected a guest line outside the request for event {}", event.getUuid()); + continue; + } + m.put("index", validIndexes.get(at)); + rejected.add(m); + } + } + } + rejected.sort(Comparator.comparingInt(m -> (Integer) m.get("index"))); + Map out = new LinkedHashMap<>(); + out.put("added", added); + out.put("rejected", rejected); + return out; + } + + public void remove(String uuid, String guestId) { + CompanyEvent event = leads.loadEvent(uuid, null); + Map body = eventBody(event); + body.put("guestId", AdminEventLeadService.parseOr(guestId, + () -> AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Guest not found", "GUEST_NOT_FOUND", null))); + body.put("doneBy", leads.caller().getUsername()); + try { + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_REMOVE), MAP, body); + } catch (HttpClientErrorException.Conflict e) { + throw AdminEventLeadService.error(HttpStatus.CONFLICT, "Guest has registered and cannot be removed", "GUEST_REGISTERED", null); + } catch (HttpClientErrorException.NotFound e) { + throw AdminEventLeadService.error(HttpStatus.NOT_FOUND, "Guest not found", "GUEST_NOT_FOUND", null); + } + } + + /** One email per guest, English then Bahasa Malaysia. Only guests whose email was accepted are marked as sent. */ + public Map send(String uuid, AdminGuestSendRequest r) { + CompanyEvent event = leads.loadEvent(uuid, null); + boolean allUnsent = r != null && Boolean.TRUE.equals(r.allUnsent()); + if (!allUnsent && (r == null || r.guestIds() == null || r.guestIds().isEmpty())) { + throw AdminEventLeadService.required(List.of("guestIds")); + } + Set wanted = allUnsent ? Set.of() : new HashSet<>(r.guestIds()); + List sentIds = new ArrayList<>(); + int skippedNoEmail = 0; + try { + for (Map g : guests(event)) { + long id = ((Number) g.get("id")).longValue(); + boolean selected = allUnsent ? !(g.get("inviteSentCount") instanceof Number n && n.intValue() > 0) : wanted.contains(id); + if (!selected) continue; + String to = AdminEventLeadService.trimmed(AdminEventLeadService.str(g.get("email"))); + if (to == null) { + skippedNoEmail++; + continue; + } + if (deliver(event, g, to)) sentIds.add(id); + } + } finally { + // Whatever was queued is marked, even if a later guest blew up, so a retry does not email them twice. + if (!sentIds.isEmpty()) { + Map body = eventBody(event); + body.put("guestIds", sentIds); + body.put("doneBy", leads.caller().getUsername()); + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_MARK_SENT), MAP, body); + } + } + Map out = new LinkedHashMap<>(); + out.put("sent", sentIds.size()); + out.put("skippedNoEmail", skippedNoEmail); + return out; + } + + public Map checkin(String uuid) { + return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_ENSURE_TOKEN), MAP, + eventBody(leads.loadEvent(uuid, null))).getBody(); + } + + public Map attendance(String uuid) { + return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_ATTENDANCE), MAP, + eventBody(leads.loadEvent(uuid, null))).getBody(); + } + + // --- helpers --- + + private boolean deliver(CompanyEvent event, Map guest, String to) { + try { + Email email = new Email(); + email.setCompanyId(event.getCompanyId()); + email.setSubject("You are invited / Anda dijemput: " + event.getName()); + email.setBody(invitationBody(event, guest)); + email.setStatus(EmailEnum.StatusType.P); + email.setRecipients(List.of(new Recipient(null, to, EmailEnum.RecipientType.R, EmailEnum.RecipientStatusType.Y))); + Optional sent = emailService.send(email); + return sent != null && sent.isPresent(); + } catch (RuntimeException e) { + log.error("Invitation email failed for event {}: {}", event.getUuid(), e.getMessage()); + return false; + } + } + + private String invitationBody(CompanyEvent event, Map guest) { + String name = esc(guest.get("name")); + String link = esc(portalBase + "/i/" + guest.get("token")); + String details = "

" + esc(event.getName()) + "
" + esc(date(event.getDateStart())) + " - " + + esc(date(event.getDateEnd())) + "
" + esc(event.getLocation()) + "

"; + return "

Dear " + name + ",

You are invited to our event.

" + details + + "

Please confirm your attendance: " + link + "

" + + "

Bahasa Malaysia

Tuan/Puan " + name + ",

Anda dijemput ke acara kami.

" + details + + "

Sila sahkan kehadiran anda: " + link + "

"; + } + + private static Object date(java.time.LocalDateTime d) { + return d == null ? null : d.toLocalDate(); + } + + private static String esc(Object value) { + return HtmlUtils.htmlEscape(String.valueOf(value == null ? "" : value)); + } + + /** Trims, normalises mobile to E.164 and email to lower case; throws the coded error of the first problem found. */ + private static Map normalise(AdminGuestsRequest.Guest g) { + String name = AdminEventLeadService.trimmed(g == null ? null : g.name()); + if (name == null) throw AdminEventLeadService.required(List.of("name")); + AdminEventLeadService.maxLength("name", name, 100); + String mobile = AdminEventLeadService.trimmed(g.mobile()); + String email = AdminEventLeadService.trimmed(g.email()); + if (mobile == null && email == null) throw AdminEventLeadService.required(List.of("mobile", "email")); + String companyName = AdminEventLeadService.maxLength("companyName", AdminEventLeadService.trimmed(g.companyName()), 150); + Map m = new LinkedHashMap<>(); + m.put("name", name); + m.put("mobileE164", mobile == null ? null : AdminEventLeadService.mobile(mobile)); + m.put("email", email == null ? null : AdminEventLeadService.maxLength("email", AdminEventLeadService.email(email), 254)); + m.put("companyName", companyName); + m.put("salespersonUserId", g.salespersonUserId()); + return m; + } + + private static Map rejection(int index, String code, String field, String message) { + Map m = new LinkedHashMap<>(); + m.put("index", index); + m.put("code", code); + m.put("field", field); + m.put("message", message); + return m; + } + + private static String field(CodedResponseStatusException e) { + return e.getBody().getProperties() != null && e.getBody().getProperties().get("details") instanceof Map d + ? AdminEventLeadService.str(d.get("field")) : null; + } + + private Map eventBody(CompanyEvent event) { + Map body = new LinkedHashMap<>(); + body.put("companyId", event.getCompanyId()); + body.put("eventUuid", event.getUuid()); + return body; + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index 36ffdc7..fcd6a11 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -267,6 +267,7 @@ public class AdminEventLeadService { body.put("interestIds", interestIds); body.put("nextFollowUpDate", followUp == null ? null : followUp.toString()); body.put("notes", trimmed(r.notes())); + body.put("attended", r.attended()); body.put("doneBy", caller.getUsername()); Map saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(); // field names only: follow-up values are personal data @@ -277,6 +278,7 @@ public class AdminEventLeadService { if (!new HashSet<>(interestIds).equals(new HashSet<>(longs(current.get("interestIds"))))) changed.add("interestIds"); if (!Objects.equals(body.get("nextFollowUpDate"), current.get("nextFollowUpDate") == null ? null : current.get("nextFollowUpDate").toString())) changed.add("nextFollowUpDate"); if (!Objects.equals(body.get("notes"), current.get("notes"))) changed.add("notes"); + if (r.attended() != null && !r.attended().equals(current.get("attended"))) changed.add("attended"); if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new)); return view(saved, known, new HashMap<>()); } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java index 93ab79f..2b34443 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventService.java @@ -1,6 +1,7 @@ package com.solvway.mobile.api.service; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.ObjectMapper; import com.solvway.core.enums.GeneralEnum; import com.solvway.core.model.User; import com.solvway.core.utils.HttpReqRespUtils; @@ -10,12 +11,14 @@ import com.solvway.mobile.api.dto.admin.AdminEventRequest; import com.solvway.mobile.api.dto.admin.CompanyEvent; import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.useraccess.AdminModuleAccess; import com.solvway.mobile.api.util.RestTemplateCustomUtil; import lombok.RequiredArgsConstructor; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; import java.time.LocalDate; import java.time.LocalDateTime; @@ -68,6 +71,8 @@ public class AdminEventService { public Map get(String uuid) { CompanyEvent event = load(uuid); Map out = row(event); + out.put("capacity", event.getCapacity()); + out.put("invitationCap", event.getInvitationCap()); List> team = new ArrayList<>(); for (Long id : teamIds(event.getUuid())) { Map user = user(id); @@ -103,6 +108,11 @@ public class AdminEventService { CompanyEvent event = load(uuid); List team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds(), teamIds(event.getUuid()), event.getCompanyId()); apply(event, f); + // Capacity and invitation cap belong to the guest-list module; other editors leave them as they are. + if (AdminModuleAccess.holds(restTemplateUtil, caller, "BO_EVENT_GUESTS")) { + event.setCapacity(positiveOrNull(r.capacity(), "capacity")); + event.setInvitationCap(positiveOrNull(r.invitationCap(), "invitationCap")); + } if (r.enabled() != null) event.setEnabled(r.enabled() ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N); event.setDoneBy(caller.getUsername()); CompanyEvent saved = save(event); @@ -110,6 +120,11 @@ public class AdminEventService { return row(saved); } + private static Integer positiveOrNull(Integer value, String field) { + if (value != null && value < 1) throw error(HttpStatus.BAD_REQUEST, field + " must be at least 1", "INVALID_LIMIT", field); + return value; + } + /** Active admins of the chosen company; a super admin who has not chosen one is offered nobody. */ public List> salespersonOptions(Long companyId) { Long company = scope.scope(caller(), companyId); @@ -236,7 +251,15 @@ public class AdminEventService { } private CompanyEvent save(CompanyEvent event) { - CompanyEvent saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody(); + CompanyEvent saved; + try { + saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody(); + } catch (HttpClientErrorException.Conflict e) { + // The counter refuses a cap below the guests already on the list (CAP_BELOW_GUESTS). + String code = counterField(e, "code", "CONFLICT"); + throw error(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS".equals(code) ? "Limit is below the guests already invited" + : counterField(e, "message", "Event could not be saved"), code, null); + } if (saved == null) throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Event could not be saved", "SAVE_FAILED", null); return saved; } @@ -253,6 +276,15 @@ public class AdminEventService { return m; } + private static String counterField(HttpClientErrorException e, String field, String fallback) { + try { + String v = new ObjectMapper().readTree(e.getResponseBodyAsString()).path(field).asText(); + return v.isEmpty() ? fallback : v; + } catch (Exception ex) { + return fallback; + } + } + private User caller() { User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java index a0729f1..3a18149 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java @@ -1,20 +1,41 @@ package com.solvway.mobile.api.useraccess; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.extern.slf4j.Slf4j; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.ResponseEntity; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.stream.Collectors; +@Slf4j public final class AdminModuleAccess { private static final String MODULES_BY_AREA = "/module/findAllByArea/{area}"; + private static final long INJECTED_ROLE_ADMIN_ID = 2L; // services-auth adds ROLE_ADMIN to every admin; never a module grant + private AdminModuleAccess() { } + /** True for a super admin or a caller whose roles hold the module. A failing lookup fails closed (false, logged). */ + public static boolean holds(RestTemplateCustomUtil restTemplateUtil, User caller, String module) { + if (AdminCompanyScope.isSuper(caller)) return true; + Set roleIds = caller.getRoles() == null ? Set.of() : caller.getRoles().stream() + .map(Role::getId).filter(id -> Objects.nonNull(id) && id != INJECTED_ROLE_ADMIN_ID).collect(Collectors.toSet()); + try { + return grantedAny(restTemplateUtil, roleIds, module); + } catch (RuntimeException e) { + log.error("Admin module lookup for {} failed, treating as not granted: {}", module, e.getClass().getSimpleName()); + return false; + } + } + /** True when one of {@code roleIds} is granted any of the named BO modules. */ public static boolean grantedAny(RestTemplateCustomUtil restTemplateUtil, Set roleIds, String... moduleNames) { if (moduleNames.length == 0) { @@ -24,7 +45,7 @@ public final class AdminModuleAccess { ResponseEntity>> ent = restTemplateUtil.getForEntity( restTemplateUtil.getURLforApiService(MODULES_BY_AREA), new ParameterizedTypeReference>>() {}, "BO"); - List> modules = ent.getBody() != null ? ent.getBody() : List.of(); + List> modules = ent != null && ent.getBody() != null ? ent.getBody() : List.of(); return modules.stream() .filter(m -> m.get("name") instanceof String name && wanted.contains(name)) // services-system writes a role already seen in this response as its bare id diff --git a/solvway-mobile-api/src/main/resources/application-local.yml b/solvway-mobile-api/src/main/resources/application-local.yml index ea3d07a..9a5ffff 100644 --- a/solvway-mobile-api/src/main/resources/application-local.yml +++ b/solvway-mobile-api/src/main/resources/application-local.yml @@ -5,3 +5,5 @@ spring: project-id: co-lite-local pubsub: emulator-host: pubsub:8085 +app: + admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL:http://localhost:3001} diff --git a/solvway-mobile-api/src/main/resources/application.yml b/solvway-mobile-api/src/main/resources/application.yml index ddc6f57..6175bb5 100644 --- a/solvway-mobile-api/src/main/resources/application.yml +++ b/solvway-mobile-api/src/main/resources/application.yml @@ -2,6 +2,8 @@ app: api-key: ${APIKEY:} api-gateway-url: ${APIGATEWAYURL} # TODO: confirm real customer-portal host + # Required outside the local profile (no default): invitation emails link to /i/. + admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL} customer-portal-base-url: ${CUSTOMER_PORTAL_BASE_URL:https://user.tastefullyexpo.com} system: format: diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java new file mode 100644 index 0000000..4124d54 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/config/AdminPortalBaseUrlSettingTest.java @@ -0,0 +1,41 @@ +package com.solvway.mobile.api.config; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** ADMIN_PORTAL_BASE_URL has a default in the local profile only. */ +class AdminPortalBaseUrlSettingTest { + + private static StandardEnvironment env(String... files) throws IOException { + StandardEnvironment env = new StandardEnvironment(); + MutablePropertySources sources = env.getPropertySources(); + for (String f : files) { + List> loaded = new YamlPropertySourceLoader().load(f, new ClassPathResource(f)); + // later files override earlier ones, as an active profile does + loaded.forEach(sources::addFirst); + } + return env; + } + + @Test + void localProfileDefaultsToLocalhost3001() throws IOException { + assertThat(env("application.yml", "application-local.yml").resolveRequiredPlaceholders("${app.admin-portal-base-url}")) + .isEqualTo("http://localhost:3001"); + } + + @Test + void otherProfilesHaveNoDefault() throws IOException { + StandardEnvironment env = env("application.yml"); + assertThatThrownBy(() -> env.resolveRequiredPlaceholders("${app.admin-portal-base-url}")).isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java new file mode 100644 index 0000000..3323968 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminEventGuestControllerTest.java @@ -0,0 +1,116 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.service.AdminEventGuestService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +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.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminEventGuestControllerTest { + + @Mock private AdminEventGuestService guests; + @InjectMocks private AdminEventGuestController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + private static List handlers() { + return Arrays.stream(AdminEventGuestController.class.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers()) && !m.isSynthetic()).toList(); + } + + @Test + void readsAreGuardedByBoEventsAndWritesByBoEventGuests() { + assertThat(handlers()).hasSize(6); + for (Method m : handlers()) { + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + String expected = Arrays.asList("list", "checkin", "attendance").contains(m.getName()) ? "BO_EVENTS" : "BO_EVENT_GUESTS"; + AdminModule module = m.getAnnotation(AdminModule.class); + assertThat(Arrays.asList(module.value())).as(m.getName()).containsExactly(expected); + // writes are a sub-module: they need BO_EVENTS too, like the other event sub-modules + assertThat(Arrays.asList(module.also())).as(m.getName() + " also").isEqualTo(expected.equals("BO_EVENTS") ? List.of() : List.of("BO_EVENTS")); + } + } + + @Test + void everyGuestWriteIsAuditedAgainstTheEventUuid() { + for (Method m : handlers()) { + if (Arrays.asList("list", "checkin", "attendance").contains(m.getName())) continue; + Audited a = m.getAnnotation(Audited.class); + assertThat(a).as(m.getName() + " @Audited").isNotNull(); + assertThat(a.targetVariable()).as(m.getName()).isEqualTo("uuid"); + } + } + + @Test + void list_checkin_attendance() throws Exception { + when(guests.list("77")).thenReturn(List.of(Map.of("id", 1))); + when(guests.checkin("77")).thenReturn(Map.of("token", "abc")); + when(guests.attendance("77")).thenReturn(Map.of("invited", 3)); + mvc.perform(get("/api/admin/events/77/guests")).andExpect(status().isOk()).andExpect(content().json("[{\"id\":1}]")); + mvc.perform(get("/api/admin/events/77/checkin")).andExpect(status().isOk()).andExpect(content().json("{\"token\":\"abc\"}")); + mvc.perform(get("/api/admin/events/77/attendance")).andExpect(status().isOk()).andExpect(content().json("{\"invited\":3}")); + } + + @Test + void add_bindsBodyAndPreviewFlag() throws Exception { + when(guests.add(eq("77"), any(), eq(true))).thenReturn(Map.of("added", List.of(), "rejected", List.of())); + String body = "{\"guests\":[{\"name\":\"Amy\",\"mobile\":\"0123456789\",\"email\":\"a@b.co\",\"companyName\":\"Acme\",\"salespersonUserId\":4,\"extra\":1}]}"; + mvc.perform(post("/api/admin/events/77/guests").param("preview", "true").contentType(MediaType.APPLICATION_JSON).content(body)) + .andExpect(status().isOk()); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminGuestsRequest.class); + verify(guests).add(eq("77"), c.capture(), eq(true)); + assertThat(c.getValue().guests()).containsExactly(new AdminGuestsRequest.Guest("Amy", "0123456789", "a@b.co", "Acme", 4L)); + } + + @Test + void add_previewDefaultsToFalse() throws Exception { + when(guests.add(eq("77"), any(), eq(false))).thenReturn(Map.of()); + mvc.perform(post("/api/admin/events/77/guests").contentType(MediaType.APPLICATION_JSON).content("{\"guests\":[]}")).andExpect(status().isOk()); + verify(guests).add(eq("77"), any(), eq(false)); + } + + @Test + void remove_returnsNoContent_andSend_bindsBody() throws Exception { + mvc.perform(delete("/api/admin/events/77/guests/9")).andExpect(status().isNoContent()); + verify(guests).remove("77", "9"); + when(guests.send(eq("77"), any())).thenReturn(Map.of("sent", 2, "skippedNoEmail", 1)); + mvc.perform(post("/api/admin/events/77/guests/send").contentType(MediaType.APPLICATION_JSON).content("{\"allUnsent\":true}")) + .andExpect(status().isOk()).andExpect(content().json("{\"sent\":2,\"skippedNoEmail\":1}")); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminGuestSendRequest.class); + verify(guests).send(eq("77"), c.capture()); + assertThat(c.getValue().allUnsent()).isTrue(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java new file mode 100644 index 0000000..f29fa6d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventGuestServiceTest.java @@ -0,0 +1,444 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Email; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminGuestSendRequest; +import com.solvway.mobile.api.dto.admin.AdminGuestsRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminEventGuestServiceTest { + + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String USER = "/user/findById/{id}"; + private static final String LIST = "/counter/eventGuest/list"; + private static final String ADD = "/counter/eventGuest/add"; + private static final String REMOVE = "/counter/eventGuest/remove"; + private static final String MARK_SENT = "/counter/eventGuest/markSent"; + private static final String ENSURE_TOKEN = "/counter/checkin/ensureToken"; + private static final String ATTENDANCE = "/counter/event/attendance"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 5L; + + private RestTemplateCustomUtil rest; + private EmailService emails; + private AdminAuthenticationService auth; + private AdminEventGuestService service; + private MockedStatic http; + private User caller; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + emails = mock(EmailService.class); + auth = mock(AdminAuthenticationService.class); + AdminCompanyScope scope = new AdminCompanyScope(); + service = new AdminEventGuestService(rest, new AdminEventLeadService(rest, auth, scope), emails, "https://portal.test/"); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + caller = new User(); + caller.setId(21L); + caller.setUsername("boss"); + caller.setCompanyId(COMPANY); + when(auth.loadUserByToken("tok")).thenReturn(caller); + stubEvent(COMPANY); + stubUser(21L, "Sales One"); + when(emails.send(any())).thenAnswer(i -> Optional.of(i.getArgument(0))); + grantGuestsModule(true); + } + + private static final String MODULES = "/module/findAllByArea/{area}"; + + private void grantGuestsModule(boolean granted) { + Role staff = new Role(); + staff.setId(3L); + caller.setRoles(List.of(staff)); + when(rest.getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of(Map.of("name", "BO_EVENT_GUESTS", "roles", List.of(Map.of("id", granted ? 3L : 99L)))))); + } + + @AfterEach + void close() { http.close(); } + + private void stubEvent(long company) { + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(company); + e.setUuid(EV); + e.setName("Fair &Co"); + e.setLocation("MITEC \"Hall\""); + e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0)); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e)); + } + + private void stubUser(long id, String name) { + Map u = new HashMap<>(); + u.put("id", id); + u.put("name", name); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u)); + } + + private void stubGuests(Map... guests) { + when(rest.postForEntity(eq(LIST), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(guests))); + } + + private static Map guest(long id, String name, String email, int sentCount) { + Map g = new LinkedHashMap<>(); + g.put("id", id); + g.put("name", name); + g.put("email", email); + g.put("token", "tok" + id); + g.put("inviteSentCount", sentCount); + g.put("salespersonUserId", 21L); + return g; + } + + private Map sent(String api) { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + private void assertNothingSent(String api) { + verify(rest, never()).postForEntity(eq(api), any(ParameterizedTypeReference.class), any()); + } + + private static AdminGuestsRequest.Guest line(String name, String mobile, String email) { + return new AdminGuestsRequest.Guest(name, mobile, email, "Acme", 21L); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + // --- scope --- + + @Test + void anotherCompanysEventIsNotFoundOnEveryOperation() { + stubEvent(99L); + AdminGuestsRequest one = new AdminGuestsRequest(List.of(line("Amy", "0123456789", null))); + String ev = String.valueOf(EV); + assertCoded(() -> service.list(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.add(ev, one, false), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.remove(ev, "1"), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.send(ev, new AdminGuestSendRequest(null, true)), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.checkin(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertCoded(() -> service.attendance(ev), HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"); + assertNothingSent(LIST); + assertNothingSent(ADD); + assertNothingSent(REMOVE); + assertNothingSent(ENSURE_TOKEN); + assertNothingSent(ATTENDANCE); + } + + // --- list --- + + @Test + void list_resolvesSalespersonName() { + stubGuests(guest(1, "Amy", "amy@x.co", 0)); + List> out = service.list(String.valueOf(EV)); + assertThat(out).hasSize(1); + assertThat(out.get(0)).containsEntry("name", "Amy").containsEntry("salespersonName", "Sales One"); + assertThat(sent(LIST)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV); + } + + // --- add --- + + @Test + void add_normalisesValidLinesAndRejectsInvalidOnesWithFieldAndIndex() { + when(rest.postForEntity(eq(ADD), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("added", List.of(Map.of("id", 1)), "rejected", List.of()))); + AdminGuestsRequest r = new AdminGuestsRequest(List.of( + line(" Amy ", "0123456789", " Amy@X.co "), + line(" ", "0123456789", null), + line("Bob", null, null), + line("Cat", "12345", null), + line("Dan", null, "dan@"), + line("E".repeat(101), "0123456789", null))); + + Map out = service.add(String.valueOf(EV), r, false); + + Map body = sent(ADD); + assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("doneBy", "boss"); + List> guests = (List>) body.get("guests"); + assertThat(guests).hasSize(1); + assertThat(guests.get(0)).containsEntry("name", "Amy").containsEntry("mobileE164", "+60123456789") + .containsEntry("email", "amy@x.co").containsEntry("companyName", "Acme").containsEntry("salespersonUserId", 21L); + List> rejected = (List>) out.get("rejected"); + assertThat(rejected).extracting(m -> m.get("index")).containsExactly(1, 2, 3, 4, 5); + assertThat(rejected).extracting(m -> m.get("field")).containsExactly("name", "mobile", "mobile", "email", "name"); + assertThat(rejected).extracting(m -> m.get("code")).containsExactly("REQUIRED_FIELD", "REQUIRED_FIELD", "INVALID_MOBILE", "INVALID_EMAIL", "TOO_LONG"); + assertThat(rejected).allSatisfy(m -> assertThat(m.get("message")).isNotNull()); + assertThat((List) out.get("added")).hasSize(1); + } + + @Test + void add_mergesCounterRejectionsKeepingOriginalIndexes() { + Map counterReject = Map.of("index", 1, "code", "DUPLICATE", "field", "mobile", "message", "already invited"); + when(rest.postForEntity(eq(ADD), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("added", List.of(Map.of("id", 1)), "rejected", List.of(counterReject)))); + // original indexes: 0 valid, 1 invalid (no name), 2 valid (counter sees it as index 1), 3 invalid + AdminGuestsRequest r = new AdminGuestsRequest(List.of( + line("Amy", "0123456789", null), line("", "0123456789", null), line("Bob", "0129876543", null), line("Cat", "x", null))); + + Map out = service.add(String.valueOf(EV), r, false); + + List> rejected = (List>) out.get("rejected"); + assertThat(rejected).extracting(m -> m.get("index")).containsExactly(1, 2, 3); + assertThat(rejected.get(1)).containsEntry("code", "DUPLICATE").containsEntry("field", "mobile"); + } + + @Test + void add_preview_validatesOnlyAndSavesNothing() { + AdminGuestsRequest r = new AdminGuestsRequest(List.of(line("Amy", "0123456789", null), line("", null, null))); + + Map out = service.add(String.valueOf(EV), r, true); + + assertNothingSent(ADD); + assertThat((List) out.get("added")).hasSize(1); + assertThat((List>) out.get("rejected")).extracting(m -> m.get("index")).containsExactly(1); + } + + @Test + void add_allInvalid_skipsTheCounterCall() { + Map out = service.add(String.valueOf(EV), new AdminGuestsRequest(List.of(line("", null, null))), false); + assertNothingSent(ADD); + assertThat((List) out.get("rejected")).hasSize(1); + } + + @Test + void add_emptyList_isBadRequest() { + assertCoded(() -> service.add(String.valueOf(EV), new AdminGuestsRequest(List.of()), false), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + } + + // --- remove --- + + @Test + void remove_registeredGuestIsConflict() { + when(rest.postForEntity(eq(REMOVE), any(ParameterizedTypeReference.class), any())) + .thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, null, null)); + assertCoded(() -> service.remove(String.valueOf(EV), "9"), HttpStatus.CONFLICT, "GUEST_REGISTERED"); + } + + @Test + void remove_sendsCompanyEventGuestAndUser() { + service.remove(String.valueOf(EV), "9"); + assertThat(sent(REMOVE)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("guestId", 9L).containsEntry("doneBy", "boss"); + } + + // --- send --- + + @Test + void send_buildsOneBilingualEscapedEmailPerGuestAndMarksOnlyThoseSent() { + stubGuests(guest(1, "Amy