From d5384c6ac042c89acf07214597292d1687820d82 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 19:40:32 +0800 Subject: [PATCH] feat(notifications): staff notification store in services-system Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- local/seed/03-colite.sql | 14 ++ .../sql/01-notification-columns.sql | 19 +++ .../sql/99-rollback.sql | 15 ++ .../changes/add-lead-notifications/tasks.md | 4 +- .../controller/NotificationController.java | 65 +++++---- .../services/system/model/Notification.java | 19 ++- .../system/repo/NotificationRepository.java | 24 +++- .../system/service/NotificationService.java | 91 ++++++++++-- .../NotificationControllerTest.java | 73 ++++++++++ .../service/NotificationServiceTest.java | 134 ++++++++++++++++++ 10 files changed, 411 insertions(+), 47 deletions(-) create mode 100644 openspec/changes/add-lead-notifications/sql/01-notification-columns.sql create mode 100644 openspec/changes/add-lead-notifications/sql/99-rollback.sql create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/NotificationControllerTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/NotificationServiceTest.java diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index e43ef3c..ddd26ab 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -506,3 +506,17 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic -- add-custom-html-block: the hide-header page option USE `service-counter`; ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`; +-- add-lead-notifications: the staff notification bell +USE `service-system`; +ALTER TABLE `notification` + CONVERT TO CHARACTER SET utf8mb4, + ADD COLUMN `recipient_type` char(1) NULL COMMENT 'A = staff user' AFTER `receiver`, + ADD COLUMN `company_id` bigint NULL AFTER `recipient_type`, + ADD COLUMN `title` varchar(255) NULL COMMENT 'Message code' AFTER `company_id`, + ADD COLUMN `type` varchar(45) NULL COMMENT 'LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE, FOLLOW_UP_DUE' AFTER `message`, + ADD COLUMN `link` varchar(512) NULL COMMENT 'Portal path opened on click' AFTER `type`, + ADD COLUMN `collapse_key` varchar(100) NULL COMMENT 'An unread row with the same receiver and key is updated, not duplicated' AFTER `link`, + ADD COLUMN `seen` tinyint(1) NOT NULL DEFAULT 0 AFTER `collapse_key`, + ADD COLUMN `read_at` datetime NULL AFTER `seen`, + ADD INDEX `idx_notification_inbox` (`recipient_type`, `receiver`, `seen`, `create_date_time`), + ADD INDEX `idx_notification_collapse` (`receiver`, `collapse_key`, `seen`); diff --git a/openspec/changes/add-lead-notifications/sql/01-notification-columns.sql b/openspec/changes/add-lead-notifications/sql/01-notification-columns.sql new file mode 100644 index 0000000..80a15d4 --- /dev/null +++ b/openspec/changes/add-lead-notifications/sql/01-notification-columns.sql @@ -0,0 +1,19 @@ +-- Co-Lite change add-lead-notifications: the staff notification bell. +-- Target: `service-system`.`notification`, the unused table from Tastefully. Pre-check (read-only): +-- SELECT COUNT(*) FROM `service-system`.`notification`; -- expect 0 +-- The table is converted to utf8mb4 (names in any script) and gains babyboo's bell columns plus company_id +-- and collapse_key. Existing columns keep their meaning. Run once. +SET NAMES utf8mb4; +USE `service-system`; +ALTER TABLE `notification` + CONVERT TO CHARACTER SET utf8mb4, + ADD COLUMN `recipient_type` char(1) NULL COMMENT 'A = staff user' AFTER `receiver`, + ADD COLUMN `company_id` bigint NULL AFTER `recipient_type`, + ADD COLUMN `title` varchar(255) NULL COMMENT 'Message code' AFTER `company_id`, + ADD COLUMN `type` varchar(45) NULL COMMENT 'LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE, FOLLOW_UP_DUE' AFTER `message`, + ADD COLUMN `link` varchar(512) NULL COMMENT 'Portal path opened on click' AFTER `type`, + ADD COLUMN `collapse_key` varchar(100) NULL COMMENT 'An unread row with the same receiver and key is updated, not duplicated' AFTER `link`, + ADD COLUMN `seen` tinyint(1) NOT NULL DEFAULT 0 AFTER `collapse_key`, + ADD COLUMN `read_at` datetime NULL AFTER `seen`, + ADD INDEX `idx_notification_inbox` (`recipient_type`, `receiver`, `seen`, `create_date_time`), + ADD INDEX `idx_notification_collapse` (`receiver`, `collapse_key`, `seen`); diff --git a/openspec/changes/add-lead-notifications/sql/99-rollback.sql b/openspec/changes/add-lead-notifications/sql/99-rollback.sql new file mode 100644 index 0000000..1c01e8a --- /dev/null +++ b/openspec/changes/add-lead-notifications/sql/99-rollback.sql @@ -0,0 +1,15 @@ +-- Co-Lite change add-lead-notifications: rollback. Drops the bell columns and labels; the previous release never +-- reads them. The charset change is left in place (utf8mb4 holds everything utf8mb3 did). +SET NAMES utf8mb4; +USE `service-system`; +ALTER TABLE `notification` + DROP INDEX `idx_notification_inbox`, + DROP INDEX `idx_notification_collapse`, + DROP COLUMN `recipient_type`, + DROP COLUMN `company_id`, + DROP COLUMN `title`, + DROP COLUMN `type`, + DROP COLUMN `link`, + DROP COLUMN `collapse_key`, + DROP COLUMN `seen`, + DROP COLUMN `read_at`; diff --git a/openspec/changes/add-lead-notifications/tasks.md b/openspec/changes/add-lead-notifications/tasks.md index ead75ce..de1aae2 100644 --- a/openspec/changes/add-lead-notifications/tasks.md +++ b/openspec/changes/add-lead-notifications/tasks.md @@ -4,8 +4,8 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-de ## 1. Store and API -- [ ] 1.1 SQL: `sql/01-notification-columns.sql` (columns, index, `utf8mb4`), `sql/99-rollback.sql`; mirror 01 into `local/seed/`. -- [ ] 1.2 services-system: the extended `Notification`; create (with `collapse_key`), list mine (paged), unread count, mark one read (own rows only), mark all read. +- [x] 1.1 SQL: `sql/01-notification-columns.sql` (columns, index, `utf8mb4`), `sql/99-rollback.sql`; mirror 01 into `local/seed/`. +- [x] 1.2 services-system: the extended `Notification`; create (with `collapse_key`), list mine (paged), unread count, mark one read (own rows only), mark all read. - Verify: `mvn -T 1C -B -pl solvway-services-system -am verify` - [ ] 1.3 mobile-api: `/api/admin/notifications`, `/unread-count`, `/{id}/read`, `/read-all`, user and company from the session. - Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify` diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/NotificationController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/NotificationController.java index ba1b36f..36eb228 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/NotificationController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/NotificationController.java @@ -1,45 +1,52 @@ package com.solvway.services.system.controller; -import com.solvway.services.system.model.Notification; import com.solvway.services.system.service.NotificationService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageRequest; +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; +import java.util.Map; +/** + * add-lead-notifications: internal endpoints of the staff bell. The receiver in a read or mark path is set by + * mobile-api from the caller's session, never from a client. + */ @RequestMapping("/notification") @RestController - public class NotificationController { - - private static final Logger log = LoggerFactory.getLogger(MessageController.class); - @Autowired - private NotificationService notificationService; - - @RequestMapping("/save") - public Notification save(@RequestBody Notification notification) { - try { - return notificationService.save(notification); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - return null; - } - - @RequestMapping("/findAllByReceiver/{receiver}/{page}/{count}") - public List findAllByReceiver(@PathVariable("receiver") String receiver, @PathVariable("page") int page, @PathVariable("count") int count) { - try { - return notificationService.findAllByReceiver(receiver, PageRequest.of(page,count)); - }catch(Exception e){ - log.error(e.getLocalizedMessage(),e); - } - return null; + private final NotificationService service; + + public NotificationController(NotificationService service) { + this.service = service; + } + + @PostMapping("/send") + public Map send(@RequestBody List rows) { + return Map.of("count", service.send(rows)); + } + + @GetMapping("/inbox/{receiver}/{page}/{count}") + public Map inbox(@PathVariable String receiver, @PathVariable int page, @PathVariable int count) { + return service.inbox(receiver, page, count); + } + + @GetMapping("/unreadCount/{receiver}") + public Map unreadCount(@PathVariable String receiver) { + return Map.of("count", service.unreadCount(receiver)); + } + + @PostMapping("/markRead/{receiver}/{id}") + public void markRead(@PathVariable String receiver, @PathVariable long id) { + service.markRead(receiver, id); + } + + @PostMapping("/markAllRead/{receiver}") + public Map markAllRead(@PathVariable String receiver) { + return Map.of("count", service.markAllRead(receiver)); } } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/Notification.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/Notification.java index ef21717..0288dfd 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/model/Notification.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/Notification.java @@ -9,15 +9,30 @@ import lombok.Setter; import java.time.LocalDateTime; +/** + * add-lead-notifications: one bell row per recipient. {@code receiver} is the staff user id; {@code title} and + * {@code message} are a message code and its JSON parameters, rendered in the reader's language by the portal. + */ @Setter @Getter @Entity public class Notification { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; + private long id; private String receiver; + /** 'A' = staff user (the only recipient type today). */ + private String recipientType; + private Long companyId; + private String title; private String message; + /** LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE or FOLLOW_UP_DUE. */ + private String type; + /** Portal path opened on click. */ + private String link; + /** An unread row of the same receiver with this key is updated instead of duplicated. */ + private String collapseKey; + private boolean seen; + private LocalDateTime readAt; private LocalDateTime createDateTime; - } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/NotificationRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/NotificationRepository.java index 576c143..24490f2 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/repo/NotificationRepository.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/NotificationRepository.java @@ -1,14 +1,32 @@ package com.solvway.services.system.repo; import com.solvway.services.system.model.Notification; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.util.List; +import java.time.LocalDateTime; +import java.util.Optional; @Repository -public interface NotificationRepository extends JpaRepository{ +public interface NotificationRepository extends JpaRepository { - List findAllByReceiverOrderByCreateDateTimeDesc(String receiver, Pageable pageable); + Page findAllByRecipientTypeAndReceiverOrderByCreateDateTimeDescIdDesc(String recipientType, String receiver, Pageable pageable); + + long countByRecipientTypeAndReceiverAndSeenFalse(String recipientType, String receiver); + + Optional findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse(String recipientType, String receiver, String collapseKey); + + /** Marks one row read only when it belongs to the caller: a foreign id updates nothing. */ + @Modifying + @Query("update Notification n set n.seen = true, n.readAt = :at where n.id = :id and n.recipientType = :type and n.receiver = :receiver") + int markSeen(@Param("id") long id, @Param("type") String recipientType, @Param("receiver") String receiver, @Param("at") LocalDateTime at); + + @Modifying + @Query("update Notification n set n.seen = true, n.readAt = :at where n.recipientType = :type and n.receiver = :receiver and n.seen = false") + int markAllSeen(@Param("type") String recipientType, @Param("receiver") String receiver, @Param("at") LocalDateTime at); } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/NotificationService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/NotificationService.java index 9bc61fe..705e919 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/NotificationService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/NotificationService.java @@ -2,25 +2,94 @@ package com.solvway.services.system.service; import com.solvway.services.system.model.Notification; import com.solvway.services.system.repo.NotificationRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; +import java.time.LocalDateTime; import java.util.List; +import java.util.Map; +import java.util.Set; +/** + * add-lead-notifications: the staff bell's store. Other services send rows (recipients resolved by the sender); + * the admin API reads and marks the caller's own rows, identified by the session's user id. + */ @Service public class NotificationService { - @Autowired - private NotificationRepository notificationRepository; - - @Transactional - public Notification save(Notification nofication) { - return notificationRepository.save(nofication); + static final String STAFF = "A"; + private static final Set TYPES = Set.of("LEAD_ASSIGNED", "WEB_SIGNUP", "WHATSAPP_MESSAGE", "FOLLOW_UP_DUE"); + private static final int MAX_PAGE = 50; + + /** One notification to store. {@code collapseKey} is optional. */ + public record Send(String receiver, Long companyId, String title, String message, String type, String link, String collapseKey) {} + + private final NotificationRepository repo; + + public NotificationService(NotificationRepository repo) { + this.repo = repo; } - - public List findAllByReceiver(String receiver, Pageable pageable){ - return notificationRepository.findAllByReceiverOrderByCreateDateTimeDesc(receiver, pageable); + + /** + * Stores each row unread. With a collapse key, the receiver's unread row with that key is refreshed instead. + * ponytail: check-then-insert, so two concurrent sends for one key can both insert (two rows at worst). + */ + @Transactional + public int send(List rows) { + rows.forEach(NotificationService::check); + LocalDateTime now = LocalDateTime.now(); + for (Send s : rows) { + Notification n = s.collapseKey() == null ? null + : repo.findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse(STAFF, s.receiver(), s.collapseKey()).orElse(null); + if (n == null) { + n = new Notification(); + n.setRecipientType(STAFF); + n.setReceiver(s.receiver()); + n.setCollapseKey(s.collapseKey()); + } + n.setCompanyId(s.companyId()); + n.setTitle(s.title()); + n.setMessage(s.message()); + n.setType(s.type()); + n.setLink(s.link()); + n.setCreateDateTime(now); + repo.save(n); + } + return rows.size(); + } + + private static void check(Send s) { + boolean ok = s.receiver() != null && !s.receiver().isBlank() && s.receiver().length() <= 45 + && s.companyId() != null && s.title() != null && !s.title().isBlank() + && TYPES.contains(s.type()) + && s.link() != null && s.link().startsWith("/") && !s.link().startsWith("//") && s.link().length() <= 512 + && (s.collapseKey() == null || s.collapseKey().length() <= 100); + if (!ok) throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "notification: invalid row"); + } + + public Map inbox(String receiver, int page, int count) { + Page p = repo.findAllByRecipientTypeAndReceiverOrderByCreateDateTimeDescIdDesc( + STAFF, receiver, PageRequest.of(Math.max(page, 0), Math.min(Math.max(count, 1), MAX_PAGE))); + return Map.of("items", p.getContent(), "total", p.getTotalElements()); + } + + public long unreadCount(String receiver) { + return repo.countByRecipientTypeAndReceiverAndSeenFalse(STAFF, receiver); + } + + @Transactional + public void markRead(String receiver, long id) { + if (repo.markSeen(id, STAFF, receiver, LocalDateTime.now()) == 0) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "notification: not found"); + } + } + + @Transactional + public int markAllRead(String receiver) { + return repo.markAllSeen(STAFF, receiver, LocalDateTime.now()); } } diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/NotificationControllerTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/NotificationControllerTest.java new file mode 100644 index 0000000..e08829a --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/NotificationControllerTest.java @@ -0,0 +1,73 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.service.NotificationService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +// add-lead-notifications: the store's internal endpoints, with explicit methods and real error statuses. +@ExtendWith(MockitoExtension.class) +class NotificationControllerTest { + + @Mock private NotificationService service; + @InjectMocks private NotificationController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void sendStoresTheRows() throws Exception { + when(service.send(anyList())).thenReturn(1); + mvc.perform(post("/notification/send").contentType(MediaType.APPLICATION_JSON) + .content("[{\"receiver\":\"11\",\"companyId\":2,\"title\":\"T\",\"message\":\"{}\",\"type\":\"LEAD_ASSIGNED\",\"link\":\"/event-leads/9\"}]")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.count").value(1)); + verify(service).send(List.of(new NotificationService.Send("11", 2L, "T", "{}", "LEAD_ASSIGNED", "/event-leads/9", null))); + } + + @Test + void inboxCountAndMarks() throws Exception { + when(service.inbox("11", 0, 20)).thenReturn(Map.of("items", List.of(), "total", 0L)); + when(service.unreadCount("11")).thenReturn(3L); + when(service.markAllRead("11")).thenReturn(2); + mvc.perform(get("/notification/inbox/11/0/20")).andExpect(status().isOk()).andExpect(jsonPath("$.total").value(0)); + mvc.perform(get("/notification/unreadCount/11")).andExpect(status().isOk()).andExpect(jsonPath("$.count").value(3)); + mvc.perform(post("/notification/markRead/11/5")).andExpect(status().isOk()); + verify(service).markRead("11", 5L); + mvc.perform(post("/notification/markAllRead/11")).andExpect(status().isOk()).andExpect(jsonPath("$.count").value(2)); + } + + @Test + void aForeignRowIs404() throws Exception { + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(service).markRead("12", 5L); + mvc.perform(post("/notification/markRead/12/5")).andExpect(status().isNotFound()); + } + + @Test + void theOldUncheckedEndpointsAreGone() throws Exception { + mvc.perform(post("/notification/save").contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isNotFound()); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/NotificationServiceTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/NotificationServiceTest.java new file mode 100644 index 0000000..e152d10 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/NotificationServiceTest.java @@ -0,0 +1,134 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.Notification; +import com.solvway.services.system.repo.NotificationRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +// add-lead-notifications: the staff bell's store. Rows come from other services; reads and marks are the caller's own. +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class NotificationServiceTest { + + @Mock private NotificationRepository repo; + private NotificationService service; + + @BeforeEach + void setUp() { + service = new NotificationService(repo); + when(repo.save(any(Notification.class))).thenAnswer(i -> i.getArgument(0)); + } + + private static NotificationService.Send send(String receiver, String collapseKey) { + return new NotificationService.Send(receiver, 2L, "NoticeLeadAssignedTitle", "{\"lead\":\"Tan\"}", "LEAD_ASSIGNED", "/event-leads/9", collapseKey); + } + + @Test + void storesOneUnreadStaffRowPerRecipient() { + assertThat(service.send(List.of(send("11", null), send("12", null)))).isEqualTo(2); + + ArgumentCaptor saved = ArgumentCaptor.forClass(Notification.class); + verify(repo, org.mockito.Mockito.times(2)).save(saved.capture()); + Notification n = saved.getAllValues().get(0); + assertThat(n.getRecipientType()).isEqualTo("A"); + assertThat(n.getReceiver()).isEqualTo("11"); + assertThat(n.getCompanyId()).isEqualTo(2L); + assertThat(n.getTitle()).isEqualTo("NoticeLeadAssignedTitle"); + assertThat(n.getMessage()).isEqualTo("{\"lead\":\"Tan\"}"); + assertThat(n.getType()).isEqualTo("LEAD_ASSIGNED"); + assertThat(n.getLink()).isEqualTo("/event-leads/9"); + assertThat(n.isSeen()).isFalse(); + assertThat(n.getCreateDateTime()).isNotNull(); + } + + @Test + void anUnreadRowWithTheSameCollapseKeyIsUpdatedNotDuplicated() { + Notification unread = new Notification(); + unread.setReceiver("11"); + unread.setMessage("old"); + unread.setCreateDateTime(LocalDateTime.of(2026, 12, 1, 9, 0)); + when(repo.findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse("A", "11", "WA:5")).thenReturn(Optional.of(unread)); + + service.send(List.of(send("11", "WA:5"))); + + verify(repo).save(unread); + assertThat(unread.getMessage()).isEqualTo("{\"lead\":\"Tan\"}"); + assertThat(unread.getCreateDateTime()).isAfter(LocalDateTime.of(2026, 12, 1, 9, 0)); + } + + @Test + void aCollapseKeyWithNoUnreadRowInsertsOne() { + when(repo.findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse("A", "11", "WA:5")).thenReturn(Optional.empty()); + + service.send(List.of(send("11", "WA:5"))); + + ArgumentCaptor saved = ArgumentCaptor.forClass(Notification.class); + verify(repo).save(saved.capture()); + assertThat(saved.getValue().getCollapseKey()).isEqualTo("WA:5"); + } + + @Test + void refusesRowsWithoutARecipientTypeCodeOrCompany() { + for (NotificationService.Send bad : List.of( + new NotificationService.Send(" ", 2L, "T", "{}", "LEAD_ASSIGNED", "/x", null), + new NotificationService.Send("11", null, "T", "{}", "LEAD_ASSIGNED", "/x", null), + new NotificationService.Send("11", 2L, null, "{}", "LEAD_ASSIGNED", "/x", null), + new NotificationService.Send("11", 2L, "T", "{}", "OTHER", "/x", null), + new NotificationService.Send("11", 2L, "T", "{}", "LEAD_ASSIGNED", "https://evil.example/x", null))) { + assertThatThrownBy(() -> service.send(List.of(bad))).isInstanceOf(ResponseStatusException.class); + } + verify(repo, never()).save(any()); + } + + @Test + void readsAndCountsOnlyTheCallersStaffRows() { + when(repo.findAllByRecipientTypeAndReceiverOrderByCreateDateTimeDescIdDesc(eq("A"), eq("11"), any())) + .thenReturn(new PageImpl<>(List.of(new Notification()), PageRequest.of(0, 20), 21)); + when(repo.countByRecipientTypeAndReceiverAndSeenFalse("A", "11")).thenReturn(3L); + + Map page = service.inbox("11", 0, 20); + assertThat(page.get("total")).isEqualTo(21L); + assertThat((List) page.get("items")).hasSize(1); + assertThat(service.unreadCount("11")).isEqualTo(3L); + } + + @Test + void markingAnotherUsersRowIsNotFound() { + when(repo.markSeen(eq(5L), eq("A"), eq("12"), any())).thenReturn(0); + when(repo.markSeen(eq(5L), eq("A"), eq("11"), any())).thenReturn(1); + + service.markRead("11", 5L); + assertThatThrownBy(() -> service.markRead("12", 5L)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404)); + } + + @Test + void markAllReadTouchesOnlyTheCallersRows() { + when(repo.markAllSeen(eq("A"), eq("11"), any())).thenReturn(4); + assertThat(service.markAllRead("11")).isEqualTo(4); + verify(repo, never()).markSeen(anyLong(), any(), any(), any()); + } +}