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());
}
}
@@ -0,0 +1,71 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.util.paging.PageableRest;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Event list search: the optional companyId property filters both the page query and the count query. */
@SuppressWarnings({"unchecked", "rawtypes"})
class EventRepositoryImplCompanyTest {
private CriteriaBuilder cb;
private EventRepositoryImpl repo;
@BeforeEach
void setUp() {
EntityManager em = mock(EntityManager.class, Answers.RETURNS_DEEP_STUBS);
cb = em.getCriteriaBuilder();
TypedQuery<Object> query = mock(TypedQuery.class, Answers.RETURNS_SELF);
when(query.getResultList()).thenReturn(List.of());
when(query.getSingleResult()).thenReturn(0L);
when(em.createQuery(any(CriteriaQuery.class))).thenReturn((TypedQuery) query);
repo = new EventRepositoryImpl();
repo.em = em;
}
private void search(HashMap<String, String> property) {
PageableRest page = new PageableRest();
page.setNumber(0);
page.setSize(10);
PageableRest.SortRest sort = new PageableRest.SortRest();
sort.setDirection("ASC");
sort.setProperty("id");
page.setSorts(new ArrayList<>(java.util.List.of(sort)));
repo.findByPropertyAndPageable(property, page);
}
@Test
void companyIdFiltersPageAndCountQueries() {
HashMap<String, String> p = new HashMap<>();
p.put("companyId", "7");
search(p);
verify(cb, times(2)).equal(any(Expression.class), eq(7L));
}
@Test
void blankOrMissingCompanyIdAddsNoFilter() {
HashMap<String, String> p = new HashMap<>();
p.put("companyId", "");
search(p);
search(new HashMap<>());
verify(cb, never()).equal(any(Expression.class), any(Object.class));
}
}
@@ -0,0 +1,82 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.util.redis.RedisUtil;
import jakarta.persistence.Column;
import org.junit.jupiter.api.BeforeEach;
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.web.server.ResponseStatusException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** EventService: an event keeps the company it was created in. */
@ExtendWith(MockitoExtension.class)
class EventServiceCompanyTest {
@Mock private EventRepository eventRepository;
@Mock private RedisUtil<Event> redisUtil;
private EventService service;
@BeforeEach
void setUp() {
service = new EventService(eventRepository, redisUtil);
lenient().when(eventRepository.save(any(Event.class))).thenAnswer(i -> i.getArgument(0));
}
private static Event event(Long id, Long companyId) {
Event e = new Event();
e.setId(id);
e.setCompanyId(companyId);
return e;
}
@Test
void newEventIsSavedWithItsCompany() {
assertThat(service.save(event(null, 7L)).getCompanyId()).isEqualTo(7L);
}
@Test
void editWithoutCompanyKeepsStoredCompany() {
when(eventRepository.findById(5L)).thenReturn(Optional.of(event(5L, 7L)));
assertThat(service.save(event(5L, null)).getCompanyId()).isEqualTo(7L);
}
@Test
void newEventWithoutCompanyIsRefused() {
assertThatThrownBy(() -> service.save(event(null, null)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode().value()).isEqualTo(400);
assertThat(e.getReason()).isEqualTo("COMPANY_REQUIRED");
});
verify(eventRepository, never()).save(any(Event.class));
}
@Test
void editAlwaysUsesStoredCompany() {
when(eventRepository.findById(5L)).thenReturn(Optional.of(event(5L, 7L)));
assertThat(service.save(event(5L, 9L)).getCompanyId()).isEqualTo(7L);
}
@Test
void companyColumnIsNotUpdatable() throws Exception {
// The column is non-updatable, so a company change can never reach the database.
assertThat(Event.class.getDeclaredField("companyId").getAnnotation(Column.class))
.isNotNull()
.extracting(Column::updatable, Column::name)
.containsExactly(false, "company_id");
}
}
@@ -44,11 +44,11 @@ class InterestServiceTest {
// --- Test 1: findByCompany orders by sortOrder asc, then name asc ---
@Test
void findByCompanyOrdersBySortOrderThenName() {
void findAllOrdersBySortOrderThenName() {
Interest b = makeInterest(2L, COMPANY_A, "banana", true, 5);
Interest a = makeInterest(1L, COMPANY_A, "apple", true, 10);
Interest c = makeInterest(3L, COMPANY_A, "apricot", true, 10);
when(repository.findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A))
when(repository.findAllByOrderBySortOrderAscNameAsc())
.thenReturn(List.of(b, a, c));
List<Interest> result = service.findByCompany(COMPANY_A);
@@ -58,7 +58,7 @@ class InterestServiceTest {
assertThat(result.get(0).getName()).isEqualTo("banana");
assertThat(result.get(1).getName()).isEqualTo("apple");
assertThat(result.get(2).getName()).isEqualTo("apricot");
verify(repository).findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A);
verify(repository).findAllByOrderBySortOrderAscNameAsc();
}
// --- Test 2: save creates a new row (id is null) ---
@@ -69,7 +69,7 @@ class InterestServiceTest {
input.setName(" tech ");
input.setActive(true);
input.setSortOrder(0);
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false);
when(repository.existsByNameIgnoreCase("tech")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> {
Interest saved = inv.getArgument(0);
saved.setId(99L);
@@ -95,7 +95,7 @@ class InterestServiceTest {
input.setName(" new ");
input.setActive(false);
input.setSortOrder(5);
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "new")).thenReturn(false);
when(repository.existsByNameIgnoreCase("new")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
Interest result = service.save(input);
@@ -106,20 +106,23 @@ class InterestServiceTest {
verify(repository).saveAndFlush(any());
}
// --- Test 4: save updates other company's row -> 404 ---
// --- Test 4: any company's user-saved row can be updated: the list is shared, the stored company is kept ---
@Test
void saveUpdatesOtherCompanyRow() {
void saveUpdatesRowOfAnyCompany() {
Interest existing = makeInterest(10L, COMPANY_B, "other", true, 1);
when(repository.findById(10L)).thenReturn(Optional.of(existing));
when(repository.existsByNameIgnoreCase("mine")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
Interest input = new Interest();
input.setId(10L);
input.setCompanyId(COMPANY_A);
input.setName(" mine ");
assertThatThrownBy(() -> service.save(input))
.isInstanceOf(ResponseStatusException.class)
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND);
Interest result = service.save(input);
assertThat(result.getName()).isEqualTo("mine");
assertThat(result.getCompanyId()).isEqualTo(COMPANY_B);
}
// --- Test 5: save duplicate name ignoring case in same company -> 409 ---
@@ -128,7 +131,7 @@ class InterestServiceTest {
Interest input = new Interest();
input.setCompanyId(COMPANY_A);
input.setName(" Tech ");
when(repository.existsByCompanyIdAndNameIgnoreCase(eq(COMPANY_A), any())).thenReturn(true);
when(repository.existsByNameIgnoreCase(any())).thenReturn(true);
assertThatThrownBy(() -> service.save(input))
.isInstanceOf(ResponseStatusException.class)
@@ -136,28 +139,32 @@ class InterestServiceTest {
.hasMessageContaining("DUPLICATE_NAME");
}
// --- Test 6: same name in different company allowed ---
// --- Test 6: same name is refused whichever company asks ---
@Test
void sameNameDifferentCompanyAllowed() {
Interest inputA = new Interest();
inputA.setCompanyId(COMPANY_A);
inputA.setName("tech");
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
void sameNameRefusedRegardlessOfCompany() {
Interest inputB = new Interest();
inputB.setCompanyId(COMPANY_B);
inputB.setName("tech");
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_B, "tech")).thenReturn(false);
when(repository.existsByNameIgnoreCase("tech")).thenReturn(true);
assertThatThrownBy(() -> service.save(inputB))
.isInstanceOf(ResponseStatusException.class)
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT)
.hasMessageContaining("DUPLICATE_NAME");
verify(repository).existsByNameIgnoreCase("tech");
verify(repository, org.mockito.Mockito.never()).saveAndFlush(any());
}
// --- New: a new interest is saved with no company ---
@Test
void newInterestSavedWithNullCompany() {
Interest input = new Interest();
input.setCompanyId(COMPANY_A);
input.setName("fresh");
when(repository.existsByNameIgnoreCase("fresh")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0));
// Company A: no duplicate -> succeeds
service.save(inputA);
// Company B: no duplicate for B -> succeeds
service.save(inputB);
verify(repository).existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech");
verify(repository).existsByCompanyIdAndNameIgnoreCase(COMPANY_B, "tech");
assertThat(service.save(input).getCompanyId()).isNull();
}
// --- Test 7: updating row with same name unchanged is allowed ---
@@ -188,7 +195,7 @@ class InterestServiceTest {
input.setId(10L);
input.setCompanyId(COMPANY_A);
input.setName(" tech ");
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(true);
when(repository.existsByNameIgnoreCase("tech")).thenReturn(true);
assertThatThrownBy(() -> service.save(input))
.isInstanceOf(ResponseStatusException.class)
@@ -202,7 +209,7 @@ class InterestServiceTest {
List<Interest> result = service.findByIds(COMPANY_A, null);
assertThat(result).isEmpty();
verify(repository, org.mockito.Mockito.never()).findByIdInAndCompanyId(any(), eq(COMPANY_A));
verify(repository, org.mockito.Mockito.never()).findByIdIn(any());
}
// --- Test 10: findByIds with empty ids returns empty ---
@@ -211,33 +218,31 @@ class InterestServiceTest {
List<Interest> result = service.findByIds(COMPANY_A, Collections.emptyList());
assertThat(result).isEmpty();
verify(repository, org.mockito.Mockito.never()).findByIdInAndCompanyId(any(), eq(COMPANY_A));
verify(repository, org.mockito.Mockito.never()).findByIdIn(any());
}
// --- Test 11: findByIds returns only company's rows ---
// --- Test 11: findByIds returns the matching rows ---
@Test
void findByIdsFiltersByCompany() {
void findByIdsReturnsMatchingRows() {
Interest row = makeInterest(5L, COMPANY_A, "filter", true, 0);
when(repository.findByIdInAndCompanyId(List.of(5L), COMPANY_A))
when(repository.findByIdIn(List.of(5L)))
.thenReturn(List.of(row));
List<Interest> result = service.findByIds(COMPANY_A, List.of(5L));
assertThat(result).hasSize(1).first().isSameAs(row);
verify(repository).findByIdInAndCompanyId(List.of(5L), COMPANY_A);
verify(repository).findByIdIn(List.of(5L));
}
// --- Test 12: findByIds filters by company — row not in company ---
// --- Test 12: findByIds returns rows of any company; the company argument is ignored ---
@Test
void findByIdsExcludesOtherCompany() {
void findByIdsReturnsRowsOfAnyCompany() {
Interest row = makeInterest(5L, COMPANY_B, "other", true, 0);
when(repository.findByIdInAndCompanyId(List.of(5L), COMPANY_A))
.thenReturn(List.of());
when(repository.findByIdIn(List.of(5L))).thenReturn(List.of(row));
List<Interest> result = service.findByIds(COMPANY_A, List.of(5L));
assertThat(result).isEmpty();
verify(repository).findByIdInAndCompanyId(List.of(5L), COMPANY_A);
assertThat(result).hasSize(1).first().isSameAs(row);
}
// --- Test 13: creating interest with active left unset defaults to true ---
@@ -247,7 +252,7 @@ class InterestServiceTest {
input.setCompanyId(COMPANY_A);
input.setName("default");
// active is left at JVM default (false)
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "default")).thenReturn(false);
when(repository.existsByNameIgnoreCase("default")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> {
Interest saved = inv.getArgument(0);
saved.setId(99L);
@@ -261,17 +266,17 @@ class InterestServiceTest {
// --- Test 14: save then find returns saved interest with trimmed name ---
@Test
void saveThenFindByCompanyReturnsTrimmedName() {
void saveThenFindReturnsTrimmedName() {
Interest input = new Interest();
input.setCompanyId(COMPANY_A);
input.setName(" tech ");
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false);
when(repository.existsByNameIgnoreCase("tech")).thenReturn(false);
when(repository.saveAndFlush(any())).thenAnswer(inv -> {
Interest saved = inv.getArgument(0);
saved.setId(99L);
return saved;
});
when(repository.findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A))
when(repository.findAllByOrderBySortOrderAscNameAsc())
.thenAnswer(inv -> List.of(input));
service.save(input);
@@ -327,7 +332,7 @@ class InterestServiceTest {
Interest input = new Interest();
input.setCompanyId(COMPANY_A);
input.setName("raced");
when(repository.existsByCompanyIdAndNameIgnoreCase(eq(COMPANY_A), any())).thenReturn(false);
when(repository.existsByNameIgnoreCase(any())).thenReturn(false);
when(repository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("duplicate key"));
assertThatThrownBy(() -> service.save(input))
@@ -341,7 +346,7 @@ class InterestServiceTest {
void updateRaceOnUniqueKeyReturns409() {
Interest existing = makeInterest(10L, COMPANY_A, "original", true, 1);
when(repository.findById(10L)).thenReturn(Optional.of(existing));
when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false);
when(repository.existsByNameIgnoreCase("tech")).thenReturn(false);
when(repository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("duplicate key"));
Interest input = new Interest();
@@ -0,0 +1,185 @@
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.LeadDetail;
import com.solvway.services.counter.dto.LeadMatchRequest;
import com.solvway.services.counter.dto.LeadSearchRequest;
import com.solvway.services.counter.dto.LeadUpdateRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
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 org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
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.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/** Leads and event leads: lists take an optional company, details report the record's company, writes need one. */
@ExtendWith(MockitoExtension.class)
class LeadCompanyScopeTest {
private static final long COMPANY = 42L;
@Mock private LeadRepository leadRepository;
@Mock private EventLeadRepository eventLeadRepository;
@Mock private EventLeadInterestRepository eventLeadInterestRepository;
private LeadService leadService;
private EventLeadService eventLeadService;
@BeforeEach
void setUp() {
leadService = new LeadService(leadRepository, eventLeadRepository);
eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository);
}
private static Lead lead(long uuid, long companyId) {
Lead l = new Lead();
l.setUuid(uuid);
l.setCompanyId(companyId);
l.setName("Ann");
return l;
}
private static EventLead eventLead(long uuid, long leadUuid, long companyId) {
EventLead e = new EventLead();
e.setId(1L);
e.setUuid(uuid);
e.setCompanyId(companyId);
e.setLeadUuid(leadUuid);
e.setEventUuid(9L);
return e;
}
// --- lead list ---
@Test
void leadSearchWithoutCompanyPassesNullMeaningAll() {
when(leadRepository.search(any(), any(), any(), any(Pageable.class))).thenReturn(Page.empty());
leadService.search(new LeadSearchRequest(null, "a", null, 0, 20));
verify(leadRepository).search(eq(null), any(), any(), any(Pageable.class));
}
@Test
void leadSearchWithCompanyStillFilters() {
when(leadRepository.search(any(), any(), any(), any(Pageable.class))).thenReturn(Page.empty());
leadService.search(new LeadSearchRequest(COMPANY, "a", null, 0, 20));
verify(leadRepository).search(eq(COMPANY), any(), any(), any(Pageable.class));
}
// --- event lead list ---
@Test
void eventLeadSearchWithoutCompanyPassesNullMeaningAll() {
when(eventLeadRepository.search(any(), anyLong(), any(), any(), any(), any(), any(), any(Pageable.class)))
.thenReturn(Page.empty());
eventLeadService.search(new EventLeadSearchRequest(null, 9L, null, null, null, null, null, 0, 20));
verify(eventLeadRepository).search(eq(null), eq(9L), any(), any(), any(), any(), any(), any(Pageable.class));
}
@Test
void eventLeadSearchWithCompanyStillFilters() {
when(eventLeadRepository.search(any(), anyLong(), any(), any(), any(), any(), any(), any(Pageable.class)))
.thenReturn(Page.empty());
eventLeadService.search(new EventLeadSearchRequest(COMPANY, 9L, null, null, null, null, null, 0, 20));
verify(eventLeadRepository).search(eq(COMPANY), eq(9L), any(), any(), any(), any(), any(), any(Pageable.class));
}
// --- detail ---
@Test
void leadDetailWithNullCompanyReturnsRecordsCompany() {
when(leadRepository.findByUuid(5L)).thenReturn(Optional.of(lead(5L, 7L)));
when(eventLeadRepository.history(anyLong(), anyLong())).thenReturn(List.of());
when(leadRepository.findMatches(anyLong(), any(), any(), any(Pageable.class))).thenReturn(List.of());
LeadDetail d = leadService.detail(null, 5L);
assertThat(d.companyId()).isEqualTo(7L);
verify(leadRepository, never()).findByUuidAndCompanyId(anyLong(), anyLong());
}
@Test
void leadDetailWithCompanyReturnsRecordsCompany() {
when(leadRepository.findByUuidAndCompanyId(5L, COMPANY)).thenReturn(Optional.of(lead(5L, COMPANY)));
when(eventLeadRepository.history(anyLong(), anyLong())).thenReturn(List.of());
when(leadRepository.findMatches(anyLong(), any(), any(), any(Pageable.class))).thenReturn(List.of());
assertThat(leadService.detail(COMPANY, 5L).companyId()).isEqualTo(COMPANY);
}
@Test
void leadDetailWithNullCompanyAndUnknownLeadIs404() {
when(leadRepository.findByUuid(5L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> leadService.detail(null, 5L))
.isInstanceOfSatisfying(ResponseStatusException.class,
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
}
@Test
void eventLeadDetailWithNullCompanyReturnsRecordsCompany() {
when(eventLeadRepository.findByUuid(3L)).thenReturn(Optional.of(eventLead(3L, 5L, 7L)));
when(leadRepository.findByUuidAndCompanyId(5L, 7L)).thenReturn(Optional.of(lead(5L, 7L)));
when(eventLeadInterestRepository.findByIdEventLeadId(1L)).thenReturn(List.of());
EventLeadDetail d = eventLeadService.findByUuid(null, 3L);
assertThat(d.companyId()).isEqualTo(7L);
assertThat(d.leadUuid()).isEqualTo(5L);
}
// --- writes need a company ---
private static void assertBadRequest(Runnable call) {
assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class,
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void captureWithNullCompanyIsRefused() {
assertBadRequest(() -> eventLeadService.capture(new EventLeadCaptureRequest(null, 9L, null, "Ann", null, null,
null, null, null, null, null, null, null, null, "me")));
verifyNoInteractions(leadRepository, eventLeadRepository);
}
@Test
void matchWithNullCompanyIsRefused() {
assertBadRequest(() -> eventLeadService.findMatches(new LeadMatchRequest(null, 9L, "+6012", null)));
verifyNoInteractions(leadRepository);
}
@Test
void eventLeadUpdateWithNullCompanyIsRefused() {
assertBadRequest(() -> eventLeadService.update(new EventLeadUpdateRequest(null, 3L, null, null, null, null, null,
null, "me")));
verifyNoInteractions(eventLeadRepository);
}
@Test
void leadUpdateWithNullCompanyIsRefused() {
assertBadRequest(() -> leadService.update(new LeadUpdateRequest(null, 5L, "Ann", null, null, null, null, null, "me")));
verifyNoInteractions(leadRepository);
}
}