feat(counter): registration links and QR self-registration capture
Registration links (event code and personal codes, oldest wins on a duplicate), lookup by token, the caller's own codes, and the capture that matches by mobile then email, never edits a matched lead, and records the source and consent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
9c9469f5e5
commit
85b40424ce
12 files changed
+877
-2
No files matched your search
+46
@@ -0,0 +1,46 @@
|
||||
package com.solvway.services.counter.controller;
|
||||
|
||||
import com.solvway.services.counter.service.RegistrationLinkService;
|
||||
import com.solvway.services.counter.service.RegistrationService;
|
||||
import lombok.AllArgsConstructor;
|
||||
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 RegistrationController {
|
||||
private final RegistrationLinkService linkService;
|
||||
private final RegistrationService registrationService;
|
||||
|
||||
@PostMapping("/registrationLink/ensure")
|
||||
public List<RegistrationLinkService.LinkView> ensure(@RequestBody RegistrationLinkService.EnsureRequest req) {
|
||||
return linkService.ensure(req);
|
||||
}
|
||||
|
||||
@PostMapping("/registrationLink/setEnabled")
|
||||
public RegistrationLinkService.LinkView setEnabled(@RequestBody RegistrationLinkService.SetEnabledRequest req) {
|
||||
return linkService.setEnabled(req);
|
||||
}
|
||||
|
||||
@GetMapping("/registrationLink/findByToken/{token}")
|
||||
public RegistrationLinkService.LinkLookup findByToken(@PathVariable("token") String token) {
|
||||
return linkService.findByToken(token);
|
||||
}
|
||||
|
||||
@PostMapping("/registrationLink/mine")
|
||||
public List<RegistrationLinkService.MineRow> mine(@RequestBody RegistrationLinkService.MineRequest req) {
|
||||
return linkService.mine(req);
|
||||
}
|
||||
|
||||
@PostMapping("/registration/register")
|
||||
public RegistrationService.RegisterResult register(@RequestBody RegistrationService.RegisterRequest req) {
|
||||
return registrationService.register(req);
|
||||
}
|
||||
}
|
||||
+7
@@ -48,6 +48,13 @@ public class EventLead {
|
||||
|
||||
private String capturedBy;
|
||||
|
||||
/** STAFF (captured in the portal) or QR (self-registered). */
|
||||
private String source = "STAFF";
|
||||
|
||||
private LocalDateTime consentAt;
|
||||
|
||||
private Long consentNoticeId;
|
||||
|
||||
@Column(updatable = false)
|
||||
private LocalDateTime capturedAt = LocalDateTime.now();
|
||||
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.solvway.services.counter.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** A QR registration code: salespersonUserId null is the event code, otherwise a salesperson's personal code. */
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "registration_link")
|
||||
public class RegistrationLink {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private long companyId;
|
||||
|
||||
@Column(name = "event_uuid")
|
||||
private long eventUuid;
|
||||
|
||||
@Column(name = "salesperson_user_id")
|
||||
private Long salespersonUserId;
|
||||
|
||||
private String token;
|
||||
|
||||
private boolean enabled = true;
|
||||
|
||||
@Column(updatable = false)
|
||||
private String createdBy;
|
||||
|
||||
@Column(updatable = false)
|
||||
private LocalDateTime createdAt = LocalDateTime.now();
|
||||
|
||||
private String updatedBy;
|
||||
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+1
@@ -12,6 +12,7 @@ import java.util.Optional;
|
||||
@Repository
|
||||
public interface EventRepository extends JpaRepository<Event,Long> , JpaRepositoryCustom<Event>{
|
||||
Optional<Event> findByUuid(long uuid);
|
||||
java.util.List<Event> findByCompanyIdAndUuidIn(Long companyId, java.util.Collection<Long> uuids);
|
||||
Optional<Event> findTop1ByDateStartLessThanEqualAndDateEndGreaterThanEqualAndEnabledOrderByDateStartDesc(LocalDateTime dateStart, LocalDateTime dateEnd, GeneralEnum.FlagYesNo enabled);
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -13,6 +13,8 @@ import java.util.List;
|
||||
public interface EventSalespersonRepository extends JpaRepository<EventSalesperson, Long> {
|
||||
List<EventSalesperson> findByEventUuid(long eventUuid);
|
||||
|
||||
List<EventSalesperson> findByCompanyIdAndUserId(long companyId, long userId);
|
||||
|
||||
@Modifying
|
||||
@Query("delete from EventSalesperson e where e.eventUuid = :eventUuid")
|
||||
void deleteByEventUuid(@Param("eventUuid") long eventUuid);
|
||||
|
||||
+4
@@ -19,6 +19,10 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
|
||||
List<Lead> findMatches(@Param("companyId") long companyId, @Param("mobile") String mobile,
|
||||
@Param("email") String email, Pageable pageable);
|
||||
|
||||
Optional<Lead> findFirstByCompanyIdAndMobileE164OrderByIdDesc(long companyId, String mobileE164);
|
||||
|
||||
Optional<Lead> findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(long companyId, String emailNormalised);
|
||||
|
||||
Optional<Lead> findByUuidAndCompanyId(long uuid, long companyId);
|
||||
|
||||
Optional<Lead> findByUuid(long uuid);
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.solvway.services.counter.repo;
|
||||
|
||||
import com.solvway.services.counter.model.RegistrationLink;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface RegistrationLinkRepository extends JpaRepository<RegistrationLink, Long> {
|
||||
Optional<RegistrationLink> findByToken(String token);
|
||||
|
||||
Optional<RegistrationLink> findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(long eventUuid, long salespersonUserId);
|
||||
|
||||
List<RegistrationLink> findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(long eventUuid);
|
||||
}
|
||||
+2
-2
@@ -175,7 +175,7 @@ public class EventLeadService {
|
||||
return detail(eventLead, lead, interestIds);
|
||||
}
|
||||
|
||||
private void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) {
|
||||
public void recordStatusChange(EventLead e, String from, String to, LocalDateTime at, String by) {
|
||||
EventLeadStatusChange row = new EventLeadStatusChange();
|
||||
row.setCompanyId(e.getCompanyId());
|
||||
row.setEventLeadId(e.getId());
|
||||
@@ -190,7 +190,7 @@ public class EventLeadService {
|
||||
if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
|
||||
}
|
||||
|
||||
private List<Long> saveInterests(long eventLeadId, long companyId, List<Long> requested) {
|
||||
public List<Long> saveInterests(long eventLeadId, long companyId, List<Long> requested) {
|
||||
List<Long> ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList();
|
||||
if (!ids.isEmpty()) {
|
||||
eventLeadInterestRepository.saveAll(ids.stream().map(id -> {
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.services.counter.model.Event;
|
||||
import com.solvway.services.counter.model.EventSalesperson;
|
||||
import com.solvway.services.counter.model.RegistrationLink;
|
||||
import com.solvway.services.counter.repo.EventRepository;
|
||||
import com.solvway.services.counter.repo.EventSalespersonRepository;
|
||||
import com.solvway.services.counter.repo.RegistrationLinkRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/** QR registration codes per event: one event code and one personal code per salesperson. */
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class RegistrationLinkService {
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
public record EnsureRequest(Long companyId, long eventUuid, List<Long> salespersonUserIds) {}
|
||||
public record SetEnabledRequest(Long companyId, long eventUuid, String token, boolean enabled, String doneBy) {}
|
||||
public record MineRequest(Long companyId, long userId, String today) {}
|
||||
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) {}
|
||||
|
||||
private final RegistrationLinkRepository linkRepository;
|
||||
private final EventRepository eventRepository;
|
||||
private final EventSalespersonRepository eventSalespersonRepository;
|
||||
|
||||
@Transactional
|
||||
public List<LinkView> ensure(EnsureRequest req) {
|
||||
requireEvent(req.companyId(), req.eventUuid());
|
||||
List<RegistrationLink> out = new ArrayList<>();
|
||||
out.add(eventCode(req.companyId(), req.eventUuid()));
|
||||
if (req.salespersonUserIds() != null) {
|
||||
req.salespersonUserIds().stream().filter(Objects::nonNull).distinct()
|
||||
.forEach(uid -> out.add(personal(req.companyId(), req.eventUuid(), uid)));
|
||||
}
|
||||
return out.stream().map(RegistrationLinkService::view).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LinkView setEnabled(SetEnabledRequest req) {
|
||||
requireEvent(req.companyId(), req.eventUuid());
|
||||
RegistrationLink link = linkRepository.findByToken(req.token())
|
||||
.filter(l -> l.getEventUuid() == req.eventUuid() && l.getCompanyId() == req.companyId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
|
||||
link.setEnabled(req.enabled());
|
||||
link.setUpdatedBy(req.doneBy());
|
||||
link.setUpdatedAt(LocalDateTime.now());
|
||||
return view(linkRepository.save(link));
|
||||
}
|
||||
|
||||
public LinkLookup findByToken(String token) {
|
||||
RegistrationLink l = linkRepository.findByToken(token)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
|
||||
return new LinkLookup(l.getCompanyId(), l.getEventUuid(), l.getSalespersonUserId(), l.getToken(), l.isEnabled());
|
||||
}
|
||||
|
||||
@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()
|
||||
.filter(e -> e.getEnabled() == GeneralEnum.FlagYesNo.Y && !e.getDateEnd().toLocalDate().isBefore(today))
|
||||
.sorted(Comparator.comparing(Event::getDateStart))
|
||||
.map(e -> {
|
||||
RegistrationLink l = personal(req.companyId(), e.getUuid(), req.userId());
|
||||
return new MineRow(String.valueOf(e.getUuid()), e.getName(), e.getDateStart().toLocalDate().toString(),
|
||||
e.getDateEnd().toLocalDate().toString(), e.getLocation(), l.getToken(), l.isEnabled());
|
||||
}).toList();
|
||||
}
|
||||
|
||||
private void requireEvent(Long companyId, long eventUuid) {
|
||||
eventRepository.findByUuid(eventUuid)
|
||||
.filter(e -> companyId != null && companyId.equals(e.getCompanyId()))
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "EVENT_NOT_FOUND"));
|
||||
}
|
||||
|
||||
private RegistrationLink eventCode(long companyId, long eventUuid) {
|
||||
List<RegistrationLink> codes = linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(eventUuid);
|
||||
if (codes.isEmpty()) {
|
||||
// The key is not unique, so concurrent first calls can each insert a code and each return its own once
|
||||
// (REPEATABLE READ hides the other insert from this re-read). Later calls converge on the oldest row;
|
||||
// the losing token stays enabled but is never shown.
|
||||
// ponytail: no unique key for personal/event codes; add one, or re-read in a new transaction, if it matters.
|
||||
linkRepository.save(newLink(companyId, eventUuid, null));
|
||||
codes = linkRepository.findByEventUuidAndSalespersonUserIdIsNullOrderByIdAsc(eventUuid);
|
||||
}
|
||||
return codes.get(0);
|
||||
}
|
||||
|
||||
private RegistrationLink personal(long companyId, long eventUuid, long userId) {
|
||||
return linkRepository.findFirstByEventUuidAndSalespersonUserIdOrderByIdAsc(eventUuid, userId)
|
||||
.orElseGet(() -> linkRepository.save(newLink(companyId, eventUuid, userId)));
|
||||
}
|
||||
|
||||
private static RegistrationLink newLink(long companyId, long eventUuid, Long userId) {
|
||||
byte[] bytes = new byte[16];
|
||||
RANDOM.nextBytes(bytes);
|
||||
RegistrationLink l = new RegistrationLink();
|
||||
l.setCompanyId(companyId);
|
||||
l.setEventUuid(eventUuid);
|
||||
l.setSalespersonUserId(userId);
|
||||
l.setToken(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes));
|
||||
l.setCreatedBy("system");
|
||||
return l;
|
||||
}
|
||||
|
||||
private static LinkView view(RegistrationLink l) {
|
||||
return new LinkView(l.getEventUuid(), l.getSalespersonUserId(), l.getToken(), l.isEnabled());
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.services.counter.model.EventLead;
|
||||
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.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* QR self-registration. Values arrive validated and normalised by mobile-api, which also picks the salesperson.
|
||||
* Never log a lead's name, mobile or email.
|
||||
*/
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
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) {}
|
||||
public record RegisterResult(String outcome, String eventLeadUuid) {}
|
||||
|
||||
private static final String QR = "qr";
|
||||
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
private final LeadRepository leadRepository;
|
||||
private final EventLeadRepository eventLeadRepository;
|
||||
private final EventLeadService eventLeadService;
|
||||
|
||||
public RegisterResult register(RegisterRequest req) {
|
||||
try {
|
||||
return transactionTemplate.execute(s -> registerOnce(req));
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
// Any constraint violation lands here, not only uk_event_lead_event_lead (the same person captured at
|
||||
// this event between our lookup and insert); one retry, then the exception propagates.
|
||||
// The failed flush leaves the transaction rollback-only and the session unusable, so the exception
|
||||
// must not be handled inside it. It has been rolled back by now; a second run in a fresh transaction
|
||||
// finds the winner's row by the normal lookup and reports ALREADY_CAPTURED or ASSIGNED.
|
||||
return transactionTemplate.execute(s -> registerOnce(req));
|
||||
}
|
||||
}
|
||||
|
||||
private RegisterResult registerOnce(RegisterRequest req) {
|
||||
Optional<Lead> match = Optional.empty();
|
||||
if (req.mobileE164() != null) {
|
||||
match = leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(req.companyId(), req.mobileE164());
|
||||
}
|
||||
if (match.isEmpty() && req.email() != null) {
|
||||
match = leadRepository.findFirstByCompanyIdAndEmailNormalisedOrderByIdDesc(req.companyId(), req.email());
|
||||
}
|
||||
|
||||
Lead lead;
|
||||
String leadType;
|
||||
String notes = null;
|
||||
if (match.isEmpty()) {
|
||||
lead = new Lead();
|
||||
lead.setCompanyId(req.companyId());
|
||||
lead.setName(req.name());
|
||||
lead.setMobileE164(req.mobileE164());
|
||||
lead.setEmailNormalised(req.email());
|
||||
lead.setCompanyName(req.companyName());
|
||||
lead.setJobTitle(req.jobTitle());
|
||||
lead.setCreatedBy(QR);
|
||||
lead = leadRepository.saveAndFlush(lead);
|
||||
leadType = "NEW";
|
||||
} else {
|
||||
lead = match.get();
|
||||
Optional<EventLead> captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid());
|
||||
if (captured.isPresent()) return alreadyCaptured(captured.get(), req.salespersonUserId());
|
||||
notes = differences(lead, req);
|
||||
leadType = "EXISTING";
|
||||
}
|
||||
|
||||
EventLead e = new EventLead();
|
||||
e.setCompanyId(req.companyId());
|
||||
e.setEventUuid(req.eventUuid());
|
||||
e.setLeadUuid(lead.getUuid());
|
||||
e.setSalespersonUserId(req.salespersonUserId());
|
||||
e.setLeadType(leadType);
|
||||
e.setStatus("OPEN");
|
||||
e.setNotes(notes);
|
||||
e.setSource("QR");
|
||||
e.setCapturedBy(QR);
|
||||
e.setConsentAt(req.consentAt());
|
||||
e.setConsentNoticeId(req.consentNoticeId());
|
||||
e = eventLeadRepository.saveAndFlush(e);
|
||||
eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR);
|
||||
eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds());
|
||||
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);
|
||||
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()));
|
||||
}
|
||||
|
||||
/** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */
|
||||
private static String differences(Lead lead, RegisterRequest req) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
diff(parts, "name", req.name(), lead.getName());
|
||||
diff(parts, "mobile", req.mobileE164(), lead.getMobileE164());
|
||||
diff(parts, "email", req.email(), lead.getEmailNormalised());
|
||||
diff(parts, "company", req.companyName(), lead.getCompanyName());
|
||||
diff(parts, "job title", req.jobTitle(), lead.getJobTitle());
|
||||
return parts.isEmpty() ? null : "Registered by QR with: " + String.join("; ", parts);
|
||||
}
|
||||
|
||||
private static void diff(List<String> parts, String label, String submitted, String current) {
|
||||
if (submitted != null && !submitted.isBlank() && !submitted.equals(current)) parts.add(label + " " + submitted);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user