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");
}