From 909c1754c0c0bcf8411395cd5ed35ad55f7e76b9 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 20:00:28 +0800 Subject: [PATCH] feat(notifications): daily follow-up summary for each salesperson Runs at 08:00 Malaysia time (leads.follow-up-notice.cron). One summary per salesperson per company, collapsed per day so a rerun does not duplicate. Message bodies now keep code before params. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- .../changes/add-lead-notifications/tasks.md | 2 +- .../counter/repo/EventLeadRepository.java | 16 +++++ .../counter/service/FollowUpNoticeJob.java | 46 ++++++++++++++ .../counter/service/StaffNotifier.java | 25 +++++++- .../service/FollowUpNoticeJobTest.java | 60 +++++++++++++++++++ .../counter/service/StaffNotifierTest.java | 15 +++++ 6 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 solvway-services-counter/src/main/java/com/solvway/services/counter/service/FollowUpNoticeJob.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/FollowUpNoticeJobTest.java diff --git a/openspec/changes/add-lead-notifications/tasks.md b/openspec/changes/add-lead-notifications/tasks.md index 0355262..f4c9f20 100644 --- a/openspec/changes/add-lead-notifications/tasks.md +++ b/openspec/changes/add-lead-notifications/tasks.md @@ -15,7 +15,7 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-de - [x] 2.1 services-counter `StaffNotifier` (after commit, 2 s timeout, never throws, ids-only logs). - Lead assigned at capture and on update, not on self-assignment or clearing. - Web sign-up to the salesperson, else the event's sales team; one notification when assigned at capture. -- [ ] 2.2 services-counter daily follow-up summary job (08:00 Asia/Kuala_Lumpur, cron property), one per salesperson with open leads due today or overdue. +- [x] 2.2 services-counter daily follow-up summary job (08:00 Asia/Kuala_Lumpur, cron property), one per salesperson with open leads due today or overdue. - Verify (2.1, 2.2): `mvn -T 1C -B -pl solvway-services-counter -am verify` - [ ] 2.3 services-whatsapp: notify the chat owner after an inbound message is recorded, collapse key `WA:`; no owner, no notification. - Verify: `mvn -T 1C -B -pl solvway-services-whatsapp -am verify` diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java index e655f1b..2e80588 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -8,6 +8,7 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.time.LocalDate; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -63,4 +64,19 @@ public interface EventLeadRepository extends JpaRepository { @Query("SELECT e, l FROM EventLead e, Lead l WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId" + " AND e.eventUuid = :eventUuid AND l.emailNormalised = :email") List findByEventAndEmail(@Param("eventUuid") long eventUuid, @Param("email") String email); + + /** add-lead-notifications: one salesperson's open leads due today and overdue. */ + interface FollowUpRow { + Long getCompanyId(); + Long getSalespersonUserId(); + Long getDueToday(); + Long getOverdue(); + } + + /** Open (not WON or LOST) event leads with a salesperson and a follow-up date today or earlier, per company and salesperson. */ + @Query(nativeQuery = true, value = "SELECT company_id AS companyId, salesperson_user_id AS salespersonUserId," + + " CAST(SUM(next_follow_up_date = :today) AS SIGNED) AS dueToday, CAST(SUM(next_follow_up_date < :today) AS SIGNED) AS overdue" + + " FROM event_lead WHERE salesperson_user_id IS NOT NULL AND status NOT IN ('WON', 'LOST')" + + " AND next_follow_up_date <= :today GROUP BY company_id, salesperson_user_id ORDER BY company_id, salesperson_user_id") + List followUpsDue(@Param("today") LocalDate today); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/FollowUpNoticeJob.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/FollowUpNoticeJob.java new file mode 100644 index 0000000..3f02918 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/FollowUpNoticeJob.java @@ -0,0 +1,46 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadRepository.FollowUpRow; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * add-lead-notifications: every morning, each salesperson with open event leads due today or overdue gets one summary + * in the bell. A second run on the same day refreshes an unread summary instead of adding one (collapse key). + */ +@Component +@Slf4j +public class FollowUpNoticeJob { + private static final ZoneId MALAYSIA = ZoneId.of("Asia/Kuala_Lumpur"); + + private final EventLeadRepository eventLeads; + private final StaffNotifier notifier; + + public FollowUpNoticeJob(EventLeadRepository eventLeads, StaffNotifier notifier) { + this.eventLeads = eventLeads; + this.notifier = notifier; + } + + @Scheduled(cron = "${leads.follow-up-notice.cron:0 0 8 * * *}", zone = "Asia/Kuala_Lumpur") + public void daily() { + int sent = run(LocalDate.now(MALAYSIA)); + log.info("Follow-up summaries sent to {} salespeople", sent); + } + + int run(LocalDate today) { + List rows = eventLeads.followUpsDue(today); + Map> byCompany = rows.stream() + .collect(Collectors.groupingBy(FollowUpRow::getCompanyId, LinkedHashMap::new, Collectors.toList())); + byCompany.forEach((company, list) -> notifier.followUpsDue(company, list, today)); + return rows.size(); + } +} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/StaffNotifier.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/StaffNotifier.java index 00240c7..63aad83 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/StaffNotifier.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/StaffNotifier.java @@ -8,6 +8,7 @@ import com.solvway.services.counter.model.Event; import com.solvway.services.counter.model.EventLead; import com.solvway.services.counter.model.EventSalesperson; import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadRepository.FollowUpRow; import com.solvway.services.counter.repo.EventRepository; import com.solvway.services.counter.repo.EventSalespersonRepository; import lombok.extern.slf4j.Slf4j; @@ -18,6 +19,7 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.client.RestTemplate; +import java.time.LocalDate; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -81,14 +83,35 @@ public class StaffNotifier { send(rows); } + /** The morning summary for one company: one row per salesperson, collapsed for the day (a rerun refreshes it). */ + public void followUpsDue(long companyId, List rows, LocalDate today) { + List> out = new ArrayList<>(); + for (FollowUpRow r : rows) { + Map params = new LinkedHashMap<>(); + params.put("due", r.getDueToday()); + params.put("overdue", r.getOverdue()); + out.add(row(r.getSalespersonUserId(), companyId, "FOLLOW_UP_DUE", "NoticeFollowUpDue", + body("NoticeFollowUpBody", params), "/leads", "FOLLOW_UP:" + today)); + } + if (!out.isEmpty()) send(out); + } + private Map row(long userId, EventLead e, Lead lead, String type, String title) { Map params = new LinkedHashMap<>(); params.put("lead", Objects.toString(lead.getName(), "")); params.put("event", events.findByUuid(e.getEventUuid()).map(Event::getName).orElse("")); - return row(userId, e.getCompanyId(), type, title, Map.of("code", "NoticeLeadBody", "params", params), + return row(userId, e.getCompanyId(), type, title, body("NoticeLeadBody", params), "/leads/" + lead.getUuid(), null); } + /** A message body: code first, then its parameters (stable order, so the stored JSON is predictable). */ + private static Map body(String code, Map params) { + Map m = new LinkedHashMap<>(); + m.put("code", code); + m.put("params", params); + return m; + } + /** One bell row; {@code message} is a code and its parameters, rendered in the reader's language. */ static Map row(long userId, Long companyId, String type, String title, Map message, String link, String collapseKey) { diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/FollowUpNoticeJobTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/FollowUpNoticeJobTest.java new file mode 100644 index 0000000..67df8c8 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/FollowUpNoticeJobTest.java @@ -0,0 +1,60 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.EventLeadRepository.FollowUpRow; +import org.junit.jupiter.api.Test; +import org.springframework.scheduling.annotation.Scheduled; + +import java.time.LocalDate; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +// add-lead-notifications: one morning summary per salesperson with open leads due today or overdue. +class FollowUpNoticeJobTest { + private static final LocalDate TODAY = LocalDate.of(2026, 12, 3); + + private final EventLeadRepository eventLeads = mock(EventLeadRepository.class); + private final StaffNotifier notifier = mock(StaffNotifier.class); + private final FollowUpNoticeJob job = new FollowUpNoticeJob(eventLeads, notifier); + + static FollowUpRow row(long company, long user, long due, long overdue) { + return new FollowUpRow() { + public Long getCompanyId() { return company; } + public Long getSalespersonUserId() { return user; } + public Long getDueToday() { return due; } + public Long getOverdue() { return overdue; } + }; + } + + @Test + void sendsOneSummaryPerSalespersonOnePostPerCompany() { + FollowUpRow a = row(2, 7, 2, 1), b = row(2, 8, 0, 3), c = row(3, 9, 1, 0); + when(eventLeads.followUpsDue(TODAY)).thenReturn(List.of(a, b, c)); + + assertThat(job.run(TODAY)).isEqualTo(3); + + verify(notifier).followUpsDue(2L, List.of(a, b), TODAY); + verify(notifier).followUpsDue(3L, List.of(c), TODAY); + } + + @Test + void nothingDueSendsNothing() { + when(eventLeads.followUpsDue(TODAY)).thenReturn(List.of()); + assertThat(job.run(TODAY)).isZero(); + verify(notifier, never()).followUpsDue(anyLong(), any(), any()); + } + + @Test + void runsAtEightMalaysiaTimeWithAnOverridableCron() throws Exception { + Scheduled s = FollowUpNoticeJob.class.getMethod("daily").getAnnotation(Scheduled.class); + assertThat(s.cron()).isEqualTo("${leads.follow-up-notice.cron:0 0 8 * * *}"); + assertThat(s.zone()).isEqualTo("Asia/Kuala_Lumpur"); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/StaffNotifierTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/StaffNotifierTest.java index 5fb19a6..dbbc729 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/StaffNotifierTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/StaffNotifierTest.java @@ -131,6 +131,21 @@ class StaffNotifierTest { server.verify(); } + @Test + void theFollowUpSummaryGoesToEachSalespersonCollapsedForTheDay() { + server.expect(requestTo(URL)) + .andExpect(content().json("[{\"receiver\":\"7\",\"companyId\":2,\"type\":\"FOLLOW_UP_DUE\",\"title\":\"NoticeFollowUpDue\"," + + "\"link\":\"/leads\",\"collapseKey\":\"FOLLOW_UP:2026-12-03\"," + + "\"message\":\"{\\\"code\\\":\\\"NoticeFollowUpBody\\\",\\\"params\\\":{\\\"due\\\":2,\\\"overdue\\\":1}}\"}," + + "{\"receiver\":\"8\",\"type\":\"FOLLOW_UP_DUE\"}]")) + .andRespond(withSuccess()); + + notifier.followUpsDue(2L, List.of(FollowUpNoticeJobTest.row(2, 7, 2, 1), FollowUpNoticeJobTest.row(2, 8, 0, 3)), + java.time.LocalDate.of(2026, 12, 3)); + + server.verify(); + } + @Test void failuresAreSwallowed() { server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));