feat: event days, guest linking, attendance and event headcount

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 16:41:37 +08:00
1 parent d7a11ab71c
commit 84bc0e5e11
22 files changed
+1036 -19

No files matched your search

@@ -1,6 +1,7 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.service.EventHeadcountService;
import com.solvway.services.counter.service.EventService;
import com.solvway.services.counter.util.paging.PageableRest;
import lombok.AllArgsConstructor;
@@ -22,6 +23,7 @@ import java.util.Optional;
public class EventController {
private final EventService eventService;
private final ModelMapper modelMapper;
private final EventHeadcountService headcountService;
@GetMapping("/findAll")
public List<Event> findAll(){
return eventService.findAll();
@@ -35,6 +37,11 @@ public class EventController {
return eventService.findByUuid(uuid);
}
@PostMapping("/attendance")
public EventHeadcountService.Headcount attendance(@RequestBody EventHeadcountService.Request req) {
return headcountService.headcount(req);
}
@PostMapping("/save")
public Event save(@RequestBody Event event) {
return eventService.save(event);
@@ -3,7 +3,12 @@ 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. */
/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. attended: true stamps now if empty, false clears, null leaves it. */
public record EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy) {}
String doneBy, Boolean attended) {
public EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) {
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, null);
}
}
@@ -24,6 +24,8 @@ public class Event implements Serializable {
private LocalDateTime dateEnd;
@Column(name = "company_id", updatable = false)
private Long companyId;
private Integer capacity;
private Integer invitationCap;
private String uploadFloorPlan;
private String uploadStageActivities;
private String uploadLuckyDraw;
@@ -0,0 +1,68 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/** A person invited to an event; linked to an event lead once they register or are captured. */
@Getter
@Setter
@Entity
@Table(name = "event_guest", uniqueConstraints = {
@UniqueConstraint(columnNames = {"token"}),
@UniqueConstraint(columnNames = {"event_uuid", "mobile_e164"}),
@UniqueConstraint(columnNames = {"event_uuid", "email"})
})
public class EventGuest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "company_id")
private long companyId;
@Column(name = "event_uuid")
private long eventUuid;
private String name;
@Column(name = "mobile_e164")
private String mobileE164;
private String email;
@Column(name = "company_name")
private String companyName;
@Column(name = "salesperson_user_id")
private Long salespersonUserId;
@Column(length = 32)
private String token;
@Column(name = "invited_at")
private LocalDateTime invitedAt;
@Column(name = "invite_sent_count")
private int inviteSentCount = 0;
@Column(name = "registered_at")
private LocalDateTime registeredAt;
@Column(name = "event_lead_id")
private Long eventLeadId;
@Column(name = "created_by", updatable = false)
private String createdBy;
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt = LocalDateTime.now();
@Column(name = "updated_by")
private String updatedBy;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
}
@@ -55,6 +55,9 @@ public class EventLead {
private Long consentNoticeId;
@Column(name = "attended_at")
private LocalDateTime attendedAt;
@Column(updatable = false)
private LocalDateTime capturedAt = LocalDateTime.now();
@@ -0,0 +1,20 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.EventGuest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface EventGuestRepository extends JpaRepository<EventGuest, Long> {
Optional<EventGuest> findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(long eventUuid, String mobileE164);
Optional<EventGuest> findFirstByEventUuidAndEventLeadIdIsNullAndEmail(long eventUuid, String email);
boolean existsByEventLeadId(Long eventLeadId);
long countByEventUuid(long eventUuid);
long countByEventUuidAndEventLeadIdIsNotNull(long eventUuid);
}
@@ -40,6 +40,13 @@ public interface EventLeadRepository extends JpaRepository<EventLead, Long> {
@Param("status") String status, @Param("interestId") Long interestId,
@Param("leadType") String leadType, Pageable pageable);
long countByEventUuidAndAttendedAtIsNotNull(long eventUuid);
/** Event leads of the event that no guest row links to. */
@Query("SELECT COUNT(e) FROM EventLead e WHERE e.eventUuid = :eventUuid"
+ " AND NOT EXISTS (SELECT 1 FROM EventGuest g WHERE g.eventLeadId = e.id)")
long countWalkIns(@Param("eventUuid") long eventUuid);
/** Rows are [EventLead, Event]; Event is null when the event row is gone. Newest capture first. */
@Query("SELECT e, ev FROM EventLead e LEFT JOIN Event ev ON ev.uuid = e.eventUuid"
+ " WHERE e.companyId = :companyId AND e.leadUuid = :leadUuid ORDER BY e.capturedAt DESC, e.id DESC")
@@ -0,0 +1,33 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventRepository;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
/** Invited / registered / attended numbers of one event. */
@Service
@AllArgsConstructor
public class EventHeadcountService {
public record Request(Long companyId, long eventUuid) {}
/** total = registered guests + walk-ins (event leads with no guest row). */
public record Headcount(long invited, Integer cap, long registered, long attended, long walkIns, long total, Integer capacity) {}
private final EventRepository eventRepository;
private final EventGuestRepository guestRepository;
private final EventLeadRepository eventLeadRepository;
public Headcount headcount(Request req) {
var event = eventRepository.findByUuid(req.eventUuid())
.filter(e -> req.companyId() != null && req.companyId().equals(e.getCompanyId()))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"));
long registered = guestRepository.countByEventUuidAndEventLeadIdIsNotNull(req.eventUuid());
long walkIns = eventLeadRepository.countWalkIns(req.eventUuid());
return new Headcount(guestRepository.countByEventUuid(req.eventUuid()), event.getInvitationCap(), registered,
eventLeadRepository.countByEventUuidAndAttendedAtIsNotNull(req.eventUuid()), walkIns, registered + walkIns,
event.getCapacity());
}
}
@@ -14,8 +14,11 @@ import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.LeadRepository;
import com.solvway.services.counter.util.EventDays;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@@ -39,7 +42,7 @@ import java.util.stream.Collectors;
* Never log a lead's name, mobile or email.
*/
@Service
@AllArgsConstructor
@AllArgsConstructor(onConstructor_ = @Autowired)
public class EventLeadService {
private static final int MAX_MATCHES = 20;
private static final int MAX_PAGE_SIZE = 100;
@@ -48,6 +51,25 @@ public class EventLeadService {
private final EventLeadRepository eventLeadRepository;
private final EventLeadInterestRepository eventLeadInterestRepository;
private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
private final EventRepository eventRepository;
private final GuestLinker guestLinker;
// ponytail: null event repository and linker keep the pre-invitation wiring working; drop once callers pass both.
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
EventLeadInterestRepository eventLeadInterestRepository,
EventLeadStatusChangeRepository eventLeadStatusChangeRepository) {
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null);
}
/** True when today is one of the event's days. */
public boolean isDuringEvent(long eventUuid) {
return eventRepository != null && eventRepository.findByUuid(eventUuid)
.map(e -> EventDays.isDuring(e, LocalDateTime.now())).orElse(false);
}
public void linkGuest(long eventUuid, EventLead eventLead, Lead lead) {
if (guestLinker != null) guestLinker.link(eventUuid, eventLead, lead);
}
public List<LeadMatch> findMatches(LeadMatchRequest req) {
requireCompany(req.companyId());
@@ -111,6 +133,7 @@ public class EventLeadService {
eventLead.setNextFollowUpDate(req.nextFollowUpDate());
eventLead.setNotes(req.notes());
eventLead.setCapturedBy(req.doneBy());
if (isDuringEvent(req.eventUuid())) eventLead.setAttendedAt(LocalDateTime.now());
try {
eventLead = eventLeadRepository.saveAndFlush(eventLead);
} catch (DataIntegrityViolationException e) {
@@ -119,6 +142,7 @@ public class EventLeadService {
}
recordStatusChange(eventLead, null, eventLead.getStatus(), eventLead.getCapturedAt(), req.doneBy());
linkGuest(req.eventUuid(), eventLead, lead);
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
return detail(eventLead, lead, interestIds);
}
@@ -162,6 +186,11 @@ public class EventLeadService {
if (req.status() != null) eventLead.setStatus(req.status());
eventLead.setNextFollowUpDate(req.nextFollowUpDate());
eventLead.setNotes(blankToNull(req.notes()));
if (Boolean.TRUE.equals(req.attended())) {
if (eventLead.getAttendedAt() == null) eventLead.setAttendedAt(LocalDateTime.now());
} else if (Boolean.FALSE.equals(req.attended())) {
eventLead.setAttendedAt(null);
}
eventLead.setUpdatedBy(req.doneBy());
eventLead.setUpdatedAt(LocalDateTime.now());
eventLead = eventLeadRepository.saveAndFlush(eventLead);
@@ -2,12 +2,14 @@ package com.solvway.services.counter.service;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.util.paging.PageableRest;
import com.solvway.services.counter.util.redis.RedisUtil;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.annotation.EnableScheduling;
@@ -24,11 +26,17 @@ import java.util.concurrent.TimeUnit;
@Service
@Slf4j
@AllArgsConstructor
@AllArgsConstructor(onConstructor_ = @Autowired)
@EnableScheduling
public class EventService {
private final EventRepository eventRepository;
private final RedisUtil<Event> redisUtil;
private final EventGuestRepository guestRepository;
// ponytail: null guest repository skips the cap-below-guests check; drop once callers pass one.
public EventService(EventRepository eventRepository, RedisUtil<Event> redisUtil) {
this(eventRepository, redisUtil, null);
}
private static final String EVENT_CACHE_PREFIX = "service:counter:event:";
private static final String EVENT_CACHE_CURRENT_PREFIX="service:counter:event:current:";
@PostConstruct
@@ -38,12 +46,20 @@ public class EventService {
}
@Transactional
public Event save(Event event) {
if (event.getCapacity() != null && event.getCapacity() < 1) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "CAPACITY_INVALID");
if (event.getInvitationCap() != null && event.getInvitationCap() < 1) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVITATION_CAP_INVALID");
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());
if (stored.isPresent()) {
event.setCompanyId(stored.get().getCompanyId());
if (event.getInvitationCap() != null && guestRepository != null
&& guestRepository.countByEventUuid(stored.get().getUuid()) > event.getInvitationCap()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "CAP_BELOW_GUESTS");
}
}
}
event = eventRepository.save(event);
updateEventCache(event);
@@ -0,0 +1,33 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.EventGuest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventGuestRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Optional;
/** Links an unlinked guest of the event to the event lead that matches by mobile, else email. Never logs contact data. */
@Service
@AllArgsConstructor
public class GuestLinker {
private final EventGuestRepository guests;
// ponytail: unlocked read-modify-write; two concurrent captures could link the same guest (last write wins). Upgrade: SELECT ... FOR UPDATE on the guest row.
public void link(long eventUuid, EventLead eventLead, Lead lead) {
if (guests.existsByEventLeadId(eventLead.getId())) return;
Optional<EventGuest> guest = lead.getMobileE164() == null ? Optional.empty()
: guests.findFirstByEventUuidAndEventLeadIdIsNullAndMobileE164(eventUuid, lead.getMobileE164());
if (guest.isEmpty() && lead.getEmailNormalised() != null) {
guest = guests.findFirstByEventUuidAndEventLeadIdIsNullAndEmail(eventUuid, lead.getEmailNormalised());
}
guest.ifPresent(g -> {
g.setEventLeadId(eventLead.getId());
if (g.getRegisteredAt() == null) g.setRegisteredAt(LocalDateTime.now());
guests.save(g);
});
}
}
@@ -19,7 +19,9 @@ import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/** QR registration codes per event: one event code and one personal code per salesperson. */
@@ -34,7 +36,7 @@ public class RegistrationLinkService {
public record LinkView(long eventUuid, Long salespersonUserId, String token, boolean enabled) {}
public record LinkLookup(long companyId, long eventUuid, Long salespersonUserId, String token, boolean enabled) {}
public record MineRow(String eventUuid, String eventName, String startDate, String endDate, String location,
String token, boolean enabled) {}
String token, boolean enabled, String addedAt) {}
private final RegistrationLinkRepository linkRepository;
private final EventRepository eventRepository;
@@ -73,16 +75,18 @@ public class RegistrationLinkService {
@Transactional
public List<MineRow> mine(MineRequest req) {
LocalDate today = LocalDate.parse(req.today());
List<Long> uuids = eventSalespersonRepository.findByCompanyIdAndUserId(req.companyId(), req.userId()).stream()
.map(EventSalesperson::getEventUuid).toList();
if (uuids.isEmpty()) return List.of();
return eventRepository.findByCompanyIdAndUuidIn(req.companyId(), uuids).stream()
Map<Long, LocalDateTime> addedAt = new HashMap<>();
eventSalespersonRepository.findByCompanyIdAndUserId(req.companyId(), req.userId())
.forEach(r -> addedAt.putIfAbsent(r.getEventUuid(), r.getCreateDateTime()));
if (addedAt.isEmpty()) return List.of();
return eventRepository.findByCompanyIdAndUuidIn(req.companyId(), addedAt.keySet()).stream()
.filter(e -> e.getEnabled() == GeneralEnum.FlagYesNo.Y && e.getDateEnd() != null && !e.getDateEnd().toLocalDate().isBefore(today))
.sorted(Comparator.comparing(Event::getDateStart, Comparator.nullsLast(Comparator.naturalOrder())))
.map(e -> {
RegistrationLink l = personal(req.companyId(), e.getUuid(), req.userId());
return new MineRow(String.valueOf(e.getUuid()), e.getName(), e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString(),
e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled());
e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled(),
addedAt.get(e.getUuid()) == null ? null : addedAt.get(e.getUuid()).toString());
}).toList();
}
@@ -5,6 +5,7 @@ import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.LeadRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
@@ -19,11 +20,18 @@ import java.util.Optional;
* Never log a lead's name, mobile or email.
*/
@Service
@AllArgsConstructor
@AllArgsConstructor(onConstructor_ = @Autowired)
public class RegistrationService {
public record RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164,
String email, String companyName, String jobTitle, List<Long> interestIds,
Long consentNoticeId, LocalDateTime consentAt) {}
Long consentNoticeId, LocalDateTime consentAt, boolean attend) {
public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164,
String email, String companyName, String jobTitle, List<Long> interestIds,
Long consentNoticeId, LocalDateTime consentAt) {
this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds,
consentNoticeId, consentAt, false);
}
}
public record RegisterResult(String outcome, String eventLeadUuid) {}
private static final String QR = "qr";
@@ -32,6 +40,13 @@ public class RegistrationService {
private final LeadRepository leadRepository;
private final EventLeadRepository eventLeadRepository;
private final EventLeadService eventLeadService;
private final GuestLinker guestLinker;
// ponytail: null linker keeps the pre-invitation wiring working; drop once callers pass one.
public RegistrationService(TransactionTemplate transactionTemplate, LeadRepository leadRepository,
EventLeadRepository eventLeadRepository, EventLeadService eventLeadService) {
this(transactionTemplate, leadRepository, eventLeadRepository, eventLeadService, null);
}
public RegisterResult register(RegisterRequest req) {
try {
@@ -72,7 +87,7 @@ public class RegistrationService {
} else {
lead = match.get();
Optional<EventLead> captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid());
if (captured.isPresent()) return alreadyCaptured(captured.get(), req.salespersonUserId());
if (captured.isPresent()) return alreadyCaptured(captured.get(), lead, req);
notes = differences(lead, req);
leadType = "EXISTING";
}
@@ -89,21 +104,30 @@ public class RegistrationService {
e.setCapturedBy(QR);
e.setConsentAt(req.consentAt());
e.setConsentNoticeId(req.consentNoticeId());
if (req.attend() || eventLeadService.isDuringEvent(req.eventUuid())) e.setAttendedAt(LocalDateTime.now());
e = eventLeadRepository.saveAndFlush(e);
eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR);
eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds());
link(req, e, lead);
return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid()));
}
private RegisterResult alreadyCaptured(EventLead e, Long salespersonUserId) {
if (e.getSalespersonUserId() == null && salespersonUserId != null) {
e.setSalespersonUserId(salespersonUserId);
private RegisterResult alreadyCaptured(EventLead e, Lead lead, RegisterRequest req) {
boolean assign = e.getSalespersonUserId() == null && req.salespersonUserId() != null;
boolean attend = req.attend() && e.getAttendedAt() == null;
if (assign) e.setSalespersonUserId(req.salespersonUserId());
if (attend) e.setAttendedAt(LocalDateTime.now());
if (assign || attend) {
e.setUpdatedBy(QR);
e.setUpdatedAt(LocalDateTime.now());
eventLeadRepository.save(e);
return new RegisterResult("ASSIGNED", String.valueOf(e.getUuid()));
}
return new RegisterResult("ALREADY_CAPTURED", String.valueOf(e.getUuid()));
link(req, e, lead);
return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid()));
}
private void link(RegisterRequest req, EventLead e, Lead lead) {
if (guestLinker != null) guestLinker.link(req.eventUuid(), e, lead);
}
/** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */
@@ -0,0 +1,18 @@
package com.solvway.services.counter.util;
import com.solvway.services.counter.model.Event;
import java.time.LocalDate;
import java.time.LocalDateTime;
/** Event days are calendar days in the server zone: the whole first and last day count. */
public final class EventDays {
private EventDays() {}
public static boolean isDuring(Event event, LocalDateTime now) {
if (event.getDateEnd() == null) return false;
LocalDate day = now.toLocalDate();
boolean started = event.getDateStart() == null || !day.isBefore(event.getDateStart().toLocalDate());
return started && !day.isAfter(event.getDateEnd().toLocalDate());
}
}