Revert "feat: add paginated notification APIs and frontend"

This reverts commit 7dd1f1b3d0.
This commit is contained in:
tim
2025-08-19 18:26:55 +08:00
parent fbca19791a
commit 1a12bec7b1
5 changed files with 209 additions and 313 deletions

View File

@@ -23,17 +23,9 @@ public class NotificationController {
private final NotificationMapper notificationMapper; private final NotificationMapper notificationMapper;
@GetMapping @GetMapping
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page, public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
Authentication auth) { Authentication auth) {
return notificationService.listNotifications(auth.getName(), null, page).stream() return notificationService.listNotifications(auth.getName(), read).stream()
.map(notificationMapper::toDto)
.collect(Collectors.toList());
}
@GetMapping("/unread")
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
Authentication auth) {
return notificationService.listNotifications(auth.getName(), false, page).stream()
.map(notificationMapper::toDto) .map(notificationMapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View File

@@ -5,8 +5,6 @@ import com.openisle.model.User;
import com.openisle.model.Post; import com.openisle.model.Post;
import com.openisle.model.Comment; import com.openisle.model.Comment;
import com.openisle.model.NotificationType; import com.openisle.model.NotificationType;
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.JpaRepository;
import java.util.List; import java.util.List;
@@ -15,8 +13,6 @@ import java.util.List;
public interface NotificationRepository extends JpaRepository<Notification, Long> { public interface NotificationRepository extends JpaRepository<Notification, Long> {
List<Notification> findByUserOrderByCreatedAtDesc(User user); List<Notification> findByUserOrderByCreatedAtDesc(User user);
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read); 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); long countByUserAndRead(User user, boolean read);
List<Notification> findByPost(Post post); List<Notification> findByPost(Post post);
List<Notification> findByComment(Comment comment); List<Notification> findByComment(Comment comment);

View File

@@ -180,16 +180,15 @@ public class NotificationService {
userRepository.save(user); userRepository.save(user);
} }
public List<Notification> listNotifications(String username, Boolean read, int page) { public List<Notification> listNotifications(String username, Boolean read) {
User user = userRepository.findByUsername(username) User user = userRepository.findByUsername(username)
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found")); .orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
Set<NotificationType> disabled = user.getDisabledNotificationTypes(); Set<NotificationType> disabled = user.getDisabledNotificationTypes();
List<Notification> list; List<Notification> list;
var pageable = org.springframework.data.domain.PageRequest.of(page, 50);
if (read == null) { if (read == null) {
list = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable).getContent(); list = notificationRepository.findByUserOrderByCreatedAtDesc(user);
} else { } else {
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable).getContent(); list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read);
} }
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList()); return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
} }

View File

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

View File

@@ -4,7 +4,9 @@ import { toast } from '~/composables/useToast'
import { authState, getToken } from '~/utils/auth' import { authState, getToken } from '~/utils/auth'
import { reactionEmojiMap } from '~/utils/reactions' import { reactionEmojiMap } from '~/utils/reactions'
export const notificationState = reactive({ unreadCount: 0 }) export const notificationState = reactive({
unreadCount: 0,
})
const iconMap = { const iconMap = {
POST_VIEWED: 'fas fa-eye', POST_VIEWED: 'fas fa-eye',
@@ -55,6 +57,7 @@ export async function markNotificationsRead(ids) {
try { try {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
const token = getToken() const token = getToken()
if (!token || !ids || ids.length === 0) return false if (!token || !ids || ids.length === 0) return false
const res = await fetch(`${API_BASE_URL}/api/notifications/read`, { const res = await fetch(`${API_BASE_URL}/api/notifications/read`, {
@@ -75,6 +78,7 @@ export async function fetchNotificationPreferences() {
try { try {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
const token = getToken() const token = getToken()
if (!token) return [] if (!token) return []
const res = await fetch(`${API_BASE_URL}/api/notifications/prefs`, { const res = await fetch(`${API_BASE_URL}/api/notifications/prefs`, {
@@ -108,20 +112,39 @@ export async function updateNotificationPreference(type, enabled) {
} }
/** /**
* 提供通知列表的分页获取与状态管理 * 处理信息的高阶函数
* @returns
*/ */
function createFetchNotifications() { function createFetchNotifications() {
const allNotifications = ref([]) const notifications = ref([])
const unreadNotifications = ref([]) const isLoadingMessage = ref(false)
const pageAll = ref(0) const fetchNotifications = async () => {
const pageUnread = ref(0) const config = useRuntimeConfig()
const isLoadingAll = ref(false) const API_BASE_URL = config.public.apiBaseUrl
const isLoadingUnread = ref(false) if (isLoadingMessage && notifications && markRead) {
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return
}
isLoadingMessage.value = true
notifications.value = []
const res = await fetch(`${API_BASE_URL}/api/notifications`, {
headers: {
Authorization: `Bearer ${token}`,
},
})
isLoadingMessage.value = false
if (!res.ok) {
toast.error('获取通知失败')
return
}
const data = await res.json()
const processAndPush = (data, target) => {
for (const n of data) { for (const n of data) {
if (n.type === 'COMMENT_REPLY') { if (n.type === 'COMMENT_REPLY') {
target.push({ notifications.value.push({
...n, ...n,
src: n.comment.author.avatar, src: n.comment.author.avatar,
iconClick: () => { iconClick: () => {
@@ -130,7 +153,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'REACTION') { } else if (n.type === 'REACTION') {
target.push({ notifications.value.push({
...n, ...n,
emoji: reactionEmojiMap[n.reactionType], emoji: reactionEmojiMap[n.reactionType],
iconClick: () => { iconClick: () => {
@@ -141,7 +164,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'POST_VIEWED') { } else if (n.type === 'POST_VIEWED') {
target.push({ notifications.value.push({
...n, ...n,
src: n.fromUser ? n.fromUser.avatar : null, src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type], icon: n.fromUser ? undefined : iconMap[n.type],
@@ -153,29 +176,29 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'LOTTERY_WIN') { } else if (n.type === 'LOTTERY_WIN') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => { iconClick: () => {
if (n.post) { if (n.post) {
markRead(n.id) markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true }) router.push(`/posts/${n.post.id}`)
} }
}, },
}) })
} else if (n.type === 'LOTTERY_DRAW') { } else if (n.type === 'LOTTERY_DRAW') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => { iconClick: () => {
if (n.post) { if (n.post) {
markRead(n.id) markRead(n.id)
navigateTo(`/posts/${n.post.id}`, { replace: true }) router.push(`/posts/${n.post.id}`)
} }
}, },
}) })
} else if (n.type === 'POST_UPDATED') { } else if (n.type === 'POST_UPDATED') {
target.push({ notifications.value.push({
...n, ...n,
src: n.comment.author.avatar, src: n.comment.author.avatar,
iconClick: () => { iconClick: () => {
@@ -184,7 +207,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'USER_ACTIVITY') { } else if (n.type === 'USER_ACTIVITY') {
target.push({ notifications.value.push({
...n, ...n,
src: n.comment.author.avatar, src: n.comment.author.avatar,
iconClick: () => { iconClick: () => {
@@ -193,7 +216,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'MENTION') { } else if (n.type === 'MENTION') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => { iconClick: () => {
@@ -204,7 +227,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') { } else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => { iconClick: () => {
@@ -215,7 +238,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'FOLLOWED_POST') { } else if (n.type === 'FOLLOWED_POST') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => { iconClick: () => {
@@ -226,7 +249,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') { } else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => { iconClick: () => {
@@ -237,7 +260,7 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'POST_REVIEW_REQUEST') { } else if (n.type === 'POST_REVIEW_REQUEST') {
target.push({ notifications.value.push({
...n, ...n,
src: n.fromUser ? n.fromUser.avatar : null, src: n.fromUser ? n.fromUser.avatar : null,
icon: n.fromUser ? undefined : iconMap[n.type], icon: n.fromUser ? undefined : iconMap[n.type],
@@ -249,78 +272,33 @@ function createFetchNotifications() {
}, },
}) })
} else if (n.type === 'REGISTER_REQUEST') { } else if (n.type === 'REGISTER_REQUEST') {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
iconClick: () => {}, iconClick: () => {},
}) })
} else { } else {
target.push({ notifications.value.push({
...n, ...n,
icon: iconMap[n.type], icon: iconMap[n.type],
}) })
} }
} }
} catch (e) {
console.error(e)
} }
const fetchAllNotifications = async () => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
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) => { const markRead = async (id) => {
if (!id) return if (!id) return
const nAll = allNotifications.value.find((n) => n.id === id) const n = notifications.value.find((n) => n.id === id)
const idxUnread = unreadNotifications.value.findIndex((n) => n.id === id) if (!n || n.read) return
const unreadItem = idxUnread !== -1 ? unreadNotifications.value[idxUnread] : null n.read = true
if (nAll) nAll.read = true
if (idxUnread !== -1) unreadNotifications.value.splice(idxUnread, 1)
if (notificationState.unreadCount > 0) notificationState.unreadCount-- if (notificationState.unreadCount > 0) notificationState.unreadCount--
const ok = await markNotificationsRead([id]) const ok = await markNotificationsRead([id])
if (!ok) { if (!ok) {
if (nAll) nAll.read = false n.read = false
if (idxUnread !== -1 && unreadItem) unreadNotifications.value.splice(idxUnread, 0, unreadItem)
notificationState.unreadCount++ notificationState.unreadCount++
} else { } else {
fetchUnreadCount() fetchUnreadCount()
@@ -328,28 +306,20 @@ function createFetchNotifications() {
} }
const markAllRead = async () => { const markAllRead = async () => {
const idsToMark = [ // 除了 REGISTER_REQUEST 类型消息
...new Set( const idsToMark = notifications.value
[...allNotifications.value, ...unreadNotifications.value]
.filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read) .filter((n) => n.type !== 'REGISTER_REQUEST' && !n.read)
.map((n) => n.id), .map((n) => n.id)
),
]
if (idsToMark.length === 0) return if (idsToMark.length === 0) return
allNotifications.value.forEach((n) => { notifications.value.forEach((n) => {
if (n.type !== 'REGISTER_REQUEST') n.read = true if (n.type !== 'REGISTER_REQUEST') n.read = true
}) })
const prevUnread = [...unreadNotifications.value] notificationState.unreadCount = notifications.value.filter((n) => !n.read).length
unreadNotifications.value = unreadNotifications.value.filter(
(n) => n.type === 'REGISTER_REQUEST',
)
notificationState.unreadCount = unreadNotifications.value.length
const ok = await markNotificationsRead(idsToMark) const ok = await markNotificationsRead(idsToMark)
if (!ok) { if (!ok) {
allNotifications.value.forEach((n) => { notifications.value.forEach((n) => {
if (idsToMark.includes(n.id)) n.read = false if (idsToMark.includes(n.id)) n.read = false
}) })
unreadNotifications.value = prevUnread
await fetchUnreadCount() await fetchUnreadCount()
return return
} }
@@ -360,40 +330,15 @@ function createFetchNotifications() {
toast.success('已读所有消息') toast.success('已读所有消息')
} }
} }
const resetAll = () => {
pageAll.value = 0
allNotifications.value = []
}
const resetUnread = () => {
pageUnread.value = 0
unreadNotifications.value = []
}
return { return {
fetchAllNotifications, fetchNotifications,
fetchUnreadNotifications, markRead,
notifications,
isLoadingMessage,
markRead, markRead,
markAllRead, markAllRead,
allNotifications,
unreadNotifications,
isLoadingAll,
isLoadingUnread,
resetAll,
resetUnread,
} }
} }
export const { export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
fetchAllNotifications, createFetchNotifications()
fetchUnreadNotifications,
markRead,
markAllRead,
allNotifications,
unreadNotifications,
isLoadingAll,
isLoadingUnread,
resetAll,
resetUnread,
} = createFetchNotifications()