feat: company on events, all-company lead lists, shared interests

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-30 19:20:16 +08:00
1 parent c9c0745955
commit a6996841ac
24 files changed
+472 -86

No files matched your search

@@ -40,6 +40,11 @@ public class EventLeadController {
return eventLeadService.findByUuid(companyId, eventLeadUuid);
}
@GetMapping("/eventLead/findByUuid/{eventLeadUuid}")
public EventLeadDetail findByUuid(@PathVariable("eventLeadUuid") long eventLeadUuid) {
return eventLeadService.findByUuid(null, eventLeadUuid);
}
@PostMapping("/eventLead/findByEvent")
public Page<EventLeadDetail> findByEvent(@RequestBody EventLeadSearchRequest req) {
return eventLeadService.search(req);
@@ -20,6 +20,9 @@ public class LeadController {
return leadService.detail(companyId, leadUuid);
}
@GetMapping("/lead/detail/{leadUuid}")
public LeadDetail detail(@PathVariable("leadUuid") long leadUuid) { return leadService.detail(null, leadUuid); }
@PostMapping("/lead/update")
public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); }
}
@@ -5,7 +5,7 @@ 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 companyId,
long eventUuid,
Long leadUuid,
String name,
@@ -21,5 +21,6 @@ public record EventLeadDetail(
LocalDate nextFollowUpDate,
String notes,
LocalDateTime capturedAt,
List<Long> interestIds
List<Long> interestIds,
Long companyId
) {}
@@ -1,5 +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,
/** One event's leads, filtered; null or blank filters are ignored. page is 0-based. companyId null means all companies. */
public record EventLeadSearchRequest(Long companyId, long eventUuid, Long salespersonUserId, String temperature,
String status, Long interestId, String leadType, int page, int size) {}
@@ -4,6 +4,6 @@ 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,
public record EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy) {}
@@ -5,4 +5,4 @@ import java.util.List;
public record LeadDetail(long leadUuid, String name, String mobileE164, String email, String companyName,
String jobTitle, String notes, LocalDateTime createdAt, LocalDateTime updatedAt,
String updatedBy, List<LeadHistoryEntry> history, List<SharedContact> sharedContacts) {}
String updatedBy, List<LeadHistoryEntry> history, List<SharedContact> sharedContacts, Long companyId) {}
@@ -1,4 +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) {}
public record LeadMatchRequest(Long companyId, long eventUuid, String mobileE164, String email) {}
@@ -1,4 +1,4 @@
package com.solvway.services.counter.dto;
/** q is free text (name or email); mobileDigits is digits only. Both optional. */
public record LeadSearchRequest(long companyId, String q, String mobileDigits, int page, int size) {}
/** q is free text (name or email); mobileDigits is digits only. Both optional. companyId null means all companies. */
public record LeadSearchRequest(Long companyId, String q, String mobileDigits, int page, int size) {}
@@ -1,4 +1,4 @@
package com.solvway.services.counter.dto;
public record LeadUpdateRequest(long companyId, long leadUuid, String name, String mobileE164, String email,
public record LeadUpdateRequest(Long companyId, long leadUuid, String name, String mobileE164, String email,
String companyName, String jobTitle, String notes, String doneBy) {}
@@ -22,6 +22,8 @@ public class Event implements Serializable {
private String location;
private LocalDateTime dateStart;
private LocalDateTime dateEnd;
@Column(name = "company_id", updatable = false)
private Long companyId;
private String uploadFloorPlan;
private String uploadStageActivities;
private String uploadLuckyDraw;
@@ -7,13 +7,14 @@ import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "interest", uniqueConstraints = @UniqueConstraint(columnNames = {"company_id", "name"}))
@Table(name = "interest", uniqueConstraints = @UniqueConstraint(columnNames = {"name"}))
public class Interest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long companyId;
/** Unused: interests are one shared list. */
private Long companyId;
private String name;
@@ -21,8 +21,10 @@ public interface EventLeadRepository extends JpaRepository<EventLead, Long> {
Optional<EventLead> findByUuidAndCompanyId(long uuid, long companyId);
Optional<EventLead> findByUuid(long uuid);
String SEARCH_WHERE = " WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId"
+ " AND e.companyId = :companyId AND e.eventUuid = :eventUuid"
+ " AND (:companyId IS NULL OR 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)"
@@ -33,7 +35,7 @@ public interface EventLeadRepository extends JpaRepository<EventLead, Long> {
/** 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,
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);
@@ -53,6 +53,10 @@ public class EventRepositoryImpl implements JpaRepositoryCustom<Event>{
case "name", "location" -> {
predicates.add(cb.like(root.get(k), "%"+value+"%"));
predicatesCount.add(cb.like(rootCount.get(k), "%"+value+"%"));
}
case "companyId" -> {
predicates.add(cb.equal(root.get("companyId"), Long.valueOf(value)));
predicatesCount.add(cb.equal(rootCount.get("companyId"), Long.valueOf(value)));
}
case "enabled" -> {
predicates.add(cb.equal(root.get(k), GeneralEnum.FlagYesNo.valueOf(value)));
@@ -9,9 +9,9 @@ import java.util.List;
@Repository
public interface InterestRepository extends JpaRepository<Interest, Long> {
List<Interest> findByCompanyIdOrderBySortOrderAscNameAsc(long companyId);
List<Interest> findAllByOrderBySortOrderAscNameAsc();
boolean existsByCompanyIdAndNameIgnoreCase(long companyId, String name);
boolean existsByNameIgnoreCase(String name);
List<Interest> findByIdInAndCompanyId(Collection<Long> ids, long companyId);
List<Interest> findByIdIn(Collection<Long> ids);
}
@@ -21,6 +21,8 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
Optional<Lead> findByUuidAndCompanyId(long uuid, long companyId);
Optional<Lead> findByUuid(long uuid);
interface SummaryRow {
long getLeadUuid();
String getName();
@@ -36,16 +38,16 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
}
/** The search condition uses only `lead` columns, so the count skips the aggregate joins. */
String SEARCH_WHERE = " WHERE l.company_id = :companyId AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'"
String SEARCH_WHERE = " WHERE (:companyId IS NULL OR l.company_id = :companyId) AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'"
+ " OR l.email_normalised LIKE :q ESCAPE '\\\\' OR (:digits IS NOT NULL AND l.mobile_e164 LIKE :digits))";
String SEARCH_FROM = " FROM `lead` l"
+ " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE company_id = :companyId GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid"
+ " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid"
+ " LEFT JOIN (SELECT lead_uuid, event_uuid, captured_at, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn"
+ " FROM event_lead WHERE company_id = :companyId) last ON last.lead_uuid = l.uuid AND last.rn = 1"
+ " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId)) last ON last.lead_uuid = l.uuid AND last.rn = 1"
+ " LEFT JOIN `event` ev ON ev.uuid = last.event_uuid"
+ " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn"
+ " FROM event_lead WHERE company_id = :companyId AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1"
+ " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1"
+ SEARCH_WHERE;
/**
@@ -60,6 +62,6 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
+ " sp.salesperson_user_id AS latestSalespersonUserId" + SEARCH_FROM
+ " ORDER BY last.captured_at IS NULL, last.captured_at DESC, l.id DESC",
countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE)
Page<SummaryRow> search(@Param("companyId") long companyId, @Param("q") String q,
Page<SummaryRow> search(@Param("companyId") Long companyId, @Param("q") String q,
@Param("digits") String digits, Pageable pageable);
}
@@ -47,6 +47,7 @@ public class EventLeadService {
private final EventLeadInterestRepository eventLeadInterestRepository;
public List<LeadMatch> findMatches(LeadMatchRequest req) {
requireCompany(req.companyId());
String mobile = blankToNull(req.mobileE164());
String email = blankToNull(req.email());
if (mobile == null && email == null) return List.of();
@@ -64,6 +65,7 @@ public class EventLeadService {
@Transactional
public EventLeadDetail capture(EventLeadCaptureRequest req) {
requireCompany(req.companyId());
Lead lead;
String leadType;
if (req.leadUuid() == null) {
@@ -117,10 +119,12 @@ public class EventLeadService {
return detail(eventLead, lead, interestIds);
}
public EventLeadDetail findByUuid(long companyId, long eventLeadUuid) {
EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId)
/** A null company looks the event lead up across all companies; the detail reports the record's own company. */
public EventLeadDetail findByUuid(Long companyId, long eventLeadUuid) {
EventLead eventLead = (companyId == null ? eventLeadRepository.findByUuid(eventLeadUuid)
: eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), companyId)
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), eventLead.getCompanyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
List<Long> interestIds = eventLeadInterestRepository.findByIdEventLeadId(eventLead.getId()).stream()
.map(r -> r.getId().getInterestId()).toList();
@@ -145,6 +149,7 @@ public class EventLeadService {
@Transactional
public EventLeadDetail update(EventLeadUpdateRequest req) {
requireCompany(req.companyId());
EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
eventLead.setSalespersonUserId(req.salespersonUserId());
@@ -162,6 +167,10 @@ public class EventLeadService {
return detail(eventLead, lead, interestIds);
}
private static void requireCompany(Long companyId) {
if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
}
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()) {
@@ -178,7 +187,7 @@ public class EventLeadService {
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);
e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds, e.getCompanyId());
}
private static void fillBlank(String current, String offered, Consumer<String> setter) {
@@ -12,6 +12,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@@ -36,6 +38,13 @@ public class EventService {
}
@Transactional
public Event save(Event event) {
if (event.getId() == null) {
if (event.getCompanyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
} else {
// company is immutable: always carry the stored one so entity and cache match the DB
Optional<Event> stored = eventRepository.findById(event.getId());
if (stored.isPresent()) event.setCompanyId(stored.get().getCompanyId());
}
event = eventRepository.save(event);
updateEventCache(event);
return event;
@@ -17,7 +17,7 @@ public class InterestService {
private final InterestRepository interestRepository;
public List<Interest> findByCompany(long companyId) {
return interestRepository.findByCompanyIdOrderBySortOrderAscNameAsc(companyId);
return interestRepository.findAllByOrderBySortOrderAscNameAsc();
}
@Transactional
@@ -36,21 +36,18 @@ public class InterestService {
try {
if (interest.getId() == null) {
// Create: check duplicate name for this company
if (interestRepository.existsByCompanyIdAndNameIgnoreCase(interest.getCompanyId(), trimmedName)) {
// Create: names are unique across the one shared list
interest.setCompanyId(null);
if (interestRepository.existsByNameIgnoreCase(trimmedName)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME");
}
return interestRepository.saveAndFlush(interest);
} else {
// Update: verify the row belongs to this company
Interest existing = interestRepository.findById(interest.getId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
if (existing.getCompanyId() != interest.getCompanyId()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
// Check duplicate name within the same company, excluding this row
interest.setCompanyId(existing.getCompanyId());
if (!existing.getName().equalsIgnoreCase(trimmedName)
&& interestRepository.existsByCompanyIdAndNameIgnoreCase(interest.getCompanyId(), trimmedName)) {
&& interestRepository.existsByNameIgnoreCase(trimmedName)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME");
}
return interestRepository.saveAndFlush(interest);
@@ -64,6 +61,6 @@ public class InterestService {
if (ids == null || ids.isEmpty()) {
return List.of();
}
return interestRepository.findByIdInAndCompanyId(ids, companyId);
return interestRepository.findByIdIn(ids);
}
}
@@ -44,12 +44,16 @@ public class LeadService {
r.getLastCapturedAt(), r.getLatestSalespersonUserId()));
}
public LeadDetail detail(long companyId, long leadUuid) {
return detail(find(companyId, leadUuid));
/** A null company looks the lead up across all companies; the detail reports the lead's own company. */
public LeadDetail detail(Long companyId, long leadUuid) {
return detail(companyId == null
? leadRepository.findByUuid(leadUuid).orElseThrow(LeadService::notFound)
: find(companyId, leadUuid));
}
@Transactional
public LeadDetail update(LeadUpdateRequest req) {
if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
Lead lead = find(req.companyId(), req.leadUuid());
lead.setName(req.name());
lead.setMobileE164(req.mobileE164());
@@ -64,7 +68,11 @@ public class LeadService {
private Lead find(long companyId, long leadUuid) {
return leadRepository.findByUuidAndCompanyId(leadUuid, companyId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"));
.orElseThrow(LeadService::notFound);
}
private static ResponseStatusException notFound() {
return new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND");
}
private LeadDetail detail(Lead l) {
@@ -85,6 +93,6 @@ public class LeadService {
l.getEmailNormalised() != null && Objects.equals(l.getEmailNormalised(), o.getEmailNormalised())))
.toList();
return new LeadDetail(l.getUuid(), l.getName(), l.getMobileE164(), l.getEmailNormalised(), l.getCompanyName(),
l.getJobTitle(), l.getNotes(), l.getCreatedAt(), l.getUpdatedAt(), l.getUpdatedBy(), history, shared);
l.getJobTitle(), l.getNotes(), l.getCreatedAt(), l.getUpdatedAt(), l.getUpdatedBy(), history, shared, l.getCompanyId());
}
}