feat: admin guest, invite email, check-in and attendance endpoints
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
4e938bb6a9
commit
87dfc48632
19 files changed
+1361
-7
No files matched your search
+6
@@ -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}";
|
||||
|
||||
+76
@@ -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<Map<String, Object>>> 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<Map<String, Object>> 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<Void> 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<Map<String, Object>> send(@PathVariable String uuid, @RequestBody AdminGuestSendRequest body) {
|
||||
return ResponseEntity.ok(guests.send(uuid, body));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENTS")
|
||||
@GetMapping("/checkin")
|
||||
public ResponseEntity<Map<String, Object>> checkin(@PathVariable String uuid) {
|
||||
return ResponseEntity.ok(guests.checkin(uuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENTS")
|
||||
@GetMapping("/attendance")
|
||||
public ResponseEntity<Map<String, Object>> attendance(@PathVariable String uuid) {
|
||||
return ResponseEntity.ok(guests.attendance(uuid));
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -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<Long> interestIds,
|
||||
String nextFollowUpDate, String notes) {}
|
||||
String nextFollowUpDate, String notes, Boolean attended) {
|
||||
public AdminEventLeadUpdateRequest(Long salespersonId, String temperature, String status, List<Long> interestIds,
|
||||
String nextFollowUpDate, String notes) {
|
||||
this(salespersonId, temperature, status, interestIds, nextFollowUpDate, notes, null);
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -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<Long> salespersonIds,
|
||||
Long companyId) {
|
||||
Long companyId, Integer capacity, Integer invitationCap) {
|
||||
public AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List<Long> 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<Long> salespersonIds) {
|
||||
this(name, location, startDate, endDate, enabled, salespersonIds, null);
|
||||
this(name, location, startDate, endDate, enabled, salespersonIds, null, null, null);
|
||||
}
|
||||
}
|
||||
+9
@@ -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<Long> guestIds, Boolean allUnsent) {}
|
||||
+12
@@ -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<Guest> guests) {
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record Guest(String name, String mobile, String email, String companyName, Long salespersonUserId) {}
|
||||
}
|
||||
@@ -9,4 +9,6 @@ import lombok.Setter;
|
||||
@Setter
|
||||
public class CompanyEvent extends Event {
|
||||
private Long companyId;
|
||||
private Integer capacity;
|
||||
private Integer invitationCap;
|
||||
}
|
||||
+272
@@ -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<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> 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<Map<String, Object>> list(String uuid) {
|
||||
CompanyEvent event = leads.loadEvent(uuid, null);
|
||||
boolean mayCopyLinks = AdminModuleAccess.holds(rest, leads.caller(), "BO_EVENT_GUESTS");
|
||||
Map<Long, Object> names = new HashMap<>();
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Map<String, Object> g : guests(event)) {
|
||||
Map<String, Object> 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<String, Object> user = leads.user(id);
|
||||
return user == null ? null : user.get("name");
|
||||
}));
|
||||
}
|
||||
out.add(row);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> guests(CompanyEvent event) {
|
||||
List<Map<String, Object>> 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<String, Object> 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<Map<String, Object>> valid = new ArrayList<>();
|
||||
List<Integer> validIndexes = new ArrayList<>();
|
||||
List<Map<String, Object>> 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<Object> added = new ArrayList<>(valid);
|
||||
if (!preview && !valid.isEmpty()) {
|
||||
Map<String, Object> body = eventBody(event);
|
||||
body.put("guests", valid);
|
||||
body.put("doneBy", leads.caller().getUsername());
|
||||
Map<String, Object> 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<Object>) result.get("added"));
|
||||
if (result != null && result.get("rejected") instanceof List<?> counterRejected) {
|
||||
for (Object o : counterRejected) {
|
||||
Map<String, Object> m = new LinkedHashMap<>((Map<String, Object>) 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<String, Object> 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<String, Object> 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<String, Object> 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<Long> wanted = allUnsent ? Set.of() : new HashSet<>(r.guestIds());
|
||||
List<Long> sentIds = new ArrayList<>();
|
||||
int skippedNoEmail = 0;
|
||||
try {
|
||||
for (Map<String, Object> 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<String, Object> 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<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("sent", sentIds.size());
|
||||
out.put("skippedNoEmail", skippedNoEmail);
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> checkin(String uuid) {
|
||||
return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_ENSURE_TOKEN), MAP,
|
||||
eventBody(leads.loadEvent(uuid, null))).getBody();
|
||||
}
|
||||
|
||||
public Map<String, Object> 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<String, Object> 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<Email> 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<String, Object> guest) {
|
||||
String name = esc(guest.get("name"));
|
||||
String link = esc(portalBase + "/i/" + guest.get("token"));
|
||||
String details = "<p><strong>" + esc(event.getName()) + "</strong><br>" + esc(date(event.getDateStart())) + " - "
|
||||
+ esc(date(event.getDateEnd())) + "<br>" + esc(event.getLocation()) + "</p>";
|
||||
return "<p>Dear " + name + ",</p><p>You are invited to our event.</p>" + details
|
||||
+ "<p>Please confirm your attendance: <a href=\"" + link + "\">" + link + "</a></p>"
|
||||
+ "<hr><p><i>Bahasa Malaysia</i></p><p>Tuan/Puan " + name + ",</p><p>Anda dijemput ke acara kami.</p>" + details
|
||||
+ "<p>Sila sahkan kehadiran anda: <a href=\"" + link + "\">" + link + "</a></p>";
|
||||
}
|
||||
|
||||
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<String, Object> 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<String, Object> 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<String, Object> rejection(int index, String code, String field, String message) {
|
||||
Map<String, Object> 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<String, Object> eventBody(CompanyEvent event) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", event.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
return body;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return rest.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+2
@@ -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<String, Object> saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody();
|
||||
// field names only: follow-up values are personal data
|
||||
@@ -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<>());
|
||||
}
|
||||
|
||||
+33
-1
@@ -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<String, Object> get(String uuid) {
|
||||
CompanyEvent event = load(uuid);
|
||||
Map<String, Object> out = row(event);
|
||||
out.put("capacity", event.getCapacity());
|
||||
out.put("invitationCap", event.getInvitationCap());
|
||||
List<Map<String, Object>> team = new ArrayList<>();
|
||||
for (Long id : teamIds(event.getUuid())) {
|
||||
Map<String, Object> user = user(id);
|
||||
@@ -103,6 +108,11 @@ public class AdminEventService {
|
||||
CompanyEvent event = load(uuid);
|
||||
List<Long> 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<Map<String, Object>> 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);
|
||||
|
||||
+22
-1
@@ -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<Long> 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<Long> roleIds, String... moduleNames) {
|
||||
if (moduleNames.length == 0) {
|
||||
@@ -24,7 +45,7 @@ public final class AdminModuleAccess {
|
||||
ResponseEntity<List<Map<String, Object>>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(MODULES_BY_AREA),
|
||||
new ParameterizedTypeReference<List<Map<String, Object>>>() {}, "BO");
|
||||
List<Map<String, Object>> modules = ent.getBody() != null ? ent.getBody() : List.of();
|
||||
List<Map<String, Object>> 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
|
||||
|
||||
@@ -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}
|
||||
@@ -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 <this>/i/<token>.
|
||||
admin-portal-base-url: ${ADMIN_PORTAL_BASE_URL}
|
||||
customer-portal-base-url: ${CUSTOMER_PORTAL_BASE_URL:https://user.tastefullyexpo.com}
|
||||
system:
|
||||
format:
|
||||
|
||||
+41
@@ -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<PropertySource<?>> 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);
|
||||
}
|
||||
}
|
||||
+116
@@ -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<Method> 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<AdminGuestsRequest> 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<AdminGuestSendRequest> c = ArgumentCaptor.forClass(AdminGuestSendRequest.class);
|
||||
verify(guests).send(eq("77"), c.capture());
|
||||
assertThat(c.getValue().allUnsent()).isTrue();
|
||||
}
|
||||
}
|
||||
+444
@@ -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<HttpReqRespUtils> 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 <b>&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<String, Object> 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<String, Object>... guests) {
|
||||
when(rest.postForEntity(eq(LIST), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(guests)));
|
||||
}
|
||||
|
||||
private static Map<String, Object> guest(long id, String name, String email, int sentCount) {
|
||||
Map<String, Object> 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<String, Object> sent(String api) {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(api), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) 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<Map<String, Object>> 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<String, Object> out = service.add(String.valueOf(EV), r, false);
|
||||
|
||||
Map<String, Object> body = sent(ADD);
|
||||
assertThat(body).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("doneBy", "boss");
|
||||
List<Map<String, Object>> guests = (List<Map<String, Object>>) 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<Map<String, Object>> rejected = (List<Map<String, Object>>) 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<String, Object> 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<String, Object> out = service.add(String.valueOf(EV), r, false);
|
||||
|
||||
List<Map<String, Object>> rejected = (List<Map<String, Object>>) 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<String, Object> out = service.add(String.valueOf(EV), r, true);
|
||||
|
||||
assertNothingSent(ADD);
|
||||
assertThat((List<?>) out.get("added")).hasSize(1);
|
||||
assertThat((List<Map<String, Object>>) out.get("rejected")).extracting(m -> m.get("index")).containsExactly(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void add_allInvalid_skipsTheCounterCall() {
|
||||
Map<String, Object> 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 <script>", "amy@x.co", 0), guest(2, "Bob", "bob@x.co", 1), guest(3, "Cat", "cat@x.co", 0));
|
||||
|
||||
Map<String, Object> out = service.send(String.valueOf(EV), new AdminGuestSendRequest(List.of(1L, 3L), null));
|
||||
|
||||
ArgumentCaptor<Email> c = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emails, times(2)).send(c.capture());
|
||||
Email first = c.getAllValues().get(0);
|
||||
assertThat(first.getCompanyId()).isEqualTo(COMPANY);
|
||||
assertThat(first.getRecipients()).extracting(r -> r.getRecipient()).containsExactly("amy@x.co");
|
||||
String body = first.getBody();
|
||||
assertThat(body).contains("https://portal.test/i/tok1").contains("Fair <b>&Co").contains("Amy <script>")
|
||||
.contains("MITEC "Hall"").contains("2027-01-15").contains("2027-01-17");
|
||||
assertThat(body).doesNotContain("<script>").doesNotContain("<b>");
|
||||
assertThat(body.indexOf("Bahasa Malaysia")).isGreaterThan(0);
|
||||
assertThat(body.indexOf("You are invited")).isLessThan(body.indexOf("Bahasa Malaysia"));
|
||||
assertThat(c.getAllValues().get(1).getBody()).contains("https://portal.test/i/tok3");
|
||||
assertThat(out).containsEntry("sent", 2).containsEntry("skippedNoEmail", 0);
|
||||
assertThat(sent(MARK_SENT)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("guestIds", List.of(1L, 3L))
|
||||
.containsEntry("doneBy", "boss");
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_allUnsent_skipsAlreadySentAndGuestsWithoutEmail() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0), guest(2, "Bob", "bob@x.co", 2), guest(3, "Cat", null, 0), guest(4, "Dan", " ", 0));
|
||||
|
||||
Map<String, Object> out = service.send(String.valueOf(EV), new AdminGuestSendRequest(null, true));
|
||||
|
||||
verify(emails, times(1)).send(any());
|
||||
assertThat(out).containsEntry("sent", 1).containsEntry("skippedNoEmail", 2);
|
||||
assertThat(sent(MARK_SENT)).containsEntry("guestIds", List.of(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_failedEmailIsNotCountedNorMarked() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0), guest(2, "Bob", "bob@x.co", 0));
|
||||
org.mockito.Mockito.doReturn(Optional.empty()).doAnswer(i -> Optional.of(i.getArgument(0))).when(emails).send(any());
|
||||
|
||||
Map<String, Object> out = service.send(String.valueOf(EV), new AdminGuestSendRequest(null, true));
|
||||
|
||||
assertThat(out).containsEntry("sent", 1);
|
||||
assertThat(sent(MARK_SENT)).containsEntry("guestIds", List.of(2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_nothingSent_doesNotCallMarkSent() {
|
||||
stubGuests(guest(1, "Amy", null, 0));
|
||||
Map<String, Object> out = service.send(String.valueOf(EV), new AdminGuestSendRequest(null, true));
|
||||
assertThat(out).containsEntry("sent", 0).containsEntry("skippedNoEmail", 1);
|
||||
assertNothingSent(MARK_SENT);
|
||||
verify(emails, never()).send(any());
|
||||
}
|
||||
|
||||
// --- checkin and attendance ---
|
||||
|
||||
@Test
|
||||
void checkin_returnsTheEnsuredToken() {
|
||||
when(rest.postForEntity(eq(ENSURE_TOKEN), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("token", "abc")));
|
||||
assertThat(service.checkin(String.valueOf(EV))).isEqualTo(Map.of("token", "abc"));
|
||||
assertThat(sent(ENSURE_TOKEN)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV);
|
||||
}
|
||||
|
||||
@Test
|
||||
void attendance_returnsTheCounterNumbers() {
|
||||
Map<String, Object> n = new LinkedHashMap<>(Map.of("invited", 5, "registered", 3, "attended", 2, "walkIns", 1, "total", 3));
|
||||
when(rest.postForEntity(eq(ATTENDANCE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(n));
|
||||
assertThat(service.attendance(String.valueOf(EV))).isEqualTo(n);
|
||||
assertThat(sent(ATTENDANCE)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV);
|
||||
}
|
||||
|
||||
// --- review fixes ---
|
||||
|
||||
@Test
|
||||
void list_withoutGuestsModule_stripsTokens_withModule_keepsThem() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0));
|
||||
grantGuestsModule(false);
|
||||
assertThat(service.list(String.valueOf(EV)).get(0)).doesNotContainKey("token").containsEntry("name", "Amy");
|
||||
grantGuestsModule(true);
|
||||
assertThat(service.list(String.valueOf(EV)).get(0)).containsEntry("token", "tok1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_superAdminKeepsTokens_failedModuleLookupStripsThem() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0));
|
||||
Role superRole = new Role();
|
||||
superRole.setId(1L);
|
||||
caller.setCompanyId(null);
|
||||
caller.setRoles(List.of(superRole));
|
||||
assertThat(service.list(String.valueOf(EV)).get(0)).containsEntry("token", "tok1");
|
||||
grantGuestsModule(true);
|
||||
when(rest.getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"))).thenThrow(new IllegalStateException("down"));
|
||||
caller.setCompanyId(COMPANY);
|
||||
assertThat(service.list(String.valueOf(EV)).get(0)).doesNotContainKey("token");
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_readsTokensEvenWhenTheCallerHasNoModuleAndSkipsSalespersonLookup() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0));
|
||||
grantGuestsModule(false);
|
||||
service.send(String.valueOf(EV), new AdminGuestSendRequest(List.of(1L), null));
|
||||
ArgumentCaptor<Email> c = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emails).send(c.capture());
|
||||
assertThat(c.getValue().getBody()).contains("/i/tok1");
|
||||
verify(rest, never()).getForEntity(eq(USER), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, times(1)).getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV));
|
||||
}
|
||||
|
||||
@Test
|
||||
void add_companyNameOver150IsRejectedPerLine() {
|
||||
Map<String, Object> out = service.add(String.valueOf(EV), new AdminGuestsRequest(List.of(
|
||||
new AdminGuestsRequest.Guest("Amy", "0[login redacted]789", null, "C".repeat(151), 21L),
|
||||
new AdminGuestsRequest.Guest("Bob", "0129876543", null, "C".repeat(150), 21L))), true);
|
||||
List<Map<String, Object>> rejected = (List<Map<String, Object>>) out.get("rejected");
|
||||
assertThat(rejected).hasSize(1);
|
||||
assertThat(rejected.get(0)).containsEntry("index", 0).containsEntry("field", "companyName").containsEntry("code", "TOO_LONG");
|
||||
assertThat((List<?>) out.get("added")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void add_noMobileNoEmail_namesBothFieldsLikeStaffCapture() {
|
||||
Map<String, Object> out = service.add(String.valueOf(EV), new AdminGuestsRequest(List.of(line("Bob", null, null))), true);
|
||||
Map<String, Object> r = ((List<Map<String, Object>>) out.get("rejected")).get(0);
|
||||
assertThat(r).containsEntry("field", "mobile").containsEntry("code", "REQUIRED_FIELD");
|
||||
assertThat((String) r.get("message")).contains("mobile").contains("email");
|
||||
}
|
||||
|
||||
@Test
|
||||
void add_counterRejectionIndexOutsideTheRequestIsIgnored() {
|
||||
Map<String, Object> bad = Map.of("index", 7, "code", "DUPLICATE", "field", "mobile", "message", "x");
|
||||
Map<String, Object> neg = Map.of("index", -1, "code", "DUPLICATE", "field", "mobile", "message", "x");
|
||||
when(rest.postForEntity(eq(ADD), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("added", List.of(Map.of("id", 1)), "rejected", List.of(bad, neg))));
|
||||
Map<String, Object> out = service.add(String.valueOf(EV), new AdminGuestsRequest(List.of(line("Amy", "0129876543", null))), false);
|
||||
assertThat((List<?>) out.get("rejected")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_oneFailingGuestDoesNotStopTheOthersAndAllQueuedAreMarked() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0), guest(2, "Bob", "bob@x.co", 0), guest(3, "Cat", "cat@x.co", 0));
|
||||
org.mockito.Mockito.doAnswer(i -> Optional.of(i.getArgument(0))).doThrow(new IllegalStateException("smtp down"))
|
||||
.doAnswer(i -> Optional.of(i.getArgument(0))).when(emails).send(any());
|
||||
Map<String, Object> out = service.send(String.valueOf(EV), new AdminGuestSendRequest(null, true));
|
||||
assertThat(out).containsEntry("sent", 2);
|
||||
assertThat(sent(MARK_SENT)).containsEntry("guestIds", List.of(1L, 3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_eventWithoutDatesStillSends() {
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0));
|
||||
CompanyEvent e = new CompanyEvent();
|
||||
e.setCompanyId(COMPANY);
|
||||
e.setUuid(EV);
|
||||
e.setName("Open");
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
assertThat(service.send(String.valueOf(EV), new AdminGuestSendRequest(null, true))).containsEntry("sent", 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdmin_addAndSendUseTheEventsCompany() {
|
||||
Role superRole = new Role();
|
||||
superRole.setId(1L);
|
||||
caller.setCompanyId(null);
|
||||
caller.setRoles(List.of(superRole));
|
||||
stubEvent(8L);
|
||||
stubGuests(guest(1, "Amy", "amy@x.co", 0));
|
||||
when(rest.postForEntity(eq(ADD), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("added", List.of(Map.of("id", 1)), "rejected", List.of())));
|
||||
service.add(String.valueOf(EV), new AdminGuestsRequest(List.of(line("Amy", "0129876543", null))), false);
|
||||
assertThat(sent(ADD)).containsEntry("companyId", 8L);
|
||||
service.send(String.valueOf(EV), new AdminGuestSendRequest(null, true));
|
||||
assertThat(sent(MARK_SENT)).containsEntry("companyId", 8L);
|
||||
ArgumentCaptor<Email> c = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emails).send(c.capture());
|
||||
assertThat(c.getValue().getCompanyId()).isEqualTo(8L);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/** Spring must be able to build the guest service from its beans and the ADMIN_PORTAL_BASE_URL property, or mobile-api fails to start. */
|
||||
class AdminEventGuestServiceWiringTest {
|
||||
|
||||
@Test
|
||||
void springCreatesTheService() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("t", Map.of("app.admin-portal-base-url", "http://portal.test")));
|
||||
ctx.registerBean(RestTemplateCustomUtil.class, () -> mock(RestTemplateCustomUtil.class));
|
||||
ctx.registerBean(AdminAuthenticationService.class, () -> mock(AdminAuthenticationService.class));
|
||||
ctx.registerBean(EmailService.class, () -> mock(EmailService.class));
|
||||
ctx.registerBean(AdminCompanyScope.class);
|
||||
ctx.register(AdminEventLeadService.class);
|
||||
ctx.register(AdminEventGuestService.class);
|
||||
ctx.refresh();
|
||||
assertThat(ctx.getBean(AdminEventGuestService.class)).isNotNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.CompanyEvent;
|
||||
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.ResponseEntity;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
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.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadAttendedTest {
|
||||
|
||||
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String FIND = "/counter/eventLead/findByUuid/{eventLeadUuid}";
|
||||
private static final String UPDATE = "/counter/eventLead/update";
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long EL = 3312853897594494976L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(rest, auth, new AdminCompanyScope());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
CompanyEvent e = new CompanyEvent();
|
||||
e.setCompanyId(5L);
|
||||
e.setUuid(EV);
|
||||
e.setName("Fair");
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
when(rest.getForEntity(eq(INTERESTS), any(ParameterizedTypeReference.class), eq(5L))).thenReturn(ResponseEntity.ok(List.of()));
|
||||
Map<String, Object> stored = new LinkedHashMap<>();
|
||||
stored.put("eventLeadUuid", EL);
|
||||
stored.put("companyId", 5L);
|
||||
stored.put("eventUuid", EV);
|
||||
stored.put("name", "Aisyah");
|
||||
stored.put("status", "OPEN");
|
||||
stored.put("interestIds", List.of());
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(EL))).thenReturn(ResponseEntity.ok(stored));
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private Map<String, Object> updateBody() {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_passesAttendedToTheCounter() {
|
||||
service.update(String.valueOf(EV), String.valueOf(EL),
|
||||
new AdminEventLeadUpdateRequest(null, null, null, List.of(), null, null, true));
|
||||
assertThat(updateBody()).containsEntry("attended", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_withoutAttendedSendsNull() {
|
||||
service.update(String.valueOf(EV), String.valueOf(EL),
|
||||
new AdminEventLeadUpdateRequest(null, null, null, List.of(), null, null));
|
||||
assertThat(updateBody()).containsEntry("attended", null);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
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.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.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.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventServiceCapacityTest {
|
||||
|
||||
private static final String BY_UUID = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String SAVE = "/counter/event/save";
|
||||
private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
private static final String MODULES = "/module/findAllByArea/{area}";
|
||||
private static final long UUID = 7123456789012345678L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventService service;
|
||||
private User caller;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventService(rest, auth, new AdminCompanyScope());
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
caller = new User();
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(5L);
|
||||
Role staff = new Role();
|
||||
staff.setId(3L);
|
||||
caller.setRoles(List.of(staff));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of()));
|
||||
CompanyEvent e = new CompanyEvent();
|
||||
e.setCompanyId(5L);
|
||||
e.setUuid(UUID);
|
||||
e.setName("Old");
|
||||
e.setLocation("Old place");
|
||||
e.setDateStart(LocalDateTime.of(2026, 5, 1, 0, 0));
|
||||
e.setDateEnd(LocalDateTime.of(2026, 5, 2, 23, 59, 59));
|
||||
e.setCapacity(500);
|
||||
e.setInvitationCap(40);
|
||||
when(rest.getForEntity(eq(BY_UUID), any(ParameterizedTypeReference.class), eq(UUID))).thenReturn(ResponseEntity.ok(e));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void grantGuestsModuleToRole(long roleId) {
|
||||
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", roleId))))));
|
||||
}
|
||||
|
||||
private static AdminEventRequest req(Integer capacity, Integer cap) {
|
||||
return new AdminEventRequest("New", "Hall", "2026-06-01", "2026-06-02", null, null, null, capacity, cap);
|
||||
}
|
||||
|
||||
private CompanyEvent saved() {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (CompanyEvent) c.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_showsCapacityAndInvitationCap() {
|
||||
assertThat(service.get(String.valueOf(UUID))).containsEntry("capacity", 500).containsEntry("invitationCap", 40);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_withGuestsModule_savesCapacityAndInvitationCap() {
|
||||
grantGuestsModuleToRole(3L);
|
||||
service.update(String.valueOf(UUID), req(800, 60));
|
||||
assertThat(saved().getCapacity()).isEqualTo(800);
|
||||
assertThat(saved().getInvitationCap()).isEqualTo(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_withGuestsModule_nullClearsTheLimits() {
|
||||
grantGuestsModuleToRole(3L);
|
||||
service.update(String.valueOf(UUID), req(null, null));
|
||||
assertThat(saved().getCapacity()).isNull();
|
||||
assertThat(saved().getInvitationCap()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_withoutGuestsModule_keepsExistingLimits() {
|
||||
grantGuestsModuleToRole(99L);
|
||||
service.update(String.valueOf(UUID), req(800, 60));
|
||||
assertThat(saved().getCapacity()).isEqualTo(500);
|
||||
assertThat(saved().getInvitationCap()).isEqualTo(40);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_withGuestsModule_rejectsLimitsBelowOne() {
|
||||
grantGuestsModuleToRole(3L);
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(UUID), req(0, 5)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", "capacity");
|
||||
});
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(UUID), req(5, -1)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e ->
|
||||
assertThat((Map<String, Object>) e.getBody().getProperties().get("details")).containsEntry("field", "invitationCap"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_counterCapBelowGuests_isPassedThroughAsConflict() {
|
||||
grantGuestsModuleToRole(3L);
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null, "{\"code\":\"CAP_BELOW_GUESTS\"}".getBytes(), null));
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(UUID), req(800, 1)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
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"));
|
||||
service.update(String.valueOf(UUID), req(800, 60));
|
||||
assertThat(saved().getCapacity()).isEqualTo(500);
|
||||
assertThat(saved().getInvitationCap()).isEqualTo(40);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_superAdminMaySetLimitsWithoutAModuleLookup() {
|
||||
Role superRole = new Role();
|
||||
superRole.setId(1L);
|
||||
caller.setCompanyId(null);
|
||||
caller.setRoles(List.of(superRole));
|
||||
service.update(String.valueOf(UUID), req(800, 60));
|
||||
assertThat(saved().getCapacity()).isEqualTo(800);
|
||||
assertThat(saved().getInvitationCap()).isEqualTo(60);
|
||||
verify(rest, org.mockito.Mockito.never()).getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_otherCounterConflictKeepsItsOwnCodeAndMessage() {
|
||||
grantGuestsModuleToRole(3L);
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", null,
|
||||
"{\"code\":\"NAME_TAKEN\",\"message\":\"Name taken\"}".getBytes(), null));
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(UUID), req(800, 60)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getCode()).isEqualTo("NAME_TAKEN");
|
||||
assertThat(e.getReason()).isEqualTo("Name taken");
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user