feat(mobile-api): GET /api/admin/dashboard/leads
BO_DASHBOARD-gated lead dashboard: Malaysian-month default period, at most 731 days, DAY or MONTH buckets, company scope, salesperson names. 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
a482a3a6d0
commit
7ff5c77b78
5 files changed
+355
No files matched your search
+1
@@ -44,6 +44,7 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search";
|
||||
public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{leadUuid}";
|
||||
public static final String API_REST_COUNTER_LEAD_UPDATE="/counter/lead/update";
|
||||
public static final String API_REST_COUNTER_DASHBOARD_LEADS="/counter/dashboard/leads";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{eventLeadUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminDashboardService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Lead dashboard. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/dashboard")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminDashboardController {
|
||||
private final AdminDashboardService adminDashboardService;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_DASHBOARD")
|
||||
@GetMapping("/leads")
|
||||
public ResponseEntity<Map<String, Object>> leads(@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminDashboardService.leads(from, to, companyId));
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
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.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
|
||||
/** Lead dashboard for the admin portal: validates the period and company scope here; services-counter aggregates. */
|
||||
@Service
|
||||
@SuppressWarnings("unchecked")
|
||||
public class AdminDashboardService {
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ZoneId KL = ZoneId.of("Asia/Kuala_Lumpur");
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AdminCompanyScope scope;
|
||||
private final Clock clock;
|
||||
|
||||
public AdminDashboardService(RestTemplateCustomUtil restTemplateUtil, AdminAuthenticationService adminAuthenticationService, AdminCompanyScope scope) {
|
||||
this(restTemplateUtil, adminAuthenticationService, scope, Clock.systemUTC());
|
||||
}
|
||||
|
||||
AdminDashboardService(RestTemplateCustomUtil restTemplateUtil, AdminAuthenticationService adminAuthenticationService, AdminCompanyScope scope, Clock clock) {
|
||||
this.restTemplateUtil = restTemplateUtil;
|
||||
this.adminAuthenticationService = adminAuthenticationService;
|
||||
this.scope = scope;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Map<String, Object> leads(String fromParam, String toParam, Long companyId) {
|
||||
Long company = scope.scope(caller(), companyId);
|
||||
LocalDate today = LocalDate.now(clock.withZone(KL));
|
||||
LocalDate from = date(fromParam, today.withDayOfMonth(1));
|
||||
LocalDate to = date(toParam, today);
|
||||
if (from.isAfter(to)) throw invalid("Start date must be on or before end date.");
|
||||
long days = ChronoUnit.DAYS.between(from, to) + 1;
|
||||
if (days > 731) throw invalid("The period can be at most 731 days.");
|
||||
String bucket = days <= 62 ? "DAY" : "MONTH";
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", company);
|
||||
body.put("from", from.toString());
|
||||
body.put("to", to.toString());
|
||||
body.put("bucket", bucket);
|
||||
Map<String, Object> res = restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_DASHBOARD_LEADS), MAP, body).getBody();
|
||||
|
||||
Map<String, Object> out = new LinkedHashMap<>(res == null ? Map.of() : res);
|
||||
out.put("from", from.toString());
|
||||
out.put("to", to.toString());
|
||||
out.put("bucket", bucket);
|
||||
Map<Long, Map<String, Object>> users = new HashMap<>();
|
||||
List<Map<String, Object>> rows = out.get("salespeople") == null ? List.of() : (List<Map<String, Object>>) out.get("salespeople");
|
||||
out.put("salespeople", rows.stream().map(r -> {
|
||||
Map<String, Object> m = new LinkedHashMap<>(r);
|
||||
m.put("name", r.get("userId") instanceof Number n ? name(n.longValue(), users) : null);
|
||||
return m;
|
||||
}).toList());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** User name, or null when the user no longer exists; one lookup per distinct id per request. */
|
||||
private String name(long id, Map<Long, Map<String, Object>> users) {
|
||||
if (!users.containsKey(id)) { // computeIfAbsent would not cache a missing user
|
||||
users.put(id, restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody());
|
||||
}
|
||||
Map<String, Object> u = users.get(id);
|
||||
return u == null || u.get("name") == null ? null : String.valueOf(u.get("name"));
|
||||
}
|
||||
|
||||
private static LocalDate date(String s, LocalDate dflt) {
|
||||
if (s == null || s.isBlank()) return dflt;
|
||||
try {
|
||||
return LocalDate.parse(s.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw invalid("Dates must be yyyy-MM-dd.");
|
||||
}
|
||||
}
|
||||
|
||||
private static RuntimeException invalid(String message) {
|
||||
return error(HttpStatus.BAD_REQUEST, message, "INVALID_PERIOD", null);
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminDashboardService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class AdminDashboardControllerTest {
|
||||
|
||||
@Test
|
||||
void leadsNeedsBoDashboard() throws Exception {
|
||||
Method m = AdminDashboardController.class.getDeclaredMethod("leads", String.class, String.class, Long.class);
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue();
|
||||
assertThat(m.getAnnotation(AdminModule.class).value()).containsExactly("BO_DASHBOARD");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesParams() throws Exception {
|
||||
AdminDashboardService s = mock(AdminDashboardService.class);
|
||||
when(s.leads("2026-11-01", "2026-11-30", 2L)).thenReturn(Map.of("bucket", "DAY"));
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminDashboardController(s)).build();
|
||||
mvc.perform(get("/api/admin/dashboard/leads").param("from", "2026-11-01").param("to", "2026-11-30").param("companyId", "2"))
|
||||
.andExpect(status().isOk()).andExpect(content().json("{\"bucket\":\"DAY\"}"));
|
||||
}
|
||||
}
|
||||
+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.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 java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
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.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminDashboardServiceTest {
|
||||
|
||||
private static final String LEADS = "/counter/dashboard/leads";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminDashboardService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private Map<String, Object> answer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminDashboardService(rest, auth, new AdminCompanyScope(), Clock.fixed(Instant.parse("2026-11-30T17:00:00Z"), ZoneOffset.UTC));
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
answer = new HashMap<>();
|
||||
answer.put("captures", 10);
|
||||
answer.put("salespeople", List.of());
|
||||
when(rest.postForEntity(eq(LEADS), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(answer));
|
||||
caller(null, true);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void caller(Long companyId, boolean superAdmin) {
|
||||
User u = new User();
|
||||
u.setId(21L);
|
||||
u.setUsername("boss");
|
||||
u.setCompanyId(companyId);
|
||||
if (superAdmin) {
|
||||
Role r = new Role("Super");
|
||||
r.setId(1L);
|
||||
u.setRoles(List.of(r));
|
||||
}
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
private Map<String, Object> sentBody() {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(LEADS), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
private void assertInvalidPeriod(String from, String to) {
|
||||
assertThatThrownBy(() -> service.leads(from, to, null)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("INVALID_PERIOD");
|
||||
});
|
||||
verify(rest, never()).postForEntity(eq(LEADS), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsToMalaysianMonthToToday() {
|
||||
Map<String, Object> r = service.leads(null, null, null);
|
||||
assertThat(r).containsEntry("from", "2026-12-01").containsEntry("to", "2026-12-01").containsEntry("bucket", "DAY");
|
||||
assertThat(sentBody()).containsEntry("from", "2026-12-01").containsEntry("to", "2026-12-01");
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsTheMissingEnd() {
|
||||
assertThat(service.leads("2026-11-20", null, null)).containsEntry("from", "2026-11-20").containsEntry("to", "2026-12-01");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bucketIsDayUpTo62DaysThenMonth() {
|
||||
assertThat(service.leads("2026-01-01", "2026-03-03", null)).containsEntry("bucket", "DAY");
|
||||
assertThat(service.leads("2026-01-01", "2026-03-04", null)).containsEntry("bucket", "MONTH");
|
||||
}
|
||||
|
||||
@Test
|
||||
void badDateIsInvalidPeriod() {
|
||||
assertInvalidPeriod("11/01/2026", "2026-11-30");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fromAfterToIsInvalidPeriod() {
|
||||
assertInvalidPeriod("2026-11-30", "2026-11-01");
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffIsPinnedToOwnCompany() {
|
||||
caller(5L, false);
|
||||
service.leads("2026-11-01", "2026-11-30", 9L);
|
||||
assertThat(sentBody()).containsEntry("companyId", 5L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminPassesRequestedCompanyOrNull() {
|
||||
service.leads("2026-11-01", "2026-11-30", 2L);
|
||||
assertThat(sentBody()).containsEntry("companyId", 2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdminWithoutCompanySendsNull() {
|
||||
service.leads("2026-11-01", "2026-11-30", null);
|
||||
assertThat(sentBody()).containsEntry("companyId", null).containsEntry("bucket", "DAY").containsEntry("to", "2026-11-30");
|
||||
}
|
||||
|
||||
@Test
|
||||
void salespeopleGetNamesOneLookupPerUser() {
|
||||
answer.put("salespeople", List.of(
|
||||
Map.of("userId", 7, "assigned", 4), Map.of("userId", 7, "assigned", 1), Map.of("userId", 8, "assigned", 2),
|
||||
new HashMap<>(Map.of("assigned", 3))));
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(7L))).thenReturn(ResponseEntity.ok(Map.of("name", "Aisyah")));
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(8L))).thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
List<Map<String, Object>> rows = (List<Map<String, Object>>) service.leads(null, null, null).get("salespeople");
|
||||
|
||||
assertThat(rows.get(0)).containsEntry("name", "Aisyah").containsEntry("assigned", 4);
|
||||
assertThat(rows.get(1)).containsEntry("name", "Aisyah");
|
||||
assertThat(rows.get(2)).containsEntry("name", null);
|
||||
assertThat(rows.get(3)).containsEntry("name", null);
|
||||
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(7L));
|
||||
verify(rest, times(2)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), any(Long.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void periodOf731DaysIsAccepted() {
|
||||
assertThat(service.leads("2025-01-01", "2027-01-01", null)).containsEntry("bucket", "MONTH");
|
||||
}
|
||||
|
||||
@Test
|
||||
void periodOf732DaysIsRefused() {
|
||||
assertInvalidPeriod("2025-01-01", "2027-01-02");
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendedYearDateIsInvalidPeriod() {
|
||||
assertInvalidPeriod("2026-11-01", "+999999999-12-31");
|
||||
assertInvalidPeriod("-999999999-01-01", "2026-11-01");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingUserIsLookedUpOnce() {
|
||||
answer.put("salespeople", List.of(Map.of("userId", 8, "assigned", 2), Map.of("userId", 8, "assigned", 1)));
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(8L))).thenReturn(ResponseEntity.ok(null));
|
||||
service.leads(null, null, null);
|
||||
verify(rest, times(1)).getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(8L));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user