diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java index 6fc11a9..25ca60d 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java @@ -29,6 +29,13 @@ public class LeadController { return leadService.whatsappContact(companyId, mobileE164); } + @GetMapping("/lead/whatsappTarget") + public WhatsappTarget whatsappTarget(@RequestParam(value = "companyId", required = false) Long companyId, + @RequestParam(value = "leadUuid", required = false) Long leadUuid, + @RequestParam(value = "eventLeadUuid", required = false) Long eventLeadUuid) { + return leadService.whatsappTarget(companyId, leadUuid, eventLeadUuid); + } + @PostMapping("/lead/update") public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); } } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java new file mode 100644 index 0000000..4759bc9 --- /dev/null +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/WhatsappTarget.java @@ -0,0 +1,4 @@ +package com.solvway.services.counter.dto; + +/** Counter GET /counter/lead/whatsappTarget response; the lead's own company id lets a super admin start without one. */ +public record WhatsappTarget(Long leadUuid, String name, String mobileE164, Long companyId) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java index 89ac5e0..80f33bc 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java @@ -7,6 +7,7 @@ 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.dto.WhatsappTarget; import com.solvway.services.counter.model.Event; import com.solvway.services.counter.model.EventLead; import com.solvway.services.counter.model.Lead; @@ -47,9 +48,7 @@ public class LeadService { /** A null company looks the lead up across all companies; the detail reports the lead's own company. */ public LeadDetail detail(Long companyId, long leadUuid) { - return detail(companyId == null - ? leadRepository.findByUuid(leadUuid).orElseThrow(LeadService::notFound) - : find(companyId, leadUuid)); + return detail(anyCompanyLead(companyId, leadUuid)); } /** The newest lead of the company with this mobile and its latest salesperson; 404 when there is none. */ @@ -59,6 +58,27 @@ public class LeadService { return new WhatsappContact(l.getUuid(), l.getName(), leadRepository.latestSalespersonUserId(companyId, l.getUuid())); } + /** The lead (or the event lead's lead) to start a WhatsApp chat with; a null company is any company. 404 when none or no mobile. */ + public WhatsappTarget whatsappTarget(Long companyId, Long leadUuid, Long eventLeadUuid) { + Long uuid = leadUuid; + if (uuid == null && eventLeadUuid != null) { + uuid = (companyId == null ? eventLeadRepository.findByUuid(eventLeadUuid) + : eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId)).map(EventLead::getLeadUuid).orElse(null); + } + if (uuid == null) { + throw notFound(); + } + Lead l = anyCompanyLead(companyId, uuid); + if (l.getMobileE164() == null || l.getMobileE164().isBlank()) { + throw notFound(); + } + return new WhatsappTarget(l.getUuid(), l.getName(), l.getMobileE164(), l.getCompanyId()); + } + + private Lead anyCompanyLead(Long companyId, long leadUuid) { + return companyId == null ? leadRepository.findByUuid(leadUuid).orElseThrow(LeadService::notFound) : find(companyId, leadUuid); + } + @Transactional public LeadDetail update(LeadUpdateRequest req) { if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java new file mode 100644 index 0000000..c21f299 --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/WhatsappTargetTest.java @@ -0,0 +1,102 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.controller.LeadController; +import com.solvway.services.counter.dto.WhatsappTarget; +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 org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** GET /counter/lead/whatsappTarget: the mobile and company of a lead (or of an event lead's lead) to start a chat with. */ +class WhatsappTargetTest { + private static final long COMPANY = 42L; + + private final LeadRepository leads = mock(LeadRepository.class); + private final EventLeadRepository eventLeads = mock(EventLeadRepository.class); + private final LeadService service = new LeadService(leads, eventLeads); + + private static Lead lead(long company, String mobile) { + Lead l = new Lead(); + l.setCompanyId(company); + l.setName("Aisyah"); + l.setMobileE164(mobile); + return l; + } + + private static void assertNotFound(Runnable call) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void leadOfTheCompanyYieldsNameMobileAndCompany() { + Lead l = lead(COMPANY, "+60111222333"); + when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l)); + + assertThat(service.whatsappTarget(COMPANY, l.getUuid(), null)) + .isEqualTo(new WhatsappTarget(l.getUuid(), "Aisyah", "+60111222333", COMPANY)); + } + + @Test + void nullCompanyLooksTheLeadUpAcrossCompaniesAndReportsItsOwn() { + Lead l = lead(7L, "+60111222333"); + when(leads.findByUuid(l.getUuid())).thenReturn(Optional.of(l)); + + assertThat(service.whatsappTarget(null, l.getUuid(), null).companyId()).isEqualTo(7L); + } + + @Test + void eventLeadResolvesToItsLead() { + Lead l = lead(COMPANY, "+60111222333"); + EventLead e = new EventLead(); + e.setCompanyId(COMPANY); + e.setLeadUuid(l.getUuid()); + when(eventLeads.findByUuidAndCompanyId(e.getUuid(), COMPANY)).thenReturn(Optional.of(e)); + when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l)); + + assertThat(service.whatsappTarget(COMPANY, null, e.getUuid()).leadUuid()).isEqualTo(l.getUuid()); + } + + @Test + void unknownLeadOtherCompanyOrNoMobileIs404() { + Lead noMobile = lead(COMPANY, null); + when(leads.findByUuidAndCompanyId(noMobile.getUuid(), COMPANY)).thenReturn(Optional.of(noMobile)); + Lead blank = lead(COMPANY, " "); + when(leads.findByUuidAndCompanyId(blank.getUuid(), COMPANY)).thenReturn(Optional.of(blank)); + + assertNotFound(() -> service.whatsappTarget(COMPANY, noMobile.getUuid(), null)); + assertNotFound(() -> service.whatsappTarget(COMPANY, blank.getUuid(), null)); + assertNotFound(() -> service.whatsappTarget(COMPANY, 1L, null)); + assertNotFound(() -> service.whatsappTarget(COMPANY, null, 2L)); + assertNotFound(() -> service.whatsappTarget(COMPANY, null, null)); + } + + @Test + void httpMapsFoundAndNotFound() throws Exception { + LeadService svc = mock(LeadService.class); + when(svc.whatsappTarget(COMPANY, 9L, null)).thenReturn(new WhatsappTarget(9L, "A", "+60111222333", COMPANY)); + when(svc.whatsappTarget(COMPANY, 1L, null)).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new LeadController(svc)).build(); + + mvc.perform(get("/counter/lead/whatsappTarget").param("companyId", "42").param("leadUuid", "9")) + .andExpect(status().isOk()).andExpect(jsonPath("$.mobileE164").value("+60111222333")) + .andExpect(jsonPath("$.companyId").value(42)); + mvc.perform(get("/counter/lead/whatsappTarget").param("companyId", "42").param("leadUuid", "1")) + .andExpect(status().isNotFound()); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java index b21063a..1a2979e 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/constants/CounterApi.java @@ -6,4 +6,7 @@ public final class CounterApi { /** GET, query params companyId and mobileE164; returns WhatsappContact. */ public static final String WHATSAPP_CONTACT = "/counter/lead/whatsappContact"; + + /** GET, query params companyId (optional) and leadUuid or eventLeadUuid; returns the lead's name, mobileE164 and companyId, 404 when none. */ + public static final String WHATSAPP_TARGET = "/counter/lead/whatsappTarget"; } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java new file mode 100644 index 0000000..2b92973 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxController.java @@ -0,0 +1,59 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.dto.ConversationPage; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.StartChatRequest; +import com.solvway.services.whatsapp.dto.ThreadView; +import com.solvway.services.whatsapp.dto.UnreadCount; +import org.springframework.http.HttpStatus; +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.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +/** Caller context (companyId, userId, admin) arrives as trusted query params from mobile-api; the service enforces access. */ +@RestController +@RequestMapping("/whatsapp") +public class InboxController { + + private final InboxService service; + + public InboxController(InboxService service) { + this.service = service; + } + + @GetMapping("/conversations") + public ConversationPage list(@RequestParam(required = false) Long companyId, @RequestParam Long userId, @RequestParam boolean admin, + @RequestParam(defaultValue = "mine") String tab, @RequestParam(required = false) String q, + @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "30") int size) { + return service.list(companyId, userId, admin, tab, q, page, size); + } + + @GetMapping("/conversations/{uuid}") + public ThreadView thread(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin, @RequestParam(required = false) String before) { + return service.thread(uuid, companyId, userId, admin, before); + } + + @PostMapping("/conversations/{uuid}/read") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void read(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin) { + service.markRead(uuid, companyId, userId, admin); + } + + @GetMapping("/unreadCount") + public UnreadCount unreadCount(@RequestParam(required = false) Long companyId, @RequestParam Long userId, @RequestParam boolean admin) { + return service.unreadCount(companyId, userId, admin); + } + + @PostMapping("/conversations/start") + public ConversationView start(@RequestParam(required = false) Long companyId, @RequestParam Long userId, @RequestParam boolean admin, + @RequestBody StartChatRequest request) { + return service.start(companyId, userId, admin, request); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java new file mode 100644 index 0000000..163e967 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java @@ -0,0 +1,269 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.constants.CounterApi; +import com.solvway.services.whatsapp.dto.ConversationPage; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.StartChatRequest; +import com.solvway.services.whatsapp.dto.ThreadView; +import com.solvway.services.whatsapp.dto.UnreadCount; +import com.solvway.services.whatsapp.dto.WhatsappContact; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaRead; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaReadRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.net.URI; +import java.time.Clock; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Inbox reads. Access is enforced here from the trusted caller context: another company's chat is always 404, and with + * admin=false so is a chat the user does not own. Never logs numbers, names or message text. + */ +@Service +public class InboxService { + + private static final int DEFAULT_PAGE = 30; + private static final int MAX_PAGE = 100; + private static final int THREAD_PAGE = 50; + private static final Sort LIST_ORDER = Sort.by(Sort.Order.desc("lastMessageAt"), Sort.Order.desc("id")); + + private final WaConversationRepository conversations; + private final WaMessageRepository messages; + private final WaReadRepository reads; + private final OwnershipService ownership; + private final CompanyDirectory companies; + private final RestTemplate rest; + private final Clock clock; + + @Autowired + public InboxService(WaConversationRepository conversations, WaMessageRepository messages, WaReadRepository reads, + OwnershipService ownership, CompanyDirectory companies, RestTemplateBuilder builder) { + this(conversations, messages, reads, ownership, companies, + builder.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(10)).build(), Clock.systemDefaultZone()); + } + + InboxService(WaConversationRepository conversations, WaMessageRepository messages, WaReadRepository reads, + OwnershipService ownership, CompanyDirectory companies, RestTemplate rest, Clock clock) { + this.conversations = conversations; + this.messages = messages; + this.reads = reads; + this.ownership = ownership; + this.companies = companies; + this.rest = rest; + this.clock = clock; + } + + /** + * mine = owned by the user; unassigned = nobody owns it (admin only, staff get an empty page, not an error); + * all = everything in scope for an admin, only own for staff. + * ponytail: q matches contact name and number only (the lead name is not stored); list rows carry no leadName + * (one counter call per row is not acceptable), the thread and start views do. + */ + public ConversationPage list(Long companyId, Long userId, boolean admin, String tab, String q, int page, int size) { + int pageNo = Math.max(page, 0); + int pageSize = size < 1 ? DEFAULT_PAGE : Math.min(size, MAX_PAGE); + if (failClosed(companyId, admin)) { + return new ConversationPage(List.of(), 0, pageNo, pageSize); + } + Long owner = userId; + boolean unassigned = false; + switch (tab == null ? "mine" : tab) { + case "mine" -> { } + case "all" -> owner = admin ? null : userId; + case "unassigned" -> { + if (!admin) { + return new ConversationPage(List.of(), 0, pageNo, pageSize); + } + owner = null; + unassigned = true; + } + default -> throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + String text = q == null ? "" : q.trim(); + String digits = text.replaceAll("\\D", ""); + // ponytail: LIKE wildcards are stripped from q instead of escaped. + String name = text.isEmpty() ? null : "%" + text.toLowerCase().replaceAll("[%_\\\\]", "") + "%"; + Page found = conversations.list(companyId, owner, unassigned, name, digits.isEmpty() || text.isEmpty() ? null : "%" + digits + "%", + PageRequest.of(pageNo, pageSize, LIST_ORDER)); + Map unread = unread(found.getContent().stream().map(c -> c.id).toList(), userId); + List items = found.getContent().stream().map(c -> view(c, null, unread.getOrDefault(c.id, 0L))).toList(); + return new ConversationPage(items, found.getTotalElements(), pageNo, pageSize); + } + + public ThreadView thread(String uuid, Long companyId, Long userId, boolean admin, String before) { + WaConversation c = visible(uuid, companyId, userId, admin); + Pageable page = PageRequest.of(0, THREAD_PAGE + 1); + List rows; + if (before == null) { + rows = messages.findByConversationIdOrderByIdDesc(c.id, page); + } else { + WaMessage cursor = messages.findByUuid(before).filter(m -> c.id.equals(m.conversationId)).orElseThrow(InboxService::notFound); + rows = messages.findByConversationIdAndIdLessThanOrderByIdDesc(c.id, cursor.id, page); + } + boolean hasOlder = rows.size() > THREAD_PAGE; + List newestFirst = new ArrayList<>(rows.subList(0, Math.min(rows.size(), THREAD_PAGE))); + Collections.reverse(newestFirst); + return new ThreadView(view(c, leadName(c), unread(List.of(c.id), userId).getOrDefault(c.id, 0L)), + newestFirst.stream().map(InboxService::message).toList(), hasOlder); + } + + /** Monotonic upsert (GREATEST in SQL): concurrent reads never move the marker back and first reads cannot collide. */ + public void markRead(String uuid, Long companyId, Long userId, boolean admin) { + WaConversation c = visible(uuid, companyId, userId, admin); + messages.findFirstByConversationIdOrderByIdDesc(c.id).ifPresent(last -> reads.markRead(c.id, userId, last.id)); + } + + /** ponytail: an admin counts every conversation of the company, so the badge can be large. */ + public UnreadCount unreadCount(Long companyId, Long userId, boolean admin) { + if (failClosed(companyId, admin)) { + return new UnreadCount(0); + } + return new UnreadCount(messages.unreadConversations(companyId, admin ? null : userId, userId)); + } + + /** Opens (or creates) the chat with a lead's number. An unowned chat becomes the starter's manual chat. */ + public ConversationView start(Long companyId, Long userId, boolean admin, StartChatRequest request) { + if (failClosed(companyId, admin)) { + throw notFound(); + } + if (request == null || (request.leadUuid() == null && request.eventLeadUuid() == null)) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + } + WhatsappTarget target = target(companyId, request); + String digits = target.mobileE164() == null ? "" : target.mobileE164().replaceAll("\\D", ""); + if (digits.isEmpty() || target.companyId() == null || (companyId != null && !companyId.equals(target.companyId()))) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); + } + Long company = target.companyId(); + String phoneNumberId = companies.phoneNumberIdOf(company) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + WaConversation c = conversations.findByCompanyIdAndContactWaId(company, digits) + .orElseGet(() -> create(company, digits, phoneNumberId, target.name())); + if (c.ownerUserId == null) { + if (conversations.claimIfUnowned(c.id, userId, target.leadUuid()) == 1) { + c.ownerUserId = userId; + c.ownerManual = true; + c.leadUuid = target.leadUuid(); + } else { // lost the race: someone owns it now + c = conversations.findById(c.id).orElse(c); + } + } + if (!admin && !userId.equals(c.ownerUserId)) { // owner fields only: no preview, no unread + return view(c, target.name(), 0, false); + } + return view(c, target.name(), unread(List.of(c.id), userId).getOrDefault(c.id, 0L), true); + } + + private WhatsappTarget target(Long companyId, StartChatRequest request) { + String query = (companyId == null ? "?" : "?companyId=" + companyId + "&") + + (request.leadUuid() != null ? "leadUuid=" + request.leadUuid() : "eventLeadUuid=" + request.eventLeadUuid()); + try { + WhatsappTarget target = rest.getForObject(URI.create("http://service-counter" + CounterApi.WHATSAPP_TARGET + query), WhatsappTarget.class); + if (target == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); + } + return target; + } catch (HttpClientErrorException.NotFound e) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); + } catch (ResponseStatusException e) { + throw e; + } catch (RuntimeException e) { + throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "COUNTER_UNAVAILABLE"); + } + } + + private WaConversation create(Long company, String digits, String phoneNumberId, String leadName) { + WaConversation c = new WaConversation(); + c.uuid = UUID.randomUUID().toString(); + c.companyId = company; + c.contactWaId = digits; + c.contactName = leadName == null || leadName.length() <= 255 ? leadName : leadName.substring(0, 255); + c.phoneNumberId = phoneNumberId; + c.createdAt = LocalDateTime.now(clock); + try { + return conversations.save(c); + } catch (DataIntegrityViolationException e) { // a concurrent first message or start created it + return conversations.findByCompanyIdAndContactWaId(company, digits).orElseThrow(() -> e); + } + } + + /** Only a super admin may span companies; a non-admin without a company must never mean "all". */ + private static boolean failClosed(Long companyId, boolean admin) { + return companyId == null && !admin; + } + + private WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) { + if (failClosed(companyId, admin)) { + throw notFound(); + } + return conversations.findByUuid(uuid) + .filter(c -> companyId == null || companyId.equals(c.companyId)) + .filter(c -> admin || userId.equals(c.ownerUserId)) + .orElseThrow(InboxService::notFound); + } + + /** Unread inbound messages per conversation for the user, in one grouped query. */ + private Map unread(List ids, Long userId) { + Map counts = new HashMap<>(); + if (!ids.isEmpty()) { + messages.unreadByConversation(ids, userId).forEach(r -> counts.put((Long) r[0], ((Number) r[1]).longValue())); + } + return counts; + } + + private String leadName(WaConversation c) { + if (c.leadUuid == null) { + return null; + } + try { + WhatsappContact contact = ownership.lookup(c); + return contact == null ? null : contact.name(); + } catch (RuntimeException e) { // the name is decoration; an unreachable counter must not fail the thread + return null; + } + } + + private ConversationView view(WaConversation c, String leadName, long unread) { + return view(c, leadName, unread, true); + } + + private ConversationView view(WaConversation c, String leadName, long unread, boolean withPreview) { + boolean open = c.lastInboundAt != null && c.lastInboundAt.isAfter(LocalDateTime.now(clock).minusHours(24)); + return new ConversationView(c.uuid, c.companyId, c.contactWaId, c.contactName, c.leadUuid, leadName, c.ownerUserId, null, + c.ownerManual, c.lastInboundAt, c.lastMessageAt, withPreview ? c.lastMessagePreview : null, open, unread); + } + + private static MessageView message(WaMessage m) { + return new MessageView(m.uuid, m.direction, m.type, m.body, m.templateName, m.mediaMime, m.mediaFilename, m.locationLat, + m.locationLng, m.locationName, m.status, m.errorCode, m.errorTitle, m.sentByUserId, m.createdAt, m.statusAt); + } + + private static ResponseStatusException notFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java new file mode 100644 index 0000000..b85cc13 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/WhatsappTarget.java @@ -0,0 +1,4 @@ +package com.solvway.services.whatsapp.inbox; + +/** Counter GET /counter/lead/whatsappTarget response: who to start a chat with, and the lead's company. */ +public record WhatsappTarget(Long leadUuid, String name, String mobileE164, Long companyId) {} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java index e66bb7f..473912c 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/model/WaReadId.java @@ -1,5 +1,27 @@ package com.solvway.services.whatsapp.model; import java.io.Serializable; +import java.util.Objects; -public record WaReadId(Long conversationId, Long userId) implements Serializable {} +/** Composite key of wa_read. A class, not a record: Hibernate 6.4 cannot bind a record as an @IdClass (startup fails). */ +public class WaReadId implements Serializable { + public Long conversationId; + public Long userId; + + public WaReadId() {} + + public WaReadId(Long conversationId, Long userId) { + this.conversationId = conversationId; + this.userId = userId; + } + + @Override + public boolean equals(Object o) { + return o instanceof WaReadId k && Objects.equals(conversationId, k.conversationId) && Objects.equals(userId, k.userId); + } + + @Override + public int hashCode() { + return Objects.hash(conversationId, userId); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java index 8806f66..2fd49fc 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/ownership/OwnershipService.java @@ -148,7 +148,8 @@ public class OwnershipService { c.lastInboundAt != null && c.lastInboundAt.isAfter(LocalDateTime.now().minusHours(24)), 0); } - private WhatsappContact lookup(WaConversation c) { + /** The newest lead for the conversation's number; null when there is none. Throws when the counter is unreachable. */ + public WhatsappContact lookup(WaConversation c) { String mobile = URLEncoder.encode("+" + c.contactWaId, StandardCharsets.UTF_8); try { return rest.getForObject(URI.create("http://service-counter" + CounterApi.WHATSAPP_CONTACT diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java index c66ac11..3283aac 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java @@ -1,6 +1,7 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaConversation; +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; @@ -32,6 +33,13 @@ public interface WaConversationRepository extends JpaRepository findByUuid(String uuid); + /** Inbox list: null companyId = all companies, null owner = any owner; q and digits are ready-made LIKE patterns. */ + @Query("select c from WaConversation c where (:companyId is null or c.companyId = :companyId) " + + "and (:owner is null or c.ownerUserId = :owner) and (:unassigned = false or c.ownerUserId is null) " + + "and (:q is null or lower(c.contactName) like :q or c.contactWaId like :digits)") + Page list(@Param("companyId") Long companyId, @Param("owner") Long owner, @Param("unassigned") boolean unassigned, + @Param("q") String q, @Param("digits") String digits, Pageable page); + List findByOwnerUserId(Long ownerUserId); /** Keyset paging (stable while rows are updated underneath), used by the nightly job. */ @@ -53,4 +61,11 @@ public interface WaConversationRepository extends JpaRepository :prevOwner", nativeQuery = true) int casOwnership(@Param("id") Long id, @Param("owner") Long owner, @Param("lead") Long lead, @Param("prevManual") boolean prevManual, @Param("prevOwner") Long prevOwner); + + /** Manual claim of an unowned chat: loses (0 rows) if someone owned it first. */ + @Transactional + @Modifying + @Query(value = "UPDATE wa_conversation SET owner_user_id = :owner, owner_manual = true, lead_uuid = :lead " + + "WHERE id = :id AND owner_user_id IS NULL", nativeQuery = true) + int claimIfUnowned(@Param("id") Long id, @Param("owner") Long owner, @Param("lead") Long lead); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java index e888ca1..f90db1f 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaMessageRepository.java @@ -1,12 +1,37 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaMessage; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import java.util.List; import java.util.Optional; public interface WaMessageRepository extends JpaRepository { boolean existsByWamid(String wamid); + Optional findByUuid(String uuid); + + List findByConversationIdOrderByIdDesc(Long conversationId, Pageable page); + + List findByConversationIdAndIdLessThanOrderByIdDesc(Long conversationId, Long beforeId, Pageable page); + + Optional findFirstByConversationIdOrderByIdDesc(Long conversationId); + + /** Rows are [conversationId, unread inbound count] for the user (messages newer than their read marker); none for zero. */ + @Query("select m.conversationId, count(m) from WaMessage m where m.conversationId in :ids and m.direction = 'IN' " + + "and m.id > coalesce((select r.lastReadMessageId from WaRead r where r.conversationId = m.conversationId and r.userId = :userId), 0) " + + "group by m.conversationId") + List unreadByConversation(@Param("ids") List ids, @Param("userId") Long userId); + + /** Conversations (null companyId = all, null owner = any) with an inbound message newer than the user's read marker. */ + @Query("select count(distinct m.conversationId) from WaMessage m, WaConversation c where c.id = m.conversationId " + + "and (:companyId is null or c.companyId = :companyId) and (:owner is null or c.ownerUserId = :owner) " + + "and m.direction = 'IN' " + + "and m.id > coalesce((select r.lastReadMessageId from WaRead r where r.conversationId = m.conversationId and r.userId = :userId), 0)") + long unreadConversations(@Param("companyId") Long companyId, @Param("owner") Long owner, @Param("userId") Long userId); + Optional findByWamidAndDirection(String wamid, String direction); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java index 4346e82..614a0c3 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaReadRepository.java @@ -3,5 +3,17 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaRead; import com.solvway.services.whatsapp.model.WaReadId; 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.transaction.annotation.Transactional; -public interface WaReadRepository extends JpaRepository {} +public interface WaReadRepository extends JpaRepository { + + /** Upsert that only moves the marker forward. */ + @Transactional + @Modifying + @Query(value = "INSERT INTO wa_read (conversation_id, user_id, last_read_message_id) VALUES (:conversation, :user, :message) " + + "ON DUPLICATE KEY UPDATE last_read_message_id = GREATEST(last_read_message_id, VALUES(last_read_message_id))", nativeQuery = true) + int markRead(@Param("conversation") Long conversation, @Param("user") Long user, @Param("message") Long message); +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java index ab029cd..6d2630f 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java @@ -64,6 +64,14 @@ public class CompanyDirectory { return Optional.ofNullable(byPhoneNumberId.get(phoneNumberId)); } + /** The configured phone number id of the company; empty when WhatsApp is not configured for it (or not resolved yet). */ + public Optional phoneNumberIdOf(long companyId) { + if (!unresolved.isEmpty() && !coolingDown()) { + resolve(); + } + return byPhoneNumberId.entrySet().stream().filter(e -> e.getValue().id() == companyId).map(Map.Entry::getKey).findFirst(); + } + private boolean coolingDown() { Instant failed = lastFailure; return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN)); diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java new file mode 100644 index 0000000..088879c --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/InboxTest.java @@ -0,0 +1,591 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.controller.ErrorHandler; +import com.solvway.services.whatsapp.dto.ConversationPage; +import com.solvway.services.whatsapp.dto.ConversationView; +import com.solvway.services.whatsapp.dto.StartChatRequest; +import com.solvway.services.whatsapp.dto.ThreadView; +import com.solvway.services.whatsapp.dto.WhatsappContact; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaRead; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaReadRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.net.URI; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +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.anyBoolean; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +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; + +class InboxTest { + + private static final LocalDateTime NOW = LocalDateTime.of(2026, 12, 2, 12, 0); + private static final long STAFF = 10L; + + private WaConversationRepository conversations; + private WaMessageRepository messages; + private WaReadRepository reads; + private OwnershipService ownership; + private CompanyDirectory directory; + private RestTemplate rest; + private InboxService service; + private MockMvc mvc; + private WhatsappTarget target; // null = counter answers 404 + private boolean counterDown; + + @BeforeEach + void setUp() { + conversations = mock(WaConversationRepository.class); + messages = mock(WaMessageRepository.class); + reads = mock(WaReadRepository.class); + ownership = mock(OwnershipService.class); + directory = mock(CompanyDirectory.class); + rest = mock(RestTemplate.class); + when(rest.getForObject(any(URI.class), eq(WhatsappTarget.class))).thenAnswer(i -> { + if (counterDown) { + throw new ResourceAccessException("down"); + } + if (target == null) { + throw HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null); + } + return target; + }); + when(conversations.claimIfUnowned(anyLong(), any(), any())).thenReturn(1); + when(directory.phoneNumberIdOf(1L)).thenReturn(Optional.of("111")); + when(conversations.save(any(WaConversation.class))).thenAnswer(i -> { + WaConversation c = i.getArgument(0); + c.id = 99L; + return c; + }); + Clock clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + service = new InboxService(conversations, messages, reads, ownership, directory, rest, clock); + mvc = MockMvcBuilders.standaloneSetup(new InboxController(service)).setControllerAdvice(new ErrorHandler()).build(); + } + + private static WaConversation conv(long id, Long company, Long owner) { + WaConversation c = new WaConversation(); + c.id = id; + c.uuid = "u-" + id; + c.companyId = company; + c.contactWaId = "6011122" + id; + c.contactName = "Name" + id; + c.ownerUserId = owner; + c.lastInboundAt = NOW.minusHours(1); + c.lastMessageAt = NOW.minusHours(1); + return c; + } + + private void given(WaConversation c) { + when(conversations.findByUuid(c.uuid)).thenReturn(Optional.of(c)); + } + + private static WaMessage msg(long id) { + WaMessage m = new WaMessage(); + m.id = id; + m.uuid = "m-" + id; + m.direction = "IN"; + m.type = "text"; + m.body = "hi" + id; + return m; + } + + private static void assertNotFound(Runnable call) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getReason()).isEqualTo("CONVERSATION_NOT_FOUND"); + }); + } + + // ---- inbox access + + @Test + void staffOpeningSomeoneElsesChatGets404OnThreadAndRead() { + given(conv(5, 1L, 11L)); + + assertNotFound(() -> service.thread("u-5", 1L, STAFF, false, null)); + assertNotFound(() -> service.markRead("u-5", 1L, STAFF, false)); + verify(reads, never()).save(any()); + } + + @Test + void conversationOfAnotherCompanyIs404EvenForAnAdmin() { + given(conv(5, 2L, STAFF)); + + assertNotFound(() -> service.thread("u-5", 1L, STAFF, true, null)); + assertNotFound(() -> service.markRead("u-5", 1L, STAFF, true)); + } + + @Test + void superAdminWithoutCompanyOpensAnyCompany() { + given(conv(5, 2L, null)); + + assertThat(service.thread("u-5", null, STAFF, true, null).conversation().uuid()).isEqualTo("u-5"); + } + + @Test + void unknownConversationIs404() { + when(conversations.findByUuid("zz")).thenReturn(Optional.empty()); + + assertNotFound(() -> service.thread("zz", 1L, STAFF, true, null)); + } + + @Test + void adminUnassignedTabListsOnlyTheirCompany() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(1L, STAFF, true, "unassigned", null, 0, 30); + + verify(conversations).list(eq(1L), isNull(), eq(true), isNull(), isNull(), any(Pageable.class)); + } + + @Test + void staffUnassignedTabIsEmptyAndNeverQueries() { + ConversationPage page = service.list(1L, STAFF, false, "unassigned", null, 0, 30); + + assertThat(page.items()).isEmpty(); + assertThat(page.total()).isZero(); + verify(conversations, never()).list(any(), any(), anyBoolean(), any(), any(), any()); + } + + @Test + void allTabIsEverythingForAdminAndOnlyOwnForStaff() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(1L, STAFF, true, "all", null, 0, 30); + service.list(1L, STAFF, false, "all", null, 0, 30); + service.list(1L, STAFF, false, "mine", null, 0, 30); + + verify(conversations).list(eq(1L), isNull(), eq(false), isNull(), isNull(), any()); + verify(conversations, times(2)).list(eq(1L), eq(STAFF), eq(false), isNull(), isNull(), any()); + } + + @Test + void superAdminListIsNotCompanyScoped() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(null, STAFF, true, "all", null, 0, 30); + + verify(conversations).list(isNull(), isNull(), eq(false), isNull(), isNull(), any()); + } + + @Test + void unknownTabIs400() { + assertThatThrownBy(() -> service.list(1L, STAFF, true, "bogus", null, 0, 30)) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + } + + // ---- list: ordering, paging, filter, flags + + @Test + void listOrdersByLastMessageThenIdAndClampsThePageSize() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + ArgumentCaptor page = ArgumentCaptor.forClass(Pageable.class); + + service.list(1L, STAFF, true, "all", null, 2, 0); + service.list(1L, STAFF, true, "all", null, -1, 500); + + verify(conversations, times(2)).list(any(), any(), anyBoolean(), any(), any(), page.capture()); + Pageable first = page.getAllValues().get(0); + Pageable second = page.getAllValues().get(1); + assertThat(first.getPageSize()).isEqualTo(30); + assertThat(first.getPageNumber()).isEqualTo(2); + assertThat(second.getPageSize()).isEqualTo(100); + assertThat(second.getPageNumber()).isZero(); + assertThat(first.getSort()).isEqualTo(Sort.by(Sort.Order.desc("lastMessageAt"), Sort.Order.desc("id"))); + } + + @Test + void qMatchesNameCaseInsensitivelyAndNumberByDigitsOnly() { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of())); + + service.list(1L, STAFF, true, "all", " Ais_% ", 0, 30); + service.list(1L, STAFF, true, "all", "+60 11-22", 0, 30); + service.list(1L, STAFF, true, "all", " ", 0, 30); + + verify(conversations).list(any(), any(), anyBoolean(), eq("%ais%"), isNull(), any()); + verify(conversations).list(any(), any(), anyBoolean(), eq("%+60 11-22%"), eq("%601122%"), any()); + verify(conversations).list(any(), any(), anyBoolean(), isNull(), isNull(), any()); + } + + @Test + void listItemsCarryWindowFlagAndUnreadFromOneGroupedQuery() { + WaConversation a = conv(1, 1L, STAFF); + WaConversation b = conv(2, 1L, STAFF); + b.lastInboundAt = NOW.minusHours(30); + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(a, b))); + when(messages.unreadByConversation(anyList(), eq(STAFF))).thenReturn(Collections.singletonList(new Object[] {1L, 3L})); + + ConversationPage page = service.list(1L, STAFF, false, "mine", null, 0, 30); + + verify(messages, times(1)).unreadByConversation(eq(List.of(1L, 2L)), eq(STAFF)); + assertThat(page.items()).extracting(ConversationView::uuid).containsExactly("u-1", "u-2"); + assertThat(page.items()).extracting(ConversationView::unreadCount).containsExactly(3L, 0L); + assertThat(page.items()).extracting(ConversationView::windowOpen).containsExactly(true, false); + assertThat(page.items()).extracting(ConversationView::leadName).containsOnlyNulls(); + assertThat(page.items().get(0).ownerName()).isNull(); + assertThat(page.total()).isEqualTo(2); + assertThat(page.size()).isEqualTo(30); + } + + @Test + void windowIsOpenAt23h59AndClosedAt24h() { + WaConversation open = conv(1, 1L, STAFF); + open.lastInboundAt = NOW.minusHours(23).minusMinutes(59); + WaConversation closed = conv(2, 1L, STAFF); + closed.lastInboundAt = NOW.minusHours(24); + WaConversation never = conv(3, 1L, STAFF); + never.lastInboundAt = null; + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(open, closed, never))); + + ConversationPage page = service.list(1L, STAFF, false, "mine", null, 0, 30); + + assertThat(page.items()).extracting(ConversationView::windowOpen).containsExactly(true, false, false); + } + + // ---- thread + + @Test + void threadReturnsNewestLastAndHasOlderWhenMoreThanAPageExists() { + given(conv(5, 1L, STAFF)); + List newestFirst = new ArrayList<>(); + for (long id = 60; id >= 10; id--) { // 51 rows + newestFirst.add(msg(id)); + } + when(messages.findByConversationIdOrderByIdDesc(eq(5L), any(Pageable.class))).thenReturn(newestFirst); + + ThreadView view = service.thread("u-5", 1L, STAFF, false, null); + + assertThat(view.hasOlder()).isTrue(); + assertThat(view.messages()).hasSize(50); + assertThat(view.messages().get(0).uuid()).isEqualTo("m-11"); + assertThat(view.messages().get(49).uuid()).isEqualTo("m-60"); + ArgumentCaptor page = ArgumentCaptor.forClass(Pageable.class); + verify(messages).findByConversationIdOrderByIdDesc(eq(5L), page.capture()); + assertThat(page.getValue().getPageSize()).isEqualTo(51); + } + + @Test + void threadWithBeforeContinuesFromThatMessageAndSaysWhenItIsTheStart() { + given(conv(5, 1L, STAFF)); + WaMessage cursor = msg(11); + cursor.conversationId = 5L; + when(messages.findByUuid("m-11")).thenReturn(Optional.of(cursor)); + when(messages.findByConversationIdAndIdLessThanOrderByIdDesc(eq(5L), eq(11L), any(Pageable.class))) + .thenReturn(List.of(msg(10), msg(9))); + + ThreadView view = service.thread("u-5", 1L, STAFF, false, "m-11"); + + assertThat(view.hasOlder()).isFalse(); + assertThat(view.messages()).extracting(m -> m.uuid()).containsExactly("m-9", "m-10"); + } + + @Test + void threadBeforeAMessageOfAnotherConversationIs404() { + given(conv(5, 1L, STAFF)); + WaMessage foreign = msg(11); + foreign.conversationId = 6L; + when(messages.findByUuid("m-11")).thenReturn(Optional.of(foreign)); + + assertNotFound(() -> service.thread("u-5", 1L, STAFF, false, "m-11")); + when(messages.findByUuid("nope")).thenReturn(Optional.empty()); + assertNotFound(() -> service.thread("u-5", 1L, STAFF, false, "nope")); + } + + @Test + void threadLooksUpTheLeadNameOnceAndToleratesFailure() { + WaConversation c = conv(5, 1L, STAFF); + c.leadUuid = 77L; + given(c); + when(ownership.lookup(c)).thenReturn(new WhatsappContact(77L, "Aisyah", 10L)); + + assertThat(service.thread("u-5", 1L, STAFF, false, null).conversation().leadName()).isEqualTo("Aisyah"); + + when(ownership.lookup(c)).thenThrow(new ResourceAccessException("down")); + assertThat(service.thread("u-5", 1L, STAFF, false, null).conversation().leadName()).isNull(); + + WaConversation noLead = conv(6, 1L, STAFF); + given(noLead); + service.thread("u-6", 1L, STAFF, false, null); + verify(ownership, never()).lookup(noLead); + } + + // ---- read markers and unread counts + + @Test + void readingMarksTheLastMessageAndAnEmptyChatIsANoOp() { + given(conv(5, 1L, STAFF)); + when(messages.findFirstByConversationIdOrderByIdDesc(5L)).thenReturn(Optional.of(msg(42))); + + service.markRead("u-5", 1L, STAFF, false); + + // monotonic upsert (GREATEST in SQL), not read-modify-write + verify(reads).markRead(5L, STAFF, 42L); + verify(reads, never()).save(any()); + + given(conv(6, 1L, STAFF)); + when(messages.findFirstByConversationIdOrderByIdDesc(6L)).thenReturn(Optional.empty()); + service.markRead("u-6", 1L, STAFF, false); + verify(reads, times(1)).markRead(anyLong(), anyLong(), anyLong()); + } + + @Test + void unreadCountIsPerUserMineForStaffAndWholeCompanyForAdmin() { + when(messages.unreadConversations(anyLong(), any(), anyLong())).thenReturn(4L); + when(messages.unreadConversations(isNull(), any(), anyLong())).thenReturn(9L); + + assertThat(service.unreadCount(1L, STAFF, false).count()).isEqualTo(4L); + verify(messages).unreadConversations(1L, STAFF, STAFF); + assertThat(service.unreadCount(1L, STAFF, true).count()).isEqualTo(4L); + verify(messages).unreadConversations(1L, null, STAFF); + assertThat(service.unreadCount(null, STAFF, true).count()).isEqualTo(9L); + } + + // ---- start a chat + + private void leadOf(long company, String mobile) { + target = new WhatsappTarget(77L, "Aisyah", mobile, company); + } + + @Test + void startOnAnUnownedChatMakesItTheStartersManualChat() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, null); + c.contactWaId = "60111222333"; + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + + verify(conversations).claimIfUnowned(5L, STAFF, 77L); + assertThat(view.ownerUserId()).isEqualTo(STAFF); + assertThat(view.ownerManual()).isTrue(); + assertThat(view.leadName()).isEqualTo("Aisyah"); + assertThat(view.leadUuid()).isEqualTo(77L); + } + + @Test + void startCreatesTheConversationWithThePhoneNumberOfTheCompany() { + leadOf(1L, "+60111222333"); + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.empty()); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(null, 500L)); + + ArgumentCaptor saved = ArgumentCaptor.forClass(WaConversation.class); + verify(conversations).save(saved.capture()); + assertThat(saved.getValue().companyId).isEqualTo(1L); + assertThat(saved.getValue().contactWaId).isEqualTo("60111222333"); + assertThat(saved.getValue().phoneNumberId).isEqualTo("111"); + assertThat(saved.getValue().uuid).isNotBlank(); + verify(conversations).claimIfUnowned(99L, STAFF, 77L); + assertThat(view.ownerUserId()).isEqualTo(STAFF); + assertThat(view.windowOpen()).isFalse(); + } + + @Test + void startOnSomeoneElsesChatShowsTheOwnerAndChangesNothing() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, 11L); + c.ownerManual = true; + c.contactWaId = "60111222333"; + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + + verify(conversations, never()).claimIfUnowned(anyLong(), any(), any()); + assertThat(view.ownerUserId()).isEqualTo(11L); + assertThat(view.ownerManual()).isTrue(); + verify(messages, never()).findByConversationIdOrderByIdDesc(anyLong(), any()); + assertThat(view.lastMessagePreview()).isNull(); + assertThat(view.unreadCount()).isZero(); + assertThat(view.contactName()).isEqualTo("Name5"); + assertThat(view.leadName()).isEqualTo("Aisyah"); + verify(messages, never()).unreadByConversation(anyList(), anyLong()); + } + + @Test + void startLosingTheClaimRaceShowsTheWinnerAsOwnerFieldsOnly() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, null); + c.contactWaId = "60111222333"; + c.lastMessagePreview = "secret"; + WaConversation winner = conv(5, 1L, 11L); + winner.ownerManual = true; + winner.lastMessagePreview = "secret"; + when(conversations.findByCompanyIdAndContactWaId(1L, "60111222333")).thenReturn(Optional.of(c)); + when(conversations.claimIfUnowned(5L, STAFF, 77L)).thenReturn(0); + when(conversations.findById(5L)).thenReturn(Optional.of(winner)); + + ConversationView view = service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + + assertThat(view.ownerUserId()).isEqualTo(11L); + assertThat(view.lastMessagePreview()).isNull(); + assertThat(view.unreadCount()).isZero(); + } + + // ---- fail closed: no company and not a super admin must never mean "all companies" + + @Test + void nonAdminWithoutCompanyIsDeniedEverywhere() { + leadOf(1L, "+60111222333"); + WaConversation c = conv(5, 1L, STAFF); + given(c); + + assertThat(service.list(null, STAFF, false, "all", null, 0, 30).items()).isEmpty(); + assertThat(service.list(null, STAFF, false, "mine", null, 0, 30).items()).isEmpty(); + assertThat(service.unreadCount(null, STAFF, false).count()).isZero(); + assertNotFound(() -> service.thread("u-5", null, STAFF, false, null)); + assertNotFound(() -> service.markRead("u-5", null, STAFF, false)); + assertNotFound(() -> service.start(null, STAFF, false, new StartChatRequest(77L, null))); + + verify(conversations, never()).list(any(), any(), anyBoolean(), any(), any(), any()); + verify(messages, never()).unreadConversations(any(), any(), anyLong()); + verify(reads, never()).markRead(anyLong(), anyLong(), anyLong()); + verifyNoInteractions(rest); + verify(conversations, never()).save(any()); + verify(conversations, never()).claimIfUnowned(anyLong(), any(), any()); + } + + @Test + void httpNonAdminWithoutCompanyIsDenied() throws Exception { + mvc.perform(get("/whatsapp/conversations").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.items").isEmpty()); + mvc.perform(get("/whatsapp/unreadCount").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.count").value(0)); + mvc.perform(post("/whatsapp/conversations/start").param("userId", "10").param("admin", "false") + .contentType("application/json").content("{\"leadUuid\":77}")) + .andExpect(status().isNotFound()); + } + + @Test + void startForALeadWithoutMobileOrWithoutLeadIs404() { + target = null; + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(conversations, never()).save(any()); + } + + @Test + void startForALeadOfAnotherCompanyIs404() { + leadOf(2L, "+60111222333"); + + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + verify(conversations, never()).save(any()); + } + + @Test + void superAdminStartUsesTheCompanyOfTheLead() { + leadOf(2L, "+60111222333"); + when(directory.phoneNumberIdOf(2L)).thenReturn(Optional.of("222")); + when(conversations.findByCompanyIdAndContactWaId(2L, "60111222333")).thenReturn(Optional.empty()); + + ConversationView view = service.start(null, STAFF, true, new StartChatRequest(77L, null)); + + assertThat(view.companyId()).isEqualTo(2L); + verify(rest).getForObject(eq(URI.create("http://service-counter/counter/lead/whatsappTarget?leadUuid=77")), eq(WhatsappTarget.class)); + } + + @Test + void startWithoutConfiguredWhatsAppForTheCompanyIs409() { + leadOf(1L, "+60111222333"); + when(directory.phoneNumberIdOf(1L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("WHATSAPP_NOT_CONFIGURED"); + }); + verify(conversations, never()).save(any()); + } + + @Test + void startAsksTheCounterByLeadOrEventLeadAndScopesToTheCompany() { + leadOf(1L, "+60111222333"); + when(conversations.findByCompanyIdAndContactWaId(any(), any())).thenReturn(Optional.empty()); + + service.start(1L, STAFF, false, new StartChatRequest(77L, null)); + service.start(1L, STAFF, false, new StartChatRequest(null, 500L)); + + verify(rest).getForObject(eq(URI.create("http://service-counter/counter/lead/whatsappTarget?companyId=1&leadUuid=77")), eq(WhatsappTarget.class)); + verify(rest).getForObject(eq(URI.create("http://service-counter/counter/lead/whatsappTarget?companyId=1&eventLeadUuid=500")), eq(WhatsappTarget.class)); + } + + @Test + void startWithCounterDownIs503AndEmptyBodyIs400() { + counterDown = true; + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(77L, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE)); + assertThatThrownBy(() -> service.start(1L, STAFF, false, new StartChatRequest(null, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + } + + // ---- HTTP + + @Test + void httpListReadAndStart() throws Exception { + when(conversations.list(any(), any(), anyBoolean(), any(), any(), any())).thenReturn(new PageImpl<>(List.of(conv(1, 1L, STAFF)))); + mvc.perform(get("/whatsapp/conversations").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.items[0].uuid").value("u-1")).andExpect(jsonPath("$.size").value(30)); + + given(conv(5, 1L, STAFF)); + mvc.perform(post("/whatsapp/conversations/u-5/read").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNoContent()); + given(conv(6, 1L, 11L)); + mvc.perform(post("/whatsapp/conversations/u-6/read").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND")); + + when(messages.unreadConversations(any(), any(), anyLong())).thenReturn(2L); + mvc.perform(get("/whatsapp/unreadCount").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(jsonPath("$.count").value(2)); + + leadOf(1L, "+60111222333"); + when(directory.phoneNumberIdOf(1L)).thenReturn(Optional.empty()); + mvc.perform(post("/whatsapp/conversations/start").param("companyId", "1").param("userId", "10").param("admin", "false") + .contentType("application/json").content("{\"leadUuid\":77}")) + .andExpect(status().isConflict()).andExpect(jsonPath("$.detail").value("WHATSAPP_NOT_CONFIGURED")); + } +}