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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 20:00:28 +08:00
1 parent e3f08bc6cf
commit 909c1754c0
6 files changed
+162 -2

No files matched your search

@@ -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:<conversation uuid>`; no owner, no notification.
- Verify: `mvn -T 1C -B -pl solvway-services-whatsapp -am verify`
@@ -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<EventLead, Long> {
@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<Object[]> 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<FollowUpRow> followUpsDue(@Param("today") LocalDate today);
}
@@ -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<FollowUpRow> rows = eventLeads.followUpsDue(today);
Map<Long, List<FollowUpRow>> byCompany = rows.stream()
.collect(Collectors.groupingBy(FollowUpRow::getCompanyId, LinkedHashMap::new, Collectors.toList()));
byCompany.forEach((company, list) -> notifier.followUpsDue(company, list, today));
return rows.size();
}
}
@@ -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<FollowUpRow> rows, LocalDate today) {
List<Map<String, Object>> out = new ArrayList<>();
for (FollowUpRow r : rows) {
Map<String, Object> 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<String, Object> row(long userId, EventLead e, Lead lead, String type, String title) {
Map<String, Object> 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<String, Object> body(String code, Map<String, Object> params) {
Map<String, Object> 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<String, Object> row(long userId, Long companyId, String type, String title, Map<String, Object> message,
String link, String collapseKey) {
@@ -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");
}
}
@@ -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));