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,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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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" },
|
||||
];
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { handlers } from "@/lib/auth";
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
@@ -0,0 +1,68 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
/* 中性色 */
|
||||
--color-background: #f6f7f9;
|
||||
--color-surface: #ffffff;
|
||||
--color-foreground: #1e293b;
|
||||
--color-muted: #f1f5f9;
|
||||
--color-muted-foreground: #64748b;
|
||||
--color-border: #e8eaed;
|
||||
|
||||
/* 主题色(现代 CMS 靛蓝) */
|
||||
--color-primary: #4f46e5;
|
||||
--color-primary-hover: #4338ca;
|
||||
--color-primary-foreground: #ffffff;
|
||||
--color-primary-soft: #eef2ff;
|
||||
|
||||
/* 侧边栏(深色) */
|
||||
--color-sidebar: #0b1220;
|
||||
--color-sidebar-muted: #94a3b8;
|
||||
--color-sidebar-foreground: #e2e8f0;
|
||||
--color-sidebar-hover: #1e293b;
|
||||
|
||||
/* 语义色 */
|
||||
--color-success: #16a34a;
|
||||
--color-success-soft: #dcfce7;
|
||||
--color-warning: #d97706;
|
||||
--color-warning-soft: #fef3c7;
|
||||
--color-danger: #e11d48;
|
||||
--color-danger-soft: #ffe4e6;
|
||||
--color-info: #0ea5e9;
|
||||
--color-info-soft: #e0f2fe;
|
||||
|
||||
--color-ring: #a5b4fc;
|
||||
|
||||
--radius: 0.625rem;
|
||||
--font-sans: ui-sans-serif, system-ui, -apple-system, "PingFang SC",
|
||||
"Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
border-color: var(--color-border);
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--color-background);
|
||||
color: var(--color-foreground);
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* 细滚动条 */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #cbd5e1;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#6366f1"/>
|
||||
<stop offset="1" stop-color="#4338ca"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="48" height="48" rx="12" fill="url(#g)"/>
|
||||
<circle cx="19" cy="24" r="8.5" stroke="#ffffff" stroke-width="3.2" opacity="0.95"/>
|
||||
<circle cx="29" cy="24" r="8.5" stroke="#c7d2fe" stroke-width="3.2"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 529 B |
@@ -0,0 +1,22 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Toaster } from "sonner";
|
||||
import { brand } from "@/lib/brand";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: `${brand.name} · ${brand.product}`,
|
||||
description: `${brand.company} ${brand.tagline}`,
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{ children: React.ReactNode }>) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body>
|
||||
{children}
|
||||
<Toaster position="top-center" richColors closeButton />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { BrandMark } from "@/components/app/brand-logo";
|
||||
import { brand, copyright } from "@/lib/brand";
|
||||
|
||||
export function LoginForm() {
|
||||
const router = useRouter();
|
||||
const params = useSearchParams();
|
||||
const callbackUrl = params.get("callbackUrl") || "/";
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setLoading(true);
|
||||
const form = new FormData(e.currentTarget);
|
||||
const res = await signIn("credentials", {
|
||||
username: form.get("username"),
|
||||
password: form.get("password"),
|
||||
redirect: false,
|
||||
});
|
||||
setLoading(false);
|
||||
if (res?.error) {
|
||||
setError("用户名或密码错误");
|
||||
return;
|
||||
}
|
||||
router.push(callbackUrl);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="mb-8 flex flex-col items-center">
|
||||
<BrandMark size={56} className="rounded-2xl shadow-lg shadow-indigo-500/30" />
|
||||
<h1 className="mt-4 text-xl font-semibold">{brand.name}</h1>
|
||||
<p className="mt-1 text-sm text-[var(--color-muted-foreground)]">
|
||||
{brand.product}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border bg-[var(--color-surface)] p-6 shadow-sm">
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">用户名</Label>
|
||||
<Input id="username" name="username" autoComplete="username" placeholder="请输入用户名" required />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="password">密码</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="请输入密码"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="rounded-md bg-[var(--color-danger-soft)] px-3 py-2 text-sm text-[var(--color-danger)]">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" size="lg" className="w-full" disabled={loading}>
|
||||
{loading ? "登录中…" : "登 录"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-xs text-[var(--color-muted-foreground)]">
|
||||
{copyright()}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Suspense } from "react";
|
||||
import { LoginForm } from "./login-form";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden px-4">
|
||||
{/* 背景装饰 */}
|
||||
<div className="pointer-events-none absolute inset-0 -z-10 bg-[radial-gradient(60%_50%_at_50%_0%,#e0e7ff_0%,transparent_60%)]" />
|
||||
<Suspense>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { brand } from "@/lib/brand";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* 品牌标识(自绘 SVG):两个相扣的环 = “联动”,靛蓝渐变。
|
||||
* 纯矢量,无需图片资源,可任意缩放。
|
||||
*/
|
||||
export function BrandMark({ size = 36, className }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 48 48"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className={cn("shrink-0", className)}
|
||||
aria-hidden
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="ld-brand" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
|
||||
<stop stopColor="#6366f1" />
|
||||
<stop offset="1" stopColor="#4338ca" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="48" height="48" rx="12" fill="url(#ld-brand)" />
|
||||
{/* 相扣双环 */}
|
||||
<circle cx="19" cy="24" r="8.5" stroke="#fff" strokeWidth="3.2" opacity="0.95" />
|
||||
<circle cx="29" cy="24" r="8.5" stroke="#c7d2fe" strokeWidth="3.2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** 品牌标识 + 文字,用于登录/侧边栏 */
|
||||
export function BrandLogo({
|
||||
size = 36,
|
||||
subtitle,
|
||||
className,
|
||||
invert = false,
|
||||
}: {
|
||||
size?: number;
|
||||
subtitle?: string;
|
||||
className?: string;
|
||||
invert?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2.5", className)}>
|
||||
<BrandMark size={size} />
|
||||
<div className="leading-tight">
|
||||
<div className={cn("font-semibold", invert ? "text-white" : "text-[var(--color-foreground)]")}>
|
||||
{brand.name}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"text-[11px]",
|
||||
invert ? "text-[var(--color-sidebar-muted)]" : "text-[var(--color-muted-foreground)]"
|
||||
)}
|
||||
>
|
||||
{subtitle ?? brand.product}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Users,
|
||||
Cake,
|
||||
UserCog,
|
||||
ShieldCheck,
|
||||
KeyRound,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
export type NavItem = {
|
||||
href: string;
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
};
|
||||
|
||||
export type NavSection = {
|
||||
title: string;
|
||||
items: NavItem[];
|
||||
};
|
||||
|
||||
export const navSections: NavSection[] = [
|
||||
{
|
||||
title: "主菜单",
|
||||
items: [
|
||||
{ href: "/", label: "控制台", icon: LayoutDashboard },
|
||||
{ href: "/customers", label: "客户管理", icon: Users },
|
||||
{ href: "/customers/birthday", label: "生日提醒", icon: Cake },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "系统管理",
|
||||
items: [
|
||||
{ href: "/rbac/admins", label: "管理员", icon: UserCog },
|
||||
{ href: "/rbac/roles", label: "角色", icon: ShieldCheck },
|
||||
{ href: "/rbac/permissions", label: "权限菜单", icon: KeyRound },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** 在给定 pathname 下,返回应高亮的导航 href(最长前缀匹配) */
|
||||
export function activeHref(pathname: string): string {
|
||||
const all = navSections.flatMap((s) => s.items.map((i) => i.href));
|
||||
let best = "";
|
||||
for (const href of all) {
|
||||
const match =
|
||||
href === "/" ? pathname === "/" : pathname === href || pathname.startsWith(href + "/");
|
||||
if (match && href.length > best.length) best = href;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { copyright } from "@/lib/brand";
|
||||
import { BrandLogo } from "./brand-logo";
|
||||
import { navSections, activeHref } from "./nav";
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const active = activeHref(pathname);
|
||||
|
||||
return (
|
||||
<aside className="flex w-60 shrink-0 flex-col bg-[var(--color-sidebar)] text-[var(--color-sidebar-foreground)]">
|
||||
{/* 品牌 */}
|
||||
<div className="flex h-16 items-center px-5">
|
||||
<Link href="/">
|
||||
<BrandLogo size={36} invert />
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 space-y-6 overflow-y-auto px-3 py-4">
|
||||
{navSections.map((section) => (
|
||||
<div key={section.title}>
|
||||
<div className="px-3 pb-2 text-[11px] font-medium uppercase tracking-wider text-[var(--color-sidebar-muted)]">
|
||||
{section.title}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{section.items.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = active === item.href;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors",
|
||||
isActive
|
||||
? "bg-[var(--color-primary)] text-white shadow-sm"
|
||||
: "text-[var(--color-sidebar-muted)] hover:bg-[var(--color-sidebar-hover)] hover:text-white"
|
||||
)}
|
||||
>
|
||||
<Icon className="h-[18px] w-[18px]" />
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="px-5 py-4 text-[11px] text-[var(--color-sidebar-muted)]">
|
||||
{copyright()}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { signOut } from "next-auth/react";
|
||||
import { ChevronDown, User, LogOut } from "lucide-react";
|
||||
import { Avatar } from "@/components/ui/avatar";
|
||||
import { navSections } from "./nav";
|
||||
|
||||
function pageTitle(pathname: string): string {
|
||||
if (pathname === "/") return "控制台";
|
||||
if (pathname.startsWith("/me")) return "个人中心";
|
||||
const flat = navSections.flatMap((s) => s.items);
|
||||
const hit = flat
|
||||
.filter((i) => i.href !== "/" && pathname.startsWith(i.href))
|
||||
.sort((a, b) => b.href.length - a.href.length)[0];
|
||||
if (pathname.includes("/new")) return "新增" + (hit?.label ?? "");
|
||||
if (pathname.includes("/edit")) return "编辑" + (hit?.label ?? "");
|
||||
return hit?.label ?? "";
|
||||
}
|
||||
|
||||
export function Topbar({
|
||||
user,
|
||||
}: {
|
||||
user: { name?: string | null; username: string; roles: string[]; image?: string | null };
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function onClick(e: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
||||
}
|
||||
document.addEventListener("mousedown", onClick);
|
||||
return () => document.removeEventListener("mousedown", onClick);
|
||||
}, []);
|
||||
|
||||
const roleLabel = user.roles.includes("super admin") ? "超级管理员" : "业务员";
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-20 flex h-16 items-center justify-between border-b bg-[var(--color-surface)]/90 px-6 backdrop-blur">
|
||||
<h1 className="text-base font-semibold">{pageTitle(pathname)}</h1>
|
||||
|
||||
<div className="relative" ref={ref}>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-2.5 rounded-full py-1 pl-1 pr-2.5 transition-colors hover:bg-[var(--color-muted)]"
|
||||
>
|
||||
<Avatar name={user.name ?? user.username} src={user.image} size={32} />
|
||||
<div className="hidden text-left leading-tight sm:block">
|
||||
<div className="text-[13px] font-medium">{user.name ?? user.username}</div>
|
||||
<div className="text-[11px] text-[var(--color-muted-foreground)]">{roleLabel}</div>
|
||||
</div>
|
||||
<ChevronDown className="h-4 w-4 text-[var(--color-muted-foreground)]" />
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute right-0 mt-2 w-48 overflow-hidden rounded-[var(--radius)] border bg-[var(--color-surface)] py-1 shadow-lg">
|
||||
<Link
|
||||
href="/me"
|
||||
onClick={() => setOpen(false)}
|
||||
className="flex items-center gap-2.5 px-4 py-2 text-sm hover:bg-[var(--color-muted)]"
|
||||
>
|
||||
<User className="h-4 w-4" /> 个人中心
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => signOut({ callbackUrl: "/login" })}
|
||||
className="flex w-full items-center gap-2.5 px-4 py-2 text-sm text-[var(--color-danger)] hover:bg-[var(--color-danger-soft)]"
|
||||
>
|
||||
<LogOut className="h-4 w-4" /> 退出登录
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** 文字头像:取昵称首字,稳定生成柔和背景色 */
|
||||
export function Avatar({
|
||||
name,
|
||||
src,
|
||||
size = 36,
|
||||
className,
|
||||
}: {
|
||||
name?: string | null;
|
||||
src?: string | null;
|
||||
size?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
const label = (name ?? "?").trim().charAt(0).toUpperCase() || "?";
|
||||
const palette = [
|
||||
"#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ec4899", "#8b5cf6", "#ef4444",
|
||||
];
|
||||
let hash = 0;
|
||||
for (const ch of name ?? "") hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;
|
||||
const bg = palette[hash % palette.length];
|
||||
|
||||
if (src) {
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt={label}
|
||||
style={{ width: size, height: size }}
|
||||
className={cn("rounded-full object-cover", className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
style={{ width: size, height: size, background: bg, fontSize: size * 0.42 }}
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center justify-center rounded-full font-semibold text-white",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const tones = {
|
||||
neutral: "bg-[var(--color-muted)] text-[var(--color-muted-foreground)]",
|
||||
primary: "bg-[var(--color-primary-soft)] text-[var(--color-primary)]",
|
||||
success: "bg-[var(--color-success-soft)] text-[var(--color-success)]",
|
||||
warning: "bg-[var(--color-warning-soft)] text-[var(--color-warning)]",
|
||||
danger: "bg-[var(--color-danger-soft)] text-[var(--color-danger)]",
|
||||
info: "bg-[var(--color-info-soft)] text-[var(--color-info)]",
|
||||
} as const;
|
||||
|
||||
export function Badge({
|
||||
tone = "neutral",
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement> & { tone?: keyof typeof tones }) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium",
|
||||
tones[tone],
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const base =
|
||||
"inline-flex items-center justify-center gap-2 rounded-[var(--radius)] text-sm font-medium transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] disabled:pointer-events-none disabled:opacity-50 whitespace-nowrap active:scale-[0.98]";
|
||||
|
||||
const variants = {
|
||||
primary:
|
||||
"bg-[var(--color-primary)] text-[var(--color-primary-foreground)] shadow-sm hover:bg-[var(--color-primary-hover)]",
|
||||
outline:
|
||||
"border bg-[var(--color-surface)] text-[var(--color-foreground)] hover:bg-[var(--color-muted)]",
|
||||
ghost: "text-[var(--color-foreground)] hover:bg-[var(--color-muted)]",
|
||||
soft: "bg-[var(--color-primary-soft)] text-[var(--color-primary)] hover:bg-[#e0e7ff]",
|
||||
danger:
|
||||
"bg-[var(--color-danger)] text-white shadow-sm hover:brightness-95",
|
||||
"danger-ghost":
|
||||
"text-[var(--color-danger)] hover:bg-[var(--color-danger-soft)]",
|
||||
} as const;
|
||||
|
||||
const sizes = {
|
||||
default: "h-9 px-4",
|
||||
sm: "h-8 px-3 text-[13px]",
|
||||
lg: "h-10 px-5",
|
||||
icon: "h-9 w-9",
|
||||
} as const;
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: keyof typeof variants;
|
||||
size?: keyof typeof sizes;
|
||||
}
|
||||
|
||||
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant = "primary", size = "default", ...props }, ref) => (
|
||||
<button
|
||||
ref={ref}
|
||||
className={cn(base, variants[variant], sizes[size], className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Card({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-[var(--radius)] border bg-[var(--color-surface)] shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex items-center justify-between border-b px-5 py-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLHeadingElement>) {
|
||||
return <h3 className={cn("text-sm font-semibold", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function CardContent({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return <div className={cn("p-5", className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const fieldCls =
|
||||
"flex h-9 w-full rounded-[var(--radius)] border bg-[var(--color-surface)] px-3 text-sm shadow-sm transition-colors placeholder:text-[var(--color-muted-foreground)] focus-visible:outline-none focus-visible:border-[var(--color-primary)] focus-visible:ring-2 focus-visible:ring-[var(--color-ring)] disabled:cursor-not-allowed disabled:opacity-50";
|
||||
|
||||
export const Input = React.forwardRef<
|
||||
HTMLInputElement,
|
||||
React.InputHTMLAttributes<HTMLInputElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<input ref={ref} className={cn(fieldCls, className)} {...props} />
|
||||
));
|
||||
Input.displayName = "Input";
|
||||
|
||||
export const Textarea = React.forwardRef<
|
||||
HTMLTextAreaElement,
|
||||
React.TextareaHTMLAttributes<HTMLTextAreaElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<textarea
|
||||
ref={ref}
|
||||
className={cn(fieldCls, "h-auto min-h-[76px] py-2 leading-relaxed", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Textarea.displayName = "Textarea";
|
||||
|
||||
export const Select = React.forwardRef<
|
||||
HTMLSelectElement,
|
||||
React.SelectHTMLAttributes<HTMLSelectElement>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<select ref={ref} className={cn(fieldCls, "pr-8", className)} {...props}>
|
||||
{children}
|
||||
</select>
|
||||
));
|
||||
Select.displayName = "Select";
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.LabelHTMLAttributes<HTMLLabelElement>) {
|
||||
return (
|
||||
<label
|
||||
className={cn(
|
||||
"text-[13px] font-medium text-[var(--color-foreground)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** 统一表格外观:外层 Card 内使用 */
|
||||
export function Table({ className, ...props }: React.TableHTMLAttributes<HTMLTableElement>) {
|
||||
return (
|
||||
<div className="w-full overflow-x-auto">
|
||||
<table className={cn("w-full text-sm", className)} {...props} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function THead(props: React.HTMLAttributes<HTMLTableSectionElement>) {
|
||||
return (
|
||||
<thead
|
||||
className="bg-[var(--color-muted)] text-left text-xs uppercase tracking-wide text-[var(--color-muted-foreground)]"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function TR({ className, ...props }: React.HTMLAttributes<HTMLTableRowElement>) {
|
||||
return (
|
||||
<tr
|
||||
className={cn("border-b last:border-0 hover:bg-[var(--color-muted)]/60", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function TH({ className, ...props }: React.ThHTMLAttributes<HTMLTableCellElement>) {
|
||||
return <th className={cn("px-4 py-3 font-medium", className)} {...props} />;
|
||||
}
|
||||
|
||||
export function TD({ className, ...props }: React.TdHTMLAttributes<HTMLTableCellElement>) {
|
||||
return <td className={cn("px-4 py-3 align-middle", className)} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { NextAuthConfig, DefaultSession } from "next-auth";
|
||||
|
||||
// Edge 安全的基础配置:不引入 Prisma / bcrypt,供 middleware 使用。
|
||||
// 真正带数据库校验的 Credentials provider 在 auth.ts 里注入。
|
||||
|
||||
declare module "next-auth" {
|
||||
interface Session {
|
||||
user: {
|
||||
id: string;
|
||||
username: string;
|
||||
roles: string[];
|
||||
permissions: string[];
|
||||
} & DefaultSession["user"];
|
||||
}
|
||||
}
|
||||
|
||||
export const authConfig = {
|
||||
session: { strategy: "jwt" },
|
||||
pages: { signIn: "/login" },
|
||||
trustHost: true,
|
||||
providers: [], // 在 auth.ts 中补充
|
||||
callbacks: {
|
||||
jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.uid = (user as { id: string }).id;
|
||||
token.username = (user as { username: string }).username;
|
||||
token.roles = (user as { roles?: string[] }).roles ?? [];
|
||||
token.permissions = (user as { permissions?: string[] }).permissions ?? [];
|
||||
}
|
||||
return token;
|
||||
},
|
||||
session({ session, token }) {
|
||||
if (session.user) {
|
||||
session.user.id = token.uid as string;
|
||||
session.user.username = token.username as string;
|
||||
session.user.roles = (token.roles as string[]) ?? [];
|
||||
session.user.permissions = (token.permissions as string[]) ?? [];
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
} satisfies NextAuthConfig;
|
||||
@@ -0,0 +1,73 @@
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
|
||||
/**
|
||||
* 读取某个后台账号的角色名与权限码(走现有 spatie 关联表)。
|
||||
*/
|
||||
async function loadAcl(adminId: number) {
|
||||
const modelRoles = await prisma.modelHasRole.findMany({
|
||||
where: { modelId: adminId, modelType: "App\\Model\\Admin" },
|
||||
select: { roleId: true },
|
||||
});
|
||||
const roleIds = modelRoles.map((r) => r.roleId);
|
||||
if (roleIds.length === 0) return { roles: [], permissions: [] };
|
||||
|
||||
const [roles, rolePerms] = await Promise.all([
|
||||
prisma.role.findMany({ where: { id: { in: roleIds } }, select: { name: true } }),
|
||||
prisma.roleHasPermission.findMany({
|
||||
where: { roleId: { in: roleIds } },
|
||||
select: { permissionId: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const permIds = [...new Set(rolePerms.map((p) => p.permissionId))];
|
||||
const perms = permIds.length
|
||||
? await prisma.permission.findMany({
|
||||
where: { id: { in: permIds } },
|
||||
select: { name: true },
|
||||
})
|
||||
: [];
|
||||
|
||||
return {
|
||||
roles: roles.map((r) => r.name),
|
||||
permissions: perms.map((p) => p.name),
|
||||
};
|
||||
}
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
...authConfig,
|
||||
providers: [
|
||||
Credentials({
|
||||
credentials: {
|
||||
username: { label: "用户名" },
|
||||
password: { label: "密码", type: "password" },
|
||||
},
|
||||
authorize: async (credentials) => {
|
||||
const username = String(credentials?.username ?? "").trim();
|
||||
const password = String(credentials?.password ?? "");
|
||||
if (!username || !password) return null;
|
||||
|
||||
const admin = await prisma.admin.findUnique({ where: { username } });
|
||||
// 软删除账号不允许登录
|
||||
if (!admin || admin.deletedAt) return null;
|
||||
|
||||
// 复用 Laravel bcrypt($2y$)哈希,老账号密码原样可登录
|
||||
const ok = await bcrypt.compare(password, admin.password);
|
||||
if (!ok) return null;
|
||||
|
||||
const acl = await loadAcl(admin.id);
|
||||
return {
|
||||
id: String(admin.id),
|
||||
name: admin.nickname || admin.username,
|
||||
username: admin.username,
|
||||
image: admin.face ?? null,
|
||||
roles: acl.roles,
|
||||
permissions: acl.permissions,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/** 品牌信息(全站统一引用,改这里即可) */
|
||||
export const brand = {
|
||||
name: "联动支付",
|
||||
nameEn: "Linkage Pay",
|
||||
product: "CRM 客户管理系统",
|
||||
tagline: "客户关系管理平台",
|
||||
company: "联动支付",
|
||||
};
|
||||
|
||||
/** 版权文案(当前年份) */
|
||||
export function copyright(): string {
|
||||
return `© ${new Date().getFullYear()} ${brand.company} · 保留所有权利`;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Solar } from "lunar-typescript";
|
||||
|
||||
function pad2(n: number): string {
|
||||
return String(Math.abs(n)).padStart(2, "0");
|
||||
}
|
||||
|
||||
function md(month: number, day: number): string {
|
||||
return `${pad2(month)}-${pad2(day)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算窗口内每一天的「公历月日」与「农历月日」集合(均为零补齐 MM-DD,
|
||||
* 与老系统 overtrue/chinese-calendar 口径一致,可直接与 DATE_FORMAT(birthday,'%m-%d') 比较)。
|
||||
*
|
||||
* @param base 基准日期(本地时区)
|
||||
* @param days 天数
|
||||
* @param includeBase true=从 base 当天算起;false=从 base 次日算起(老系统"未来7天"用后者)
|
||||
*/
|
||||
export function birthdayMatchLists(
|
||||
base: Date,
|
||||
days: number,
|
||||
includeBase: boolean
|
||||
): { solar: string[]; lunar: string[] } {
|
||||
const solar = new Set<string>();
|
||||
const lunar = new Set<string>();
|
||||
const start = includeBase ? 0 : 1;
|
||||
|
||||
for (let i = 0; i < days; i++) {
|
||||
const d = new Date(
|
||||
base.getFullYear(),
|
||||
base.getMonth(),
|
||||
base.getDate() + start + i
|
||||
);
|
||||
solar.add(md(d.getMonth() + 1, d.getDate()));
|
||||
|
||||
const l = Solar.fromYmd(d.getFullYear(), d.getMonth() + 1, d.getDate()).getLunar();
|
||||
lunar.add(md(l.getMonth(), l.getDay()));
|
||||
}
|
||||
|
||||
return { solar: [...solar], lunar: [...lunar] };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
// 避免开发热重载下重复实例化
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
export const prisma =
|
||||
globalForPrisma.prisma ??
|
||||
new PrismaClient({
|
||||
log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
/** Date(Prisma @db.Date,UTC 午夜)→ "YYYY-MM-DD";空值返回 "" */
|
||||
export function fmtDate(d: Date | null | undefined): string {
|
||||
if (!d) return "";
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** "YYYY-MM-DD" 字符串 → Date(按 UTC 解析,避免时区偏移);空/非法返回 null */
|
||||
export function parseDate(s: string | null | undefined): Date | null {
|
||||
if (!s) return null;
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s.trim());
|
||||
if (!m) return null;
|
||||
const d = new Date(`${s.trim()}T00:00:00.000Z`);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import NextAuth from "next-auth";
|
||||
import { NextResponse } from "next/server";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
|
||||
// Edge 安全:只用基础配置校验 JWT,不触碰 Prisma / bcrypt
|
||||
const { auth } = NextAuth(authConfig);
|
||||
|
||||
export default auth((req) => {
|
||||
const { pathname } = req.nextUrl;
|
||||
const isLoggedIn = !!req.auth;
|
||||
|
||||
const isPublic =
|
||||
pathname.startsWith("/login") || pathname.startsWith("/api/auth");
|
||||
|
||||
if (!isLoggedIn && !isPublic) {
|
||||
const url = new URL("/login", req.nextUrl.origin);
|
||||
url.searchParams.set("callbackUrl", pathname);
|
||||
return NextResponse.redirect(url);
|
||||
}
|
||||
|
||||
if (isLoggedIn && pathname.startsWith("/login")) {
|
||||
return NextResponse.redirect(new URL("/", req.nextUrl.origin));
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
});
|
||||
|
||||
export const config = {
|
||||
// 排除静态资源
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.png$).*)"],
|
||||
};
|
||||
Reference in New Issue
Block a user