Compare commits

...

20 Commits

Author SHA1 Message Date
Tim
a3b28eafe4 Fix notification pagination after filtering disabled types 2025-08-19 19:48:41 +08:00
tim
805a8df7d3 Reapply "feat: add paginated notification endpoints"
This reverts commit e7a1e1d159.
2025-08-19 19:38:04 +08:00
tim
02be045f55 Revert "feat: add paginated notification APIs and frontend support"
This reverts commit c344b5b4ae.
2025-08-19 19:37:59 +08:00
Tim
ac3c7b7bec Merge pull request #646 from nagisa77/codex/add-pagination-support-for-messages-6ssiwm
feat: add paginated notifications and unread endpoint
2025-08-19 19:35:39 +08:00
Tim
c344b5b4ae feat: add paginated notification APIs and frontend support 2025-08-19 19:34:13 +08:00
tim
e7a1e1d159 Revert "feat: add paginated notification endpoints"
This reverts commit cc525c1c27.
2025-08-19 19:33:13 +08:00
Tim
30b56e54cf Merge pull request #645 from nagisa77/codex/add-pagination-support-for-messages-owucez
feat: add paginated notification endpoints
2025-08-19 19:27:27 +08:00
Tim
cc525c1c27 feat: add paginated notification endpoints 2025-08-19 19:27:07 +08:00
tim
3f2829cd37 Revert "feat: support paginated notifications"
This reverts commit a64fd71bbe.
2025-08-19 19:01:54 +08:00
Tim
3258a42b44 Merge pull request #644 from nagisa77/codex/add-pagination-support-for-messages
feat: paginate and load notifications per page
2025-08-19 18:46:12 +08:00
Tim
a64fd71bbe feat: support paginated notifications 2025-08-19 18:45:56 +08:00
tim
1a12bec7b1 Revert "feat: add paginated notification APIs and frontend"
This reverts commit 7dd1f1b3d0.
2025-08-19 18:26:55 +08:00
Tim
fbca19791a Merge pull request #643 from nagisa77/codex/add-pagination-support-for-message-page-ymy51v
feat: add paginated notification APIs and frontend
2025-08-19 18:25:10 +08:00
tim
10b6fdd1cb Revert "feat: add paginated notifications and unread endpoint"
This reverts commit 73168c1859.
2025-08-19 18:24:49 +08:00
Tim
7dd1f1b3d0 feat: add paginated notification APIs and frontend 2025-08-19 18:24:27 +08:00
Tim
df92ff664c Merge pull request #642 from nagisa77/codex/add-pagination-support-for-message-page-2bmo7x
feat: add paginated notifications and unread endpoint
2025-08-19 18:20:39 +08:00
Tim
73168c1859 feat: add paginated notifications and unread endpoint 2025-08-19 18:20:26 +08:00
tim
77856ff9af fix: make full page 2025-08-19 17:23:50 +08:00
tim
df49b21620 Revert "feat: add paginated notification API and frontend support"
This reverts commit df7ca77652.
2025-08-19 17:23:36 +08:00
Tim
fbe2c66955 Merge pull request #641 from nagisa77/codex/add-pagination-support-for-message-page
feat: paginate notifications and add unread filter
2025-08-19 17:08:05 +08:00
7 changed files with 172 additions and 125 deletions

View File

@@ -24,16 +24,18 @@ public class NotificationController {
@GetMapping
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) {
return notificationService.listNotifications(auth.getName(), null, page).stream()
return notificationService.listNotifications(auth.getName(), null, page, size).stream()
.map(notificationMapper::toDto)
.collect(Collectors.toList());
}
@GetMapping("/unread")
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) {
return notificationService.listNotifications(auth.getName(), false, page).stream()
return notificationService.listNotifications(auth.getName(), false, page, size).stream()
.map(notificationMapper::toDto)
.collect(Collectors.toList());
}

View File

@@ -5,9 +5,9 @@ import com.openisle.model.User;
import com.openisle.model.Post;
import com.openisle.model.Comment;
import com.openisle.model.NotificationType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
@@ -15,10 +15,12 @@ import java.util.List;
public interface NotificationRepository extends JpaRepository<Notification, Long> {
List<Notification> findByUserOrderByCreatedAtDesc(User user);
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
Page<Notification> findByUserAndTypeNotInOrderByCreatedAtDesc(User user, java.util.Collection<NotificationType> types, Pageable pageable);
Page<Notification> findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(User user, boolean read, java.util.Collection<NotificationType> types, Pageable pageable);
long countByUserAndRead(User user, boolean read);
long countByUserAndReadAndTypeNotIn(User user, boolean read, java.util.Collection<NotificationType> types);
List<Notification> findByPost(Post post);
List<Notification> findByComment(Comment comment);

View File

@@ -23,9 +23,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/** Service for creating and retrieving notifications. */
@Service
@@ -182,22 +179,26 @@ public class NotificationService {
userRepository.save(user);
}
public List<Notification> listNotifications(String username, Boolean read) {
return listNotifications(username, read, 0);
}
public List<Notification> listNotifications(String username, Boolean read, int page) {
public List<Notification> listNotifications(String username, Boolean read, int page, int size) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
Page<Notification> p;
Pageable pageable = org.springframework.data.domain.PageRequest.of(page, 50);
org.springframework.data.domain.Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
org.springframework.data.domain.Page<Notification> result;
if (read == null) {
p = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
if (disabled.isEmpty()) {
result = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
} else {
result = notificationRepository.findByUserAndTypeNotInOrderByCreatedAtDesc(user, disabled, pageable);
}
} else {
p = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
if (disabled.isEmpty()) {
result = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
} else {
result = notificationRepository.findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(user, read, disabled, pageable);
}
}
return p.getContent().stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
return result.getContent();
}
public void markRead(String username, List<Long> ids) {
@@ -216,8 +217,10 @@ public class NotificationService {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
return notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, false).stream()
.filter(n -> !disabled.contains(n.getType())).count();
if (disabled.isEmpty()) {
return notificationRepository.countByUserAndRead(user, false);
}
return notificationRepository.countByUserAndReadAndTypeNotIn(user, false, disabled);
}
public void notifyMentions(String content, User fromUser, Post post, Comment comment) {

View File

@@ -45,7 +45,7 @@ class NotificationControllerTest {
p.setId(2L);
n.setPost(p);
n.setCreatedAt(LocalDateTime.now());
when(notificationService.listNotifications("alice", null, 0))
when(notificationService.listNotifications("alice", null, 0, 30))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
@@ -65,18 +65,19 @@ class NotificationControllerTest {
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(3L);
n.setId(5L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0)).thenReturn(List.of(n));
when(notificationService.listNotifications("alice", false, 0, 30))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(3L);
dto.setId(5L);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications/unread")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(3));
.andExpect(jsonPath("$[0].id").value(5));
}
@Test

View File

@@ -11,6 +11,9 @@ import org.mockito.Mockito;
import java.util.List;
import java.util.Optional;
import java.util.HashSet;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -62,18 +65,17 @@ class NotificationServiceTest {
User user = new User();
user.setId(2L);
user.setUsername("bob");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
Notification n = new Notification();
org.springframework.data.domain.Page<Notification> page =
new org.springframework.data.domain.PageImpl<>(List.of(n));
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(org.springframework.data.domain.Pageable.class)))
.thenReturn(page);
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("bob", null);
List<Notification> list = service.listNotifications("bob", null, 0, 10);
assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(org.springframework.data.domain.Pageable.class));
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
}
@Test
@@ -90,6 +92,7 @@ class NotificationServiceTest {
User user = new User();
user.setId(3L);
user.setUsername("carl");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
@@ -99,6 +102,56 @@ class NotificationServiceTest {
verify(nRepo).countByUserAndRead(user, false);
}
@Test
void listNotificationsFiltersDisabledTypes() {
NotificationRepository nRepo = mock(NotificationRepository.class);
UserRepository uRepo = mock(UserRepository.class);
ReactionRepository rRepo = mock(ReactionRepository.class);
EmailSender email = mock(EmailSender.class);
PushNotificationService push = mock(PushNotificationService.class);
Executor executor = Runnable::run;
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
User user = new User();
user.setId(4L);
user.setUsername("dana");
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
Notification n = new Notification();
when(nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("dana", null, 0, 10);
assertEquals(1, list.size());
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class));
}
@Test
void countUnreadFiltersDisabledTypes() {
NotificationRepository nRepo = mock(NotificationRepository.class);
UserRepository uRepo = mock(UserRepository.class);
ReactionRepository rRepo = mock(ReactionRepository.class);
EmailSender email = mock(EmailSender.class);
PushNotificationService push = mock(PushNotificationService.class);
Executor executor = Runnable::run;
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
User user = new User();
user.setId(5L);
user.setUsername("erin");
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes())))
.thenReturn(2L);
long count = service.countUnread("erin");
assertEquals(2L, count);
verify(nRepo).countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes()));
}
@Test
void createRegisterRequestNotificationsDeletesOldOnes() {
NotificationRepository nRepo = mock(NotificationRepository.class);

View File

@@ -505,14 +505,14 @@
</div>
</template>
</BaseTimeline>
<InfiniteLoadMore :key="ioKey" :on-load="fetchNextPage" :pause="isLoadingMessage" />
<InfiniteLoadMore :key="selectedTab" :on-load="loadMore" :pause="isLoadingMessage" />
</div>
</template>
</div>
</template>
<script setup>
import { onActivated, ref, watch } from 'vue'
import { ref, watch, onActivated } from 'vue'
import BasePlaceholder from '~/components/BasePlaceholder.vue'
import BaseTimeline from '~/components/BaseTimeline.vue'
import NotificationContainer from '~/components/NotificationContainer.vue'
@@ -527,6 +527,7 @@ import {
markRead,
notifications,
markAllRead,
hasMore,
fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification'
@@ -539,7 +540,25 @@ const selectedTab = ref(
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
)
const notificationPrefs = ref([])
const ioKey = ref(0)
const page = ref(0)
const pageSize = 30
const loadMore = async () => {
if (!hasMore.value) return true
page.value++
await fetchNotifications({
page: page.value,
size: pageSize,
unread: selectedTab.value === 'unread',
append: true,
})
return !hasMore.value
}
watch(selectedTab, async (tab) => {
page.value = 0
await fetchNotifications({ page: 0, size: pageSize, unread: tab === 'unread' })
})
const fetchPrefs = async () => {
notificationPrefs.value = await fetchNotificationPreferences()
@@ -549,7 +568,11 @@ const togglePref = async (pref) => {
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
if (ok) {
pref.enabled = !pref.enabled
await fetchNotifications(selectedTab.value, true)
await fetchNotifications({
page: page.value,
size: pageSize,
unread: selectedTab.value === 'unread',
})
await fetchUnreadCount()
} else {
toast.error('操作失败')
@@ -629,21 +652,11 @@ const formatType = (t) => {
}
}
onActivated(() => {
fetchNotifications(selectedTab.value, true)
onActivated(async () => {
page.value = 0
await fetchNotifications({ page: 0, size: pageSize, unread: selectedTab.value === 'unread' })
fetchPrefs()
})
watch(selectedTab, (tab) => {
if (tab !== 'control') {
fetchNotifications(tab, true)
} else {
fetchPrefs()
}
ioKey.value++
})
const fetchNextPage = () => fetchNotifications(selectedTab.value)
</script>
<style scoped>
@@ -657,8 +670,6 @@ const fetchNextPage = () => fetchNotifications(selectedTab.value)
.message-page {
background-color: var(--background-color);
overflow-x: hidden;
height: calc(100vh - var(--header-height));
overflow-y: auto;
}
.message-page-header {

View File

@@ -118,44 +118,43 @@ export async function updateNotificationPreference(type, enabled) {
function createFetchNotifications() {
const notifications = ref([])
const isLoadingMessage = ref(false)
const page = ref(0)
const finished = ref(false)
const currentTab = ref('all')
const hasMore = ref(true)
const fetchNotifications = async (tab = 'all', reset = false) => {
const fetchNotifications = async ({
page = 0,
size = 30,
unread = false,
append = false,
} = {}) => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return true
return
}
if (reset || tab !== currentTab.value) {
notifications.value = []
page.value = 0
finished.value = false
currentTab.value = tab
}
if (finished.value) return true
if (!append) notifications.value = []
isLoadingMessage.value = true
let url = `${API_BASE_URL}/api/notifications`
if (currentTab.value === 'unread') url += '/unread'
url += `?page=${page.value}`
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
const res = await fetch(
`${API_BASE_URL}/api/notifications${unread ? '/unread' : ''}?page=${page}&size=${size}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
})
)
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return true
return
}
const data = await res.json()
const arr = []
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
notifications.value.push({
arr.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
@@ -164,7 +163,7 @@ function createFetchNotifications() {
},
})
} else if (n.type === 'REACTION') {
notifications.value.push({
arr.push({
...n,
emoji: reactionEmojiMap[n.reactionType],
iconClick: () => {
@@ -175,7 +174,7 @@ function createFetchNotifications() {
},
})
} else if (n.type === 'POST_VIEWED') {
notifications.value.push({
arr.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
@@ -186,8 +185,8 @@ function createFetchNotifications() {
}
},
})
} else if (n.type === 'LOTTERY_WIN') {
notifications.value.push({
} else if (n.type === 'LOTTERY_WIN' || n.type === 'LOTTERY_DRAW') {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
@@ -197,28 +196,8 @@ function createFetchNotifications() {
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'POST_UPDATED') {
notifications.value.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'USER_ACTIVITY') {
notifications.value.push({
} else if (n.type === 'POST_UPDATED' || n.type === 'USER_ACTIVITY') {
arr.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
@@ -227,7 +206,7 @@ function createFetchNotifications() {
},
})
} else if (n.type === 'MENTION') {
notifications.value.push({
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
@@ -238,7 +217,7 @@ function createFetchNotifications() {
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
notifications.value.push({
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
@@ -248,19 +227,12 @@ function createFetchNotifications() {
}
},
})
} else if (n.type === 'FOLLOWED_POST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
notifications.value.push({
} else if (
n.type === 'FOLLOWED_POST' ||
n.type === 'POST_SUBSCRIBED' ||
n.type === 'POST_UNSUBSCRIBED'
) {
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
@@ -271,7 +243,7 @@ function createFetchNotifications() {
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
notifications.value.push({
arr.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
@@ -283,29 +255,25 @@ function createFetchNotifications() {
},
})
} else if (n.type === 'REGISTER_REQUEST') {
notifications.value.push({
arr.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
arr.push({
...n,
icon: iconMap[n.type],
})
}
}
const done = data.length < 50
if (!done) {
page.value++
} else {
finished.value = true
}
return done
if (append) notifications.value.push(...arr)
else notifications.value = arr
hasMore.value = data.length === size
} catch (e) {
console.error(e)
isLoadingMessage.value = false
return true
}
}
@@ -355,8 +323,15 @@ function createFetchNotifications() {
notifications,
isLoadingMessage,
markAllRead,
hasMore,
}
}
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
createFetchNotifications()
export const {
fetchNotifications,
markRead,
notifications,
isLoadingMessage,
markAllRead,
hasMore,
} = createFetchNotifications()