feat(mobile-api): admin events API with salesperson teams

/api/admin/events list, get, create, update and salesperson-options, all behind
BO_EVENTS. Whole-day dates, uuid as a string, team ids checked before saving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-27 00:18:32 +08:00
1 parent 70e0651a75
commit 1fa7c60fee
8 files changed
+814 -2

No files matched your search

@@ -32,6 +32,12 @@ public class RestApiCounterServiceConstants {
public static final String API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_MEMBER_UUID="/counter/eventRedeemCode/findByMemberUuid/{memberUuid}";
public static final String API_REST_COUNTER_EVENT_FIND_BY_UUID="/counter/event/findByUuid/{uuid}";
//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_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}";
public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace";
//Event Product
public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}";
@@ -0,0 +1,56 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminEventRequest;
import com.solvway.mobile.api.service.AdminEventService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/** Admin events and their salesperson teams. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminEventController {
private final AdminEventService adminEventService;
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events")
public ResponseEntity<Map<String, Object>> list(@RequestParam(required = false) String q,
@RequestParam(required = false) String enabled,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String sortBy,
@RequestParam(required = false) String sortDir) {
return ResponseEntity.ok(adminEventService.list(q, enabled, page, size, sortBy, sortDir));
}
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events/salesperson-options")
public ResponseEntity<List<Map<String, Object>>> salespersonOptions() {
return ResponseEntity.ok(adminEventService.salespersonOptions());
}
@AppAuth
@AdminModule("BO_EVENTS")
@GetMapping("/events/{uuid}")
public ResponseEntity<Map<String, Object>> getByUuid(@PathVariable String uuid) {
return ResponseEntity.ok(adminEventService.get(uuid));
}
@AppAuth
@AdminModule("BO_EVENTS")
@PostMapping("/events")
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminEventRequest request) {
return ResponseEntity.ok(adminEventService.create(request));
}
@AppAuth
@AdminModule("BO_EVENTS")
@PutMapping("/events/{uuid}")
public ResponseEntity<Map<String, Object>> update(@PathVariable String uuid, @RequestBody AdminEventRequest request) {
return ResponseEntity.ok(adminEventService.update(uuid, request));
}
}
@@ -0,0 +1,9 @@
package com.solvway.mobile.api.dto.admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record AdminEventRequest(String name, String location, String startDate, String endDate, Boolean enabled, List<Long> salespersonIds) {}
@@ -0,0 +1,257 @@
package com.solvway.mobile.api.service;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.model.Event;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.admin.AdminEventRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
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 java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* Admin events for the portal. The event table lives in services-counter, users in services-system, so this
* validates, maps to and from the counter's Event, and resolves team members through services-system.
* Event uuids are Snowflake values beyond JavaScript's number precision, so they leave here as strings.
*/
@Service
@RequiredArgsConstructor
public class AdminEventService {
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 ParameterizedTypeReference<EventPage> PAGE = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<Event> EVENT = new ParameterizedTypeReference<>() {};
private static final Map<String, String> SORTS = Map.of("name", "name", "startDate", "dateStart", "endDate", "dateEnd");
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
/** The slice of a Spring Page this service reads. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record EventPage(List<Event> content, long totalElements, int totalPages, int number, int size) {}
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir) {
Map<String, Object> property = new LinkedHashMap<>();
property.put("name", q == null ? "" : q.trim());
property.put("enabled", "Y".equals(enabled) || "N".equals(enabled) ? enabled : "");
Map<String, Object> sort = Map.of("direction", "desc".equalsIgnoreCase(sortDir) ? "DESC" : "ASC",
"property", sortBy == null ? "name" : SORTS.getOrDefault(sortBy, "name"));
Map<String, Object> request = Map.of("property", property,
"pageableRest", Map.of("number", Math.max(page, 0), "size", Math.max(size, 1), "sorts", List.of(sort)));
EventPage p = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_PROPERTY_AND_PAGEABLE), PAGE, request).getBody();
if (p == null) return Map.of("content", List.of(), "totalElements", 0L, "totalPages", 0, "number", 0, "size", Math.max(size, 1));
return Map.of("content", p.content() == null ? List.of() : p.content().stream().map(AdminEventService::row).toList(), "totalElements", p.totalElements(),
"totalPages", p.totalPages(), "number", p.number(), "size", p.size());
}
public Map<String, Object> get(String uuid) {
Event event = load(uuid);
Map<String, Object> out = row(event);
List<Map<String, Object>> team = new ArrayList<>();
for (Long id : teamIds(event.getUuid())) {
Map<String, Object> user = user(id);
Map<String, Object> member = new LinkedHashMap<>();
member.put("id", id);
member.put("name", user == null ? null : user.get("name"));
member.put("username", user == null ? null : user.get("username"));
member.put("enabled", user != null && Boolean.TRUE.equals(user.get("enabled")));
team.add(member);
}
out.put("team", team);
return out;
}
public Map<String, Object> create(AdminEventRequest r) {
Fields f = validate(r);
User caller = caller();
List<Long> team = checkedTeam(r.salespersonIds());
Event event = new Event();
apply(event, f);
event.setCreateBy(caller.getUsername());
event.setDoneBy(caller.getUsername());
Event saved = save(event);
replaceTeam(saved.getUuid(), team, caller);
return row(saved);
}
public Map<String, Object> update(String uuid, AdminEventRequest r) {
Fields f = validate(r);
User caller = caller();
Event event = load(uuid);
List<Long> team = r.salespersonIds() == null ? null : checkedTeam(r.salespersonIds());
apply(event, f);
if (r.enabled() != null) event.setEnabled(r.enabled() ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N);
event.setDoneBy(caller.getUsername());
Event saved = save(event);
if (team != null) replaceTeam(saved.getUuid(), team, caller);
return row(saved);
}
public List<Map<String, Object>> salespersonOptions() {
Map<String, Object> request = Map.of("property", Map.of("type", "A"),
"pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id"))));
Map<String, Object> body = restTemplateUtil.postForEntity(
url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request).getBody();
List<Map<String, Object>> all = body == null || body.get("content") == null ? List.of() : (List<Map<String, Object>>) body.get("content");
// ponytail: loads all admins (staff-sized) like AdminUserService.list; not company-scoped yet.
return all.stream().filter(AdminEventService::isActiveAdmin)
.sorted(Comparator.comparing(m -> String.valueOf(m.get("name")).toLowerCase()))
.map(m -> {
Map<String, Object> o = new LinkedHashMap<>();
o.put("id", ((Number) m.get("id")).longValue());
o.put("name", m.get("name"));
o.put("username", m.get("username"));
return o;
}).toList();
}
private record Fields(String name, String location, LocalDate start, LocalDate end) {}
private static Fields validate(AdminEventRequest r) {
if (r == null) throw error(HttpStatus.BAD_REQUEST, "Name, location, start date and end date are required", "REQUIRED_FIELD", "name");
Map<String, String> in = new LinkedHashMap<>();
in.put("name", r.name());
in.put("location", r.location());
in.put("startDate", r.startDate());
in.put("endDate", r.endDate());
List<String> missing = in.entrySet().stream().filter(e -> !StringUtils.hasText(e.getValue())).map(Map.Entry::getKey).toList();
if (!missing.isEmpty()) {
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, "Required: " + String.join(", ", missing), "REQUIRED_FIELD", missing.get(0));
e.getBody().setProperty("fields", missing);
throw e;
}
String name = r.name().trim();
String location = r.location().trim();
if (name.length() > 100) throw error(HttpStatus.BAD_REQUEST, "Name is at most 100 characters", "TOO_LONG", "name");
if (location.length() > 200) throw error(HttpStatus.BAD_REQUEST, "Location is at most 200 characters", "TOO_LONG", "location");
LocalDate start = date(r.startDate(), "startDate");
LocalDate end = date(r.endDate(), "endDate");
if (end.isBefore(start)) throw error(HttpStatus.BAD_REQUEST, "End date is before the start date", "END_BEFORE_START", "endDate");
return new Fields(name, location, start, end);
}
private static LocalDate date(String s, String field) {
try {
return LocalDate.parse(s.trim());
} catch (DateTimeParseException e) {
throw error(HttpStatus.BAD_REQUEST, field + " must be a date as YYYY-MM-DD", "INVALID_DATE", field);
}
}
private static void apply(Event e, Fields f) {
e.setName(f.name());
e.setLocation(f.location());
e.setDateStart(f.start().atStartOfDay());
e.setDateEnd(LocalDateTime.of(f.end(), LocalTime.of(23, 59, 59)));
}
/** Duplicates collapse; every id must be an enabled admin user. One services-system lookup per id. */
private List<Long> checkedTeam(List<Long> ids) {
List<Long> team = ids == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(ids));
for (Long id : team) {
if (id == null || !isActiveAdmin(user(id))) {
throw error(HttpStatus.BAD_REQUEST, "Unknown or inactive admin user " + id, "UNKNOWN_USER", "salespersonIds");
}
}
return team;
}
private static boolean isActiveAdmin(Map<String, Object> user) {
return user != null && "A".equals(user.get("type")) && Boolean.TRUE.equals(user.get("enabled"));
}
private Map<String, Object> user(Long id) {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
}
private List<Long> teamIds(long eventUuid) {
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody();
return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList();
}
/** The event already exists when this fails, so the client gets the uuid to retry the team save on. */
private void replaceTeam(long eventUuid, List<Long> userIds, User caller) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("eventUuid", eventUuid);
body.put("companyId", caller.getCompanyId());
body.put("userIds", userIds);
body.put("doneBy", caller.getUsername());
try {
restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_REPLACE), MAP_LIST, body);
} catch (RuntimeException ex) {
CodedResponseStatusException e = error(HttpStatus.BAD_GATEWAY,
"Event " + eventUuid + " was saved but its team was not; save the team again", "TEAM_NOT_SAVED", null);
e.getBody().setProperty("eventUuid", String.valueOf(eventUuid));
throw e;
}
}
private Event load(String uuid) {
long id;
try {
id = Long.parseLong(uuid);
} catch (NumberFormatException e) {
throw notFound();
}
Event event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
if (event == null) throw notFound();
return event;
}
private Event save(Event event) {
Event saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SAVE), EVENT, event).getBody();
if (saved == null) throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Event could not be saved", "SAVE_FAILED", null);
return saved;
}
private static Map<String, Object> row(Event e) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("uuid", String.valueOf(e.getUuid()));
m.put("name", e.getName());
m.put("location", e.getLocation());
m.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
m.put("endDate", e.getDateEnd() == null ? null : e.getDateEnd().toLocalDate().toString());
m.put("enabled", e.getEnabled() == GeneralEnum.FlagYesNo.Y);
return m;
}
private User caller() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
return caller;
}
private String url(String api) {
return restTemplateUtil.getURLforApiService(api);
}
private static CodedResponseStatusException notFound() {
return error(HttpStatus.NOT_FOUND, "Event not found", "EVENT_NOT_FOUND", null);
}
/** field, when given, rides on the ProblemDetail body next to code, so the portal can mark the failing input. */
private static CodedResponseStatusException error(HttpStatus status, String reason, String code, String field) {
CodedResponseStatusException e = new CodedResponseStatusException(status, reason, code);
if (field != null) e.getBody().setProperty("field", field);
return e;
}
}