Revert "feat: add paginated notification APIs and frontend support"

This reverts commit c344b5b4ae.
This commit is contained in:
tim
2025-08-19 19:37:59 +08:00
parent ac3c7b7bec
commit 02be045f55
5 changed files with 204 additions and 340 deletions

View File

@@ -24,19 +24,8 @@ public class NotificationController {
@GetMapping @GetMapping
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read, public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) { Authentication auth) {
return notificationService.listNotifications(auth.getName(), read, page, size).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,
@RequestParam(value = "size", defaultValue = "30") int size,
Authentication auth) {
return notificationService.listNotifications(auth.getName(), false, page, size).stream()
.map(notificationMapper::toDto) .map(notificationMapper::toDto)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View File

@@ -6,8 +6,6 @@ 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.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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,21 +180,15 @@ public class NotificationService {
userRepository.save(user); userRepository.save(user);
} }
public List<Notification> listNotifications(String username, Boolean read, int page, int size) { 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();
org.springframework.data.domain.Pageable pageable =
org.springframework.data.domain.PageRequest.of(page, size);
List<Notification> list; List<Notification> list;
if (read == null) { if (read == null) {
list = notificationRepository list = notificationRepository.findByUserOrderByCreatedAtDesc(user);
.findByUserOrderByCreatedAtDesc(user, pageable)
.getContent();
} else { } else {
list = notificationRepository list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read);
.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable)
.getContent();
} }
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

@@ -505,16 +505,13 @@
</div> </div>
</template> </template>
</BaseTimeline> </BaseTimeline>
<div v-if="hasMore" class="load-more">
<button class="load-more-button" @click="loadMore">加载更多</button>
</div>
</div> </div>
</template> </template>
</div> </div>
</template> </template>
<script setup> <script setup>
import { computed, onMounted, 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'
@@ -522,17 +519,12 @@ 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 { import {
fetchAllNotifications, fetchNotifications,
fetchUnreadNotifications,
fetchUnreadCount, fetchUnreadCount,
isLoadingAll, isLoadingMessage,
isLoadingUnread,
markRead, markRead,
notificationsAll, notifications,
notificationsUnread,
markAllRead, markAllRead,
fetchNotificationPreferences,
updateNotificationPreference,
} from '~/utils/notification' } from '~/utils/notification'
import TimeManager from '~/utils/time' import TimeManager from '~/utils/time'
@@ -543,18 +535,8 @@ 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 pageAll = ref(0)
const pageUnread = ref(0)
const hasMoreAll = ref(true)
const hasMoreUnread = ref(true)
const filteredNotifications = computed(() => const filteredNotifications = computed(() =>
selectedTab.value === 'all' ? notificationsAll.value : notificationsUnread.value, selectedTab.value === 'all' ? notifications.value : notifications.value.filter((n) => !n.read),
)
const isLoadingMessage = computed(() =>
selectedTab.value === 'all' ? isLoadingAll.value : isLoadingUnread.value,
)
const hasMore = computed(() =>
selectedTab.value === 'all' ? hasMoreAll.value : hasMoreUnread.value,
) )
const fetchPrefs = async () => { const fetchPrefs = async () => {
@@ -565,14 +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
pageAll.value = 0 await fetchNotifications()
pageUnread.value = 0
const countAll = await fetchAllNotifications(0)
const countUnread = await fetchUnreadNotifications(0)
pageAll.value = 1
pageUnread.value = 1
hasMoreAll.value = countAll === 30
hasMoreUnread.value = countUnread === 30
await fetchUnreadCount() await fetchUnreadCount()
} else { } else {
toast.error('操作失败') toast.error('操作失败')
@@ -652,34 +627,9 @@ const formatType = (t) => {
} }
} }
const loadMore = async () => { onActivated(() => {
if (selectedTab.value === 'all') { fetchNotifications()
const c = await fetchAllNotifications(pageAll.value) fetchPrefs()
pageAll.value++
if (c < 30) hasMoreAll.value = false
} else {
const c = await fetchUnreadNotifications(pageUnread.value)
pageUnread.value++
if (c < 30) hasMoreUnread.value = false
}
}
onMounted(async () => {
await fetchPrefs()
await loadMore()
await fetchUnreadCount()
})
watch(selectedTab, async (tab) => {
if (tab === 'all' && notificationsAll.value.length === 0) {
pageAll.value = 0
hasMoreAll.value = true
await loadMore()
} else if (tab === 'unread' && notificationsUnread.value.length === 0) {
pageUnread.value = 0
hasMoreUnread.value = true
await loadMore()
}
}) })
</script> </script>
@@ -741,19 +691,6 @@ watch(selectedTab, async (tab) => {
height: 100%; height: 100%;
} }
.load-more {
text-align: center;
}
.load-more-button {
margin: 10px auto;
padding: 6px 12px;
border: 1px solid var(--normal-border-color);
border-radius: 6px;
background: transparent;
cursor: pointer;
}
.notif-content { .notif-content {
display: flex; display: flex;
flex-direction: column; flex-direction: column;

View File

@@ -116,251 +116,210 @@ export async function updateNotificationPreference(type, enabled) {
* @returns * @returns
*/ */
function createFetchNotifications() { function createFetchNotifications() {
const notificationsAll = ref([]) const notifications = ref([])
const notificationsUnread = ref([]) const isLoadingMessage = ref(false)
const isLoadingAll = ref(false) const fetchNotifications = async () => {
const isLoadingUnread = ref(false)
const pageSize = 30
function pushNotification(n, target) {
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)
router.push(`/posts/${n.post.id}`)
}
},
})
} else if (n.type === 'LOTTERY_DRAW') {
target.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') {
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],
})
}
}
async function fetchAllNotifications(page = 0) {
const config = useRuntimeConfig() const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl const API_BASE_URL = config.public.apiBaseUrl
try { if (isLoadingMessage && notifications && markRead) {
const token = getToken() try {
if (!token) { const token = getToken()
toast.error('请先登录') if (!token) {
return 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()
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],
})
}
}
} catch (e) {
console.error(e)
} }
isLoadingAll.value = true
const res = await fetch(`${API_BASE_URL}/api/notifications?page=${page}&size=${pageSize}`, {
headers: { Authorization: `Bearer ${token}` },
})
isLoadingAll.value = false
if (!res.ok) {
toast.error('获取通知失败')
return
}
const data = await res.json()
if (page === 0) notificationsAll.value = []
for (const n of data) {
pushNotification(n, notificationsAll.value)
}
return data.length
} catch (e) {
console.error(e)
return 0
} }
} }
async function fetchUnreadNotifications(page = 0) { const markRead = async (id) => {
const config = useRuntimeConfig()
const API_BASE_URL = config.public.apiBaseUrl
try {
const token = getToken()
if (!token) {
toast.error('请先登录')
return
}
isLoadingUnread.value = true
const res = await fetch(
`${API_BASE_URL}/api/notifications/unread?page=${page}&size=${pageSize}`,
{ headers: { Authorization: `Bearer ${token}` } },
)
isLoadingUnread.value = false
if (!res.ok) {
toast.error('获取通知失败')
return
}
const data = await res.json()
if (page === 0) notificationsUnread.value = []
for (const n of data) {
pushNotification(n, notificationsUnread.value)
}
return data.length
} catch (e) {
console.error(e)
return 0
}
}
async function markRead(id) {
if (!id) return if (!id) return
const nAll = notificationsAll.value.find((n) => n.id === id) const n = notifications.value.find((n) => n.id === id)
const nUnreadIndex = notificationsUnread.value.findIndex((n) => n.id === id) if (!n || n.read) return
const target = nAll || notificationsUnread.value[nUnreadIndex] n.read = true
if (!target || target.read) return
target.read = true
if (nUnreadIndex !== -1) notificationsUnread.value.splice(nUnreadIndex, 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) {
target.read = false n.read = false
if (nUnreadIndex !== -1) notificationsUnread.value.splice(nUnreadIndex, 0, target)
notificationState.unreadCount++ notificationState.unreadCount++
} else { } else {
fetchUnreadCount() fetchUnreadCount()
} }
} }
async function markAllRead() { const markAllRead = async () => {
const ids = [ // 除了 REGISTER_REQUEST 类型消息
...new Set( const idsToMark = notifications.value
[...notificationsAll.value, ...notificationsUnread.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
), notifications.value.forEach((n) => {
]
if (ids.length === 0) return
notificationsAll.value.forEach((n) => {
if (n.type !== 'REGISTER_REQUEST') n.read = true if (n.type !== 'REGISTER_REQUEST') n.read = true
}) })
notificationsUnread.value = [] notificationState.unreadCount = notifications.value.filter((n) => !n.read).length
notificationState.unreadCount = 0 const ok = await markNotificationsRead(idsToMark)
const ok = await markNotificationsRead(ids)
if (!ok) { if (!ok) {
notifications.value.forEach((n) => {
if (idsToMark.includes(n.id)) n.read = false
})
await fetchUnreadCount() await fetchUnreadCount()
return return
} }
@@ -371,26 +330,15 @@ function createFetchNotifications() {
toast.success('已读所有消息') toast.success('已读所有消息')
} }
} }
return { return {
fetchAllNotifications, fetchNotifications,
fetchUnreadNotifications, markRead,
notifications,
isLoadingMessage,
markRead, markRead,
notificationsAll,
notificationsUnread,
isLoadingAll,
isLoadingUnread,
markAllRead, markAllRead,
} }
} }
export const { export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
fetchAllNotifications, createFetchNotifications()
fetchUnreadNotifications,
markRead,
notificationsAll,
notificationsUnread,
isLoadingAll,
isLoadingUnread,
markAllRead,
} = createFetchNotifications()