feat: add notification feature

This commit is contained in:
luo
2026-07-29 10:25:13 +08:00
parent d115363115
commit d060edb698
11 changed files with 785 additions and 10 deletions

View File

@@ -1,12 +1,14 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ref, computed, nextTick, onMounted } from 'vue'
import { getUserInfo, logout as logoutApi } from '@/api/auth'
import { clearToken } from '@/utils/auth'
import type { UserInfo } from '@/api/auth'
import { getFundSummary, getCommissionDailyStats } from '@/api/commission'
import type { FundSummary, DailyCommissionStats } from '@/api/commission'
import { getNotificationUnreadCount, getNotifications, markNotificationRead } from '@/api/notifications'
import AgentFundSummaryCard from '@/components/AgentFundSummaryCard.vue'
const NOTIFICATION_REMINDER_PENDING_KEY = 'notification_reminder_pending'
// 用户信息
const userInfo = ref<UserInfo | null>(null)
@@ -20,10 +22,16 @@
// 店铺ID
const shopId = ref<number>(0)
// 通知未读数
const notificationUnreadCount = ref<number | null>(null)
// 是否为代理账号
const isAgent = computed(() => userInfo.value?.user_type === 3)
const todayStat = computed(() => dailyStats.value[0] || null)
const notificationUnreadDisplayCount = computed(() => {
if (!notificationUnreadCount.value) return ''
return notificationUnreadCount.value > 99 ? '99+' : String(notificationUnreadCount.value)
})
function getLoginUserInfo() {
return uni.getStorageSync('user_info') as Partial<UserInfo> | undefined
@@ -113,6 +121,62 @@
}
}
async function loadNotificationUnreadCount() {
try {
const response = await getNotificationUnreadCount()
notificationUnreadCount.value = Math.max(response.count || 0, 0)
}
catch (error) {
console.error('加载通知未读数失败:', error)
}
}
function decreaseNotificationUnreadCount() {
if (notificationUnreadCount.value && notificationUnreadCount.value > 0) {
notificationUnreadCount.value -= 1
}
}
async function showUnreadNotificationReminder() {
if (uni.getStorageSync(NOTIFICATION_REMINDER_PENDING_KEY) !== true) return
// 一次登录只消费一次提醒标记,避免首页重复展示同一条提醒。
uni.removeStorageSync(NOTIFICATION_REMINDER_PENDING_KEY)
try {
const response = await getNotifications({
is_read: false,
page: 1,
page_size: 1,
})
const notification = response.items?.[0]
if (!notification) return
uni.showModal({
title: notification.title || '通知提醒',
content: notification.body || '你有一条新的未读通知',
showCancel: false,
confirmText: '知道了',
})
// 弹窗已经把通知内容呈现给用户,立即同步已读状态,不要求额外点击“已读”。
decreaseNotificationUnreadCount()
void markNotificationRead(notification.id).catch((error) => {
console.error(`标记通知 ${notification.id} 已读失败:`, error)
})
}
catch (error) {
console.error('加载未读通知提醒失败:', error)
}
}
async function loadNotificationData() {
await Promise.all([
loadNotificationUnreadCount(),
showUnreadNotificationReminder(),
])
}
// 跳转页面
function navigateTo(path : string) {
uni.navigateTo({ url: path })
@@ -137,6 +201,7 @@
clearToken()
uni.removeStorageSync('refresh_token')
uni.removeStorageSync('user_info')
uni.removeStorageSync(NOTIFICATION_REMINDER_PENDING_KEY)
// 跳转到登录页
uni.reLaunch({
@@ -148,8 +213,12 @@
})
}
onMounted(() => {
loadHomeData()
onMounted(async () => {
await loadHomeData()
if (userInfo.value) {
await nextTick()
await loadNotificationData()
}
})
</script>
@@ -175,17 +244,25 @@
</view>
<!-- 右侧用户信息 -->
<view class="flex-1">
<text class="text-18px font-700 text-[#212121] block mb-1">
{{ userInfo?.username || '欢迎回来' }}
</text>
<text class="text-13px text-[#999]">
{{ userInfo?.phone || '-' }}
</text>
<view class="flex-1">
<text class="text-18px font-700 text-[#212121] block mb-1">
{{ userInfo?.username || '欢迎回来' }}
</text>
<text class="text-13px text-[#999]">
{{ userInfo?.phone || '-' }}
</text>
</view>
<!-- 通知入口 -->
<view class="relative w-44px h-44px rounded-14px bg-[#fff7ed] flex items-center justify-center ml-3" @click="navigateTo('/pages/agent-system/notifications/index')">
<image src="@/static/icons/通知.png" class="w-26px h-26px" mode="aspectFit" />
<view v-if="notificationUnreadDisplayCount" class="absolute -top-1 -right-1 min-w-5 h-5 px-1 rounded-full bg-[#ff4d4f] flex items-center justify-center">
<text class="text-10px text-white leading-none">{{ notificationUnreadDisplayCount }}</text>
</view>
</view>
</view>
</view>
</view>
<!-- 代理端: 佣金展示 -->
<view v-if="isAgent" class="px-4 pt-4">

View File

@@ -0,0 +1,153 @@
<template>
<view class="min-h-screen bg-[#f7f8fa] px-4 py-4">
<view v-if="loading" class="flex justify-center pt-20">
<text class="text-14px text-[#64748b]">
加载中...
</text>
</view>
<view v-else-if="notifications.length" class="space-y-3">
<view
v-for="notification in notifications"
:key="notification.id"
class="rounded-16px bg-white p-4 shadow-[0_2px_10px_rgba(0,0,0,0.04)]"
>
<view class="flex items-start justify-between gap-3">
<view class="min-w-0 flex flex-1 items-center gap-2">
<text class="truncate text-15px text-[#212121] font-600">
{{ notification.title }}
</text>
<view
v-if="!notification.is_read"
class="flex-shrink-0 rounded-4px bg-[#fff1f0] px-1.5 py-0.5 text-10px text-[#f5222d]"
>
未读
</view>
</view>
<text class="flex-shrink-0 text-11px text-[#999]">
{{ formatTime(notification.created_at) }}
</text>
</view>
<text class="mt-3 break-all text-13px text-[#666] leading-6">
{{ notification.body }}
</text>
<view class="mt-3 flex items-center gap-2">
<view class="rounded-4px bg-[#f5f5f5] px-2 py-0.5 text-11px text-[#666]">
{{ categoryLabels[notification.category] || notification.category }}
</view>
<view
class="rounded-4px px-2 py-0.5 text-11px"
:class="getSeverityClass(notification.severity)"
>
{{ severityLabels[notification.severity] || notification.severity }}
</view>
<text class="ml-auto text-11px text-[#b5b5b5]">
{{ notification.is_read ? '已读' : '未读' }}
</text>
</view>
</view>
</view>
<view v-else class="flex flex-col items-center pt-24">
<image src="@/static/icons/通知.png" class="h-18 w-18 opacity-40" mode="aspectFit" />
<text class="mt-4 text-14px text-[#999]">
暂无通知
</text>
</view>
</view>
</template>
<script setup lang="ts">
import type {
NotificationCategory,
NotificationItem,
NotificationSeverity,
} from '@/api/notifications';
import { nextTick, onMounted, ref } from 'vue';
import {
getNotifications,
markNotificationRead,
} from '@/api/notifications';
const notifications = ref<NotificationItem[]>([]);
const loading = ref(true);
const categoryLabels: Record<NotificationCategory, string> = {
approval: '审批',
expiry: '临期',
sync: '同步',
system: '系统',
};
const severityLabels: Record<NotificationSeverity, string> = {
info: '提示',
warning: '警告',
error: '错误',
critical: '严重',
};
function formatTime(time: string) {
if (!time) return '-';
const date = new Date(time);
if (Number.isNaN(date.getTime())) return time;
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}
function getSeverityClass(severity: NotificationSeverity) {
const classes: Record<NotificationSeverity, string> = {
info: 'bg-[#e6f4ff] text-[#1677ff]',
warning: 'bg-[#fff7e6] text-[#d46b08]',
error: 'bg-[#fff2f0] text-[#cf1322]',
critical: 'bg-[#fff1f0] text-[#a8071a]',
};
return classes[severity];
}
async function markVisibleNotificationsAsRead() {
await nextTick();
const unreadNotifications = notifications.value.filter(notification => !notification.is_read);
unreadNotifications.forEach((notification) => {
notification.is_read = true;
notification.read_at = new Date().toISOString();
void markNotificationRead(notification.id).catch((error) => {
console.error(`标记通知 ${notification.id} 已读失败:`, error);
});
});
}
async function loadNotifications() {
loading.value = true;
try {
const response = await getNotifications({
page: 1,
page_size: 50,
});
notifications.value = response.items || [];
loading.value = false;
await markVisibleNotificationsAsRead();
}
catch (error) {
console.error('加载通知失败:', error);
}
finally {
loading.value = false;
}
}
onMounted(() => {
loadNotifications();
});
</script>
<style scoped>
.space-y-3 > view:not(:last-child) {
margin-bottom: 12px;
}
</style>

View File

@@ -74,6 +74,7 @@ const accountFocused = ref<boolean>(false);
const passwordFocused = ref<boolean>(false);
const showPassword = ref<boolean>(false);
const loading = ref<boolean>(false);
const NOTIFICATION_REMINDER_PENDING_KEY = 'notification_reminder_pending';
let redirect = HOME_PATH;
const isFormValid = computed(() => {
@@ -139,6 +140,7 @@ async function submit() {
// 保存用户信息到本地存储
uni.setStorageSync('user_info', sessionUser);
uni.setStorageSync(NOTIFICATION_REMINDER_PENDING_KEY, true);
uni.showToast({
title: '登录成功',