Compare commits

...

4 Commits

Author SHA1 Message Date
Tim
7dd1f1b3d0 feat: add paginated notification APIs and frontend 2025-08-19 18:24:27 +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
6 changed files with 302 additions and 271 deletions

View File

@@ -15,7 +15,6 @@ 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);
long countByUserAndRead(User user, boolean read);

View File

@@ -24,8 +24,6 @@ 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 +180,18 @@ 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) {
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);
List<Notification> list;
var pageable = org.springframework.data.domain.PageRequest.of(page, 50);
if (read == null) {
p = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
list = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable).getContent();
} else {
p = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable).getContent();
}
return p.getContent().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))
when(notificationService.listNotifications("alice", null))
.thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
@@ -62,23 +62,6 @@ class NotificationControllerTest {
.andExpect(jsonPath("$[0].post.id").value(2));
}
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(3L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0)).thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(3L);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications/unread")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(3));
}
@Test
void markReadEndpoint() throws Exception {
mockMvc.perform(post("/api/notifications/read")

View File

@@ -65,15 +65,12 @@ class NotificationServiceTest {
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(user)).thenReturn(List.of(n));
List<Notification> list = service.listNotifications("bob", null);
assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(org.springframework.data.domain.Pageable.class));
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
}
@Test

View File

@@ -53,13 +53,13 @@
</div>
<BasePlaceholder
v-else-if="notifications.length === 0"
v-else-if="displayNotifications.length === 0"
text="暂时没有消息 :)"
icon="fas fa-inbox"
/>
<div class="timeline-container" v-if="notifications.length > 0">
<BaseTimeline :items="notifications">
<div class="timeline-container" v-if="displayNotifications.length > 0">
<BaseTimeline :items="displayNotifications">
<template #item="{ item }">
<div class="notif-content" :class="{ read: item.read }">
<span v-if="!item.read" class="unread-dot"></span>
@@ -505,30 +505,40 @@
</div>
</template>
</BaseTimeline>
<InfiniteLoadMore :key="ioKey" :on-load="fetchNextPage" :pause="isLoadingMessage" />
</div>
<InfiniteLoadMore
v-if="displayNotifications.length > 0"
:key="ioKey"
:on-load="fetchNextPage"
:pause="isLoadingMessage"
root-margin="200px 0px"
/>
</template>
</div>
</template>
<script setup>
import { onActivated, ref, watch } from 'vue'
import { computed, onActivated, ref, watch } 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 { toast } from '~/main'
import { authState, getToken } from '~/utils/auth'
import { stripMarkdownLength } from '~/utils/markdown'
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
import {
fetchNotifications,
fetchAllNotifications,
fetchUnreadNotifications,
fetchUnreadCount,
isLoadingMessage,
isLoadingAll,
isLoadingUnread,
markRead,
notifications,
allNotifications,
unreadNotifications,
markAllRead,
fetchNotificationPreferences,
updateNotificationPreference,
resetAll,
resetUnread,
} from '~/utils/notification'
import TimeManager from '~/utils/time'
@@ -539,8 +549,25 @@ const selectedTab = ref(
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
)
const notificationPrefs = ref([])
const displayNotifications = computed(() =>
selectedTab.value === 'all' ? allNotifications.value : unreadNotifications.value,
)
const isLoadingMessage = computed(() =>
selectedTab.value === 'all' ? isLoadingAll.value : isLoadingUnread.value,
)
const ioKey = ref(0)
const fetchNextPage = () =>
selectedTab.value === 'all' ? fetchAllNotifications() : fetchUnreadNotifications()
const loadInitial = async () => {
if (selectedTab.value === 'all') {
if (allNotifications.value.length === 0) await fetchAllNotifications()
} else if (selectedTab.value === 'unread') {
if (unreadNotifications.value.length === 0) await fetchUnreadNotifications()
}
}
const fetchPrefs = async () => {
notificationPrefs.value = await fetchNotificationPreferences()
}
@@ -549,7 +576,9 @@ const togglePref = async (pref) => {
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
if (ok) {
pref.enabled = !pref.enabled
await fetchNotifications(selectedTab.value, true)
resetAll()
resetUnread()
await loadInitial()
await fetchUnreadCount()
} else {
toast.error('操作失败')
@@ -629,21 +658,15 @@ const formatType = (t) => {
}
}
onActivated(() => {
fetchNotifications(selectedTab.value, true)
fetchPrefs()
})
watch(selectedTab, (tab) => {
if (tab !== 'control') {
fetchNotifications(tab, true)
} else {
fetchPrefs()
}
watch(selectedTab, async () => {
await loadInitial()
ioKey.value++
})
const fetchNextPage = () => fetchNotifications(selectedTab.value)
onActivated(() => {
loadInitial()
fetchPrefs()
})
</script>
<style scoped>
@@ -657,8 +680,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

@@ -4,9 +4,7 @@ import { toast } from '~/composables/useToast'
import { authState, getToken } from '~/utils/auth'
import { reactionEmojiMap } from '~/utils/reactions'
export const notificationState = reactive({
unreadCount: 0,
})
export const notificationState = reactive({ unreadCount: 0 })
const iconMap = {
POST_VIEWED: 'fas fa-eye',
@@ -57,7 +55,6 @@ export async function markNotificationsRead(ids) {
try {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const token = getToken()
if (!token || !ids || ids.length === 0) return false
const res = await fetch(`${API_BASE_URL}/api/notifications/read`, {
@@ -78,7 +75,6 @@ export async function fetchNotificationPreferences() {
try {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const token = getToken()
if (!token) return []
const res = await fetch(`${API_BASE_URL}/api/notifications/prefs`, {
@@ -112,212 +108,219 @@ export async function updateNotificationPreference(type, enabled) {
}
/**
* 处理信息的高阶函数
* @returns
* 提供通知列表的分页获取与状态管理
*/
function createFetchNotifications() {
const notifications = ref([])
const isLoadingMessage = ref(false)
const page = ref(0)
const finished = ref(false)
const currentTab = ref('all')
const allNotifications = ref([])
const unreadNotifications = ref([])
const pageAll = ref(0)
const pageUnread = ref(0)
const isLoadingAll = ref(false)
const isLoadingUnread = ref(false)
const fetchNotifications = async (tab = 'all', reset = false) => {
const processAndPush = (data, target) => {
for (const n of data) {
if (n.type === 'COMMENT_REPLY') {
target.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'REACTION') {
target.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') {
target.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') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {
if (n.post) {
markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true })
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
target.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_UPDATED') {
target.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') {
target.push({
...n,
src: n.comment.author.avatar,
iconClick: () => {
markRead(n.id)
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
},
})
} else if (n.type === 'MENTION') {
target.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') {
target.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') {
target.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') {
target.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') {
target.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') {
target.push({
...n,
icon: iconMap[n.type],
iconClick: () => {},
})
} else {
target.push({
...n,
icon: iconMap[n.type],
})
}
}
}
const fetchAllNotifications = async () => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return true
}
if (reset || tab !== currentTab.value) {
notifications.value = []
page.value = 0
finished.value = false
currentTab.value = tab
}
if (finished.value) return true
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}`,
},
})
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)
navigateTo(`/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)
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({
...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 < 50
if (!done) {
page.value++
} else {
finished.value = true
}
return done
} catch (e) {
console.error(e)
isLoadingMessage.value = false
return true
const token = getToken()
if (!token) {
toast.error('请先登录')
return { done: true }
}
isLoadingAll.value = true
const res = await fetch(`${API_BASE_URL}/api/notifications?page=${pageAll.value}`, {
headers: { Authorization: `Bearer ${token}` },
})
isLoadingAll.value = false
if (!res.ok) {
toast.error('获取通知失败')
return { done: true }
}
const data = await res.json()
processAndPush(data, allNotifications.value)
pageAll.value++
return { done: data.length < 50 }
}
const fetchUnreadNotifications = async () => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
const token = getToken()
if (!token) {
toast.error('请先登录')
return { done: true }
}
isLoadingUnread.value = true
const res = await fetch(`${API_BASE_URL}/api/notifications/unread?page=${pageUnread.value}`, {
headers: { Authorization: `Bearer ${token}` },
})
isLoadingUnread.value = false
if (!res.ok) {
toast.error('获取通知失败')
return { done: true }
}
const data = await res.json()
processAndPush(data, unreadNotifications.value)
pageUnread.value++
return { done: data.length < 50 }
}
const markRead = async (id) => {
if (!id) return
const n = notifications.value.find((n) => n.id === id)
if (!n || n.read) return
n.read = true
const nAll = allNotifications.value.find((n) => n.id === id)
const idxUnread = unreadNotifications.value.findIndex((n) => n.id === id)
const unreadItem = idxUnread !== -1 ? unreadNotifications.value[idxUnread] : null
if (nAll) nAll.read = true
if (idxUnread !== -1) unreadNotifications.value.splice(idxUnread, 1)
if (notificationState.unreadCount > 0) notificationState.unreadCount--
const ok = await markNotificationsRead([id])
if (!ok) {
n.read = false
if (nAll) nAll.read = false
if (idxUnread !== -1 && unreadItem) unreadNotifications.value.splice(idxUnread, 0, unreadItem)
notificationState.unreadCount++
} else {
fetchUnreadCount()
@@ -325,20 +328,28 @@ function createFetchNotifications() {
}
const markAllRead = async () => {
// 除了 REGISTER_REQUEST 类型消息
const idsToMark = notifications.value
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
.map((n) => n.id)
const idsToMark = [
...new Set(
[...allNotifications.value, ...unreadNotifications.value]
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
.map((n) => n.id),
),
]
if (idsToMark.length === 0) return
notifications.value.forEach((n) => {
allNotifications.value.forEach((n) => {
if (n.type !== 'REGISTER_REQUEST') n.read = true
})
notificationState.unreadCount = notifications.value.filter((n) => !n.read).length
const prevUnread = [...unreadNotifications.value]
unreadNotifications.value = unreadNotifications.value.filter(
(n) => n.type === 'REGISTER_REQUEST',
)
notificationState.unreadCount = unreadNotifications.value.length
const ok = await markNotificationsRead(idsToMark)
if (!ok) {
notifications.value.forEach((n) => {
allNotifications.value.forEach((n) => {
if (idsToMark.includes(n.id)) n.read = false
})
unreadNotifications.value = prevUnread
await fetchUnreadCount()
return
}
@@ -349,14 +360,40 @@ function createFetchNotifications() {
toast.success('已读所有消息')
}
}
const resetAll = () => {
pageAll.value = 0
allNotifications.value = []
}
const resetUnread = () => {
pageUnread.value = 0
unreadNotifications.value = []
}
return {
fetchNotifications,
fetchAllNotifications,
fetchUnreadNotifications,
markRead,
notifications,
isLoadingMessage,
markAllRead,
allNotifications,
unreadNotifications,
isLoadingAll,
isLoadingUnread,
resetAll,
resetUnread,
}
}
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
createFetchNotifications()
export const {
fetchAllNotifications,
fetchUnreadNotifications,
markRead,
markAllRead,
allNotifications,
unreadNotifications,
isLoadingAll,
isLoadingUnread,
resetAll,
resetUnread,
} = createFetchNotifications()