feat: 完成 P1 全部功能 + 修复 proxy 导出 + 切换 MySQL 端口至 14013

## P1 功能(20 项)
- 站内消息系统、家长仪表盘、学生考勤管理
- Excel 导入导出、用户批量导入、成绩导出
- 排课规则+自动排课+课表调整
- 成绩趋势+对比分析、密码安全策略、速率限制
- 数据变更日志、文件预览+存储策略、全文检索
- 依赖审计集成 CI、数据库定时备份、E2E 测试完善
- 通知偏好管理

## 基础设施修复
- src/proxy.ts: 将 middleware 导出重命名为 proxy(Next.js 16 要求)
- .env: MySQL 端口从 13002 切换至 14013
- scripts/create-db.ts: 新增数据库初始化脚本

## 架构文档同步
- 004_architecture_impact_map.md 和 005_architecture_data.json
  完整记录所有新增表、模块、路由、权限、依赖关系
This commit is contained in:
SpecialX
2026-06-17 13:44:37 +08:00
parent 125f7ec54c
commit 3b6272c99d
195 changed files with 27274 additions and 416 deletions

View File

@@ -0,0 +1,245 @@
"use server"
import { revalidatePath } from "next/cache"
import { PermissionDeniedError, requireAuth, requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state"
import { SendMessageSchema } from "./schema"
import {
getMessages,
getMessageById,
createMessage,
markMessageAsRead,
deleteMessage,
getNotifications,
createNotification,
markNotificationAsRead,
markAllNotificationsAsRead,
getRecipients,
} from "./data-access"
import {
getNotificationPreferences,
upsertNotificationPreferences,
} from "./notification-preferences"
import type {
Message,
Notification,
MessageType,
NotificationPreferences,
RecipientOption,
UpdateNotificationPreferencesInput,
} from "./types"
export async function sendMessageAction(
prevState: ActionState<string> | null,
formData: FormData
): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_SEND)
const parsed = SendMessageSchema.safeParse({
receiverId: formData.get("receiverId"),
subject: formData.get("subject") || undefined,
content: formData.get("content"),
parentMessageId: formData.get("parentMessageId") || undefined,
})
if (!parsed.success) {
return { success: false, message: "Invalid form data", errors: parsed.error.flatten().fieldErrors }
}
const input = parsed.data
if (input.receiverId === ctx.userId) {
return { success: false, message: "Cannot send a message to yourself" }
}
const id = await createMessage({
senderId: ctx.userId,
receiverId: input.receiverId,
subject: input.subject,
content: input.content,
parentMessageId: input.parentMessageId,
})
// Notify the receiver about the new message
await createNotification({
userId: input.receiverId,
type: "message",
title: input.subject ? `New message: ${input.subject}` : "New message",
content: input.content.slice(0, 200),
link: `/messages/${id}`,
})
revalidatePath("/messages")
revalidatePath(`/messages/${id}`)
return { success: true, message: "Message sent", data: id }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markMessageAsReadAction(messageId: string): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
await markMessageAsRead(messageId, ctx.userId)
revalidatePath("/messages")
revalidatePath(`/messages/${messageId}`)
return { success: true, message: "Marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function deleteMessageAction(messageId: string): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_DELETE)
await deleteMessage(messageId, ctx.userId)
revalidatePath("/messages")
revalidatePath(`/messages/${messageId}`)
return { success: true, message: "Message deleted" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getMessagesAction(
params: { type: MessageType; page?: number; pageSize?: number }
): Promise<ActionState<{ items: Message[]; total: number; page: number; pageSize: number; totalPages: number }>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const result = await getMessages({ userId: ctx.userId, ...params })
return { success: true, data: result }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getMessageDetailAction(messageId: string): Promise<ActionState<Message>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const message = await getMessageById(messageId, ctx.userId)
if (!message) return { success: false, message: "Message not found" }
// Auto-mark as read when viewed by receiver
if (!message.isRead && message.receiverId === ctx.userId) {
await markMessageAsRead(messageId, ctx.userId)
revalidatePath("/messages")
}
return { success: true, data: message }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getRecipientsAction(): Promise<ActionState<RecipientOption[]>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_SEND)
const recipients = await getRecipients(ctx.userId, ctx.dataScope)
return { success: true, data: recipients }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getNotificationsAction(
params?: { page?: number; pageSize?: number; unreadOnly?: boolean }
): Promise<ActionState<{ items: Notification[]; total: number; page: number; pageSize: number; totalPages: number }>> {
try {
const ctx = await requireAuth()
const result = await getNotifications(ctx.userId, params)
return { success: true, data: result }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markNotificationAsReadAction(
notificationId: string
): Promise<ActionState<string>> {
try {
const ctx = await requireAuth()
await markNotificationAsRead(notificationId, ctx.userId)
revalidatePath("/messages")
return { success: true, message: "Notification marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markAllNotificationsAsReadAction(): Promise<ActionState<string>> {
try {
const ctx = await requireAuth()
await markAllNotificationsAsRead(ctx.userId)
revalidatePath("/messages")
return { success: true, message: "All notifications marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getNotificationPreferencesAction(): Promise<ActionState<NotificationPreferences>> {
try {
const ctx = await requireAuth()
const prefs = await getNotificationPreferences(ctx.userId)
return { success: true, data: prefs }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function updateNotificationPreferencesAction(
prevState: ActionState<NotificationPreferences> | null,
formData: FormData
): Promise<ActionState<NotificationPreferences>> {
try {
const ctx = await requireAuth()
// 从 FormData 中解析布尔值checkbox 提交 "on" 或不提交)
const parseBool = (key: string): boolean => formData.get(key) === "on"
const input: UpdateNotificationPreferencesInput = {
emailEnabled: parseBool("emailEnabled"),
smsEnabled: parseBool("smsEnabled"),
pushEnabled: parseBool("pushEnabled"),
homeworkNotifications: parseBool("homeworkNotifications"),
gradeNotifications: parseBool("gradeNotifications"),
announcementNotifications: parseBool("announcementNotifications"),
messageNotifications: parseBool("messageNotifications"),
attendanceNotifications: parseBool("attendanceNotifications"),
}
const updated = await upsertNotificationPreferences(ctx.userId, input)
if (!updated) {
return { success: false, message: "Failed to update notification preferences" }
}
revalidatePath("/settings")
return { success: true, message: "Notification preferences updated", data: updated }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}

View File

@@ -0,0 +1,146 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { ArrowLeft, Send } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select"
import { sendMessageAction } from "../actions"
import type { RecipientOption } from "../types"
export function MessageCompose({
recipients,
parentMessageId,
defaultReceiverId,
defaultSubject,
backHref = "/messages",
}: {
recipients: RecipientOption[]
parentMessageId?: string
defaultReceiverId?: string
defaultSubject?: string
backHref?: string
}) {
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "")
const handleSubmit = async (formData: FormData) => {
if (!receiverId) {
toast.error("Please select a recipient")
return
}
formData.set("receiverId", receiverId)
if (parentMessageId) {
formData.set("parentMessageId", parentMessageId)
}
setIsWorking(true)
try {
const res = await sendMessageAction(null, formData)
if (res.success) {
toast.success(res.message)
router.push("/messages")
router.refresh()
} else {
toast.error(res.message || "Failed to send message")
}
} catch {
toast.error("Failed to send message")
} finally {
setIsWorking(false)
}
}
return (
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Button asChild variant="ghost" size="icon">
<a href={backHref}>
<ArrowLeft className="h-4 w-4" />
</a>
</Button>
<CardTitle>{parentMessageId ? "Reply" : "New Message"}</CardTitle>
</div>
</CardHeader>
<CardContent>
<form action={handleSubmit} className="space-y-6">
<div className="grid gap-2">
<Label htmlFor="receiverId">To</Label>
<Select value={receiverId} onValueChange={setReceiverId} disabled={!!defaultReceiverId}>
<SelectTrigger>
<SelectValue placeholder="Select a recipient" />
</SelectTrigger>
<SelectContent>
{recipients.map((r) => (
<SelectItem key={r.id} value={r.id}>
{r.name}
{r.role ? ` (${r.role})` : ""}
</SelectItem>
))}
</SelectContent>
</Select>
<input type="hidden" name="receiverId" value={receiverId} />
</div>
<div className="grid gap-2">
<Label htmlFor="subject">Subject</Label>
<Input
id="subject"
name="subject"
placeholder="Message subject"
defaultValue={defaultSubject ?? ""}
maxLength={255}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="content">Content</Label>
<Textarea
id="content"
name="content"
placeholder="Write your message..."
className="min-h-[200px]"
required
/>
</div>
<CardFooter className="justify-end gap-2 px-0">
<Button
type="button"
variant="outline"
onClick={() => router.push(backHref)}
disabled={isWorking}
>
Cancel
</Button>
<Button type="submit" disabled={isWorking || !receiverId}>
{isWorking ? (
"Sending..."
) : (
<>
<Send className="mr-2 h-4 w-4" />
Send
</>
)}
</Button>
</CardFooter>
</form>
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,153 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { ArrowLeft, Mail, Reply, Trash2 } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { formatDate } from "@/shared/lib/utils"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"
import { deleteMessageAction } from "../actions"
import type { Message } from "../types"
export function MessageDetail({
message,
currentUserId,
backHref = "/messages",
}: {
message: Message
currentUserId: string
backHref?: string
}) {
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const [deleteOpen, setDeleteOpen] = useState(false)
const { hasPermission } = usePermission()
const canSend = hasPermission(Permissions.MESSAGE_SEND)
const canDelete = hasPermission(Permissions.MESSAGE_DELETE)
const isReceived = message.receiverId === currentUserId
const counterpart = isReceived ? message.senderName : message.receiverName
const counterpartLabel = isReceived ? "From" : "To"
const handleDelete = async () => {
setIsWorking(true)
try {
const res = await deleteMessageAction(message.id)
if (res.success) {
toast.success(res.message)
router.push("/messages")
router.refresh()
} else {
toast.error(res.message || "Failed to delete")
}
} catch {
toast.error("Failed to delete")
} finally {
setIsWorking(false)
setDeleteOpen(false)
}
}
const replyHref = canSend
? `/messages/compose?parentId=${message.id}&receiverId=${isReceived ? message.senderId : message.receiverId}&subject=${encodeURIComponent(
message.subject?.startsWith("Re:") ? message.subject : `Re: ${message.subject ?? ""}`
)}`
: undefined
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Button asChild variant="ghost" size="icon">
<a href={backHref}>
<ArrowLeft className="h-4 w-4" />
</a>
</Button>
<h2 className="text-2xl font-bold tracking-tight">Message</h2>
</div>
<div className="flex flex-wrap items-center gap-2">
{canSend ? (
<Button asChild variant="outline">
<Link href={replyHref ?? "#"}>
<Reply className="mr-2 h-4 w-4" />
Reply
</Link>
</Button>
) : null}
{canDelete ? (
<Button onClick={() => setDeleteOpen(true)} disabled={isWorking} variant="destructive">
<Trash2 className="mr-2 h-4 w-4" />
Delete
</Button>
) : null}
</div>
</div>
<Card>
<CardHeader className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<Mail className="text-muted-foreground h-4 w-4" />
{isReceived && !message.isRead ? (
<Badge variant="default">New</Badge>
) : isReceived ? (
<Badge variant="secondary">Read</Badge>
) : (
<Badge variant="outline">Sent</Badge>
)}
</div>
<CardTitle className="text-2xl">{message.subject ?? "(no subject)"}</CardTitle>
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span>
{counterpartLabel}: <span className="font-medium">{counterpart ?? "Unknown"}</span>
</span>
<span>·</span>
<span>{formatDate(message.createdAt)}</span>
{message.readAt && isReceived ? (
<>
<span>·</span>
<span>Read {formatDate(message.readAt)}</span>
</>
) : null}
</div>
</CardHeader>
<CardContent>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{message.content}</p>
</CardContent>
</Card>
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete message</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete the message &quot;{message.subject ?? "(no subject)"}&quot;.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isWorking}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} disabled={isWorking}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -0,0 +1,117 @@
"use client"
import { useMemo, useState } from "react"
import Link from "next/link"
import { Mail, MailOpen, Plus, Send, Inbox } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { formatDate } from "@/shared/lib/utils"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"
import type { Message, MessageType } from "../types"
type Tab = "inbox" | "sent"
export function MessageList({
messages,
currentUserId,
initialType = "inbox",
}: {
messages: Message[]
currentUserId: string
initialType?: MessageType
}) {
const [tab, setTab] = useState<Tab>(initialType === "sent" ? "sent" : "inbox")
const { hasPermission } = usePermission()
const canSend = hasPermission(Permissions.MESSAGE_SEND)
const filtered = useMemo(() => {
if (tab === "inbox") return messages.filter((m) => m.receiverId === currentUserId)
return messages.filter((m) => m.senderId === currentUserId)
}, [messages, tab, currentUserId])
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<Tabs value={tab} onValueChange={(v) => setTab(v as Tab)}>
<TabsList>
<TabsTrigger value="inbox" className="gap-2">
<Inbox className="h-4 w-4" />
Inbox
</TabsTrigger>
<TabsTrigger value="sent" className="gap-2">
<Send className="h-4 w-4" />
Sent
</TabsTrigger>
</TabsList>
</Tabs>
{canSend ? (
<Button asChild>
<Link href="/messages/compose">
<Plus className="mr-2 h-4 w-4" />
Compose
</Link>
</Button>
) : null}
</div>
{filtered.length === 0 ? (
<EmptyState
title={tab === "inbox" ? "Inbox is empty" : "No sent messages"}
description={
tab === "inbox"
? "You have no incoming messages yet."
: "You have not sent any messages yet."
}
icon={Mail}
className="h-auto border-none shadow-none"
/>
) : (
<div className="space-y-3">
{filtered.map((m) => {
const isReceived = m.receiverId === currentUserId
const counterpart = isReceived ? m.senderName : m.receiverName
const unread = isReceived && !m.isRead
return (
<Link key={m.id} href={`/messages/${m.id}`} className="block">
<Card className={`transition-colors hover:bg-accent/50 ${unread ? "border-primary/40" : ""}`}>
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
{unread ? (
<Mail className="h-4 w-4 text-primary" />
) : (
<MailOpen className="text-muted-foreground h-4 w-4" />
)}
<span className={`text-sm font-medium ${unread ? "text-primary" : ""}`}>
{m.subject ?? "(no subject)"}
</span>
{unread ? <Badge variant="default" className="text-xs">New</Badge> : null}
</div>
<p className="text-muted-foreground text-xs">
{isReceived ? "From" : "To"}: {counterpart ?? "Unknown"}
</p>
</div>
<span className="text-muted-foreground shrink-0 text-xs">
{formatDate(m.createdAt)}
</span>
</CardHeader>
<CardContent className="pt-0">
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{m.content}
</p>
</CardContent>
</Card>
</Link>
)
})}
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,159 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { formatDate } from "@/shared/lib/utils"
import {
getNotificationsAction,
markAllNotificationsAsReadAction,
markNotificationAsReadAction,
} from "../actions"
import type { Notification, NotificationType } from "../types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare,
announcement: Megaphone,
homework: PenTool,
grade: GraduationCap,
}
export function NotificationDropdown() {
const router = useRouter()
const [notifications, setNotifications] = useState<Notification[]>([])
const [unreadCount, setUnreadCount] = useState(0)
const [open, setOpen] = useState(false)
useEffect(() => {
let active = true
void (async () => {
const res = await getNotificationsAction({ pageSize: 10 })
if (!active) return
if (res.success && res.data) {
setNotifications(res.data.items)
setUnreadCount(res.data.items.filter((n) => !n.isRead).length)
}
})()
return () => {
active = false
}
}, [])
const handleMarkAllRead = async () => {
const res = await markAllNotificationsAsReadAction()
if (res.success) {
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })))
setUnreadCount(0)
router.refresh()
}
}
const handleMarkRead = async (id: string) => {
const res = await markNotificationAsReadAction(id)
if (res.success) {
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
)
setUnreadCount((c) => Math.max(0, c - 1))
router.refresh()
}
}
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="relative text-muted-foreground">
<Bell className="size-5" />
{unreadCount > 0 ? (
<Badge
variant="destructive"
className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center px-1 text-[10px]"
>
{unreadCount > 9 ? "9+" : unreadCount}
</Badge>
) : null}
<span className="sr-only">Notifications</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 p-0">
<DropdownMenuLabel className="flex items-center justify-between">
<span>Notifications</span>
{unreadCount > 0 ? (
<button
type="button"
onClick={handleMarkAllRead}
className="text-primary text-xs hover:underline"
>
<CheckCheck className="mr-1 inline h-3 w-3" />
Mark all read
</button>
) : null}
</DropdownMenuLabel>
<DropdownMenuSeparator className="mb-0" />
<ScrollArea className="max-h-[320px]">
{notifications.length === 0 ? (
<div className="text-muted-foreground px-4 py-8 text-center text-sm">
No notifications
</div>
) : (
notifications.map((n) => {
const Icon = TYPE_ICON[n.type] ?? Bell
return (
<DropdownMenuItem
key={n.id}
className="flex items-start gap-2 py-3"
onSelect={(e) => {
if (!n.isRead) {
e.preventDefault()
handleMarkRead(n.id)
}
}}
>
<div className="bg-muted mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full">
<Icon className="h-3.5 w-3.5" />
</div>
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex items-center gap-1.5">
{!n.isRead ? (
<span className="bg-primary size-1.5 shrink-0 rounded-full" />
) : null}
<span className={`text-xs ${!n.isRead ? "font-semibold" : "font-medium"}`}>
{n.title}
</span>
</div>
{n.content ? (
<p className="text-muted-foreground line-clamp-2 text-xs">{n.content}</p>
) : null}
<span className="text-muted-foreground text-[10px]">
{formatDate(n.createdAt)}
</span>
</div>
</DropdownMenuItem>
)
})
)}
</ScrollArea>
<DropdownMenuSeparator className="mt-0" />
<DropdownMenuItem asChild>
<Link href="/messages" className="text-primary justify-center text-xs">
View all notifications
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}

View File

@@ -0,0 +1,141 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Bell, CheckCheck, MessageSquare, Megaphone, PenTool, GraduationCap } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { formatDate } from "@/shared/lib/utils"
import { markAllNotificationsAsReadAction, markNotificationAsReadAction } from "../actions"
import type { Notification, NotificationType } from "../types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare,
announcement: Megaphone,
homework: PenTool,
grade: GraduationCap,
}
const TYPE_LABEL: Record<NotificationType, string> = {
message: "Message",
announcement: "Announcement",
homework: "Homework",
grade: "Grade",
}
export function NotificationList({ notifications }: { notifications: Notification[] }) {
const router = useRouter()
const [isWorking, setIsWorking] = useState(false)
const hasUnread = notifications.some((n) => !n.isRead)
const handleMarkAllRead = async () => {
setIsWorking(true)
try {
const res = await markAllNotificationsAsReadAction()
if (res.success) {
toast.success(res.message)
router.refresh()
} else {
toast.error(res.message || "Failed to mark all as read")
}
} catch {
toast.error("Failed to mark all as read")
} finally {
setIsWorking(false)
}
}
const handleMarkRead = async (id: string) => {
try {
const res = await markNotificationAsReadAction(id)
if (res.success) {
router.refresh()
}
} catch {
toast.error("Failed to mark as read")
}
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-2xl font-bold tracking-tight">Notifications</h2>
<p className="text-muted-foreground text-sm">Stay updated on your latest activities.</p>
</div>
{hasUnread ? (
<Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
<CheckCheck className="mr-2 h-4 w-4" />
Mark all as read
</Button>
) : null}
</div>
{notifications.length === 0 ? (
<EmptyState
title="No notifications"
description="You have no notifications yet."
icon={Bell}
className="h-auto border-none shadow-none"
/>
) : (
<div className="space-y-3">
{notifications.map((n) => {
const Icon = TYPE_ICON[n.type] ?? Bell
return (
<Card
key={n.id}
className={`transition-colors ${!n.isRead ? "border-primary/40 bg-primary/5" : ""}`}
>
<CardContent className="flex items-start gap-3 py-4">
<div className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
<Icon className="h-4 w-4" />
</div>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className={`text-sm ${!n.isRead ? "font-semibold" : "font-medium"}`}>
{n.title}
</span>
{!n.isRead ? <Badge variant="default" className="text-xs">New</Badge> : null}
</div>
{n.content ? (
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{n.content}
</p>
) : null}
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Badge variant="outline" className="text-xs">
{TYPE_LABEL[n.type]}
</Badge>
<span>{formatDate(n.createdAt)}</span>
{!n.isRead ? (
<button
type="button"
onClick={() => handleMarkRead(n.id)}
className="text-primary hover:underline"
>
Mark as read
</button>
) : null}
{n.link ? (
<Link href={n.link} className="ml-auto text-primary hover:underline">
View
</Link>
) : null}
</div>
</div>
</CardContent>
</Card>
)
})}
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,252 @@
import "server-only"
import { cache } from "react"
import { createId } from "@paralleldrive/cuid2"
import { and, count, desc, eq, inArray, or } from "drizzle-orm"
import { db } from "@/shared/db"
import {
messages,
messageNotifications,
users,
classEnrollments,
classes,
} from "@/shared/db/schema"
import type { DataScope } from "@/shared/types/permissions"
import type {
Message,
Notification,
NotificationType,
GetMessagesParams,
GetNotificationsParams,
CreateMessageInput,
CreateNotificationInput,
PaginatedResult,
RecipientOption,
} from "./types"
const toIso = (d: Date | null | undefined): string | null => (d ? d.toISOString() : null)
interface MessageRow {
id: string
senderId: string
receiverId: string
subject: string | null
content: string
isRead: boolean
readAt: Date | null
parentMessageId: string | null
createdAt: Date
}
interface NotificationRow {
id: string
userId: string
type: string
title: string
content: string | null
link: string | null
isRead: boolean
createdAt: Date
}
async function resolveUserNames(userIds: string[]): Promise<Map<string, string>> {
const uniqueIds = [...new Set(userIds)].filter(Boolean)
if (uniqueIds.length === 0) return new Map()
const rows = await db
.select({ id: users.id, name: users.name })
.from(users)
.where(inArray(users.id, uniqueIds))
return new Map(rows.map((r) => [r.id, r.name ?? r.id]))
}
const mapMessage = (r: MessageRow, nameMap: Map<string, string>): Message => ({
id: r.id,
senderId: r.senderId,
senderName: nameMap.get(r.senderId) ?? null,
receiverId: r.receiverId,
receiverName: nameMap.get(r.receiverId) ?? null,
subject: r.subject,
content: r.content,
isRead: r.isRead,
readAt: toIso(r.readAt),
parentMessageId: r.parentMessageId,
createdAt: toIso(r.createdAt) as string,
})
const mapNotification = (r: NotificationRow): Notification => ({
id: r.id,
userId: r.userId,
type: r.type as NotificationType,
title: r.title,
content: r.content,
link: r.link,
isRead: r.isRead,
createdAt: toIso(r.createdAt) as string,
})
export const getMessages = cache(
async (params: GetMessagesParams): Promise<PaginatedResult<Message>> => {
const page = Math.max(1, params.page ?? 1)
const pageSize = Math.max(1, params.pageSize ?? 20)
const offset = (page - 1) * pageSize
const conds = []
if (params.type === "inbox") conds.push(eq(messages.receiverId, params.userId))
else if (params.type === "sent") conds.push(eq(messages.senderId, params.userId))
else conds.push(or(eq(messages.receiverId, params.userId), eq(messages.senderId, params.userId))!)
const where = and(...conds)
const [rows, [totalRow]] = await Promise.all([
db.select().from(messages).where(where).orderBy(desc(messages.createdAt)).limit(pageSize).offset(offset),
db.select({ value: count() }).from(messages).where(where),
])
const userIds = rows.flatMap((r) => [r.senderId, r.receiverId])
const nameMap = await resolveUserNames(userIds)
const total = Number(totalRow?.value ?? 0)
return { items: rows.map((r) => mapMessage(r, nameMap)), total, page, pageSize, totalPages: Math.ceil(total / pageSize) }
}
)
export const getMessageById = cache(
async (id: string, userId: string): Promise<Message | null> => {
const [row] = await db
.select()
.from(messages)
.where(and(eq(messages.id, id), or(eq(messages.senderId, userId), eq(messages.receiverId, userId))!))
.limit(1)
if (!row) return null
const nameMap = await resolveUserNames([row.senderId, row.receiverId])
return mapMessage(row, nameMap)
}
)
export const getMessageThread = cache(async (messageId: string): Promise<Message[]> => {
const [root] = await db.select().from(messages).where(eq(messages.id, messageId)).limit(1)
if (!root) return []
const replies = await db
.select()
.from(messages)
.where(eq(messages.parentMessageId, messageId))
.orderBy(desc(messages.createdAt))
const allRows = [root, ...replies]
const nameMap = await resolveUserNames(allRows.flatMap((r) => [r.senderId, r.receiverId]))
return allRows.map((r) => mapMessage(r, nameMap))
})
export async function createMessage(data: CreateMessageInput): Promise<string> {
const id = createId()
await db.insert(messages).values({
id,
senderId: data.senderId,
receiverId: data.receiverId,
subject: data.subject ?? null,
content: data.content,
parentMessageId: data.parentMessageId ?? null,
})
return id
}
export async function markMessageAsRead(id: string, userId: string): Promise<void> {
await db
.update(messages)
.set({ isRead: true, readAt: new Date() })
.where(and(eq(messages.id, id), eq(messages.receiverId, userId), eq(messages.isRead, false)))
}
export async function deleteMessage(id: string, userId: string): Promise<void> {
await db
.delete(messages)
.where(and(eq(messages.id, id), or(eq(messages.senderId, userId), eq(messages.receiverId, userId))!))
}
export const getUnreadMessageCount = cache(async (userId: string): Promise<number> => {
const [row] = await db
.select({ value: count() })
.from(messages)
.where(and(eq(messages.receiverId, userId), eq(messages.isRead, false)))
return Number(row?.value ?? 0)
})
export const getNotifications = cache(
async (userId: string, params?: GetNotificationsParams): Promise<PaginatedResult<Notification>> => {
const page = Math.max(1, params?.page ?? 1)
const pageSize = Math.max(1, params?.pageSize ?? 20)
const offset = (page - 1) * pageSize
const conds = [eq(messageNotifications.userId, userId)]
if (params?.unreadOnly) conds.push(eq(messageNotifications.isRead, false))
const where = and(...conds)
const [rows, [totalRow]] = await Promise.all([
db.select().from(messageNotifications).where(where).orderBy(desc(messageNotifications.createdAt)).limit(pageSize).offset(offset),
db.select({ value: count() }).from(messageNotifications).where(where),
])
const total = Number(totalRow?.value ?? 0)
return { items: rows.map(mapNotification), total, page, pageSize, totalPages: Math.ceil(total / pageSize) }
}
)
export async function createNotification(data: CreateNotificationInput): Promise<string> {
const id = createId()
await db.insert(messageNotifications).values({
id,
userId: data.userId,
type: data.type,
title: data.title,
content: data.content ?? null,
link: data.link ?? null,
})
return id
}
export async function markNotificationAsRead(id: string, userId: string): Promise<void> {
await db
.update(messageNotifications)
.set({ isRead: true })
.where(and(eq(messageNotifications.id, id), eq(messageNotifications.userId, userId)))
}
export async function markAllNotificationsAsRead(userId: string): Promise<void> {
await db
.update(messageNotifications)
.set({ isRead: true })
.where(and(eq(messageNotifications.userId, userId), eq(messageNotifications.isRead, false)))
}
export const getUnreadNotificationCount = cache(async (userId: string): Promise<number> => {
const [row] = await db
.select({ value: count() })
.from(messageNotifications)
.where(and(eq(messageNotifications.userId, userId), eq(messageNotifications.isRead, false)))
return Number(row?.value ?? 0)
})
export const getRecipients = cache(
async (userId: string, scope: DataScope): Promise<RecipientOption[]> => {
if (scope.type === "all") {
const all = await db.select({ id: users.id, name: users.name, email: users.email }).from(users)
return all.filter((r) => r.id !== userId).map((r) => ({ ...r, name: r.name ?? r.email }))
}
if (scope.type === "class_taught" && scope.classIds.length > 0) {
const rows = await db
.selectDistinct({ id: users.id, name: users.name, email: users.email })
.from(users)
.innerJoin(classEnrollments, eq(classEnrollments.studentId, users.id))
.where(inArray(classEnrollments.classId, scope.classIds))
return rows.map((r) => ({ ...r, name: r.name ?? r.email, role: "student" }))
}
if (scope.type === "grade_managed" && scope.gradeIds.length > 0) {
const rows = await db
.selectDistinct({ id: users.id, name: users.name, email: users.email })
.from(users)
.innerJoin(classEnrollments, eq(classEnrollments.studentId, users.id))
.innerJoin(classes, eq(classes.id, classEnrollments.classId))
.where(inArray(classes.gradeId, scope.gradeIds))
return rows.map((r) => ({ ...r, name: r.name ?? r.email, role: "student" }))
}
return []
}
)

View File

@@ -0,0 +1,166 @@
import "server-only"
import { cache } from "react"
import { createId } from "@paralleldrive/cuid2"
import { and, eq } from "drizzle-orm"
import { db } from "@/shared/db"
import { notificationPreferences } from "@/shared/db/schema"
import type {
NotificationPreferences,
UpdateNotificationPreferencesInput,
} from "./types"
const toIso = (d: Date): string => d.toISOString()
const mapRow = (
row: typeof notificationPreferences.$inferSelect
): NotificationPreferences => ({
id: row.id,
userId: row.userId,
emailEnabled: row.emailEnabled,
smsEnabled: row.smsEnabled,
pushEnabled: row.pushEnabled,
homeworkNotifications: row.homeworkNotifications,
gradeNotifications: row.gradeNotifications,
announcementNotifications: row.announcementNotifications,
messageNotifications: row.messageNotifications,
attendanceNotifications: row.attendanceNotifications,
createdAt: toIso(row.createdAt),
updatedAt: toIso(row.updatedAt),
})
// 默认偏好值(首次创建时使用)
const DEFAULTS = {
emailEnabled: false,
smsEnabled: false,
pushEnabled: true,
homeworkNotifications: true,
gradeNotifications: true,
announcementNotifications: true,
messageNotifications: true,
attendanceNotifications: true,
}
/**
* 获取用户的通知偏好设置
* 如果用户尚无记录,则自动创建一条默认记录并返回
*/
export const getNotificationPreferences = cache(
async (userId: string): Promise<NotificationPreferences> => {
// 先查询
const [existing] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.userId, userId))
.limit(1)
if (existing) {
return mapRow(existing)
}
// 不存在则创建默认记录
const id = createId()
try {
await db.insert(notificationPreferences).values({
id,
userId,
...DEFAULTS,
})
const [created] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.id, id))
.limit(1)
if (created) return mapRow(created)
} catch {
// 并发情况下可能违反唯一约束,回退到查询
const [fallback] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.userId, userId))
.limit(1)
if (fallback) return mapRow(fallback)
}
// 极端情况:返回内存中的默认值(不带 id
return {
id: "",
userId,
...DEFAULTS,
createdAt: toIso(new Date()),
updatedAt: toIso(new Date()),
}
}
)
/**
* 更新(或创建)用户的通知偏好设置
* 使用 upsert 语义:存在则更新,不存在则插入
*/
export async function upsertNotificationPreferences(
userId: string,
input: UpdateNotificationPreferencesInput
): Promise<NotificationPreferences | null> {
// 先查询是否存在
const [existing] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.userId, userId))
.limit(1)
if (existing) {
// 更新
const updateData: Partial<typeof notificationPreferences.$inferInsert> = {}
if (input.emailEnabled !== undefined) updateData.emailEnabled = input.emailEnabled
if (input.smsEnabled !== undefined) updateData.smsEnabled = input.smsEnabled
if (input.pushEnabled !== undefined) updateData.pushEnabled = input.pushEnabled
if (input.homeworkNotifications !== undefined) updateData.homeworkNotifications = input.homeworkNotifications
if (input.gradeNotifications !== undefined) updateData.gradeNotifications = input.gradeNotifications
if (input.announcementNotifications !== undefined) updateData.announcementNotifications = input.announcementNotifications
if (input.messageNotifications !== undefined) updateData.messageNotifications = input.messageNotifications
if (input.attendanceNotifications !== undefined) updateData.attendanceNotifications = input.attendanceNotifications
if (Object.keys(updateData).length === 0) {
return mapRow(existing)
}
await db
.update(notificationPreferences)
.set(updateData)
.where(and(eq(notificationPreferences.id, existing.id), eq(notificationPreferences.userId, userId)))
const [updated] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.id, existing.id))
.limit(1)
return updated ? mapRow(updated) : null
}
// 不存在则插入
const id = createId()
try {
await db.insert(notificationPreferences).values({
id,
userId,
emailEnabled: input.emailEnabled ?? DEFAULTS.emailEnabled,
smsEnabled: input.smsEnabled ?? DEFAULTS.smsEnabled,
pushEnabled: input.pushEnabled ?? DEFAULTS.pushEnabled,
homeworkNotifications: input.homeworkNotifications ?? DEFAULTS.homeworkNotifications,
gradeNotifications: input.gradeNotifications ?? DEFAULTS.gradeNotifications,
announcementNotifications: input.announcementNotifications ?? DEFAULTS.announcementNotifications,
messageNotifications: input.messageNotifications ?? DEFAULTS.messageNotifications,
attendanceNotifications: input.attendanceNotifications ?? DEFAULTS.attendanceNotifications,
})
const [created] = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.id, id))
.limit(1)
return created ? mapRow(created) : null
} catch {
return null
}
}

View File

@@ -0,0 +1,18 @@
import { z } from "zod"
export const SendMessageSchema = z
.object({
receiverId: z.string().trim().min(1),
subject: z.string().trim().max(255).optional().nullable(),
content: z.string().trim().min(1),
parentMessageId: z.string().trim().optional().nullable(),
})
.transform((v) => ({
receiverId: v.receiverId,
subject: v.subject && v.subject.length > 0 ? v.subject : null,
content: v.content,
parentMessageId:
v.parentMessageId && v.parentMessageId.length > 0 ? v.parentMessageId : null,
}))
export type SendMessageInput = z.infer<typeof SendMessageSchema>

View File

@@ -0,0 +1,108 @@
export type MessageType = "inbox" | "sent" | "all"
export interface Message {
id: string
senderId: string
senderName: string | null
receiverId: string
receiverName: string | null
subject: string | null
content: string
isRead: boolean
readAt: string | null
parentMessageId: string | null
createdAt: string
}
export type MessageListItem = Message
export interface MessageThread {
messages: Message[]
}
export type NotificationType = "message" | "announcement" | "homework" | "grade"
export interface Notification {
id: string
userId: string
type: NotificationType
title: string
content: string | null
link: string | null
isRead: boolean
createdAt: string
}
export type NotificationListItem = Notification
export interface PaginatedResult<T> {
items: T[]
total: number
page: number
pageSize: number
totalPages: number
}
export interface GetMessagesParams {
userId: string
type: MessageType
page?: number
pageSize?: number
}
export interface GetNotificationsParams {
page?: number
pageSize?: number
unreadOnly?: boolean
}
export interface CreateMessageInput {
senderId: string
receiverId: string
subject?: string | null
content: string
parentMessageId?: string | null
}
export interface CreateNotificationInput {
userId: string
type: NotificationType
title: string
content?: string | null
link?: string | null
}
export interface RecipientOption {
id: string
name: string
email: string
role?: string
}
// 通知偏好设置
export interface NotificationPreferences {
id: string
userId: string
emailEnabled: boolean
smsEnabled: boolean
pushEnabled: boolean
homeworkNotifications: boolean
gradeNotifications: boolean
announcementNotifications: boolean
messageNotifications: boolean
attendanceNotifications: boolean
createdAt: string
updatedAt: string
}
// 更新通知偏好的输入(部分字段可选,未提供则保留原值)
export interface UpdateNotificationPreferencesInput {
emailEnabled?: boolean
smsEnabled?: boolean
pushEnabled?: boolean
homeworkNotifications?: boolean
gradeNotifications?: boolean
announcementNotifications?: boolean
messageNotifications?: boolean
attendanceNotifications?: boolean
}