Compare commits

..

6 Commits

Author SHA1 Message Date
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
7 changed files with 224 additions and 225 deletions

View File

@@ -23,18 +23,19 @@ public class NotificationController {
private final NotificationMapper notificationMapper;
@GetMapping
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
@RequestParam(value = "page", defaultValue = "0") int page,
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(), read, page, 50).stream()
return notificationService.listNotifications(auth.getName(), 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, 50).stream()
return notificationService.listUnreadNotifications(auth.getName(), 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;

View File

@@ -25,8 +25,8 @@ 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;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/** Service for creating and retrieving notifications. */
@@ -184,19 +184,26 @@ public class NotificationService {
userRepository.save(user);
}
public List<Notification> listNotifications(String username, Boolean read, int page, int size) {
public List<Notification> listNotifications(String username, int page, int size) {
return listNotifications(username, null, page, size);
}
public List<Notification> listUnreadNotifications(String username, int page, int size) {
return listNotifications(username, false, page, size);
}
private 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();
Pageable pageable = PageRequest.of(page, size,
Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Notification> pg;
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Notification> list;
if (read == null) {
pg = notificationRepository.findByUser(user, pageable);
list = notificationRepository.findByUser(user, pageable);
} else {
pg = notificationRepository.findByUserAndRead(user, read, pageable);
list = notificationRepository.findByUserAndRead(user, read, pageable);
}
return pg.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
}
public void markRead(String username, List<Long> ids) {

View File

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

View File

@@ -11,6 +11,7 @@ import org.mockito.Mockito;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Pageable;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -65,12 +66,12 @@ class NotificationServiceTest {
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
Notification n = new Notification();
when(nRepo.findByUser(eq(user), any())).thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(n)));
when(nRepo.findByUser(eq(user), any(Pageable.class))).thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("bob", null, 0, 50);
List<Notification> list = service.listNotifications("bob", 0, 30);
assertEquals(1, list.size());
verify(nRepo).findByUser(eq(user), any());
verify(nRepo).findByUser(eq(user), any(Pageable.class));
}
@Test

View File

@@ -505,23 +505,18 @@
</div>
</template>
</BaseTimeline>
<InfiniteLoadMore
:key="ioKey"
:on-load="fetchNextPage"
:pause="isLoadingMessage"
root-margin="200px 0px"
/>
<InfiniteLoadMore :key="selectedTab" :on-load="fetchMore" :pause="isLoadingMessage" />
</div>
</template>
</div>
</template>
<script setup>
import { computed, 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'
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
import NotificationContainer from '~/components/NotificationContainer.vue'
import { toast } from '~/main'
import { authState, getToken } from '~/utils/auth'
import { stripMarkdownLength } from '~/utils/markdown'
@@ -532,6 +527,8 @@ import {
markRead,
notifications,
markAllRead,
fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification'
import TimeManager from '~/utils/time'
@@ -542,11 +539,16 @@ const selectedTab = ref(
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
)
const notificationPrefs = ref([])
const ioKey = computed(() => selectedTab.value)
const loadFirstPage = async () => {
await fetchNotifications({ unread: selectedTab.value === 'unread', reset: true })
const fetchMore = () => fetchNotifications()
const loadInitial = async () => {
await fetchNotifications({ reset: true, read: selectedTab.value === 'unread' ? false : null })
}
const fetchNextPage = async () => fetchNotifications()
watch(selectedTab, async (t) => {
await fetchNotifications({ reset: true, read: t === 'unread' ? false : null })
})
const fetchPrefs = async () => {
notificationPrefs.value = await fetchNotificationPreferences()
@@ -556,7 +558,7 @@ const togglePref = async (pref) => {
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
if (ok) {
pref.enabled = !pref.enabled
await fetchNotifications({ unread: selectedTab.value === 'unread', reset: true })
await fetchNotifications({ reset: true, read: selectedTab.value === 'unread' ? false : null })
await fetchUnreadCount()
} else {
toast.error('操作失败')
@@ -636,12 +638,8 @@ const formatType = (t) => {
}
}
watch(selectedTab, (val) => {
if (val !== 'control') loadFirstPage()
})
onActivated(() => {
if (selectedTab.value !== 'control') loadFirstPage()
loadInitial()
fetchPrefs()
})
</script>

View File

@@ -119,188 +119,189 @@ function createFetchNotifications() {
const notifications = ref([])
const isLoadingMessage = ref(false)
const page = ref(0)
const currentUnread = ref(false)
const fetchNotifications = async ({ unread = false, reset = false } = {}) => {
const pageSize = 30
const readFilter = ref(null)
const fetchNotifications = async ({ reset = false, read = null } = {}) => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
if (isLoadingMessage && notifications && markRead) {
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return false
}
if (reset) {
notifications.value = []
page.value = 0
currentUnread.value = unread
}
isLoadingMessage.value = true
const endpoint = currentUnread.value
? `/api/notifications/unread?page=${page.value}`
: `/api/notifications?page=${page.value}`
const res = await fetch(`${API_BASE_URL}${endpoint}`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return true
}
const data = await res.json()
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
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 === 'REACTION') {
notifications.value.push({
...n,
emoji: reactionEmojiMap[n.reactionType],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_VIEWED') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_WIN') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/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({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} 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({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'REGISTER_REQUEST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
...n,
icon: iconMap[n.type],
})
}
}
page.value++
return data.length < 50
} catch (e) {
console.error(e)
if (isLoadingMessage.value) return false
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return true
}
if (reset) {
notifications.value = []
page.value = 0
readFilter.value = read
}
isLoadingMessage.value = true
let url = `${API_BASE_URL}/api/notifications`
if (readFilter.value === false) url += '/unread'
url += `?page=${page.value}&size=${pageSize}`
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return true
}
const data = await res.json()
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
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 === 'REACTION') {
notifications.value.push({
...n,
emoji: reactionEmojiMap[n.reactionType],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_VIEWED') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_WIN') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
router.push(`/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({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.fromUser) {
markRead(n.id)
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
}
},
})
} 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({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'POST_REVIEW_REQUEST') {
notifications.value.push({
...n,
src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'REGISTER_REQUEST') {
notifications.value.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
notifications.value.push({
...n,
icon: iconMap[n.type],
})
}
}
const done = data.length < pageSize
if (!done) page.value++
return done
} catch (e) {
console.error(e)
isLoadingMessage.value = false
return true
}
return true
}
const markRead = async (id) => {