feat: counter WhatsApp contact lookup and lead-changed notify
GET /counter/lead/whatsappContact returns the company's newest lead for a mobile with its latest salesperson (the Leads list's definition). Event lead capture, registration and salesperson changes notify the WhatsApp service after commit, best effort, never logging the mobile. 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
b13e39ac75
commit
ae96e316ec
11 files changed
+434
-5
No files matched your search
+6
@@ -0,0 +1,6 @@
|
||||
package com.solvway.services.counter.constant;
|
||||
|
||||
public class RestApiWhatsappServiceConstant {
|
||||
public static final String SERVICE_ID_WHATSAPP = "service-whatsapp";
|
||||
public static final String API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED = "/whatsapp/ownership/leadChanged";
|
||||
}
|
||||
+6
@@ -23,6 +23,12 @@ public class LeadController {
|
||||
@GetMapping("/lead/detail/{leadUuid}")
|
||||
public LeadDetail detail(@PathVariable("leadUuid") long leadUuid) { return leadService.detail(null, leadUuid); }
|
||||
|
||||
@GetMapping("/lead/whatsappContact")
|
||||
public WhatsappContact whatsappContact(@RequestParam("companyId") long companyId,
|
||||
@RequestParam("mobileE164") String mobileE164) {
|
||||
return leadService.whatsappContact(companyId, mobileE164);
|
||||
}
|
||||
|
||||
@PostMapping("/lead/update")
|
||||
public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); }
|
||||
}
|
||||
+10
-2
@@ -46,13 +46,16 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
|
||||
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))";
|
||||
|
||||
/** The most recently captured event lead that has a salesperson, per lead; alias sp. Shared by search and the WhatsApp lookup. */
|
||||
String LATEST_SALESPERSON_JOIN = " 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 (: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";
|
||||
|
||||
String SEARCH_FROM = " FROM `lead` l"
|
||||
+ " 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 (: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 (: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"
|
||||
+ LATEST_SALESPERSON_JOIN
|
||||
+ SEARCH_WHERE;
|
||||
|
||||
/**
|
||||
@@ -69,4 +72,9 @@ public interface LeadRepository extends JpaRepository<Lead, Long> {
|
||||
countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE)
|
||||
Page<SummaryRow> search(@Param("companyId") Long companyId, @Param("q") String q,
|
||||
@Param("digits") String digits, Pageable pageable);
|
||||
|
||||
/** Salesperson of the lead's most recently captured event lead that has one; null when none. */
|
||||
@Query(nativeQuery = true, value = "SELECT sp.salesperson_user_id FROM `lead` l" + LATEST_SALESPERSON_JOIN
|
||||
+ " WHERE l.company_id = :companyId AND l.uuid = :leadUuid")
|
||||
Long latestSalespersonUserId(@Param("companyId") long companyId, @Param("leadUuid") long leadUuid);
|
||||
}
|
||||
+21
-2
@@ -53,12 +53,28 @@ public class EventLeadService {
|
||||
private final EventLeadStatusChangeRepository eventLeadStatusChangeRepository;
|
||||
private final EventRepository eventRepository;
|
||||
private final GuestLinker guestLinker;
|
||||
private final WhatsappNotifier whatsappNotifier;
|
||||
|
||||
// ponytail: null event repository and linker keep the pre-invitation wiring working; drop once callers pass both.
|
||||
// ponytail: null event repository, linker and notifier keep older wiring working; drop once callers pass all.
|
||||
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
|
||||
EventLeadInterestRepository eventLeadInterestRepository,
|
||||
EventLeadStatusChangeRepository eventLeadStatusChangeRepository) {
|
||||
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null);
|
||||
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository, null, null, null);
|
||||
}
|
||||
|
||||
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
|
||||
EventLeadInterestRepository eventLeadInterestRepository,
|
||||
EventLeadStatusChangeRepository eventLeadStatusChangeRepository,
|
||||
EventRepository eventRepository, GuestLinker guestLinker) {
|
||||
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository,
|
||||
eventRepository, guestLinker, null);
|
||||
}
|
||||
|
||||
/** The one place every capture or salesperson change tells the WhatsApp service; skipped for a lead with no mobile. */
|
||||
public void notifyLeadChanged(Lead lead) {
|
||||
if (whatsappNotifier != null && lead.getMobileE164() != null) {
|
||||
whatsappNotifier.leadChanged(lead.getCompanyId(), lead.getMobileE164(), lead.getUuid());
|
||||
}
|
||||
}
|
||||
|
||||
/** True when today is one of the event's days. */
|
||||
@@ -144,6 +160,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());
|
||||
notifyLeadChanged(lead);
|
||||
return detail(eventLead, lead, interestIds);
|
||||
}
|
||||
|
||||
@@ -180,6 +197,7 @@ public class EventLeadService {
|
||||
requireCompany(req.companyId());
|
||||
EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
|
||||
boolean salespersonChanged = !Objects.equals(eventLead.getSalespersonUserId(), req.salespersonUserId());
|
||||
eventLead.setSalespersonUserId(req.salespersonUserId());
|
||||
eventLead.setTemperature(blankToNull(req.temperature()));
|
||||
String oldStatus = eventLead.getStatus();
|
||||
@@ -201,6 +219,7 @@ public class EventLeadService {
|
||||
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
|
||||
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
|
||||
if (salespersonChanged) notifyLeadChanged(lead);
|
||||
return detail(eventLead, lead, interestIds);
|
||||
}
|
||||
|
||||
|
||||
+8
@@ -6,6 +6,7 @@ import com.solvway.services.counter.dto.LeadSearchRequest;
|
||||
import com.solvway.services.counter.dto.LeadSummary;
|
||||
import com.solvway.services.counter.dto.LeadUpdateRequest;
|
||||
import com.solvway.services.counter.dto.SharedContact;
|
||||
import com.solvway.services.counter.dto.WhatsappContact;
|
||||
import com.solvway.services.counter.model.Event;
|
||||
import com.solvway.services.counter.model.EventLead;
|
||||
import com.solvway.services.counter.model.Lead;
|
||||
@@ -51,6 +52,13 @@ public class LeadService {
|
||||
: find(companyId, leadUuid));
|
||||
}
|
||||
|
||||
/** The newest lead of the company with this mobile and its latest salesperson; 404 when there is none. */
|
||||
public WhatsappContact whatsappContact(long companyId, String mobileE164) {
|
||||
Lead l = leadRepository.findFirstByCompanyIdAndMobileE164OrderByIdDesc(companyId, mobileE164)
|
||||
.orElseThrow(LeadService::notFound);
|
||||
return new WhatsappContact(l.getUuid(), l.getName(), leadRepository.latestSalespersonUserId(companyId, l.getUuid()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LeadDetail update(LeadUpdateRequest req) {
|
||||
if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED");
|
||||
|
||||
+2
@@ -119,6 +119,7 @@ public class RegistrationService {
|
||||
eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR);
|
||||
eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds());
|
||||
link(req, e, lead);
|
||||
eventLeadService.notifyLeadChanged(lead);
|
||||
return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid()));
|
||||
}
|
||||
|
||||
@@ -133,6 +134,7 @@ public class RegistrationService {
|
||||
eventLeadRepository.save(e);
|
||||
}
|
||||
link(req, e, lead);
|
||||
if (assign) eventLeadService.notifyLeadChanged(lead);
|
||||
return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid()));
|
||||
}
|
||||
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.services.counter.constant.RestApiWhatsappServiceConstant;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Tells the WhatsApp service an event lead was captured or its salesperson changed, so it can re-run ownership
|
||||
* (a lead's mobile edit does not notify; the nightly repair covers it). Best effort: it runs
|
||||
* after the surrounding transaction commits, never throws, and logs the lead uuid only (never the mobile).
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class WhatsappNotifier {
|
||||
private static final int TIMEOUT_MS = 2000;
|
||||
private static final String URL = "http://" + RestApiWhatsappServiceConstant.SERVICE_ID_WHATSAPP
|
||||
+ RestApiWhatsappServiceConstant.API_REST_WHATSAPP_OWNERSHIP_LEAD_CHANGED;
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
public WhatsappNotifier() {
|
||||
// The shared RestTemplate bean has 5 s timeouts; this call must never hold a request thread that long.
|
||||
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
|
||||
f.setConnectTimeout(TIMEOUT_MS);
|
||||
f.setReadTimeout(TIMEOUT_MS);
|
||||
this.restTemplate = new RestTemplate(f);
|
||||
}
|
||||
|
||||
WhatsappNotifier(RestTemplate restTemplate) { this.restTemplate = restTemplate; }
|
||||
|
||||
public void leadChanged(long companyId, String mobileE164, long leadUuid) {
|
||||
if (mobileE164 == null || mobileE164.isBlank()) return;
|
||||
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
send(companyId, mobileE164, leadUuid);
|
||||
return;
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override public void afterCommit() { send(companyId, mobileE164, leadUuid); }
|
||||
});
|
||||
}
|
||||
|
||||
private void send(long companyId, String mobileE164, long leadUuid) {
|
||||
try {
|
||||
restTemplate.postForLocation(URL, Map.of("companyId", companyId, "mobileE164", mobileE164));
|
||||
} catch (Exception e) {
|
||||
// ponytail: no retry; the WhatsApp service also re-resolves ownership when it next sees the contact.
|
||||
log.warn("WhatsApp ownership notify failed for lead {}: {}", leadUuid, e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user