feat: 联动支付 CRM 后台(Next.js + TS + Prisma 重构)
从旧 Laravel 5.7 重构为现代技术栈,对接现有 MySQL。 - 技术栈: Next.js 15 App Router + TypeScript + Prisma + Auth.js + Tailwind v4 - 认证: 复用旧库 admins 的 bcrypt 密码,Auth.js Credentials - 客户管理: 列表(搜索/报单区间/分页)、增改删、Excel 导入导出 - 生日提醒: 阴阳历(lunar-typescript),口径对齐旧 overtrue 库 - RBAC: 管理员/角色/权限(菜单树) 完整 CRUD + 分配 - 控制台: 统计卡 + 月度新增报单柱状图 - 个人中心: 改昵称/改密码 - 现代 CMS 界面 + 联动支付品牌(logo/登录/底部/icon) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
const ADMIN_MODEL = "App\\Model\\Admin";
|
||||
|
||||
export type FormState = { error?: string };
|
||||
|
||||
/** 仅超级管理员可操作 RBAC */
|
||||
async function requireSuperAdmin(): Promise<boolean> {
|
||||
const session = await auth();
|
||||
return !!session?.user?.roles?.includes("super admin");
|
||||
}
|
||||
|
||||
// ===================== 管理员 =====================
|
||||
|
||||
const adminSchema = z.object({
|
||||
username: z.string().trim().min(2, "用户名至少 2 位").max(32),
|
||||
nickname: z.string().trim().min(1, "昵称必填").max(64),
|
||||
roleId: z.coerce.number().int().optional(),
|
||||
});
|
||||
|
||||
export async function saveAdmin(
|
||||
id: number | null,
|
||||
_prev: FormState,
|
||||
formData: FormData
|
||||
): Promise<FormState> {
|
||||
if (!(await requireSuperAdmin())) return { error: "无权限" };
|
||||
|
||||
const parsed = adminSchema.safeParse({
|
||||
username: formData.get("username"),
|
||||
nickname: formData.get("nickname"),
|
||||
roleId: formData.get("roleId") || undefined,
|
||||
});
|
||||
if (!parsed.success) return { error: parsed.error.issues[0].message };
|
||||
const { username, nickname, roleId } = parsed.data;
|
||||
const password = String(formData.get("password") ?? "");
|
||||
|
||||
// 用户名唯一校验
|
||||
const dup = await prisma.admin.findFirst({
|
||||
where: { username, id: id ? { not: id } : undefined },
|
||||
});
|
||||
if (dup) return { error: "用户名已存在" };
|
||||
|
||||
let adminId = id;
|
||||
if (id) {
|
||||
await prisma.admin.update({
|
||||
where: { id },
|
||||
data: {
|
||||
username,
|
||||
nickname,
|
||||
...(password ? { password: bcrypt.hashSync(password, 10) } : {}),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
if (password.length < 6) return { error: "新增账号密码至少 6 位" };
|
||||
const created = await prisma.admin.create({
|
||||
data: { username, nickname, password: bcrypt.hashSync(password, 10) },
|
||||
});
|
||||
adminId = created.id;
|
||||
}
|
||||
|
||||
// 角色分配(单角色,覆盖式)
|
||||
if (adminId && roleId) {
|
||||
await prisma.modelHasRole.deleteMany({
|
||||
where: { modelId: adminId, modelType: ADMIN_MODEL },
|
||||
});
|
||||
await prisma.modelHasRole.create({
|
||||
data: { roleId, modelId: adminId, modelType: ADMIN_MODEL },
|
||||
});
|
||||
}
|
||||
|
||||
revalidatePath("/rbac/admins");
|
||||
redirect("/rbac/admins");
|
||||
}
|
||||
|
||||
export async function deleteAdmin(id: number): Promise<void> {
|
||||
if (!(await requireSuperAdmin())) return;
|
||||
if (id === 1) return; // 保护超级管理员主账号
|
||||
await prisma.admin.update({ where: { id }, data: { deletedAt: new Date() } });
|
||||
await prisma.modelHasRole.deleteMany({
|
||||
where: { modelId: id, modelType: ADMIN_MODEL },
|
||||
});
|
||||
revalidatePath("/rbac/admins");
|
||||
}
|
||||
|
||||
// ===================== 角色 =====================
|
||||
|
||||
const roleSchema = z.object({
|
||||
name: z.string().trim().min(1, "角色标识必填").max(255),
|
||||
title: z.string().trim().min(1, "角色名称必填").max(64),
|
||||
remark: z.string().trim().max(255).optional().default(""),
|
||||
});
|
||||
|
||||
export async function saveRole(
|
||||
id: number | null,
|
||||
_prev: FormState,
|
||||
formData: FormData
|
||||
): Promise<FormState> {
|
||||
if (!(await requireSuperAdmin())) return { error: "无权限" };
|
||||
const parsed = roleSchema.safeParse({
|
||||
name: formData.get("name"),
|
||||
title: formData.get("title"),
|
||||
remark: formData.get("remark") ?? "",
|
||||
});
|
||||
if (!parsed.success) return { error: parsed.error.issues[0].message };
|
||||
|
||||
if (id) {
|
||||
await prisma.role.update({ where: { id }, data: parsed.data });
|
||||
} else {
|
||||
await prisma.role.create({ data: { ...parsed.data, guardName: "admin" } });
|
||||
}
|
||||
revalidatePath("/rbac/roles");
|
||||
redirect("/rbac/roles");
|
||||
}
|
||||
|
||||
export async function deleteRole(id: number): Promise<void> {
|
||||
if (!(await requireSuperAdmin())) return;
|
||||
if (id === 1) return; // 保护超管角色
|
||||
await prisma.roleHasPermission.deleteMany({ where: { roleId: id } });
|
||||
await prisma.modelHasRole.deleteMany({ where: { roleId: id } });
|
||||
await prisma.role.delete({ where: { id } });
|
||||
revalidatePath("/rbac/roles");
|
||||
}
|
||||
|
||||
/** 分配角色权限(覆盖式) */
|
||||
export async function assignPermissions(
|
||||
roleId: number,
|
||||
permissionIds: number[]
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
if (!(await requireSuperAdmin())) return { ok: false, error: "无权限" };
|
||||
await prisma.roleHasPermission.deleteMany({ where: { roleId } });
|
||||
if (permissionIds.length) {
|
||||
await prisma.roleHasPermission.createMany({
|
||||
data: permissionIds.map((permissionId) => ({ roleId, permissionId })),
|
||||
});
|
||||
}
|
||||
revalidatePath("/rbac/roles");
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// ===================== 权限 =====================
|
||||
|
||||
const permSchema = z.object({
|
||||
name: z.string().trim().min(1, "权限标识必填").max(64),
|
||||
title: z.string().trim().min(1, "权限名称必填").max(64),
|
||||
pid: z.coerce.number().int().default(0),
|
||||
icon: z.string().trim().max(64).optional().default(""),
|
||||
sort: z.coerce.number().int().default(0),
|
||||
isMenu: z.coerce.boolean().default(false),
|
||||
});
|
||||
|
||||
export async function savePermission(
|
||||
id: number | null,
|
||||
_prev: FormState,
|
||||
formData: FormData
|
||||
): Promise<FormState> {
|
||||
if (!(await requireSuperAdmin())) return { error: "无权限" };
|
||||
const parsed = permSchema.safeParse({
|
||||
name: formData.get("name"),
|
||||
title: formData.get("title"),
|
||||
pid: formData.get("pid") || 0,
|
||||
icon: formData.get("icon") ?? "",
|
||||
sort: formData.get("sort") || 0,
|
||||
isMenu: formData.get("isMenu") === "on",
|
||||
});
|
||||
if (!parsed.success) return { error: parsed.error.issues[0].message };
|
||||
const data = { ...parsed.data, guardName: "admin" };
|
||||
|
||||
if (id) {
|
||||
await prisma.permission.update({ where: { id }, data });
|
||||
} else {
|
||||
await prisma.permission.create({ data });
|
||||
}
|
||||
revalidatePath("/rbac/permissions");
|
||||
redirect("/rbac/permissions");
|
||||
}
|
||||
|
||||
export async function deletePermission(id: number): Promise<void> {
|
||||
if (!(await requireSuperAdmin())) return;
|
||||
await prisma.roleHasPermission.deleteMany({ where: { permissionId: id } });
|
||||
await prisma.permission.delete({ where: { id } });
|
||||
revalidatePath("/rbac/permissions");
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { saveAdmin } from "../../../actions";
|
||||
import { AdminForm } from "../../admin-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
const ADMIN_MODEL = "App\\Model\\Admin";
|
||||
|
||||
export default async function EditAdminPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const adminId = Number(id);
|
||||
const [admin, roles, link] = await Promise.all([
|
||||
prisma.admin.findFirst({ where: { id: adminId, deletedAt: null } }),
|
||||
prisma.role.findMany({ orderBy: { id: "asc" } }),
|
||||
prisma.modelHasRole.findFirst({ where: { modelId: adminId, modelType: ADMIN_MODEL } }),
|
||||
]);
|
||||
if (!admin) notFound();
|
||||
|
||||
const action = saveAdmin.bind(null, admin.id);
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>编辑管理员 · {admin.nickname}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<AdminForm
|
||||
action={action}
|
||||
roles={roles}
|
||||
isEdit
|
||||
defaultValues={{
|
||||
username: admin.username,
|
||||
nickname: admin.nickname,
|
||||
roleId: link?.roleId,
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Select } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import type { FormState } from "../actions";
|
||||
|
||||
export function AdminForm({
|
||||
action,
|
||||
roles,
|
||||
defaultValues,
|
||||
isEdit,
|
||||
}: {
|
||||
action: (prev: FormState, formData: FormData) => Promise<FormState>;
|
||||
roles: { id: number; title: string | null; name: string }[];
|
||||
defaultValues?: { username?: string; nickname?: string; roleId?: number };
|
||||
isEdit?: boolean;
|
||||
}) {
|
||||
const [state, formAction, pending] = useActionState(action, {});
|
||||
const v = defaultValues ?? {};
|
||||
|
||||
return (
|
||||
<form action={formAction} className="max-w-lg space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">用户名<span className="ml-0.5 text-[var(--color-danger)]">*</span></Label>
|
||||
<Input id="username" name="username" defaultValue={v.username} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="nickname">昵称<span className="ml-0.5 text-[var(--color-danger)]">*</span></Label>
|
||||
<Input id="nickname" name="nickname" defaultValue={v.nickname} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">
|
||||
密码{!isEdit && <span className="ml-0.5 text-[var(--color-danger)]">*</span>}
|
||||
</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
placeholder={isEdit ? "留空则不修改" : "至少 6 位"}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="roleId">角色</Label>
|
||||
<Select id="roleId" name="roleId" defaultValue={String(v.roleId ?? "")}>
|
||||
<option value="">未分配</option>
|
||||
{roles.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.title || r.name}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{state.error && (
|
||||
<p className="rounded-md bg-[var(--color-danger-soft)] px-3 py-2 text-sm text-[var(--color-danger)]">
|
||||
{state.error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 border-t pt-4">
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "保存中…" : "保存"}
|
||||
</Button>
|
||||
<Link href="/rbac/admins">
|
||||
<Button type="button" variant="outline">取消</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { saveAdmin } from "../../actions";
|
||||
import { AdminForm } from "../admin-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default async function NewAdminPage() {
|
||||
const roles = await prisma.role.findMany({ orderBy: { id: "asc" } });
|
||||
const action = saveAdmin.bind(null, null);
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>新增管理员</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<AdminForm action={action} roles={roles} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import Link from "next/link";
|
||||
import { Plus } from "lucide-react";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Avatar } from "@/components/ui/avatar";
|
||||
import { deleteAdmin } from "../actions";
|
||||
import { ConfirmDelete } from "../confirm-delete";
|
||||
|
||||
const ADMIN_MODEL = "App\\Model\\Admin";
|
||||
|
||||
export default async function AdminsPage() {
|
||||
const admins = await prisma.admin.findMany({
|
||||
where: { deletedAt: null },
|
||||
orderBy: { id: "asc" },
|
||||
});
|
||||
|
||||
// 批量取每个管理员的角色
|
||||
const links = await prisma.modelHasRole.findMany({ where: { modelType: ADMIN_MODEL } });
|
||||
const roles = await prisma.role.findMany();
|
||||
const roleMap = new Map(roles.map((r) => [r.id, r.title || r.name]));
|
||||
const adminRole = new Map<number, string>();
|
||||
for (const l of links) adminRole.set(l.modelId, roleMap.get(l.roleId) ?? "");
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Link href="/rbac/admins/new">
|
||||
<Button><Plus className="h-4 w-4" />新增管理员</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Card className="overflow-hidden">
|
||||
<Table>
|
||||
<THead>
|
||||
<tr>
|
||||
<TH>账号</TH>
|
||||
<TH>昵称</TH>
|
||||
<TH>角色</TH>
|
||||
<TH className="text-right">操作</TH>
|
||||
</tr>
|
||||
</THead>
|
||||
<tbody>
|
||||
{admins.map((a) => (
|
||||
<TR key={a.id}>
|
||||
<TD className="tabular-nums">{a.username}</TD>
|
||||
<TD>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<Avatar name={a.nickname} size={30} />
|
||||
<span className="font-medium">{a.nickname}</span>
|
||||
</div>
|
||||
</TD>
|
||||
<TD>
|
||||
{adminRole.get(a.id) ? (
|
||||
<Badge tone="primary">{adminRole.get(a.id)}</Badge>
|
||||
) : (
|
||||
<span className="text-[var(--color-muted-foreground)]">未分配</span>
|
||||
)}
|
||||
</TD>
|
||||
<TD>
|
||||
<div className="flex justify-end gap-1.5">
|
||||
<Link href={`/rbac/admins/${a.id}/edit`}>
|
||||
<Button variant="outline" size="sm">编辑</Button>
|
||||
</Link>
|
||||
<ConfirmDelete
|
||||
action={deleteAdmin.bind(null, a.id)}
|
||||
name={a.nickname}
|
||||
disabled={a.id === 1}
|
||||
/>
|
||||
</div>
|
||||
</TD>
|
||||
</TR>
|
||||
))}
|
||||
</tbody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** 通用确认删除按钮:接收一个已绑定 id 的 server action */
|
||||
export function ConfirmDelete({
|
||||
action,
|
||||
name,
|
||||
disabled,
|
||||
}: {
|
||||
action: () => Promise<void>;
|
||||
name: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const [pending, start] = useTransition();
|
||||
return (
|
||||
<Button
|
||||
variant="danger-ghost"
|
||||
size="sm"
|
||||
disabled={disabled || pending}
|
||||
onClick={() => {
|
||||
if (!confirm(`确认删除「${name}」?`)) return;
|
||||
start(async () => {
|
||||
await action();
|
||||
toast.success("已删除");
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
删除
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { savePermission } from "../../../actions";
|
||||
import { PermissionForm } from "../../permission-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default async function EditPermissionPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const permId = Number(id);
|
||||
const [perm, menus] = await Promise.all([
|
||||
prisma.permission.findUnique({ where: { id: permId } }),
|
||||
prisma.permission.findMany({
|
||||
where: { isMenu: true },
|
||||
orderBy: [{ sort: "asc" }, { id: "asc" }],
|
||||
}),
|
||||
]);
|
||||
if (!perm) notFound();
|
||||
|
||||
const parents = menus
|
||||
.filter((m) => m.id !== permId) // 不能把自己设为上级
|
||||
.map((m) => ({ id: m.id, label: m.title || m.name }));
|
||||
const action = savePermission.bind(null, perm.id);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>编辑权限 · {perm.title || perm.name}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<PermissionForm
|
||||
action={action}
|
||||
parents={parents}
|
||||
defaultValues={{
|
||||
name: perm.name,
|
||||
title: perm.title ?? "",
|
||||
pid: perm.pid ?? 0,
|
||||
icon: perm.icon ?? "",
|
||||
sort: perm.sort ?? 0,
|
||||
isMenu: !!perm.isMenu,
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { savePermission } from "../../actions";
|
||||
import { PermissionForm } from "../permission-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default async function NewPermissionPage() {
|
||||
const menus = await prisma.permission.findMany({
|
||||
where: { isMenu: true },
|
||||
orderBy: [{ sort: "asc" }, { id: "asc" }],
|
||||
});
|
||||
const parents = menus.map((m) => ({ id: m.id, label: m.title || m.name }));
|
||||
const action = savePermission.bind(null, null);
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>新增权限</CardTitle></CardHeader>
|
||||
<CardContent><PermissionForm action={action} parents={parents} /></CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Link from "next/link";
|
||||
import { Plus } from "lucide-react";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { deletePermission } from "../actions";
|
||||
import { ConfirmDelete } from "../confirm-delete";
|
||||
|
||||
type Perm = {
|
||||
id: number;
|
||||
pid: number | null;
|
||||
title: string | null;
|
||||
name: string;
|
||||
icon: string | null;
|
||||
isMenu: boolean | null;
|
||||
sort: number | null;
|
||||
};
|
||||
|
||||
function order(perms: Perm[]): { p: Perm; depth: number }[] {
|
||||
const byParent = new Map<number, Perm[]>();
|
||||
perms.forEach((p) => {
|
||||
const k = p.pid ?? 0;
|
||||
if (!byParent.has(k)) byParent.set(k, []);
|
||||
byParent.get(k)!.push(p);
|
||||
});
|
||||
const out: { p: Perm; depth: number }[] = [];
|
||||
const walk = (pid: number, depth: number) => {
|
||||
(byParent.get(pid) ?? [])
|
||||
.sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0) || a.id - b.id)
|
||||
.forEach((p) => {
|
||||
out.push({ p, depth });
|
||||
walk(p.id, depth + 1);
|
||||
});
|
||||
};
|
||||
walk(0, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
export default async function PermissionsPage() {
|
||||
const perms = await prisma.permission.findMany();
|
||||
const rows = order(perms as Perm[]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Link href="/rbac/permissions/new">
|
||||
<Button><Plus className="h-4 w-4" />新增权限</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Card className="overflow-hidden">
|
||||
<Table>
|
||||
<THead>
|
||||
<tr>
|
||||
<TH>权限名称</TH>
|
||||
<TH>标识</TH>
|
||||
<TH>类型</TH>
|
||||
<TH className="text-right">操作</TH>
|
||||
</tr>
|
||||
</THead>
|
||||
<tbody>
|
||||
{rows.map(({ p, depth }) => (
|
||||
<TR key={p.id}>
|
||||
<TD>
|
||||
<span style={{ paddingLeft: depth * 20 }} className="font-medium">
|
||||
{depth > 0 && <span className="mr-1 text-[var(--color-muted-foreground)]">└</span>}
|
||||
{p.title || p.name}
|
||||
</span>
|
||||
</TD>
|
||||
<TD className="text-[var(--color-muted-foreground)]">{p.name}</TD>
|
||||
<TD>
|
||||
{p.isMenu ? <Badge tone="primary">菜单</Badge> : <Badge>操作</Badge>}
|
||||
</TD>
|
||||
<TD>
|
||||
<div className="flex justify-end gap-1.5">
|
||||
<Link href={`/rbac/permissions/${p.id}/edit`}>
|
||||
<Button variant="outline" size="sm">编辑</Button>
|
||||
</Link>
|
||||
<ConfirmDelete action={deletePermission.bind(null, p.id)} name={p.title || p.name} />
|
||||
</div>
|
||||
</TD>
|
||||
</TR>
|
||||
))}
|
||||
</tbody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Select } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import type { FormState } from "../actions";
|
||||
|
||||
export function PermissionForm({
|
||||
action,
|
||||
parents,
|
||||
defaultValues,
|
||||
}: {
|
||||
action: (prev: FormState, formData: FormData) => Promise<FormState>;
|
||||
parents: { id: number; label: string }[];
|
||||
defaultValues?: {
|
||||
name?: string;
|
||||
title?: string;
|
||||
pid?: number;
|
||||
icon?: string;
|
||||
sort?: number;
|
||||
isMenu?: boolean;
|
||||
};
|
||||
}) {
|
||||
const [state, formAction, pending] = useActionState(action, {});
|
||||
const v = defaultValues ?? {};
|
||||
return (
|
||||
<form action={formAction} className="max-w-lg space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title">权限名称<span className="ml-0.5 text-[var(--color-danger)]">*</span></Label>
|
||||
<Input id="title" name="title" defaultValue={v.title} placeholder="如:客户列表" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="name">权限标识<span className="ml-0.5 text-[var(--color-danger)]">*</span></Label>
|
||||
<Input id="name" name="name" defaultValue={v.name} placeholder="如:customers" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="pid">上级</Label>
|
||||
<Select id="pid" name="pid" defaultValue={String(v.pid ?? 0)}>
|
||||
<option value="0">顶级</option>
|
||||
{parents.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.label}</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="icon">图标(可选)</Label>
|
||||
<Input id="icon" name="icon" defaultValue={v.icon} placeholder="如:fa fa-users" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="sort">排序</Label>
|
||||
<Input id="sort" name="sort" type="number" defaultValue={String(v.sort ?? 0)} />
|
||||
</div>
|
||||
<label className="flex items-center gap-2 self-end pb-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="isMenu"
|
||||
defaultChecked={v.isMenu}
|
||||
className="h-4 w-4 accent-[var(--color-primary)]"
|
||||
/>
|
||||
<span className="text-sm">显示为菜单</span>
|
||||
</label>
|
||||
</div>
|
||||
{state.error && (
|
||||
<p className="rounded-md bg-[var(--color-danger-soft)] px-3 py-2 text-sm text-[var(--color-danger)]">
|
||||
{state.error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2 border-t pt-4">
|
||||
<Button type="submit" disabled={pending}>{pending ? "保存中…" : "保存"}</Button>
|
||||
<Link href="/rbac/permissions"><Button type="button" variant="outline">取消</Button></Link>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { saveRole } from "../../../actions";
|
||||
import { RoleForm } from "../../role-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default async function EditRolePage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const role = await prisma.role.findUnique({ where: { id: Number(id) } });
|
||||
if (!role) notFound();
|
||||
const action = saveRole.bind(null, role.id);
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>编辑角色 · {role.title || role.name}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<RoleForm
|
||||
action={action}
|
||||
defaultValues={{ name: role.name, title: role.title ?? "", remark: role.remark ?? "" }}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { assignPermissions } from "../../../actions";
|
||||
|
||||
export type PermNode = {
|
||||
id: number;
|
||||
title: string;
|
||||
name: string;
|
||||
children: PermNode[];
|
||||
};
|
||||
|
||||
export function AssignPermissions({
|
||||
roleId,
|
||||
tree,
|
||||
checkedIds,
|
||||
}: {
|
||||
roleId: number;
|
||||
tree: PermNode[];
|
||||
checkedIds: number[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [checked, setChecked] = useState<Set<number>>(new Set(checkedIds));
|
||||
const [pending, start] = useTransition();
|
||||
|
||||
function toggle(node: PermNode, on: boolean) {
|
||||
const next = new Set(checked);
|
||||
const walk = (n: PermNode) => {
|
||||
if (on) next.add(n.id);
|
||||
else next.delete(n.id);
|
||||
n.children.forEach(walk);
|
||||
};
|
||||
walk(node);
|
||||
setChecked(next);
|
||||
}
|
||||
|
||||
function save() {
|
||||
start(async () => {
|
||||
const res = await assignPermissions(roleId, [...checked]);
|
||||
if (res.ok) {
|
||||
toast.success("权限已保存");
|
||||
router.push("/rbac/roles");
|
||||
router.refresh();
|
||||
} else toast.error(res.error ?? "保存失败");
|
||||
});
|
||||
}
|
||||
|
||||
const renderNode = (node: PermNode, depth: number) => (
|
||||
<div key={node.id}>
|
||||
<label
|
||||
className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-[var(--color-muted)]"
|
||||
style={{ paddingLeft: depth * 20 + 8 }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 accent-[var(--color-primary)]"
|
||||
checked={checked.has(node.id)}
|
||||
onChange={(e) => toggle(node, e.target.checked)}
|
||||
/>
|
||||
<span className="text-sm">{node.title}</span>
|
||||
<span className="text-xs text-[var(--color-muted-foreground)]">{node.name}</span>
|
||||
</label>
|
||||
{node.children.map((c) => renderNode(c, depth + 1))}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-[var(--radius)] border p-2">
|
||||
{tree.map((n) => renderNode(n, 0))}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={save} disabled={pending}>
|
||||
{pending ? "保存中…" : `保存(已选 ${checked.size} 项)`}
|
||||
</Button>
|
||||
<Link href="/rbac/roles"><Button variant="outline">取消</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { AssignPermissions, type PermNode } from "./assign-permissions";
|
||||
|
||||
function buildTree(
|
||||
perms: { id: number; pid: number | null; title: string | null; name: string }[]
|
||||
): PermNode[] {
|
||||
const byId = new Map<number, PermNode>();
|
||||
perms.forEach((p) =>
|
||||
byId.set(p.id, { id: p.id, title: p.title || p.name, name: p.name, children: [] })
|
||||
);
|
||||
const roots: PermNode[] = [];
|
||||
perms.forEach((p) => {
|
||||
const node = byId.get(p.id)!;
|
||||
const parent = p.pid ? byId.get(p.pid) : undefined;
|
||||
if (parent) parent.children.push(node);
|
||||
else roots.push(node);
|
||||
});
|
||||
return roots;
|
||||
}
|
||||
|
||||
export default async function AssignPermissionsPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const roleId = Number(id);
|
||||
const [role, perms, owned] = await Promise.all([
|
||||
prisma.role.findUnique({ where: { id: roleId } }),
|
||||
prisma.permission.findMany({ orderBy: [{ sort: "asc" }, { id: "asc" }] }),
|
||||
prisma.roleHasPermission.findMany({ where: { roleId } }),
|
||||
]);
|
||||
if (!role) notFound();
|
||||
|
||||
const tree = buildTree(perms);
|
||||
const checkedIds = owned.map((o) => o.permissionId);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>分配权限 · {role.title || role.name}</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<AssignPermissions roleId={roleId} tree={tree} checkedIds={checkedIds} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { saveRole } from "../../actions";
|
||||
import { RoleForm } from "../role-form";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default function NewRolePage() {
|
||||
const action = saveRole.bind(null, null);
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader><CardTitle>新增角色</CardTitle></CardHeader>
|
||||
<CardContent><RoleForm action={action} /></CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import Link from "next/link";
|
||||
import { Plus, ShieldCheck } from "lucide-react";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { deleteRole } from "../actions";
|
||||
import { ConfirmDelete } from "../confirm-delete";
|
||||
|
||||
export default async function RolesPage() {
|
||||
const roles = await prisma.role.findMany({ orderBy: { id: "asc" } });
|
||||
const perms = await prisma.roleHasPermission.groupBy({
|
||||
by: ["roleId"],
|
||||
_count: { permissionId: true },
|
||||
});
|
||||
const countMap = new Map(perms.map((p) => [p.roleId, p._count.permissionId]));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Link href="/rbac/roles/new">
|
||||
<Button><Plus className="h-4 w-4" />新增角色</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Card className="overflow-hidden">
|
||||
<Table>
|
||||
<THead>
|
||||
<tr>
|
||||
<TH>角色名称</TH>
|
||||
<TH>标识</TH>
|
||||
<TH>权限数</TH>
|
||||
<TH>备注</TH>
|
||||
<TH className="text-right">操作</TH>
|
||||
</tr>
|
||||
</THead>
|
||||
<tbody>
|
||||
{roles.map((r) => (
|
||||
<TR key={r.id}>
|
||||
<TD className="font-medium">
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<ShieldCheck className="h-4 w-4 text-[var(--color-primary)]" />
|
||||
{r.title || r.name}
|
||||
</span>
|
||||
</TD>
|
||||
<TD className="text-[var(--color-muted-foreground)]">{r.name}</TD>
|
||||
<TD><Badge tone="info">{countMap.get(r.id) ?? 0}</Badge></TD>
|
||||
<TD className="text-[var(--color-muted-foreground)]">{r.remark}</TD>
|
||||
<TD>
|
||||
<div className="flex justify-end gap-1.5">
|
||||
<Link href={`/rbac/roles/${r.id}/permissions`}>
|
||||
<Button variant="soft" size="sm">分配权限</Button>
|
||||
</Link>
|
||||
<Link href={`/rbac/roles/${r.id}/edit`}>
|
||||
<Button variant="outline" size="sm">编辑</Button>
|
||||
</Link>
|
||||
<ConfirmDelete action={deleteRole.bind(null, r.id)} name={r.title || r.name} disabled={r.id === 1} />
|
||||
</div>
|
||||
</TD>
|
||||
</TR>
|
||||
))}
|
||||
</tbody>
|
||||
</Table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import type { FormState } from "../actions";
|
||||
|
||||
export function RoleForm({
|
||||
action,
|
||||
defaultValues,
|
||||
}: {
|
||||
action: (prev: FormState, formData: FormData) => Promise<FormState>;
|
||||
defaultValues?: { name?: string; title?: string; remark?: string };
|
||||
}) {
|
||||
const [state, formAction, pending] = useActionState(action, {});
|
||||
const v = defaultValues ?? {};
|
||||
return (
|
||||
<form action={formAction} className="max-w-lg space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title">角色名称<span className="ml-0.5 text-[var(--color-danger)]">*</span></Label>
|
||||
<Input id="title" name="title" defaultValue={v.title} placeholder="如:业务员" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="name">角色标识<span className="ml-0.5 text-[var(--color-danger)]">*</span></Label>
|
||||
<Input id="name" name="name" defaultValue={v.name} placeholder="如:staff(英文唯一标识)" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="remark">备注</Label>
|
||||
<Textarea id="remark" name="remark" defaultValue={v.remark} rows={2} />
|
||||
</div>
|
||||
{state.error && (
|
||||
<p className="rounded-md bg-[var(--color-danger-soft)] px-3 py-2 text-sm text-[var(--color-danger)]">
|
||||
{state.error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2 border-t pt-4">
|
||||
<Button type="submit" disabled={pending}>{pending ? "保存中…" : "保存"}</Button>
|
||||
<Link href="/rbac/roles"><Button type="button" variant="outline">取消</Button></Link>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user