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:
2026-07-08 15:02:03 +08:00
co-authored by Claude Opus 4.8
commit 5d46afe439
68 changed files with 6998 additions and 0 deletions
@@ -0,0 +1,40 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { updateCustomer } from "../../actions";
import { CustomerForm } from "../../customer-form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
export default async function EditCustomerPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const customer = await prisma.customer.findFirst({
where: { id: Number(id), deletedAt: null },
});
if (!customer) notFound();
const action = updateCustomer.bind(null, customer.id);
return (
<div className="mx-auto max-w-4xl space-y-4">
<Link
href="/customers"
className="inline-flex items-center gap-1.5 text-sm text-[var(--color-muted-foreground)] hover:text-[var(--color-foreground)]"
>
<ArrowLeft className="h-4 w-4" /> 返回客户列表
</Link>
<Card>
<CardHeader>
<CardTitle>编辑客户 · {customer.customerName}</CardTitle>
</CardHeader>
<CardContent>
<CustomerForm action={action} defaultValues={customer} submitLabel="保存" />
</CardContent>
</Card>
</div>
);
}
+166
View File
@@ -0,0 +1,166 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import * as XLSX from "xlsx";
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { parseDate } from "@/lib/utils";
// 校验规则对齐老系统必填项(customer_name/contacts/balance_user/detail/salesman/report_date)
const schema = z.object({
customerName: z.string().trim().min(1, "客户名称必填").max(500),
contacts: z.string().trim().min(1, "联系人必填").max(500),
balanceUser: z.string().trim().min(1, "结算人必填").max(500),
detail: z.string().trim().min(1, "详情必填"),
salesman: z.string().trim().min(1, "业务员必填"),
reportDate: z
.string()
.trim()
.min(1, "报单时间必填")
.refine((s) => parseDate(s) !== null, "报单时间格式应为 YYYY-MM-DD"),
phone: z.string().trim().optional().default(""),
deposit: z.string().trim().optional().default(""),
buy: z.string().trim().optional().default(""),
birthdayType: z.coerce.number().int().min(1).max(2).default(1),
birthday: z.string().trim().optional().default(""),
remark: z.string().trim().optional().default(""),
});
export type ActionState = { error?: string };
function parse(formData: FormData) {
return schema.safeParse({
customerName: formData.get("customerName"),
contacts: formData.get("contacts"),
balanceUser: formData.get("balanceUser"),
detail: formData.get("detail"),
salesman: formData.get("salesman"),
reportDate: formData.get("reportDate"),
phone: formData.get("phone") ?? "",
deposit: formData.get("deposit") ?? "",
buy: formData.get("buy") ?? "",
birthdayType: formData.get("birthdayType") ?? 1,
birthday: formData.get("birthday") ?? "",
remark: formData.get("remark") ?? "",
});
}
/** 把校验后的表单值转成 Prisma 写入数据(日期字段转 Date) */
function toData(v: z.infer<typeof schema>) {
const { reportDate, birthday, ...rest } = v;
return {
...rest,
reportDate: parseDate(reportDate),
birthday: parseDate(birthday),
};
}
export async function createCustomer(
_prev: ActionState,
formData: FormData
): Promise<ActionState> {
if (!(await auth())) return { error: "未登录" };
const r = parse(formData);
if (!r.success) return { error: r.error.issues[0].message };
await prisma.customer.create({ data: toData(r.data) });
revalidatePath("/customers");
redirect("/customers");
}
export async function updateCustomer(
id: number,
_prev: ActionState,
formData: FormData
): Promise<ActionState> {
if (!(await auth())) return { error: "未登录" };
const r = parse(formData);
if (!r.success) return { error: r.error.issues[0].message };
await prisma.customer.update({ where: { id }, data: toData(r.data) });
revalidatePath("/customers");
redirect("/customers");
}
export async function deleteCustomer(id: number): Promise<void> {
if (!(await auth())) return;
// 软删除,对齐老系统 deleted_at
await prisma.customer.update({
where: { id },
data: { deletedAt: new Date() },
});
revalidatePath("/customers");
}
// ============ Excel 导入 ============
const HEADER_MAP: Record<string, string> = {
客户名称: "customerName",
联系人: "contacts",
结算人: "balanceUser",
电话: "phone",
详情: "detail",
押金: "deposit",
买断: "buy",
生日类型: "birthdayType",
生日: "birthday",
业务员: "salesman",
报单时间: "reportDate",
备注: "remark",
};
export type ImportResult = { ok: boolean; inserted?: number; skipped?: number; error?: string };
export async function importCustomers(formData: FormData): Promise<ImportResult> {
if (!(await auth())) return { ok: false, error: "未登录" };
const file = formData.get("file");
if (!(file instanceof File) || file.size === 0) return { ok: false, error: "请选择文件" };
try {
const buf = Buffer.from(await file.arrayBuffer());
const wb = XLSX.read(buf, { type: "buffer", cellDates: true });
const sheet = wb.Sheets[wb.SheetNames[0]];
const raw = XLSX.utils.sheet_to_json<Record<string, unknown>>(sheet, { raw: false, defval: "" });
const data: Prisma.CustomerCreateManyInput[] = [];
let skipped = 0;
for (const row of raw) {
const rec: Record<string, string> = {};
for (const [header, val] of Object.entries(row)) {
const key = HEADER_MAP[String(header).trim()];
if (key) rec[key] = String(val ?? "").trim();
}
// 报单时间为必填且需可解析,否则跳过
const reportDate = parseDate(rec.reportDate);
if (!rec.customerName || !reportDate) {
skipped++;
continue;
}
data.push({
customerName: rec.customerName,
contacts: rec.contacts || null,
balanceUser: rec.balanceUser || null,
phone: rec.phone || null,
detail: rec.detail || null,
deposit: rec.deposit || null,
buy: rec.buy || null,
salesman: rec.salesman || null,
remark: rec.remark || null,
birthdayType: rec.birthdayType === "阴历" || rec.birthdayType === "2" ? 2 : 1,
birthday: parseDate(rec.birthday),
reportDate,
});
}
if (data.length === 0) return { ok: false, error: `无有效数据(跳过 ${skipped} 行)` };
await prisma.customer.createMany({ data });
revalidatePath("/customers");
return { ok: true, inserted: data.length, skipped };
} catch (e) {
return { ok: false, error: (e as Error).message };
}
}
@@ -0,0 +1,51 @@
"use client";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
export function BirthdayControl({
mode,
date,
}: {
mode: "today" | "week";
date: string;
}) {
const router = useRouter();
function go(next: { mode?: string; date?: string }) {
const params = new URLSearchParams();
params.set("mode", next.mode ?? mode);
const d = next.date ?? date;
if (d) params.set("date", d);
router.push(`/customers/birthday?${params.toString()}`);
}
return (
<div className="flex flex-wrap items-center gap-2">
<div className="flex overflow-hidden rounded-md border">
<button
onClick={() => go({ mode: "today" })}
className={`px-3 py-1.5 text-sm ${mode === "today" ? "bg-[var(--color-primary)] text-white" : "bg-white hover:bg-[var(--color-accent)]"}`}
>
当天
</button>
<button
onClick={() => go({ mode: "week" })}
className={`border-l px-3 py-1.5 text-sm ${mode === "week" ? "bg-[var(--color-primary)] text-white" : "bg-white hover:bg-[var(--color-accent)]"}`}
>
未来 7 天
</button>
</div>
<Input
type="date"
defaultValue={date}
onChange={(e) => go({ date: e.target.value })}
className="w-40"
/>
<span className="text-sm text-[var(--color-muted-foreground)]">
(不填默认今天)
</span>
</div>
);
}
@@ -0,0 +1,113 @@
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { birthdayMatchLists } from "@/lib/lunar";
import { fmtDate } from "@/lib/utils";
import { Card } from "@/components/ui/card";
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { BirthdayControl } from "./birthday-control";
type Row = {
id: number;
customerName: string | null;
contacts: string | null;
phone: string | null;
salesman: string | null;
reportDate: Date | null;
birthday: Date | null;
birthdayType: number | null;
remark: string | null;
};
function baseDate(s?: string): Date {
if (s) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
if (m) return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
}
return new Date();
}
export default async function BirthdayPage({
searchParams,
}: {
searchParams: Promise<{ mode?: string; date?: string }>;
}) {
const sp = await searchParams;
const mode = sp.mode === "week" ? "week" : "today";
const dateStr = sp.date ?? "";
const base = baseDate(sp.date);
const { solar, lunar } =
mode === "week"
? birthdayMatchLists(base, 7, false)
: birthdayMatchLists(base, 1, true);
const rows = await prisma.$queryRaw<Row[]>(Prisma.sql`
SELECT
id,
customer_name AS customerName,
contacts,
phone,
salesman,
report_date AS reportDate,
birthday,
birthday_type AS birthdayType,
remark
FROM customers
WHERE deleted_at IS NULL AND (
(birthday_type = 1 AND DATE_FORMAT(birthday, '%m-%d') IN (${Prisma.join(solar)}))
OR
(birthday_type = 2 AND DATE_FORMAT(birthday, '%m-%d') IN (${Prisma.join(lunar)}))
)
ORDER BY DATE_FORMAT(birthday, '%m-%d')
`);
return (
<div className="space-y-4">
<Card className="flex flex-wrap items-center justify-between gap-3 p-3">
<BirthdayControl mode={mode} date={dateStr} />
<div className="pr-1 text-sm text-[var(--color-muted-foreground)]">
命中 <span className="font-semibold text-[var(--color-foreground)]">{rows.length}</span> 位客户
</div>
</Card>
<Card className="overflow-hidden">
<Table>
<THead>
<tr>
<TH>客户名称</TH>
<TH>联系人</TH>
<TH>电话</TH>
<TH>业务员</TH>
<TH>生日</TH>
<TH>历法</TH>
</tr>
</THead>
<tbody>
{rows.length === 0 && (
<tr>
<TD colSpan={6} className="py-14 text-center text-[var(--color-muted-foreground)]">
该时段暂无生日客户
</TD>
</tr>
)}
{rows.map((c) => (
<TR key={c.id}>
<TD className="font-medium">{c.customerName}</TD>
<TD>{c.contacts}</TD>
<TD className="tabular-nums">{c.phone}</TD>
<TD>{c.salesman}</TD>
<TD className="tabular-nums">{fmtDate(c.birthday)}</TD>
<TD>
<Badge tone={c.birthdayType === 2 ? "warning" : "info"}>
{c.birthdayType === 2 ? "农历" : "阳历"}
</Badge>
</TD>
</TR>
))}
</tbody>
</Table>
</Card>
</div>
);
}
@@ -0,0 +1,119 @@
"use client";
import { useActionState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input, Textarea, Select } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { fmtDate } from "@/lib/utils";
import type { ActionState } from "./actions";
type CustomerValues = {
customerName?: string | null;
contacts?: string | null;
balanceUser?: string | null;
phone?: string | null;
detail?: string | null;
deposit?: string | null;
buy?: string | null;
birthdayType?: number | null;
birthday?: Date | null;
salesman?: string | null;
reportDate?: Date | null;
remark?: string | null;
};
function Field({
label,
name,
defaultValue,
required,
type = "text",
}: {
label: string;
name: string;
defaultValue?: string | null;
required?: boolean;
type?: string;
}) {
return (
<div className="space-y-1.5">
<Label htmlFor={name}>
{label}
{required && <span className="ml-0.5 text-[var(--color-danger)]">*</span>}
</Label>
<Input id={name} name={name} type={type} defaultValue={defaultValue ?? ""} />
</div>
);
}
export function CustomerForm({
action,
defaultValues,
submitLabel = "保存",
}: {
action: (prev: ActionState, formData: FormData) => Promise<ActionState>;
defaultValues?: CustomerValues;
submitLabel?: string;
}) {
const [state, formAction, pending] = useActionState(action, {});
const v = defaultValues ?? {};
return (
<form action={formAction} className="space-y-6">
<div className="grid grid-cols-1 gap-x-5 gap-y-4 sm:grid-cols-2 lg:grid-cols-3">
<Field label="客户名称" name="customerName" defaultValue={v.customerName} required />
<Field label="联系人" name="contacts" defaultValue={v.contacts} required />
<Field label="结算人" name="balanceUser" defaultValue={v.balanceUser} required />
<Field label="业务员" name="salesman" defaultValue={v.salesman} required />
<Field label="电话" name="phone" defaultValue={v.phone} />
<Field
label="报单时间"
name="reportDate"
type="date"
defaultValue={fmtDate(v.reportDate)}
required
/>
<Field label="押金" name="deposit" defaultValue={v.deposit} />
<Field label="买断" name="buy" defaultValue={v.buy} />
<div className="space-y-1.5">
<Label htmlFor="birthdayType">生日类型</Label>
<Select id="birthdayType" name="birthdayType" defaultValue={String(v.birthdayType ?? 1)}>
<option value="1">阳历</option>
<option value="2">阴历</option>
</Select>
</div>
<Field label="生日" name="birthday" type="date" defaultValue={fmtDate(v.birthday)} />
</div>
<div className="space-y-1.5">
<Label htmlFor="detail">
详情<span className="ml-0.5 text-[var(--color-danger)]">*</span>
</Label>
<Textarea id="detail" name="detail" defaultValue={v.detail ?? ""} rows={3} />
</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 ? "保存中…" : submitLabel}
</Button>
<Link href="/customers">
<Button type="button" variant="outline">
取消
</Button>
</Link>
</div>
</form>
);
}
@@ -0,0 +1,103 @@
"use client";
import { useRef, useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Plus, Upload, Download, Search, RotateCcw } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { importCustomers } from "./actions";
export function CustomerToolbar({
defaultKeyword,
defaultStart,
defaultEnd,
exportHref,
}: {
defaultKeyword?: string;
defaultStart?: string;
defaultEnd?: string;
exportHref: string;
}) {
const router = useRouter();
const fileRef = useRef<HTMLInputElement>(null);
const [importing, startImport] = useTransition();
const [pending, startSearch] = useTransition();
function onSearch(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const f = new FormData(e.currentTarget);
const params = new URLSearchParams();
const kw = String(f.get("keyword") ?? "").trim();
const start = String(f.get("start") ?? "");
const end = String(f.get("end") ?? "");
if (kw) params.set("keyword", kw);
if (start) params.set("start", start);
if (end) params.set("end", end);
startSearch(() => router.push(`/customers?${params.toString()}`));
}
function onFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) return;
const fd = new FormData();
fd.append("file", file);
startImport(async () => {
const res = await importCustomers(fd);
if (res.ok) {
toast.success(`导入成功:新增 ${res.inserted} 条${res.skipped ? `,跳过 ${res.skipped} 条` : ""}`);
router.refresh();
} else {
toast.error(res.error ?? "导入失败");
}
if (fileRef.current) fileRef.current.value = "";
});
}
return (
<Card className="flex flex-wrap items-center justify-between gap-3 p-3">
<form onSubmit={onSearch} className="flex flex-wrap items-center gap-2">
<div className="relative">
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-muted-foreground)]" />
<Input
name="keyword"
placeholder="客户 / 联系人 / 电话 / 业务员"
defaultValue={defaultKeyword}
className="w-64 pl-8"
/>
</div>
<Input name="start" type="date" defaultValue={defaultStart} className="w-[150px]" />
<span className="text-[var(--color-muted-foreground)]">~</span>
<Input name="end" type="date" defaultValue={defaultEnd} className="w-[150px]" />
<Button type="submit" variant="soft" disabled={pending}>
查询
</Button>
<Button type="button" variant="ghost" size="icon" title="重置" onClick={() => router.push("/customers")}>
<RotateCcw className="h-4 w-4" />
</Button>
</form>
<div className="flex items-center gap-2">
<input ref={fileRef} type="file" accept=".xlsx,.xls" hidden onChange={onFile} />
<Button variant="outline" disabled={importing} onClick={() => fileRef.current?.click()}>
<Upload className="h-4 w-4" />
{importing ? "导入中…" : "导入"}
</Button>
<a href={exportHref}>
<Button variant="outline">
<Download className="h-4 w-4" />
导出
</Button>
</a>
<Link href="/customers/new">
<Button>
<Plus className="h-4 w-4" />
新增客户
</Button>
</Link>
</div>
</Card>
);
}
@@ -0,0 +1,26 @@
"use client";
import { useTransition } from "react";
import { Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { deleteCustomer } from "./actions";
export function DeleteButton({ id, name }: { id: number; name: string }) {
const [pending, start] = useTransition();
function onDelete() {
if (!confirm(`确认删除客户「${name}」?`)) return;
start(async () => {
await deleteCustomer(id);
toast.success("已删除");
});
}
return (
<Button variant="danger-ghost" size="sm" disabled={pending} onClick={onDelete}>
<Trash2 className="h-3.5 w-3.5" />
删除
</Button>
);
}
@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from "next/server";
import * as XLSX from "xlsx";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { fmtDate } from "@/lib/utils";
import { buildCustomerWhere, EXCEL_COLUMNS } from "../query";
export async function GET(req: NextRequest) {
if (!(await auth())) {
return NextResponse.json({ error: "未登录" }, { status: 401 });
}
const sp = req.nextUrl.searchParams;
const where = buildCustomerWhere({
keyword: sp.get("keyword") ?? undefined,
start: sp.get("start") ?? undefined,
end: sp.get("end") ?? undefined,
});
const rows = await prisma.customer.findMany({
where,
orderBy: { reportDate: "desc" },
});
const aoa: (string | number)[][] = [EXCEL_COLUMNS.map((c) => c.header)];
for (const c of rows) {
aoa.push([
c.customerName ?? "",
c.contacts ?? "",
c.balanceUser ?? "",
c.phone ?? "",
c.detail ?? "",
c.deposit ?? "",
c.buy ?? "",
c.birthdayType === 2 ? "阴历" : "阳历",
fmtDate(c.birthday),
c.salesman ?? "",
fmtDate(c.reportDate),
c.remark ?? "",
]);
}
const ws = XLSX.utils.aoa_to_sheet(aoa);
ws["!cols"] = EXCEL_COLUMNS.map(() => ({ wch: 16 }));
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "客户");
const buf = XLSX.write(wb, { type: "buffer", bookType: "xlsx" }) as Buffer;
const filename = `客户导出_${fmtDate(new Date())}.xlsx`;
return new NextResponse(new Uint8Array(buf), {
status: 200,
headers: {
"Content-Type":
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
},
});
}
@@ -0,0 +1,26 @@
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { createCustomer } from "../actions";
import { CustomerForm } from "../customer-form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
export default function NewCustomerPage() {
return (
<div className="mx-auto max-w-4xl space-y-4">
<Link
href="/customers"
className="inline-flex items-center gap-1.5 text-sm text-[var(--color-muted-foreground)] hover:text-[var(--color-foreground)]"
>
<ArrowLeft className="h-4 w-4" /> 返回客户列表
</Link>
<Card>
<CardHeader>
<CardTitle>新增客户</CardTitle>
</CardHeader>
<CardContent>
<CustomerForm action={createCustomer} submitLabel="创建" />
</CardContent>
</Card>
</div>
);
}
+148
View File
@@ -0,0 +1,148 @@
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { fmtDate } from "@/lib/utils";
import { Card } from "@/components/ui/card";
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { CustomerToolbar } from "./customer-toolbar";
import { DeleteButton } from "./delete-button";
import { buildCustomerWhere } from "./query";
const PAGE_SIZE = 15;
type SearchParams = {
keyword?: string;
start?: string;
end?: string;
page?: string;
};
export default async function CustomersPage({
searchParams,
}: {
searchParams: Promise<SearchParams>;
}) {
const sp = await searchParams;
const keyword = (sp.keyword ?? "").trim();
const page = Math.max(1, Number(sp.page) || 1);
const where = buildCustomerWhere(sp);
const [rows, total] = await Promise.all([
prisma.customer.findMany({
where,
orderBy: { reportDate: "desc" },
skip: (page - 1) * PAGE_SIZE,
take: PAGE_SIZE,
}),
prisma.customer.count({ where }),
]);
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const exportQs = new URLSearchParams();
if (sp.keyword) exportQs.set("keyword", sp.keyword);
if (sp.start) exportQs.set("start", sp.start);
if (sp.end) exportQs.set("end", sp.end);
return (
<div className="space-y-4">
<CustomerToolbar
defaultKeyword={keyword}
defaultStart={sp.start}
defaultEnd={sp.end}
exportHref={`/customers/export?${exportQs.toString()}`}
/>
<Card className="overflow-hidden">
<Table>
<THead>
<tr>
<TH>客户名称</TH>
<TH>联系人</TH>
<TH>电话</TH>
<TH>业务员</TH>
<TH>报单时间</TH>
<TH>生日</TH>
<TH className="text-right">操作</TH>
</tr>
</THead>
<tbody>
{rows.length === 0 && (
<tr>
<TD colSpan={7} className="py-14 text-center text-[var(--color-muted-foreground)]">
暂无数据
</TD>
</tr>
)}
{rows.map((c) => (
<TR key={c.id}>
<TD className="font-medium">{c.customerName}</TD>
<TD>{c.contacts}</TD>
<TD className="tabular-nums">{c.phone}</TD>
<TD>{c.salesman}</TD>
<TD className="tabular-nums">{fmtDate(c.reportDate)}</TD>
<TD>
<span className="tabular-nums">{fmtDate(c.birthday)}</span>
{c.birthday && (
<Badge tone={c.birthdayType === 2 ? "warning" : "info"} className="ml-2">
{c.birthdayType === 2 ? "农历" : "阳历"}
</Badge>
)}
</TD>
<TD>
<div className="flex justify-end gap-1.5">
<Link href={`/customers/${c.id}/edit`}>
<Button variant="outline" size="sm">编辑</Button>
</Link>
<DeleteButton id={c.id} name={c.customerName ?? ""} />
</div>
</TD>
</TR>
))}
</tbody>
</Table>
</Card>
{/* 分页 */}
<div className="flex items-center justify-between text-sm text-[var(--color-muted-foreground)]">
<span>共 <span className="font-medium text-[var(--color-foreground)]">{total.toLocaleString()}</span> 条</span>
<div className="flex items-center gap-2">
<PageLink page={page - 1} disabled={page <= 1} sp={sp} label="上一页" />
<span className="px-1 tabular-nums">{page} / {totalPages}</span>
<PageLink page={page + 1} disabled={page >= totalPages} sp={sp} label="下一页" />
</div>
</div>
</div>
);
}
function PageLink({
page,
disabled,
sp,
label,
}: {
page: number;
disabled: boolean;
sp: SearchParams;
label: string;
}) {
if (disabled) {
return (
<span className="rounded-md border px-3 py-1.5 opacity-40">{label}</span>
);
}
const params = new URLSearchParams();
if (sp.keyword) params.set("keyword", sp.keyword);
if (sp.start) params.set("start", sp.start);
if (sp.end) params.set("end", sp.end);
params.set("page", String(page));
return (
<Link
href={`/customers?${params.toString()}`}
className="rounded-md border bg-[var(--color-surface)] px-3 py-1.5 hover:bg-[var(--color-muted)]"
>
{label}
</Link>
);
}
+44
View File
@@ -0,0 +1,44 @@
import { Prisma } from "@prisma/client";
import { parseDate } from "@/lib/utils";
export type CustomerSearch = {
keyword?: string;
start?: string;
end?: string;
};
/** 客户列表 / 导出 共用的查询条件 */
export function buildCustomerWhere(sp: CustomerSearch): Prisma.CustomerWhereInput {
const keyword = (sp.keyword ?? "").trim();
const where: Prisma.CustomerWhereInput = { deletedAt: null };
if (keyword) {
where.OR = [
{ customerName: { contains: keyword } },
{ contacts: { contains: keyword } },
{ balanceUser: { contains: keyword } },
{ phone: { contains: keyword } },
{ detail: { contains: keyword } },
{ salesman: { contains: keyword } },
];
}
const start = parseDate(sp.start);
const end = parseDate(sp.end);
if (start && end) where.reportDate = { gte: start, lte: end };
return where;
}
/** 导出/导入的列定义(表头 ↔ 字段) */
export const EXCEL_COLUMNS: { header: string; key: string }[] = [
{ header: "客户名称", key: "customerName" },
{ header: "联系人", key: "contacts" },
{ header: "结算人", key: "balanceUser" },
{ header: "电话", key: "phone" },
{ header: "详情", key: "detail" },
{ header: "押金", key: "deposit" },
{ header: "买断", key: "buy" },
{ header: "生日类型", key: "birthdayType" },
{ header: "生日", key: "birthday" },
{ header: "业务员", key: "salesman" },
{ header: "报单时间", key: "reportDate" },
{ header: "备注", key: "remark" },
];
+38
View File
@@ -0,0 +1,38 @@
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { Sidebar } from "@/components/app/sidebar";
import { Topbar } from "@/components/app/topbar";
import { brand, copyright } from "@/lib/brand";
export default async function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await auth();
if (!session?.user) redirect("/login");
const u = session.user;
return (
<div className="flex h-screen overflow-hidden">
<Sidebar />
<div className="flex min-w-0 flex-1 flex-col">
<Topbar
user={{
name: u.name,
username: u.username,
roles: u.roles,
image: null, // 旧 face 为老站点相对路径,统一用文字头像
}}
/>
<main className="flex-1 overflow-y-auto">
<div className="p-6">{children}</div>
<footer className="flex items-center justify-between border-t px-6 py-4 text-xs text-[var(--color-muted-foreground)]">
<span>{copyright()}</span>
<span>{brand.name} · {brand.tagline}</span>
</footer>
</main>
</div>
</div>
);
}
+44
View File
@@ -0,0 +1,44 @@
"use server";
import { revalidatePath } from "next/cache";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
export type MeState = { ok?: boolean; error?: string };
/** 修改昵称 */
export async function updateProfile(_prev: MeState, formData: FormData): Promise<MeState> {
const session = await auth();
if (!session?.user) return { error: "未登录" };
const nickname = String(formData.get("nickname") ?? "").trim();
if (!nickname) return { error: "昵称不能为空" };
await prisma.admin.update({
where: { id: Number(session.user.id) },
data: { nickname },
});
revalidatePath("/me");
return { ok: true };
}
/** 修改密码:校验原密码 */
export async function changePassword(_prev: MeState, formData: FormData): Promise<MeState> {
const session = await auth();
if (!session?.user) return { error: "未登录" };
const oldPw = String(formData.get("oldPassword") ?? "");
const newPw = String(formData.get("newPassword") ?? "");
const confirm = String(formData.get("confirmPassword") ?? "");
if (newPw.length < 6) return { error: "新密码至少 6 位" };
if (newPw !== confirm) return { error: "两次输入的新密码不一致" };
const admin = await prisma.admin.findUnique({ where: { id: Number(session.user.id) } });
if (!admin) return { error: "账号不存在" };
if (!bcrypt.compareSync(oldPw, admin.password)) return { error: "原密码错误" };
await prisma.admin.update({
where: { id: admin.id },
data: { password: bcrypt.hashSync(newPw, 10) },
});
return { ok: true };
}
+55
View File
@@ -0,0 +1,55 @@
"use client";
import { useActionState, useEffect } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { updateProfile, changePassword, type MeState } from "./actions";
function useToastOnDone(state: MeState, okMsg: string) {
useEffect(() => {
if (state.ok) toast.success(okMsg);
else if (state.error) toast.error(state.error);
}, [state, okMsg]);
}
export function ProfileForm({ nickname, username }: { nickname: string; username: string }) {
const [state, action, pending] = useActionState(updateProfile, {});
useToastOnDone(state, "资料已更新");
return (
<form action={action} className="max-w-md space-y-4">
<div className="space-y-1.5">
<Label>用户名</Label>
<Input value={username} disabled />
</div>
<div className="space-y-1.5">
<Label htmlFor="nickname">昵称</Label>
<Input id="nickname" name="nickname" defaultValue={nickname} />
</div>
<Button type="submit" disabled={pending}>{pending ? "保存中…" : "保存资料"}</Button>
</form>
);
}
export function PasswordForm() {
const [state, action, pending] = useActionState(changePassword, {});
useToastOnDone(state, "密码已修改");
return (
<form action={action} className="max-w-md space-y-4">
<div className="space-y-1.5">
<Label htmlFor="oldPassword">原密码</Label>
<Input id="oldPassword" name="oldPassword" type="password" autoComplete="current-password" />
</div>
<div className="space-y-1.5">
<Label htmlFor="newPassword">新密码</Label>
<Input id="newPassword" name="newPassword" type="password" autoComplete="new-password" placeholder="至少 6 位" />
</div>
<div className="space-y-1.5">
<Label htmlFor="confirmPassword">确认新密码</Label>
<Input id="confirmPassword" name="confirmPassword" type="password" autoComplete="new-password" />
</div>
<Button type="submit" disabled={pending}>{pending ? "提交中…" : "修改密码"}</Button>
</form>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { Avatar } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ProfileForm, PasswordForm } from "./me-forms";
export default async function MePage() {
const session = await auth();
if (!session?.user) redirect("/login");
const admin = await prisma.admin.findUnique({ where: { id: Number(session.user.id) } });
if (!admin) redirect("/login");
const roleLabel = session.user.roles.includes("super admin") ? "超级管理员" : "业务员";
return (
<div className="mx-auto max-w-3xl space-y-4">
<Card>
<CardContent className="flex items-center gap-4">
<Avatar name={admin.nickname} size={56} />
<div>
<div className="text-lg font-semibold">{admin.nickname}</div>
<div className="mt-1 flex items-center gap-2 text-sm text-[var(--color-muted-foreground)]">
<span className="tabular-nums">{admin.username}</span>
<Badge tone="primary">{roleLabel}</Badge>
</div>
</div>
</CardContent>
</Card>
<div className="grid gap-4 md:grid-cols-2">
<Card>
<CardHeader><CardTitle>基本资料</CardTitle></CardHeader>
<CardContent>
<ProfileForm nickname={admin.nickname} username={admin.username} />
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle>修改密码</CardTitle></CardHeader>
<CardContent>
<PasswordForm />
</CardContent>
</Card>
</div>
</div>
);
}
+161
View File
@@ -0,0 +1,161 @@
import Link from "next/link";
import { Prisma } from "@prisma/client";
import { Users, Cake, UserCheck, CalendarClock, ArrowUpRight } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { birthdayMatchLists } from "@/lib/lunar";
import { fmtDate } from "@/lib/utils";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, THead, TR, TH, TD } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { MonthlyReportChart, type MonthPoint } from "./report-chart";
export default async function DashboardPage() {
const now = new Date();
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const { solar, lunar } = birthdayMatchLists(now, 1, true);
// 近 12 个月窗口
const monthWindow: { key: string; label: string }[] = [];
const cur = new Date(now.getFullYear(), now.getMonth(), 1);
for (let i = 11; i >= 0; i--) {
const d = new Date(cur.getFullYear(), cur.getMonth() - i, 1);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
monthWindow.push({
key,
label: `${String(d.getFullYear()).slice(2)}/${String(d.getMonth() + 1).padStart(2, "0")}`,
});
}
const windowStart = new Date(cur.getFullYear(), cur.getMonth() - 11, 1);
const [total, admins, monthNew, birthdayToday, recent, monthly] = await Promise.all([
prisma.customer.count({ where: { deletedAt: null } }),
prisma.admin.count({ where: { deletedAt: null } }),
prisma.customer.count({ where: { deletedAt: null, reportDate: { gte: monthStart } } }),
prisma.$queryRaw<{ n: bigint }[]>(Prisma.sql`
SELECT COUNT(*) AS n FROM customers WHERE deleted_at IS NULL AND (
(birthday_type = 1 AND DATE_FORMAT(birthday,'%m-%d') IN (${Prisma.join(solar)}))
OR (birthday_type = 2 AND DATE_FORMAT(birthday,'%m-%d') IN (${Prisma.join(lunar)})))`),
prisma.customer.findMany({
where: { deletedAt: null },
orderBy: { reportDate: "desc" },
take: 6,
}),
prisma.$queryRaw<{ m: string; c: bigint }[]>(Prisma.sql`
SELECT DATE_FORMAT(report_date,'%Y-%m') m, COUNT(*) c
FROM customers
WHERE deleted_at IS NULL AND report_date >= ${windowStart}
GROUP BY m`),
]);
const birthdayCount = Number(birthdayToday[0]?.n ?? 0);
const cmap = new Map(monthly.map((r) => [r.m, Number(r.c)]));
const chartData: MonthPoint[] = monthWindow.map((m) => ({
month: m.key,
label: m.label,
count: cmap.get(m.key) ?? 0,
}));
const last12Total = chartData.reduce((s, d) => s + d.count, 0);
const stats = [
{ label: "客户总数", value: total.toLocaleString(), icon: Users, tone: "primary" as const },
{ label: "本月新增", value: monthNew.toLocaleString(), icon: CalendarClock, tone: "info" as const },
{ label: "今日生日", value: birthdayCount.toLocaleString(), icon: Cake, tone: "warning" as const },
{ label: "后台账号", value: admins.toLocaleString(), icon: UserCheck, tone: "success" as const },
];
const toneBg: Record<string, string> = {
primary: "var(--color-primary-soft)",
info: "var(--color-info-soft)",
warning: "var(--color-warning-soft)",
success: "var(--color-success-soft)",
};
const toneFg: Record<string, string> = {
primary: "var(--color-primary)",
info: "var(--color-info)",
warning: "var(--color-warning)",
success: "var(--color-success)",
};
return (
<div className="space-y-6">
{/* 统计卡片 */}
<div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
{stats.map((s) => {
const Icon = s.icon;
return (
<Card key={s.label}>
<CardContent className="flex items-center gap-4">
<span
className="flex h-12 w-12 items-center justify-center rounded-xl"
style={{ background: toneBg[s.tone], color: toneFg[s.tone] }}
>
<Icon className="h-6 w-6" />
</span>
<div>
<div className="text-sm text-[var(--color-muted-foreground)]">{s.label}</div>
<div className="mt-0.5 text-2xl font-semibold tabular-nums">{s.value}</div>
</div>
</CardContent>
</Card>
);
})}
</div>
{/* 月度新增报单 */}
<Card>
<CardHeader>
<CardTitle>月度新增报单(近 12 个月)</CardTitle>
<span className="text-[13px] text-[var(--color-muted-foreground)]">
合计 <span className="font-semibold text-[var(--color-foreground)]">{last12Total.toLocaleString()}</span> 单
</span>
</CardHeader>
<CardContent>
<MonthlyReportChart data={chartData} />
</CardContent>
</Card>
{/* 最近客户 */}
<Card>
<CardHeader>
<CardTitle>最近报单客户</CardTitle>
<Link
href="/customers"
className="flex items-center gap-1 text-[13px] font-medium text-[var(--color-primary)] hover:underline"
>
查看全部 <ArrowUpRight className="h-3.5 w-3.5" />
</Link>
</CardHeader>
<Table>
<THead>
<tr>
<TH>客户名称</TH>
<TH>联系人</TH>
<TH>业务员</TH>
<TH>报单时间</TH>
<TH>生日</TH>
</tr>
</THead>
<tbody>
{recent.map((c) => (
<TR key={c.id}>
<TD className="font-medium">{c.customerName}</TD>
<TD>{c.contacts}</TD>
<TD>{c.salesman}</TD>
<TD className="tabular-nums">{fmtDate(c.reportDate)}</TD>
<TD>
<span className="tabular-nums">{fmtDate(c.birthday)}</span>
{c.birthday && (
<Badge tone={c.birthdayType === 2 ? "warning" : "info"} className="ml-2">
{c.birthdayType === 2 ? "农历" : "阳历"}
</Badge>
)}
</TD>
</TR>
))}
</tbody>
</Table>
</Card>
</div>
);
}
+189
View File
@@ -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>
);
}
+80
View File
@@ -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>
);
}
+67
View File
@@ -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>
);
}
+60
View File
@@ -0,0 +1,60 @@
"use client";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Cell,
} from "recharts";
export type MonthPoint = { month: string; label: string; count: number };
export function MonthlyReportChart({ data }: { data: MonthPoint[] }) {
const max = Math.max(1, ...data.map((d) => d.count));
return (
<div className="h-72 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#eef0f3" vertical={false} />
<XAxis
dataKey="label"
tick={{ fontSize: 12, fill: "#64748b" }}
tickLine={false}
axisLine={{ stroke: "#e8eaed" }}
/>
<YAxis
allowDecimals={false}
width={40}
tick={{ fontSize: 12, fill: "#64748b" }}
tickLine={false}
axisLine={false}
/>
<Tooltip
cursor={{ fill: "rgba(79,70,229,0.06)" }}
contentStyle={{
borderRadius: 10,
border: "1px solid #e8eaed",
boxShadow: "0 4px 16px rgba(0,0,0,0.08)",
fontSize: 13,
}}
labelStyle={{ color: "#1e293b", fontWeight: 600 }}
formatter={(value) => [`${value} 单`, "新增报单"] as [string, string]}
/>
<Bar dataKey="count" radius={[6, 6, 0, 0]} maxBarSize={44}>
{data.map((d, i) => (
<Cell
key={i}
fill={d.count === max ? "#4338ca" : "#6366f1"}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
);
}