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,22 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.dashboard.LeadDashboardService;
import com.solvway.services.counter.dto.LeadDashboardRequest;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import lombok.AllArgsConstructor;
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.RestController;
@RestController
@RequestMapping("/counter")
@AllArgsConstructor
public class LeadDashboardController {
private final LeadDashboardService service;
@PostMapping("/dashboard/leads")
public LeadDashboardResponse leads(@RequestBody LeadDashboardRequest req) {
return service.leads(req);
}
}
@@ -0,0 +1,116 @@
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.dto.LeadDashboardResponse.EventRow;
import com.solvway.services.counter.dto.LeadDashboardResponse.InterestRow;
import com.solvway.services.counter.dto.LeadDashboardResponse.Salesperson;
import com.solvway.services.counter.dto.LeadDashboardResponse.TrendPoint;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/** Pure aggregation of the dashboard rows; no Spring, no DB. */
public final class LeadDashboardCalculator {
public static final ZoneId KL = ZoneId.of("Asia/Kuala_Lumpur");
private static final List<String> STATUSES = List.of("OPEN", "CONTACTED", "QUALIFIED", "WON", "LOST");
public record Capture(long id, long eventUuid, String eventName, long companyId, Long salespersonUserId,
String leadType, String status, LocalDateTime capturedAt) {}
public record Win(long id, LocalDateTime capturedAt, LocalDateTime wonAt) {}
public record Overdue(Long salespersonUserId, long count) {}
private LeadDashboardCalculator() {}
/**
* ponytail: one row per capture in the period, aggregated in memory; move the sums into SQL when a company
* captures hundreds of thousands of leads a year.
* storedZone is the zone the stored wall times are in (the JVM default zone in production).
*/
public static LeadDashboardResponse calculate(LocalDate from, LocalDate to, Bucket bucket, ZoneId storedZone,
List<Capture> captures, List<Win> wins, List<Overdue> overdue,
Map<Long, List<Long>> interestsByEventLead, Map<Long, String> interestNames) {
Function<LocalDateTime, LocalDate> klDate = t -> t.atZone(storedZone).withZoneSameInstant(KL).toLocalDate();
Map<String, Long> funnel = new LinkedHashMap<>();
STATUSES.forEach(s -> funnel.put(s, 0L));
captures.forEach(c -> funnel.computeIfPresent(c.status(), (k, v) -> v + 1));
List<Long> days = wins.stream()
.map(w -> ChronoUnit.DAYS.between(klDate.apply(w.capturedAt()), klDate.apply(w.wonAt()))).sorted().toList();
Long median = days.isEmpty() ? null : days.get((days.size() - 1) / 2);
TreeMap<LocalDate, long[]> trend = new TreeMap<>();
for (LocalDate d = bucketOf(from, bucket); !d.isAfter(to); d = bucket == Bucket.DAY ? d.plusDays(1) : d.plusMonths(1)) {
trend.put(d, new long[2]);
}
captures.forEach(c -> bump(trend, bucketOf(klDate.apply(c.capturedAt()), bucket), 0));
wins.forEach(w -> bump(trend, bucketOf(klDate.apply(w.wonAt()), bucket), 1));
List<EventRow> events = captures.stream().collect(Collectors.groupingBy(Capture::eventUuid)).values().stream()
.map(l -> new EventRow(String.valueOf(l.get(0).eventUuid()), l.get(0).eventName(), l.get(0).companyId(),
l.size(), count(l, c -> "NEW".equals(c.leadType())), count(l, c -> "WON".equals(c.status()))))
.sorted(Comparator.comparingLong(EventRow::captures).reversed()
.thenComparing(EventRow::name, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
Map<Long, Long> overdueByUser = new LinkedHashMap<>();
overdue.forEach(o -> overdueByUser.merge(o.salespersonUserId(), o.count(), Long::sum));
Map<Long, List<Capture>> byUser = new LinkedHashMap<>();
captures.forEach(c -> byUser.computeIfAbsent(c.salespersonUserId(), k -> new ArrayList<>()).add(c));
overdueByUser.keySet().forEach(u -> byUser.computeIfAbsent(u, k -> new ArrayList<>()));
List<Salesperson> salespeople = byUser.entrySet().stream()
.map(e -> new Salesperson(e.getKey(), e.getValue().size(), count(e.getValue(), c -> !"OPEN".equals(c.status())),
count(e.getValue(), c -> "WON".equals(c.status())), count(e.getValue(), c -> "LOST".equals(c.status())),
overdueByUser.getOrDefault(e.getKey(), 0L)))
.sorted(Comparator.comparingLong(Salesperson::assigned).reversed()
.thenComparing(Comparator.comparingLong(Salesperson::overdue).reversed())
.thenComparing(Salesperson::userId, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
Map<Long, long[]> interestTotals = new LinkedHashMap<>();
for (Capture c : captures) {
for (Long interestId : interestsByEventLead.getOrDefault(c.id(), List.of())) {
long[] t = interestTotals.computeIfAbsent(interestId, k -> new long[2]);
t[0]++;
if ("WON".equals(c.status())) t[1]++;
}
}
List<InterestRow> interests = interestTotals.entrySet().stream()
.map(e -> new InterestRow(e.getKey(), interestNames.get(e.getKey()), e.getValue()[0], e.getValue()[1]))
.sorted(Comparator.comparingLong(InterestRow::captures).reversed()
.thenComparing(InterestRow::name, Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
return new LeadDashboardResponse(captures.size(), count(captures, c -> "NEW".equals(c.leadType())), wins.size(),
median, overdueByUser.values().stream().mapToLong(Long::longValue).sum(), funnel,
trend.entrySet().stream().map(e -> new TrendPoint(e.getKey(), e.getValue()[0], e.getValue()[1])).toList(),
events, salespeople, interests);
}
/** Rows outside the period's buckets are ignored. */
private static void bump(Map<LocalDate, long[]> trend, LocalDate bucket, int slot) {
long[] t = trend.get(bucket);
if (t != null) t[slot]++;
}
private static LocalDate bucketOf(LocalDate d, Bucket bucket) {
return bucket == Bucket.MONTH ? d.withDayOfMonth(1) : d;
}
private static <T> long count(List<T> l, java.util.function.Predicate<T> p) {
return l.stream().filter(p).count();
}
}
@@ -0,0 +1,72 @@
package com.solvway.services.counter.dashboard;
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 com.solvway.services.counter.dto.LeadDashboardRequest;
import com.solvway.services.counter.dto.LeadDashboardResponse;
import com.solvway.services.counter.model.Interest;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.InterestRepository;
import com.solvway.services.counter.repo.LeadDashboardRepository;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class LeadDashboardService {
private static final int CHUNK = 1000;
private static final int MAX_DAYS = 731;
private final LeadDashboardRepository repo;
private final EventLeadInterestRepository eventLeadInterestRepository;
private final InterestRepository interestRepository;
@Transactional(readOnly = true)
public LeadDashboardResponse leads(LeadDashboardRequest req) {
if (req.from() == null || req.to() == null || req.bucket() == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "PERIOD_AND_BUCKET_REQUIRED");
}
if (req.from().isAfter(req.to()) || ChronoUnit.DAYS.between(req.from(), req.to()) + 1 > MAX_DAYS) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PERIOD");
}
ZoneId system = ZoneId.systemDefault();
LocalDateTime fromTs = req.from().atStartOfDay(LeadDashboardCalculator.KL).withZoneSameInstant(system).toLocalDateTime();
LocalDateTime toTs = req.to().plusDays(1).atStartOfDay(LeadDashboardCalculator.KL).withZoneSameInstant(system).toLocalDateTime();
List<Capture> captures = repo.captures(req.companyId(), fromTs, toTs).stream()
.map(r -> new Capture(r.getId(), r.getEventUuid(), r.getEventName(), r.getCompanyId(),
r.getSalespersonUserId(), r.getLeadType(), r.getStatus(), r.getCapturedAt())).toList();
List<Win> wins = repo.wins(req.companyId(), fromTs, toTs).stream()
.map(r -> new Win(r.getId(), r.getCapturedAt(), r.getWonAt())).toList();
List<Overdue> overdue = repo.overdue(req.companyId(), LocalDate.now(LeadDashboardCalculator.KL)).stream()
.map(r -> new Overdue(r.getSalespersonUserId(), r.getTotal())).toList();
Map<Long, List<Long>> interestsByLead = new HashMap<>();
List<Long> ids = captures.stream().map(Capture::id).toList();
for (int i = 0; i < ids.size(); i += CHUNK) {
eventLeadInterestRepository.findByIdEventLeadIdIn(ids.subList(i, Math.min(i + CHUNK, ids.size())))
.forEach(r -> interestsByLead.computeIfAbsent(r.getId().getEventLeadId(), k -> new java.util.ArrayList<>())
.add(r.getId().getInterestId()));
}
Map<Long, String> names = interestsByLead.isEmpty() ? Map.of()
: interestRepository.findAllById(interestsByLead.values().stream().flatMap(List::stream).distinct().toList())
.stream().collect(Collectors.toMap(Interest::getId, Interest::getName));
return LeadDashboardCalculator.calculate(req.from(), req.to(), req.bucket(), system, captures, wins, overdue,
interestsByLead, names);
}
}
@@ -0,0 +1,8 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
/** companyId null means all companies. The period is whole Asia/Kuala_Lumpur days, both ends included. */
public record LeadDashboardRequest(Long companyId, LocalDate from, LocalDate to, Bucket bucket) {
public enum Bucket { DAY, MONTH }
}
@@ -0,0 +1,17 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
public record LeadDashboardResponse(long captures, long newLeads, long wonInPeriod, Long medianDaysToWin,
long overdueFollowUps, Map<String, Long> funnel, List<TrendPoint> trend,
List<EventRow> events, List<Salesperson> salespeople, List<InterestRow> interests) {
public record TrendPoint(LocalDate bucket, long captures, long wins) {}
public record EventRow(String eventUuid, String name, Long companyId, long captures, long newLeads, long won) {}
public record Salesperson(Long userId, long assigned, long worked, long won, long lost, long overdue) {}
public record InterestRow(long interestId, String name, long captures, long won) {}
}
@@ -0,0 +1,31 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/** Append-only status history of an event lead; rows are never updated or deleted. */
@Getter
@Setter
@Entity
@Table(name = "event_lead_status_change")
public class EventLeadStatusChange {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long companyId;
private long eventLeadId;
/** Null for the first row written at capture. */
private String fromStatus;
private String toStatus;
private LocalDateTime changedAt;
private String changedBy;
}
@@ -0,0 +1,8 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventLeadStatusChange;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EventLeadStatusChangeRepository extends JpaRepository<EventLeadStatusChange, Long> {}
@@ -0,0 +1,58 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventLead;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/** Read-only dashboard queries. Times are bound as wall time in the JVM default zone; companyId null means all. */
public interface LeadDashboardRepository extends Repository<EventLead, Long> {
interface CaptureRow {
long getId();
long getEventUuid();
String getEventName();
long getCompanyId();
Long getSalespersonUserId();
String getLeadType();
String getStatus();
LocalDateTime getCapturedAt();
}
interface WinRow {
long getId();
LocalDateTime getCapturedAt();
LocalDateTime getWonAt();
}
interface OverdueRow {
Long getSalespersonUserId();
long getTotal();
}
@Query(nativeQuery = true, value = "SELECT el.id AS id, el.event_uuid AS eventUuid, ev.name AS eventName,"
+ " el.company_id AS companyId, el.salesperson_user_id AS salespersonUserId, el.lead_type AS leadType,"
+ " el.status AS status, el.captured_at AS capturedAt FROM event_lead el"
+ " LEFT JOIN `event` ev ON ev.uuid = el.event_uuid"
+ " WHERE (:companyId IS NULL OR el.company_id = :companyId) AND el.captured_at >= :fromTs AND el.captured_at < :toTs")
List<CaptureRow> captures(@Param("companyId") Long companyId, @Param("fromTs") LocalDateTime fromTs,
@Param("toTs") LocalDateTime toTs);
/** Leads currently WON whose latest transition to WON falls in the period. */
@Query(nativeQuery = true, value = "SELECT el.id AS id, el.captured_at AS capturedAt, w.won_at AS wonAt"
+ " FROM event_lead el JOIN (SELECT event_lead_id, MAX(changed_at) won_at FROM event_lead_status_change"
+ " WHERE to_status = 'WON' AND (:companyId IS NULL OR company_id = :companyId) GROUP BY event_lead_id) w ON w.event_lead_id = el.id"
+ " WHERE el.status = 'WON' AND (:companyId IS NULL OR el.company_id = :companyId)"
+ " AND w.won_at >= :fromTs AND w.won_at < :toTs")
List<WinRow> wins(@Param("companyId") Long companyId, @Param("fromTs") LocalDateTime fromTs,
@Param("toTs") LocalDateTime toTs);
@Query(nativeQuery = true, value = "SELECT salesperson_user_id AS salespersonUserId, COUNT(*) AS total FROM event_lead"
+ " WHERE (:companyId IS NULL OR company_id = :companyId) AND status NOT IN ('WON', 'LOST')"
+ " AND next_follow_up_date < :today GROUP BY salesperson_user_id")
List<OverdueRow> overdue(@Param("companyId") Long companyId, @Param("today") LocalDate today);
}
@@ -9,9 +9,11 @@ import com.solvway.services.counter.dto.LeadMatchRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventLeadInterest;
import com.solvway.services.counter.model.EventLeadInterestId;
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 lombok.AllArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
@@ -45,6 +47,7 @@ public class EventLeadService {
private final LeadRepository leadRepository;
private final EventLeadRepository eventLeadRepository;
private final EventLeadInterestRepository eventLeadInterestRepository;
private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
public List<LeadMatch> findMatches(LeadMatchRequest req) {
requireCompany(req.companyId());
@@ -115,6 +118,7 @@ public class EventLeadService {
throw new ResponseStatusException(HttpStatus.CONFLICT, "ALREADY_CAPTURED");
}
recordStatusChange(eventLead, null, eventLead.getStatus(), eventLead.getCapturedAt(), req.doneBy());
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
return detail(eventLead, lead, interestIds);
}
@@ -154,12 +158,16 @@ public class EventLeadService {
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
eventLead.setSalespersonUserId(req.salespersonUserId());
eventLead.setTemperature(blankToNull(req.temperature()));
String oldStatus = eventLead.getStatus();
if (req.status() != null) eventLead.setStatus(req.status());
eventLead.setNextFollowUpDate(req.nextFollowUpDate());
eventLead.setNotes(blankToNull(req.notes()));
eventLead.setUpdatedBy(req.doneBy());
eventLead.setUpdatedAt(LocalDateTime.now());
eventLead = eventLeadRepository.saveAndFlush(eventLead);
if (req.status() != null && !req.status().equals(oldStatus)) {
recordStatusChange(eventLead, oldStatus, req.status(), eventLead.getUpdatedAt(), req.doneBy());
}
eventLeadInterestRepository.deleteByEventLeadId(eventLead.getId());
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId())
@@ -167,6 +175,17 @@ public class EventLeadService {
return detail(eventLead, lead, interestIds);
}
private void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) {
EventLeadStatusChange row = new EventLeadStatusChange();
row.setCompanyId(e.getCompanyId());
row.setEventLeadId(e.getId());
row.setFromStatus(from);
row.setToStatus(to);
row.setChangedAt(at);
row.setChangedBy(by);
eventLeadStatusChangeRepository.save(row);
}
private static void requireCompany(Long companyId) {
if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
}
@@ -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) {