diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index c81ec37..4cafe19 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -30,7 +30,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial - Scope: `solvway-services-counter/src/**/*Interest*`, plus a `dto/` record if needed. - Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`. -- [ ] 2.2 Add the lead backend (design decisions 3, 6, 7): +- [x] 2.2 Add the lead backend (design decisions 3, 6, 7): - `Lead`, `EventLead` and `EventLeadInterest` entities and repositories. Uuids come from `SnowflakeIdWorker.getUUID()`. - `EventLeadController` and service: - `POST /counter/lead/findMatches` with `{companyId, mobileE164, email}`: leads matching either value in the company, at most 20, newest first. Each match carries the `eventLeadUuid` when the lead is already captured at the given `eventUuid`. diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java new file mode 100644 index 0000000..9da6d13 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java @@ -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 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 findByEvent(@RequestBody EventLeadSearchRequest req) { + return eventLeadService.search(req); + } + + @PostMapping("/eventLead/update") + public EventLeadDetail update(@RequestBody EventLeadUpdateRequest req) { + return eventLeadService.update(req); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java new file mode 100644 index 0000000..efd6eff --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java @@ -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 interestIds, + LocalDate nextFollowUpDate, + String notes, + String doneBy +) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java new file mode 100644 index 0000000..40c6cda --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java @@ -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 interestIds +) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java new file mode 100644 index 0000000..17ee57e --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java @@ -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) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java new file mode 100644 index 0000000..2bda50a --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java @@ -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 interestIds, LocalDate nextFollowUpDate, String notes, + String doneBy) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java new file mode 100644 index 0000000..ae1ba8a --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatch.java @@ -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) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java new file mode 100644 index 0000000..5938529 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java @@ -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) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java new file mode 100644 index 0000000..82c44b6 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLead.java @@ -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; + +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java new file mode 100644 index 0000000..31e62df --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterest.java @@ -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 { + @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; + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java new file mode 100644 index 0000000..e81bbc9 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/EventLeadInterestId.java @@ -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); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java new file mode 100644 index 0000000..26ba4a2 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Lead.java @@ -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; +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java new file mode 100644 index 0000000..dc61804 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadInterestRepository.java @@ -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 { + + List findByIdEventLeadId(long eventLeadId); + + List findByIdEventLeadIdIn(Collection eventLeadIds); + + @Modifying + @Query("DELETE FROM EventLeadInterest i WHERE i.id.eventLeadId = :eventLeadId") + void deleteByEventLeadId(@Param("eventLeadId") long eventLeadId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java new file mode 100644 index 0000000..12cea09 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -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 { + + Optional findByEventUuidAndLeadUuid(long eventUuid, long leadUuid); + + List findByEventUuidAndLeadUuidIn(long eventUuid, Collection leadUuids); + + Optional 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 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); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java new file mode 100644 index 0000000..e5f7b48 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -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 { + + /** 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 findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile, + @Param("email") String email, Pageable pageable); + + Optional findByUuidAndCompanyId(long uuid, long companyId); +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java new file mode 100644 index 0000000..62f27fb --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -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 findMatches(LeadMatchRequest req) { + String mobile = blankToNull(req.mobileE164()); + String email = blankToNull(req.email()); + if (mobile == null && email == null) return List.of(); + + List leads = leadRepository.findMatches(req.companyId(), mobile, email, PageRequest.of(0, MAX_MATCHES)); + if (leads.isEmpty()) return List.of(); + Map 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 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 interestIds = eventLeadInterestRepository.findByIdEventLeadId(eventLead.getId()).stream() + .map(r -> r.getId().getInterestId()).toList(); + return detail(eventLead, lead, interestIds); + } + + public Page 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 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> 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 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 saveInterests(long eventLeadId, long companyId, List requested) { + List 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 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 setter) { + if (blankToNull(current) == null && blankToNull(offered) != null) setter.accept(offered); + } + + private static String blankToNull(String s) { + return s == null || s.isBlank() ? null : s; + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java new file mode 100644 index 0000000..841add4 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/controller/EventLeadControllerTest.java @@ -0,0 +1,71 @@ +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 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.data.domain.Page; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** EventLeadController delegates to the service and returns its result. */ +@ExtendWith(MockitoExtension.class) +class EventLeadControllerTest { + + @Mock private EventLeadService service; + + @Test + void findMatchesDelegates() { + LeadMatchRequest req = new LeadMatchRequest(42L, 1L, "+60123456789", null); + List out = List.of(new LeadMatch(2L, "Aisyah", "+60123456789", null, null, null, null)); + when(service.findMatches(req)).thenReturn(out); + + assertThat(new EventLeadController(service).findMatches(req)).isSameAs(out); + } + + @Test + void captureReturnsTheCapturedEventLead() { + EventLeadCaptureRequest req = mock(EventLeadCaptureRequest.class); + EventLeadDetail out = mock(EventLeadDetail.class); + when(service.capture(req)).thenReturn(out); + + assertThat(new EventLeadController(service).capture(req)).isSameAs(out); + } + + @Test + void findByUuidDelegates() { + EventLeadDetail out = mock(EventLeadDetail.class); + when(service.findByUuid(42L, 9L)).thenReturn(out); + + assertThat(new EventLeadController(service).findByUuid(42L, 9L)).isSameAs(out); + } + + @Test + void findByEventDelegates() { + EventLeadSearchRequest req = new EventLeadSearchRequest(42L, 1L, null, null, null, null, null, 0, 20); + Page out = Page.empty(); + when(service.search(req)).thenReturn(out); + + assertThat(new EventLeadController(service).findByEvent(req)).isSameAs(out); + } + + @Test + void updateDelegates() { + EventLeadUpdateRequest req = mock(EventLeadUpdateRequest.class); + EventLeadDetail out = mock(EventLeadDetail.class); + when(service.update(req)).thenReturn(out); + + assertThat(new EventLeadController(service).update(req)).isSameAs(out); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java new file mode 100644 index 0000000..a9cee1c --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/model/LeadMappingTest.java @@ -0,0 +1,32 @@ +package com.solvway.services.counter.model; + +import jakarta.persistence.Column; +import jakarta.persistence.Table; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Lead's column names that the default naming strategy gets wrong: mobileE164 would map to `mobilee164`, + * and LEAD is a MySQL 8 reserved word, so the table name must stay quoted. + */ +class LeadMappingTest { + + @Test + void mobileMapsToMobileE164Column() throws Exception { + Column column = Lead.class.getDeclaredField("mobileE164").getAnnotation(Column.class); + assertThat(column).isNotNull(); + assertThat(column.name()).isEqualTo("mobile_e164"); + } + + @Test + void tableNameIsQuoted() { + assertThat(Lead.class.getAnnotation(Table.class).name()).isEqualTo("`lead`"); + } + + @Test + void eventLeadInterestRowsAreAlwaysInsertedWithoutALookup() { + // Rows are only ever inserted (replacing the set deletes in bulk first), so saveAll must persist, not merge. + assertThat(new EventLeadInterest().isNew()).isTrue(); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java new file mode 100644 index 0000000..863bd9a --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadListAndUpdateTest.java @@ -0,0 +1,212 @@ +package com.solvway.services.counter.service; + +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.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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +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.anyCollection; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** EventLeadService: the event leads listing and the event lead edit. */ +@ExtendWith(MockitoExtension.class) +class EventLeadListAndUpdateTest { + + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository eventLeadInterestRepository; + + private EventLeadService service; + + @BeforeEach + void setUp() { + service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository); + } + + @Test + void listingPassesEveryFilterAndPagesNewestCaptureFirstWithIdTieBreak() { + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), eq(11L), eq("HOT"), eq("OPEN"), eq(3L), eq("NEW"), any())) + .thenReturn(Page.empty()); + + service.search(new EventLeadSearchRequest(COMPANY, EVENT, 11L, "HOT", "OPEN", 3L, "NEW", 2, 25)); + + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); + verify(eventLeadRepository).search(eq(COMPANY), eq(EVENT), eq(11L), eq("HOT"), eq("OPEN"), eq(3L), eq("NEW"), pageable.capture()); + assertThat(pageable.getValue().getPageNumber()).isEqualTo(2); + assertThat(pageable.getValue().getPageSize()).isEqualTo(25); + assertThat(pageable.getValue().getSort().toString()).isEqualTo("capturedAt: DESC,id: DESC"); + } + + @Test + void blankFiltersAreIgnoredAndPageSizeIsBounded() { + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), eq(null), eq(null), eq(null), eq(null), eq(null), any())) + .thenReturn(Page.empty()); + + service.search(new EventLeadSearchRequest(COMPANY, EVENT, null, " ", "", null, null, -1, 1000)); + + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); + verify(eventLeadRepository).search(eq(COMPANY), eq(EVENT), eq(null), eq(null), eq(null), eq(null), eq(null), pageable.capture()); + assertThat(pageable.getValue().getPageNumber()).isZero(); + assertThat(pageable.getValue().getPageSize()).isEqualTo(100); + } + + @Test + void listingRowsCarryLeadDetailsAndInterestsFetchedInOneQuery() { + EventLead a = eventLead(1L, 501L); + EventLead b = eventLead(2L, 502L); + Lead la = lead(501L, "Aisyah"); + Lead lb = lead(502L, "Ahmad"); + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), any(), any(), any(), any(), any(), any())) + .thenReturn(new PageImpl<>(List.of(new Object[]{a, la}, new Object[]{b, lb}), PageRequest.of(0, 20), 2)); + when(eventLeadInterestRepository.findByIdEventLeadIdIn(anyCollection())) + .thenReturn(List.of(row(1L, 3L), row(1L, 4L), row(2L, 3L))); + + Page page = service.search(new EventLeadSearchRequest(COMPANY, EVENT, null, null, null, null, null, 0, 20)); + + assertThat(page.getTotalElements()).isEqualTo(2); + assertThat(page.getContent()).extracting(EventLeadDetail::name).containsExactly("Aisyah", "Ahmad"); + assertThat(page.getContent().get(0).interestIds()).containsExactlyInAnyOrder(3L, 4L); + assertThat(page.getContent().get(1).interestIds()).containsExactly(3L); + verify(eventLeadInterestRepository).findByIdEventLeadIdIn(anyCollection()); + } + + @Test + void emptyPageSkipsTheInterestQuery() { + when(eventLeadRepository.search(eq(COMPANY), eq(EVENT), any(), any(), any(), any(), any(), any())).thenReturn(Page.empty()); + + assertThat(service.search(new EventLeadSearchRequest(COMPANY, EVENT, null, null, null, null, null, 0, 20)).getContent()).isEmpty(); + verify(eventLeadInterestRepository, never()).findByIdEventLeadIdIn(anyCollection()); + } + + @Test + void updateReplacesWorkingFieldsAndTheInterestSet() { + EventLead el = eventLead(7L, 501L); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(lead(501L, "Aisyah"))); + + EventLeadDetail detail = service.update(new EventLeadUpdateRequest(COMPANY, el.getUuid(), 12L, "COLD", "CONTACTED", + List.of(4L, 4L, 5L), LocalDate.of(2027, 1, 20), "called back", "sales2")); + + assertThat(el.getSalespersonUserId()).isEqualTo(12L); + assertThat(el.getTemperature()).isEqualTo("COLD"); + assertThat(el.getStatus()).isEqualTo("CONTACTED"); + assertThat(el.getNextFollowUpDate()).isEqualTo(LocalDate.of(2027, 1, 20)); + assertThat(el.getNotes()).isEqualTo("called back"); + assertThat(el.getUpdatedBy()).isEqualTo("sales2"); + assertThat(el.getUpdatedAt()).isNotNull(); + assertThat(detail.interestIds()).containsExactlyInAnyOrder(4L, 5L); + + InOrder order = inOrder(eventLeadInterestRepository); + order.verify(eventLeadInterestRepository).deleteByEventLeadId(7L); + @SuppressWarnings("unchecked") + ArgumentCaptor> rows = ArgumentCaptor.forClass(List.class); + order.verify(eventLeadInterestRepository).saveAll(rows.capture()); + assertThat(rows.getValue()).extracting(r -> r.getId().getInterestId()).containsExactlyInAnyOrder(4L, 5L); + } + + @Test + void updateCanClearTemperatureSalespersonAndInterests() { + EventLead el = eventLead(7L, 501L); + el.setTemperature("HOT"); + el.setSalespersonUserId(11L); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(lead(501L, "Aisyah"))); + + service.update(new EventLeadUpdateRequest(COMPANY, el.getUuid(), null, null, "OPEN", List.of(), null, null, "sales2")); + + assertThat(el.getTemperature()).isNull(); + assertThat(el.getSalespersonUserId()).isNull(); + verify(eventLeadInterestRepository).deleteByEventLeadId(7L); + verify(eventLeadInterestRepository, never()).saveAll(any()); + } + + @Test + void updateOfUnknownOrOtherCompanyEventLeadIsNotFound() { + when(eventLeadRepository.findByUuidAndCompanyId(9L, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.update(new EventLeadUpdateRequest(COMPANY, 9L, null, null, "OPEN", List.of(), null, null, "x"))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + verify(eventLeadInterestRepository, never()).deleteByEventLeadId(any(Long.class)); + } + + @Test + void updateWithoutStatusKeepsTheCurrentStatus() { + EventLead el = eventLead(7L, 501L); + el.setStatus("WON"); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(eventLeadRepository.saveAndFlush(el)).thenReturn(el); + when(leadRepository.findByUuidAndCompanyId(501L, COMPANY)).thenReturn(Optional.of(lead(501L, "Aisyah"))); + + service.update(new EventLeadUpdateRequest(COMPANY, el.getUuid(), null, null, null, List.of(), null, null, "sales2")); + + assertThat(el.getStatus()).isEqualTo("WON"); + } + + @Test + void updateIsOneTransaction() throws Exception { + assertThat(EventLeadService.class.getMethod("update", EventLeadUpdateRequest.class) + .isAnnotationPresent(Transactional.class)).isTrue(); + } + + private static EventLead eventLead(long id, long leadUuid) { + EventLead e = new EventLead(); + e.setId(id); + e.setCompanyId(COMPANY); + e.setEventUuid(EVENT); + e.setLeadUuid(leadUuid); + e.setLeadType("NEW"); + e.setStatus("OPEN"); + return e; + } + + private static Lead lead(long uuid, String name) { + Lead l = new Lead(); + l.setUuid(uuid); + l.setCompanyId(COMPANY); + l.setName(name); + return l; + } + + private static EventLeadInterest row(long eventLeadId, long interestId) { + EventLeadInterest r = new EventLeadInterest(); + r.setId(new EventLeadInterestId(eventLeadId, interestId)); + return r; + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java new file mode 100644 index 0000000..68e7065 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventLeadServiceTest.java @@ -0,0 +1,299 @@ +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.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 org.junit.jupiter.api.BeforeEach; +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 org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +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.anyCollection; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** EventLeadService: matching, capture (NEW / EXISTING, fill blanks only, already captured) and find. */ +@ExtendWith(MockitoExtension.class) +class EventLeadServiceTest { + + private static final long COMPANY = 42L; + private static final long EVENT = 1000L; + private static final long LEAD_UUID = 2000L; + private static final String MOBILE = "+60123456789"; + private static final String EMAIL = "aisyah@example.com"; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository eventLeadInterestRepository; + + private EventLeadService service; + + @BeforeEach + void setUp() { + service = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository); + } + + // --- findMatches --- + + @Test + void matchesByMobileOrEmailNewestFirstAtMostTwenty() { + Lead a = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + when(leadRepository.findMatches(COMPANY, MOBILE, EMAIL, PageRequest.of(0, 20))).thenReturn(List.of(a)); + + List matches = service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, EMAIL)); + + assertThat(matches).extracting(LeadMatch::leadUuid).containsExactly(LEAD_UUID); + assertThat(matches.get(0).eventLeadUuid()).isNull(); + } + + @Test + void blankMobileIsNotMatchedOn() { + when(leadRepository.findMatches(eq(COMPANY), eq(null), eq(EMAIL), any())).thenReturn(List.of()); + + service.findMatches(new LeadMatchRequest(COMPANY, EVENT, " ", EMAIL)); + + verify(leadRepository).findMatches(eq(COMPANY), eq(null), eq(EMAIL), any()); + } + + @Test + void blankEmailIsNotMatchedOn() { + when(leadRepository.findMatches(eq(COMPANY), eq(MOBILE), eq(null), any())).thenReturn(List.of()); + + service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, "")); + + verify(leadRepository).findMatches(eq(COMPANY), eq(MOBILE), eq(null), any()); + } + + @Test + void bothBlankFindsNothingWithoutQuerying() { + assertThat(service.findMatches(new LeadMatchRequest(COMPANY, EVENT, null, " "))).isEmpty(); + verify(leadRepository, never()).findMatches(anyLong(), any(), any(), any()); + } + + @Test + void matchAlreadyCapturedAtThisEventCarriesItsEventLeadUuid() { + Lead a = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + Lead b = lead(LEAD_UUID + 1, "Ahmad", MOBILE, null, null); + when(leadRepository.findMatches(eq(COMPANY), eq(MOBILE), eq(null), any())).thenReturn(List.of(a, b)); + EventLead captured = eventLead(LEAD_UUID, "NEW"); + when(eventLeadRepository.findByEventUuidAndLeadUuidIn(eq(EVENT), anyCollection())).thenReturn(List.of(captured)); + + List matches = service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, null)); + + assertThat(matches.get(0).eventLeadUuid()).isEqualTo(captured.getUuid()); + assertThat(matches.get(1).eventLeadUuid()).isNull(); + } + + // --- capture --- + + @Test + void newPersonCreatesLeadAndNewEventLeadWithInterests() { + when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> withId(inv.getArgument(0), 7L)); + + EventLeadDetail detail = service.capture(request(null, "Aisyah", MOBILE, EMAIL, "Acme", List.of(3L, 3L, 4L))); + + ArgumentCaptor lead = ArgumentCaptor.forClass(Lead.class); + verify(leadRepository).saveAndFlush(lead.capture()); + assertThat(lead.getValue().getCompanyId()).isEqualTo(COMPANY); + assertThat(lead.getValue().getName()).isEqualTo("Aisyah"); + assertThat(lead.getValue().getMobileE164()).isEqualTo(MOBILE); + assertThat(lead.getValue().getEmailNormalised()).isEqualTo(EMAIL); + assertThat(lead.getValue().getNotes()).isNull(); + assertThat(detail.leadType()).isEqualTo("NEW"); + assertThat(detail.status()).isEqualTo("OPEN"); + assertThat(detail.leadUuid()).isEqualTo(lead.getValue().getUuid()); + assertThat(detail.interestIds()).containsExactlyInAnyOrder(3L, 4L); + + @SuppressWarnings("unchecked") + ArgumentCaptor> rows = ArgumentCaptor.forClass(List.class); + verify(eventLeadInterestRepository).saveAll(rows.capture()); + assertThat(rows.getValue()).extracting(r -> r.getId().getEventLeadId()).containsOnly(7L); + assertThat(rows.getValue()).extracting(EventLeadInterest::getCompanyId).containsOnly(COMPANY); + } + + @Test + void pickedLeadIsExistingAndOnlyBlankFieldsAreFilled() { + Lead stored = lead(LEAD_UUID, "Aisyah", MOBILE, null, "Acme"); + stored.setNotes("met at expo"); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(stored)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, LEAD_UUID)).thenReturn(Optional.empty()); + when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> withId(inv.getArgument(0), 8L)); + + EventLeadDetail detail = service.capture(request(LEAD_UUID, "Aisyah Binti Ali", "+60199999999", EMAIL, "Other Co", List.of())); + + assertThat(detail.leadType()).isEqualTo("EXISTING"); + assertThat(stored.getName()).isEqualTo("Aisyah"); + assertThat(stored.getMobileE164()).isEqualTo(MOBILE); + assertThat(stored.getEmailNormalised()).isEqualTo(EMAIL); + assertThat(stored.getCompanyName()).isEqualTo("Acme"); + assertThat(stored.getJobTitle()).isEqualTo("Buyer"); + assertThat(stored.getNotes()).isEqualTo("met at expo"); + assertThat(stored.getUpdatedBy()).isEqualTo("sales1"); + verify(leadRepository).saveAndFlush(stored); + verify(eventLeadInterestRepository, never()).saveAll(any()); + } + + @Test + void alreadyCapturedAtThisEventIsRefusedAndNothingIsWritten() { + Lead stored = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(stored)); + EventLead already = eventLead(LEAD_UUID, "NEW"); + long capturedUuid = already.getUuid(); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, LEAD_UUID)).thenReturn(Optional.of(already)); + + assertThatThrownBy(() -> service.capture(request(LEAD_UUID, "Aisyah", MOBILE, EMAIL, null, List.of(3L)))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("ALREADY_CAPTURED") + .satisfies(e -> assertThat(((ResponseStatusException) e).getBody().getProperties()) + .containsEntry("eventLeadUuid", String.valueOf(capturedUuid))); + verify(leadRepository, never()).saveAndFlush(any()); + verify(eventLeadRepository, never()).saveAndFlush(any()); + verify(eventLeadInterestRepository, never()).saveAll(any()); + } + + @Test + void concurrentCaptureHittingTheUniqueKeyIsAlreadyCaptured() { + Lead stored = lead(LEAD_UUID, "Aisyah", MOBILE, null, null); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(stored)); + when(eventLeadRepository.findByEventUuidAndLeadUuid(EVENT, LEAD_UUID)).thenReturn(Optional.empty()); + when(eventLeadRepository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("uk_event_lead_event_lead")); + + assertThatThrownBy(() -> service.capture(request(LEAD_UUID, "Aisyah", MOBILE, null, null, List.of()))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("ALREADY_CAPTURED"); + } + + @Test + void leadOfAnotherCompanyIsNotFound() { + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.capture(request(LEAD_UUID, "Aisyah", MOBILE, null, null, List.of()))) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + verify(eventLeadRepository, never()).saveAndFlush(any()); + } + + @Test + void captureIsOneTransaction() throws Exception { + assertThat(EventLeadService.class.getMethod("capture", EventLeadCaptureRequest.class) + .isAnnotationPresent(Transactional.class)).isTrue(); + } + + @Test + void mobileAndEmailMatchingDifferentLeadsReturnsBothUnmerged() { + Lead byMobile = lead(LEAD_UUID, "A", MOBILE, null, null); + Lead byEmail = lead(LEAD_UUID + 1, "B", null, "b@example.com", null); + when(leadRepository.findMatches(eq(COMPANY), eq(MOBILE), eq("b@example.com"), any())).thenReturn(List.of(byEmail, byMobile)); + EventLead bHere = eventLead(LEAD_UUID + 1, "NEW"); + when(eventLeadRepository.findByEventUuidAndLeadUuidIn(eq(EVENT), anyCollection())).thenReturn(List.of(bHere)); + + List matches = service.findMatches(new LeadMatchRequest(COMPANY, EVENT, MOBILE, "b@example.com")); + + assertThat(matches).extracting(LeadMatch::name).containsExactly("B", "A"); + assertThat(matches).extracting(LeadMatch::mobileE164).containsExactly(null, MOBILE); + assertThat(matches).extracting(LeadMatch::email).containsExactly("b@example.com", null); + assertThat(matches.get(0).eventLeadUuid()).isEqualTo(bHere.getUuid()); + assertThat(matches.get(1).eventLeadUuid()).isNull(); + } + + @Test + void failureSavingInterestsPropagatesSoTheTransactionRollsBack() { + when(leadRepository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); + when(eventLeadRepository.saveAndFlush(any())).thenAnswer(inv -> withId(inv.getArgument(0), 7L)); + RuntimeException boom = new org.springframework.dao.DataIntegrityViolationException("interest insert failed"); + when(eventLeadInterestRepository.saveAll(any())).thenThrow(boom); + + assertThatThrownBy(() -> service.capture(request(null, "Aisyah", MOBILE, null, null, List.of(3L)))).isSameAs(boom); + } + + // --- findByUuid --- + + @Test + void findByUuidReturnsEventLeadWithLeadAndInterests() { + EventLead el = withId(eventLead(LEAD_UUID, "EXISTING"), 9L); + when(eventLeadRepository.findByUuidAndCompanyId(el.getUuid(), COMPANY)).thenReturn(Optional.of(el)); + when(leadRepository.findByUuidAndCompanyId(LEAD_UUID, COMPANY)).thenReturn(Optional.of(lead(LEAD_UUID, "Aisyah", MOBILE, EMAIL, "Acme"))); + EventLeadInterest row = new EventLeadInterest(); + row.setId(new EventLeadInterestId(9L, 3L)); + when(eventLeadInterestRepository.findByIdEventLeadId(9L)).thenReturn(List.of(row)); + + EventLeadDetail detail = service.findByUuid(COMPANY, el.getUuid()); + + assertThat(detail.name()).isEqualTo("Aisyah"); + assertThat(detail.companyName()).isEqualTo("Acme"); + assertThat(detail.leadType()).isEqualTo("EXISTING"); + assertThat(detail.eventUuid()).isEqualTo(EVENT); + assertThat(detail.interestIds()).containsExactly(3L); + } + + @Test + void findByUuidOfAnotherCompanyIsNotFound() { + when(eventLeadRepository.findByUuidAndCompanyId(5L, COMPANY)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.findByUuid(COMPANY, 5L)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + } + + // --- helpers --- + + private static EventLeadCaptureRequest request(Long leadUuid, String name, String mobile, String email, + String companyName, List interestIds) { + return new EventLeadCaptureRequest(COMPANY, EVENT, leadUuid, name, mobile, email, companyName, "Buyer", + 11L, "HOT", null, interestIds, LocalDate.of(2027, 1, 20), "wants a demo", "sales1"); + } + + private static Lead lead(long uuid, String name, String mobile, String email, String companyName) { + Lead l = new Lead(); + l.setUuid(uuid); + l.setCompanyId(COMPANY); + l.setName(name); + l.setMobileE164(mobile); + l.setEmailNormalised(email); + l.setCompanyName(companyName); + return l; + } + + private static EventLead eventLead(long leadUuid, String type) { + EventLead e = new EventLead(); + e.setCompanyId(COMPANY); + e.setEventUuid(EVENT); + e.setLeadUuid(leadUuid); + e.setLeadType(type); + e.setStatus("OPEN"); + return e; + } + + private static EventLead withId(EventLead e, long id) { + e.setId(id); + return e; + } +}