feat(services-counter): capture, match, list and edit event leads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-27 11:13:49 +08:00
1 parent b75d636886
commit 48507979bd
20 files changed
+1183 -1

No files matched your search

@@ -0,0 +1,52 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.dto.EventLeadCaptureRequest;
import com.solvway.services.counter.dto.EventLeadDetail;
import com.solvway.services.counter.dto.EventLeadSearchRequest;
import com.solvway.services.counter.dto.EventLeadUpdateRequest;
import com.solvway.services.counter.dto.LeadMatch;
import com.solvway.services.counter.dto.LeadMatchRequest;
import com.solvway.services.counter.service.EventLeadService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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;
import java.util.List;
@RestController
@RequestMapping("/counter")
@AllArgsConstructor
public class EventLeadController {
private final EventLeadService eventLeadService;
@PostMapping("/lead/findMatches")
public List<LeadMatch> findMatches(@RequestBody LeadMatchRequest req) {
return eventLeadService.findMatches(req);
}
@PostMapping("/eventLead/capture")
public EventLeadDetail capture(@RequestBody EventLeadCaptureRequest req) {
return eventLeadService.capture(req);
}
@GetMapping("/eventLead/findByUuid/{companyId}/{eventLeadUuid}")
public EventLeadDetail findByUuid(@PathVariable("companyId") long companyId,
@PathVariable("eventLeadUuid") long eventLeadUuid) {
return eventLeadService.findByUuid(companyId, eventLeadUuid);
}
@PostMapping("/eventLead/findByEvent")
public Page<EventLeadDetail> findByEvent(@RequestBody EventLeadSearchRequest req) {
return eventLeadService.search(req);
}
@PostMapping("/eventLead/update")
public EventLeadDetail update(@RequestBody EventLeadUpdateRequest req) {
return eventLeadService.update(req);
}
}
@@ -0,0 +1,23 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
import java.util.List;
/** Capture a lead at an event. leadUuid null means a new person. Values arrive validated and normalised by mobile-api. */
public record EventLeadCaptureRequest(
long companyId,
long eventUuid,
Long leadUuid,
String name,
String mobileE164,
String email,
String companyName,
String jobTitle,
Long salespersonUserId,
String temperature,
String status,
List<Long> interestIds,
LocalDate nextFollowUpDate,
String notes,
String doneBy
) {}
@@ -0,0 +1,25 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/** An event lead with its lead's contact details and its interest ids. */
public record EventLeadDetail(
long eventLeadUuid,
long eventUuid,
long leadUuid,
String name,
String mobileE164,
String email,
String companyName,
String jobTitle,
String leadType,
Long salespersonUserId,
String temperature,
String status,
LocalDate nextFollowUpDate,
String notes,
LocalDateTime capturedAt,
List<Long> interestIds
) {}
@@ -0,0 +1,5 @@
package com.solvway.services.counter.dto;
/** One event's leads, filtered; null or blank filters are ignored. page is 0-based. */
public record EventLeadSearchRequest(long companyId, long eventUuid, Long salespersonUserId, String temperature,
String status, Long interestId, String leadType, int page, int size) {}
@@ -0,0 +1,9 @@
package com.solvway.services.counter.dto;
import java.time.LocalDate;
import java.util.List;
/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. */
public record EventLeadUpdateRequest(long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy) {}
@@ -0,0 +1,5 @@
package com.solvway.services.counter.dto;
/** A matching lead; eventLeadUuid is set when the lead is already captured at the requested event. */
public record LeadMatch(long leadUuid, String name, String mobileE164, String email,
String companyName, String jobTitle, Long eventLeadUuid) {}
@@ -0,0 +1,4 @@
package com.solvway.services.counter.dto;
/** Find the company's leads whose mobile or email matches; blank values are ignored. */
public record LeadMatchRequest(long companyId, long eventUuid, String mobileE164, String email) {}
@@ -0,0 +1,58 @@
package com.solvway.services.counter.model;
import com.solvway.core.utils.SnowflakeIdWorker;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@Table(name = "event_lead", uniqueConstraints = {
@UniqueConstraint(columnNames = {"uuid"}),
@UniqueConstraint(columnNames = {"event_uuid", "lead_uuid"})
})
public class EventLead {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(updatable = false)
private long uuid = SnowflakeIdWorker.getUUID();
private long companyId;
@Column(name = "event_uuid")
private long eventUuid;
@Column(name = "lead_uuid")
private long leadUuid;
@Column(name = "salesperson_user_id")
private Long salespersonUserId;
private String leadType;
private String temperature;
private String status;
@Column(name = "next_follow_up_date")
private LocalDate nextFollowUpDate;
private String notes;
private String capturedBy;
@Column(updatable = false)
private LocalDateTime capturedAt = LocalDateTime.now();
private String updatedBy;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,24 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.Persistable;
@Getter
@Setter
@Entity
@Table(name = "event_lead_interest", uniqueConstraints = @UniqueConstraint(columnNames = {"event_lead_id", "interest_id"}))
public class EventLeadInterest implements Persistable<EventLeadInterestId> {
@EmbeddedId
private EventLeadInterestId id;
private long companyId;
/** Rows are only inserted (a set is replaced by a bulk delete first), so saveAll persists without a SELECT per row. */
@Override
@Transient
public boolean isNew() {
return true;
}
}
@@ -0,0 +1,41 @@
package com.solvway.services.counter.model;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.Objects;
@Getter
@Setter
@Embeddable
public class EventLeadInterestId implements Serializable {
@Column(name = "event_lead_id")
private long eventLeadId;
@Column(name = "interest_id")
private long interestId;
public EventLeadInterestId() {}
public EventLeadInterestId(long eventLeadId, long interestId) {
this.eventLeadId = eventLeadId;
this.interestId = interestId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EventLeadInterestId)) return false;
EventLeadInterestId that = (EventLeadInterestId) o;
return eventLeadId == that.eventLeadId && interestId == that.interestId;
}
@Override
public int hashCode() {
return Objects.hash(eventLeadId, interestId);
}
}
@@ -0,0 +1,45 @@
package com.solvway.services.counter.model;
import com.solvway.core.utils.SnowflakeIdWorker;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@Table(name = "`lead`", uniqueConstraints = @UniqueConstraint(columnNames = {"uuid"}))
public class Lead {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(updatable = false)
private long uuid = SnowflakeIdWorker.getUUID();
private long companyId;
private String name;
@Column(name = "mobile_e164")
private String mobileE164;
private String emailNormalised;
private String companyName;
private String jobTitle;
private String notes;
private String createdBy;
@Column(updatable = false)
private LocalDateTime createdAt = LocalDateTime.now();
private String updatedBy;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,24 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventLeadInterest;
import com.solvway.services.counter.model.EventLeadInterestId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
@Repository
public interface EventLeadInterestRepository extends JpaRepository<EventLeadInterest, EventLeadInterestId> {
List<EventLeadInterest> findByIdEventLeadId(long eventLeadId);
List<EventLeadInterest> findByIdEventLeadIdIn(Collection<Long> eventLeadIds);
@Modifying
@Query("DELETE FROM EventLeadInterest i WHERE i.id.eventLeadId = :eventLeadId")
void deleteByEventLeadId(@Param("eventLeadId") long eventLeadId);
}
@@ -0,0 +1,40 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventLead;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@Repository
public interface EventLeadRepository extends JpaRepository<EventLead, Long> {
Optional<EventLead> findByEventUuidAndLeadUuid(long eventUuid, long leadUuid);
List<EventLead> findByEventUuidAndLeadUuidIn(long eventUuid, Collection<Long> leadUuids);
Optional<EventLead> findByUuidAndCompanyId(long uuid, long companyId);
String SEARCH_WHERE = " WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId"
+ " AND e.companyId = :companyId AND e.eventUuid = :eventUuid"
+ " AND (:salespersonUserId IS NULL OR e.salespersonUserId = :salespersonUserId)"
+ " AND (:temperature IS NULL OR e.temperature = :temperature)"
+ " AND (:status IS NULL OR e.status = :status)"
+ " AND (:leadType IS NULL OR e.leadType = :leadType)"
+ " AND (:interestId IS NULL OR EXISTS (SELECT 1 FROM EventLeadInterest i"
+ " WHERE i.id.eventLeadId = e.id AND i.id.interestId = :interestId))";
/** Rows are [EventLead, Lead]; the caller supplies the sort through the pageable. */
@Query(value = "SELECT e, l FROM EventLead e, Lead l" + SEARCH_WHERE,
countQuery = "SELECT COUNT(e) FROM EventLead e, Lead l" + SEARCH_WHERE)
Page<Object[]> search(@Param("companyId") long companyId, @Param("eventUuid") long eventUuid,
@Param("salespersonUserId") Long salespersonUserId, @Param("temperature") String temperature,
@Param("status") String status, @Param("interestId") Long interestId,
@Param("leadType") String leadType, Pageable pageable);
}
@@ -0,0 +1,22 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.Lead;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface LeadRepository extends JpaRepository<Lead, Long> {
/** Leads in the company whose mobile or email equals the given value; a null value matches nothing. Newest first. */
@Query("SELECT l FROM Lead l WHERE l.companyId = :companyId AND (l.mobileE164 = :mobile OR l.emailNormalised = :email) ORDER BY l.id DESC")
List<Lead> findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile,
@Param("email") String email, Pageable pageable);
Optional<Lead> findByUuidAndCompanyId(long uuid, long companyId);
}
@@ -0,0 +1,191 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.EventLeadCaptureRequest;
import com.solvway.services.counter.dto.EventLeadDetail;
import com.solvway.services.counter.dto.EventLeadSearchRequest;
import com.solvway.services.counter.dto.EventLeadUpdateRequest;
import com.solvway.services.counter.dto.LeadMatch;
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.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.LeadRepository;
import lombok.AllArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Lead capture at events. Values arrive validated and normalised by mobile-api; this service applies the
* New/Existing rules and keeps the lead, its event lead and its interests in one transaction.
* Never log a lead's name, mobile or email.
*/
@Service
@AllArgsConstructor
public class EventLeadService {
private static final int MAX_MATCHES = 20;
private static final int MAX_PAGE_SIZE = 100;
private final LeadRepository leadRepository;
private final EventLeadRepository eventLeadRepository;
private final EventLeadInterestRepository eventLeadInterestRepository;
public List<LeadMatch> findMatches(LeadMatchRequest req) {
String mobile = blankToNull(req.mobileE164());
String email = blankToNull(req.email());
if (mobile == null && email == null) return List.of();
List<Lead> leads = leadRepository.findMatches(req.companyId(), mobile, email, PageRequest.of(0, MAX_MATCHES));
if (leads.isEmpty()) return List.of();
Map<Long, Long> capturedHere = eventLeadRepository
.findByEventUuidAndLeadUuidIn(req.eventUuid(), leads.stream().map(Lead::getUuid).toList()).stream()
.collect(Collectors.toMap(EventLead::getLeadUuid, EventLead::getUuid));
return leads.stream()
.map(l -> new LeadMatch(l.getUuid(), l.getName(), l.getMobileE164(), l.getEmailNormalised(),
l.getCompanyName(), l.getJobTitle(), capturedHere.get(l.getUuid())))
.toList();
}
@Transactional
public EventLeadDetail capture(EventLeadCaptureRequest req) {
Lead lead;
String leadType;
if (req.leadUuid() == null) {
lead = new Lead();
lead.setCompanyId(req.companyId());
lead.setName(req.name());
lead.setMobileE164(blankToNull(req.mobileE164()));
lead.setEmailNormalised(blankToNull(req.email()));
lead.setCompanyName(blankToNull(req.companyName()));
lead.setJobTitle(blankToNull(req.jobTitle()));
lead.setCreatedBy(req.doneBy());
leadType = "NEW";
} else {
lead = leadRepository.findByUuidAndCompanyId(req.leadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"));
eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid()).ifPresent(existing -> {
ResponseStatusException e = new ResponseStatusException(HttpStatus.CONFLICT, "ALREADY_CAPTURED");
e.getBody().setProperty("eventLeadUuid", String.valueOf(existing.getUuid()));
throw e;
});
fillBlank(lead.getName(), req.name(), lead::setName);
fillBlank(lead.getMobileE164(), req.mobileE164(), lead::setMobileE164);
fillBlank(lead.getEmailNormalised(), req.email(), lead::setEmailNormalised);
fillBlank(lead.getCompanyName(), req.companyName(), lead::setCompanyName);
fillBlank(lead.getJobTitle(), req.jobTitle(), lead::setJobTitle);
lead.setUpdatedBy(req.doneBy());
lead.setUpdatedAt(LocalDateTime.now());
leadType = "EXISTING";
}
leadRepository.saveAndFlush(lead);
EventLead eventLead = new EventLead();
eventLead.setCompanyId(req.companyId());
eventLead.setEventUuid(req.eventUuid());
eventLead.setLeadUuid(lead.getUuid());
eventLead.setSalespersonUserId(req.salespersonUserId());
eventLead.setLeadType(leadType);
eventLead.setTemperature(req.temperature());
eventLead.setStatus(req.status() == null ? "OPEN" : req.status());
eventLead.setNextFollowUpDate(req.nextFollowUpDate());
eventLead.setNotes(req.notes());
eventLead.setCapturedBy(req.doneBy());
try {
eventLead = eventLeadRepository.saveAndFlush(eventLead);
} catch (DataIntegrityViolationException e) {
// uk_event_lead_event_lead: another capture of the same person at this event won the race.
throw new ResponseStatusException(HttpStatus.CONFLICT, "ALREADY_CAPTURED");
}
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
return detail(eventLead, lead, interestIds);
}
public EventLeadDetail findByUuid(long companyId, long eventLeadUuid) {
EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), companyId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
List<Long> interestIds = eventLeadInterestRepository.findByIdEventLeadId(eventLead.getId()).stream()
.map(r -> r.getId().getInterestId()).toList();
return detail(eventLead, lead, interestIds);
}
public Page<EventLeadDetail> search(EventLeadSearchRequest req) {
Pageable pageable = PageRequest.of(Math.max(req.page(), 0), Math.min(Math.max(req.size(), 1), MAX_PAGE_SIZE),
Sort.by(Sort.Order.desc("capturedAt"), Sort.Order.desc("id")));
Page<Object[]> rows = eventLeadRepository.search(req.companyId(), req.eventUuid(), req.salespersonUserId(),
blankToNull(req.temperature()), blankToNull(req.status()), req.interestId(), blankToNull(req.leadType()), pageable);
if (rows.isEmpty()) return rows.map(r -> null);
Map<Long, List<Long>> interests = eventLeadInterestRepository
.findByIdEventLeadIdIn(rows.map(r -> ((EventLead) r[0]).getId()).getContent()).stream()
.collect(Collectors.groupingBy(i -> i.getId().getEventLeadId(),
Collectors.mapping(i -> i.getId().getInterestId(), Collectors.toList())));
return rows.map(r -> {
EventLead e = (EventLead) r[0];
return detail(e, (Lead) r[1], interests.getOrDefault(e.getId(), List.of()));
});
}
@Transactional
public EventLeadDetail update(EventLeadUpdateRequest req) {
EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
eventLead.setSalespersonUserId(req.salespersonUserId());
eventLead.setTemperature(blankToNull(req.temperature()));
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);
eventLeadInterestRepository.deleteByEventLeadId(eventLead.getId());
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
return detail(eventLead, lead, interestIds);
}
private List<Long> saveInterests(long eventLeadId, long companyId, List<Long> requested) {
List<Long> ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList();
if (!ids.isEmpty()) {
eventLeadInterestRepository.saveAll(ids.stream().map(id -> {
EventLeadInterest row = new EventLeadInterest();
row.setId(new EventLeadInterestId(eventLeadId, id));
row.setCompanyId(companyId);
return row;
}).toList());
}
return ids;
}
private static EventLeadDetail detail(EventLead e, Lead l, List<Long> interestIds) {
return new EventLeadDetail(e.getUuid(), e.getEventUuid(), l.getUuid(), l.getName(), l.getMobileE164(),
l.getEmailNormalised(), l.getCompanyName(), l.getJobTitle(), e.getLeadType(), e.getSalespersonUserId(),
e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds);
}
private static void fillBlank(String current, String offered, Consumer<String> setter) {
if (blankToNull(current) == null && blankToNull(offered) != null) setter.accept(offered);
}
private static String blankToNull(String s) {
return s == null || s.isBlank() ? null : s;
}
}