feat(counter): event lead status history and lead dashboard endpoint

Capture and status edits append to event_lead_status_change. POST
/counter/dashboard/leads aggregates captures, wins, overdue follow-ups
and the breakdowns for a Malaysian-day period (at most 731 days).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 10:21:36 +08:00
1 parent 8d5f3747bf
commit a482a3a6d0
15 files changed
+745 -3

No files matched your search

@@ -0,0 +1,170 @@
package com.solvway.services.counter.dashboard;
import com.solvway.services.counter.dto.LeadDashboardRequest.Bucket;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Capture;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Overdue;
import com.solvway.services.counter.dashboard.LeadDashboardCalculator.Win;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class LeadDashboardCalculatorTest {
private static final ZoneId UTC = ZoneId.of("UTC");
private static final LocalDate FROM = LocalDate.of(2026, 11, 1);
private static final LocalDate TO = LocalDate.of(2026, 11, 30);
private static final LocalDateTime T = LocalDateTime.of(2026, 11, 10, 2, 0);
private static Capture cap(long id, long ev, String evName, Long sp, String type, String status, LocalDateTime at) {
return new Capture(id, ev, evName, 2L, sp, type, status, at);
}
private static LeadDashboardResponse calc(Bucket b, List<Capture> c, List<Win> w, List<Overdue> o,
Map<Long, List<Long>> li, Map<Long, String> names) {
return LeadDashboardCalculator.calculate(FROM, TO, b, UTC, c, w, o, li, names);
}
private static LeadDashboardResponse calc(List<Capture> c, List<Win> w, List<Overdue> o) {
return calc(Bucket.DAY, c, w, o, Map.of(), Map.of());
}
@Test
void countsCapturesNewLeadsAndFunnelWithAllKeysInOrder() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", 7L, "NEW", "OPEN", T), cap(2, 10, "A", 7L, "EXISTING", "WON", T),
cap(3, 10, "A", 7L, "NEW", "OPEN", T)), List.of(), List.of());
assertThat(r.captures()).isEqualTo(3);
assertThat(r.newLeads()).isEqualTo(2);
assertThat(r.funnel().keySet()).containsExactly("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
assertThat(r.funnel()).containsEntry("OPEN", 2L).containsEntry("WON", 1L).containsEntry("LOST", 0L);
}
@Test
void wonInPeriodCountsWinRowsAndMedianIsLowerMiddle() {
LocalDateTime c = LocalDateTime.of(2026, 11, 1, 10, 0);
List<Win> odd = List.of(new Win(1, c, c.plusDays(1)), new Win(2, c, c.plusDays(9)), new Win(3, c, c.plusDays(5)));
assertThat(calc(List.of(), odd, List.of()).wonInPeriod()).isEqualTo(3);
assertThat(calc(List.of(), odd, List.of()).medianDaysToWin()).isEqualTo(5L);
List<Win> even = List.of(new Win(1, c, c.plusDays(2)), new Win(2, c, c.plusDays(8)));
assertThat(calc(List.of(), even, List.of()).medianDaysToWin()).isEqualTo(2L);
}
@Test
void medianIsNullWithoutWins() {
LeadDashboardResponse r = calc(List.of(), List.of(), List.of());
assertThat(r.wonInPeriod()).isZero();
assertThat(r.medianDaysToWin()).isNull();
}
@Test
void medianUsesKualaLumpurDates() {
// 2026-11-01 17:00 UTC = 2 Nov 01:00 KL; 2026-11-03 15:00 UTC = 3 Nov 23:00 KL -> 1 day
Win w = new Win(1, LocalDateTime.of(2026, 11, 1, 17, 0), LocalDateTime.of(2026, 11, 3, 15, 0));
assertThat(calc(List.of(), List.of(w), List.of()).medianDaysToWin()).isEqualTo(1L);
}
@Test
void overdueSumsAndSalespeopleIncludeOverdueOnlyAndUnassigned() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", 7L, "NEW", "OPEN", T), cap(2, 10, "A", 7L, "NEW", "CONTACTED", T),
cap(3, 10, "A", 7L, "NEW", "WON", T), cap(4, 10, "A", 7L, "NEW", "LOST", T),
cap(5, 10, "A", null, "NEW", "OPEN", T)),
List.of(), List.of(new Overdue(7L, 2), new Overdue(9L, 5), new Overdue(null, 1)));
assertThat(r.overdueFollowUps()).isEqualTo(8);
assertThat(r.salespeople()).extracting(LeadDashboardResponse.Salesperson::userId)
.containsExactly(7L, null, 9L);
LeadDashboardResponse.Salesperson s7 = r.salespeople().get(0);
assertThat(s7.assigned()).isEqualTo(4);
assertThat(s7.worked()).isEqualTo(3);
assertThat(s7.won()).isEqualTo(1);
assertThat(s7.lost()).isEqualTo(1);
assertThat(s7.overdue()).isEqualTo(2);
LeadDashboardResponse.Salesperson s9 = r.salespeople().get(2);
assertThat(s9.assigned()).isZero();
assertThat(s9.overdue()).isEqualTo(5);
LeadDashboardResponse.Salesperson un = r.salespeople().get(1);
assertThat(un.assigned()).isEqualTo(1);
assertThat(un.overdue()).isEqualTo(1);
}
@Test
void salespeopleOrderByAssignedThenOverdueThenUserIdNullLast() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", null, "NEW", "OPEN", T), cap(2, 10, "A", 5L, "NEW", "OPEN", T),
cap(3, 10, "A", 3L, "NEW", "OPEN", T)), List.of(), List.of());
assertThat(r.salespeople()).extracting(LeadDashboardResponse.Salesperson::userId)
.containsExactly(3L, 5L, null);
}
@Test
void interestWithTwoInterestsCountsUnderBoth() {
LeadDashboardResponse r = calc(Bucket.DAY,
List.of(cap(1, 10, "A", 7L, "NEW", "WON", T), cap(2, 10, "A", 7L, "NEW", "OPEN", T)),
List.of(), List.of(), Map.of(1L, List.of(5L, 6L), 2L, List.of(6L)),
Map.of(5L, "Cookware", 6L, "Appliances"));
assertThat(r.interests()).extracting(LeadDashboardResponse.InterestRow::name, LeadDashboardResponse.InterestRow::captures,
LeadDashboardResponse.InterestRow::won).containsExactly(
org.assertj.core.groups.Tuple.tuple("Appliances", 2L, 1L),
org.assertj.core.groups.Tuple.tuple("Cookware", 1L, 1L));
}
@Test
void eventsOrderedByCapturesDescThenNameWithWonAndUuidAsString() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "Zed", 7L, "NEW", "WON", T), cap(2, 20, "Alpha", 7L, "EXISTING", "OPEN", T),
cap(3, 30, "Beta", 7L, "NEW", "OPEN", T), cap(4, 10, "Zed", 7L, "NEW", "OPEN", T)),
List.of(), List.of());
assertThat(r.events()).extracting(LeadDashboardResponse.EventRow::eventUuid).containsExactly("10", "20", "30");
LeadDashboardResponse.EventRow zed = r.events().get(0);
assertThat(zed.captures()).isEqualTo(2);
assertThat(zed.newLeads()).isEqualTo(2);
assertThat(zed.won()).isEqualTo(1);
assertThat(zed.companyId()).isEqualTo(2L);
}
@Test
void eventWithNullNameSortsLastAmongEqualCaptures() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, null, 7L, "NEW", "OPEN", T), cap(2, 20, "Beta", 7L, "NEW", "OPEN", T),
cap(3, 30, "Alpha", 7L, "NEW", "OPEN", T)), List.of(), List.of());
assertThat(r.events()).extracting(LeadDashboardResponse.EventRow::eventUuid).containsExactly("30", "20", "10");
}
@Test
void dayTrendIsZeroFilledAndAscending() {
LeadDashboardResponse r = calc(List.of(cap(1, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 11, 3, 2, 0))),
List.of(new Win(2, T, LocalDateTime.of(2026, 11, 3, 3, 0))), List.of());
assertThat(r.trend()).hasSize(30);
assertThat(r.trend().get(0).bucket()).isEqualTo(LocalDate.of(2026, 11, 1));
assertThat(r.trend().get(2).bucket()).isEqualTo(LocalDate.of(2026, 11, 3));
assertThat(r.trend().get(2).captures()).isEqualTo(1);
assertThat(r.trend().get(2).wins()).isEqualTo(1);
assertThat(r.trend().get(1).captures()).isZero();
}
@Test
void monthTrendStartsAtFirstOfFromMonth() {
LeadDashboardResponse r = LeadDashboardCalculator.calculate(LocalDate.of(2026, 1, 15), LocalDate.of(2026, 3, 2),
Bucket.MONTH, UTC, List.of(cap(1, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 2, 20, 1, 0))),
List.of(), List.of(), Map.of(), Map.of());
assertThat(r.trend()).extracting(LeadDashboardResponse.TrendPoint::bucket)
.containsExactly(LocalDate.of(2026, 1, 1), LocalDate.of(2026, 2, 1), LocalDate.of(2026, 3, 1));
assertThat(r.trend().get(1).captures()).isEqualTo(1);
}
@Test
void kualaLumpurDayBoundary() {
LeadDashboardResponse r = calc(List.of(
cap(1, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 11, 30, 15, 30)),
cap(2, 10, "A", 7L, "NEW", "OPEN", LocalDateTime.of(2026, 11, 30, 16, 30))), List.of(), List.of());
assertThat(r.trend().get(29).captures()).isEqualTo(1); // 30 Nov
assertThat(r.trend()).hasSize(30);
}
}
@@ -0,0 +1,82 @@
package com.solvway.services.counter.dashboard;
import com.solvway.services.counter.dto.LeadDashboardRequest;
import com.solvway.services.counter.dto.LeadDashboardRequest.Bucket;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.InterestRepository;
import com.solvway.services.counter.repo.LeadDashboardRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
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.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class LeadDashboardServiceTest {
@Mock private LeadDashboardRepository repo;
@Mock private EventLeadInterestRepository interests;
@Mock private InterestRepository interestRepository;
private LeadDashboardService service() {
return new LeadDashboardService(repo, interests, interestRepository);
}
@Test
void fromAfterToIsInvalidPeriod() {
LeadDashboardRequest req = new LeadDashboardRequest(2L, LocalDate.of(2026, 11, 30), LocalDate.of(2026, 11, 1), Bucket.DAY);
assertThatThrownBy(() -> service().leads(req)).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo("INVALID_PERIOD");
});
}
@Test
void missingFieldsAreBadRequest() {
assertThatThrownBy(() -> service().leads(new LeadDashboardRequest(null, null, LocalDate.now(), Bucket.DAY)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
assertThatThrownBy(() -> service().leads(new LeadDashboardRequest(null, LocalDate.now(), LocalDate.now(), null)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void nullCompanyPassesThroughAndPeriodIsKualaLumpurDaysInSystemZone() {
when(repo.captures(any(), any(), any())).thenReturn(List.of());
when(repo.wins(any(), any(), any())).thenReturn(List.of());
when(repo.overdue(any(), any())).thenReturn(List.of());
service().leads(new LeadDashboardRequest(null, LocalDate.of(2026, 11, 1), LocalDate.of(2026, 11, 30), Bucket.MONTH));
LocalDateTime start = LocalDate.of(2026, 11, 1).atStartOfDay(ZoneId.of("Asia/Kuala_Lumpur"))
.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
LocalDateTime end = LocalDate.of(2026, 12, 1).atStartOfDay(ZoneId.of("Asia/Kuala_Lumpur"))
.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
verify(repo).captures(eq(null), eq(start), eq(end));
verify(repo).wins(eq(null), eq(start), eq(end));
verify(repo).overdue(eq(null), any());
}
@Test
void rangeOf731DaysIsAcceptedAnd732IsRefused() {
LocalDate from = LocalDate.of(2025, 1, 1);
when(repo.captures(any(), any(), any())).thenReturn(List.of());
when(repo.wins(any(), any(), any())).thenReturn(List.of());
when(repo.overdue(any(), any())).thenReturn(List.of());
assertThat(service().leads(new LeadDashboardRequest(null, from, from.plusDays(730), Bucket.DAY)).trend()).hasSize(731);
assertThatThrownBy(() -> service().leads(new LeadDashboardRequest(null, from, from.plusDays(731), Bucket.DAY)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo("INVALID_PERIOD");
});
}
}
@@ -9,6 +9,7 @@ import com.solvway.services.counter.model.EventLeadInterestId;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -49,12 +50,13 @@ class EventLeadListAndUpdateTest {
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private EventLeadService service;
@BeforeEach
void setUp() {
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository);
}
@Test
@@ -10,6 +10,7 @@ import com.solvway.services.counter.model.EventLeadInterestId;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -50,12 +51,13 @@ class EventLeadServiceTest {
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private EventLeadService service;
@BeforeEach
void setUp() {
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository);
}
// --- findMatches ---
@@ -0,0 +1,133 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.EventLeadCaptureRequest;
import com.solvway.services.counter.dto.EventLeadUpdateRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventLeadStatusChange;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Event lead status history: capture writes the first row, update writes one row per real status change. */
@ExtendWith(MockitoExtension.class)
class EventLeadStatusHistoryTest {
private static final long COMPANY = 42L;
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository history;
private EventLeadService service() {
return new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, history);
}
private static EventLeadCaptureRequest capture(String status) {
return new EventLeadCaptureRequest(COMPANY, 1000L, null, "Aisyah", null, null, null, null, 11L, null, status,
List.of(), null, null, "sales1");
}
private static EventLead existing(String status) {
EventLead e = new EventLead();
e.setId(7L);
e.setCompanyId(COMPANY);
e.setLeadUuid(501L);
e.setStatus(status);
return e;
}
private static EventLeadUpdateRequest update(EventLead e, String status) {
return new EventLeadUpdateRequest(COMPANY, e.getUuid(), null, null, status, List.of(), null, null, "sales2");
}
private void stubUpdate(EventLead e) {
when(eventLeadRepository.findByUuidAndCompanyId(e.getUuid(), COMPANY)).thenReturn(Optional.of(e));
when(eventLeadRepository.saveAndFlush(e)).thenReturn(e);
when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(new Lead()));
}
@Test
void captureWritesTheFirstHistoryRow() {
when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> {
EventLead e = inv.getArgument(0);
e.setId(7L);
return e;
});
service().capture(capture("QUALIFIED"));
ArgumentCaptor<EventLeadStatusChange> row = ArgumentCaptor.forClass(EventLeadStatusChange.class);
verify(history).save(row.capture());
assertThat(row.getValue().getFromStatus()).isNull();
assertThat(row.getValue().getToStatus()).isEqualTo("QUALIFIED");
assertThat(row.getValue().getEventLeadId()).isEqualTo(7L);
assertThat(row.getValue().getCompanyId()).isEqualTo(COMPANY);
assertThat(row.getValue().getChangedBy()).isEqualTo("sales1");
assertThat(row.getValue().getChangedAt()).isNotNull();
}
@Test
void captureDefaultsToOpenAndUsesCapturedAt() {
LocalDateTime at = LocalDateTime.of(2026, 11, 3, 10, 0);
when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> {
EventLead e = inv.getArgument(0);
e.setId(7L);
e.setCapturedAt(at);
return e;
});
service().capture(capture(null));
ArgumentCaptor<EventLeadStatusChange> row = ArgumentCaptor.forClass(EventLeadStatusChange.class);
verify(history).save(row.capture());
assertThat(row.getValue().getToStatus()).isEqualTo("OPEN");
assertThat(row.getValue().getChangedAt()).isEqualTo(at);
}
@Test
void updateWritesOneRowWhenStatusChanges() {
EventLead e = existing("OPEN");
stubUpdate(e);
service().update(update(e, "WON"));
ArgumentCaptor<EventLeadStatusChange> row = ArgumentCaptor.forClass(EventLeadStatusChange.class);
verify(history).save(row.capture());
assertThat(row.getValue().getFromStatus()).isEqualTo("OPEN");
assertThat(row.getValue().getToStatus()).isEqualTo("WON");
assertThat(row.getValue().getEventLeadId()).isEqualTo(7L);
assertThat(row.getValue().getCompanyId()).isEqualTo(COMPANY);
assertThat(row.getValue().getChangedBy()).isEqualTo("sales2");
assertThat(row.getValue().getChangedAt()).isEqualTo(e.getUpdatedAt());
}
@Test
void updateWritesNoRowWhenStatusIsUnchangedOrNull() {
EventLead e = existing("OPEN");
stubUpdate(e);
service().update(update(e, "OPEN"));
service().update(update(e, null));
verify(history, never()).save(any());
}
}
@@ -12,6 +12,7 @@ import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -46,6 +47,7 @@ class LeadCompanyScopeTest {
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
@Mock private EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private LeadService leadService;
private EventLeadService eventLeadService;
@@ -53,7 +55,7 @@ class LeadCompanyScopeTest {
@BeforeEach
void setUp() {
leadService = new LeadService(leadRepository, eventLeadRepository);
eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository);
}
private static Lead lead(long uuid, long companyId) {