feat(cms): 添加 CMS 内容管理系统与 Admin 管理后台

- 新增 Prisma + SQLite 数据库模型 (Category, Content, Media, User 等)
- 新增 Admin 管理后台 (认证、内容管理、媒体管理)
- 新增 CMS API 路由 (CRUD, 草稿/发布, 重新验证)
- 新增 CMS 内容版本的历史归档页面
- 新增 components/cms 内容渲染组件
- 新增 components/admin 管理后台 UI 组件
- 更新 Contact API 路由
This commit is contained in:
张翔
2026-07-07 06:53:58 +08:00
parent 829d83522c
commit b5245f9aa2
87 changed files with 25659 additions and 0 deletions
@@ -0,0 +1,391 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useAuth } from '@/components/admin/auth-context';
import { adminApi } from '@/lib/admin-api';
import { ArrowLeft, Save } from 'lucide-react';
const MODEL_LABELS: Record<string, string> = {
news: '新闻资讯',
'case-study': '案例研究',
service: '服务管理',
product: '产品管理',
solution: '解决方案',
'hero-banner': 'Hero Banner',
'stat-item': '数据指标',
};
interface FieldDef {
name: string;
type: string;
label: string;
required?: boolean;
description?: string;
placeholder?: string;
defaultValue?: unknown;
options?: Array<{ label: string; value: string | number | boolean }>;
fields?: FieldDef[];
}
interface ModelData {
id: string;
code: string;
name: string;
fields: FieldDef[];
}
export default function ContentEditorPage() {
const params = useParams();
const modelCode = params.modelCode as string;
const itemId = params.itemId as string;
const isNew = itemId === 'new';
const { user, loading: authLoading } = useAuth();
const router = useRouter();
const [model, setModel] = useState<ModelData | null>(null);
const [formData, setFormData] = useState<Record<string, unknown>>({});
const [title, setTitle] = useState('');
const [slug, setSlug] = useState('');
const [status, setStatus] = useState('draft');
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const modelLabel = MODEL_LABELS[modelCode] || modelCode;
useEffect(() => {
if (!authLoading && !user) {
router.push('/admin/login');
return;
}
if (!user) return;
const load = async () => {
try {
// 获取模型定义
const modelsRes = await adminApi.getModels();
const models = (modelsRes as ModelData[]) || [];
const found = models.find((m) => m.code === modelCode);
if (!found) throw new Error('模型未找到');
setModel(found);
// 初始化默认值
const defaults: Record<string, unknown> = {};
found.fields.forEach((f) => {
if (f.defaultValue !== undefined) defaults[f.name] = f.defaultValue;
});
setFormData(defaults);
// 如果是编辑,加载现有数据
if (!isNew) {
const itemsRes = await adminApi.getItems({ modelCode, page: 1, pageSize: 100 });
const items = (itemsRes as { items: Array<{ id: string; title: string; slug: string; status: string; data: Record<string, unknown> }> }).items || [];
const item = items.find((i) => i.id === itemId);
if (item) {
setTitle(item.title);
setSlug(item.slug);
setStatus(item.status);
setFormData(item.data || {});
}
}
} catch (err) {
setError(err instanceof Error ? err.message : '加载失败');
} finally {
setLoading(false);
}
};
load();
}, [user, authLoading, router, modelCode, itemId, isNew]);
const handleFieldChange = (name: string, value: unknown) => {
setFormData((prev) => ({ ...prev, [name]: value }));
};
const handleSave = async () => {
if (!title.trim()) {
alert('请输入标题');
return;
}
setSaving(true);
setError('');
try {
if (isNew) {
await adminApi.createItem({
modelId: model?.id,
modelCode,
title: title.trim(),
slug: slug.trim() || undefined,
status,
data: formData,
});
} else {
await adminApi.updateItem(itemId, {
title: title.trim(),
slug: slug.trim() || undefined,
status,
data: formData,
});
}
router.push(`/admin/content/${modelCode}`);
} catch (err) {
setError(err instanceof Error ? err.message : '保存失败');
setSaving(false);
}
};
const renderField = (field: FieldDef, prefix = '') => {
const key = prefix + field.name;
const value = formData[field.name];
switch (field.type) {
case 'text':
return (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
{field.required && <span className="text-red-500 ml-1">*</span>}
</label>
{field.description && (
<p className="text-xs text-gray-400 mb-1.5">{field.description}</p>
)}
<input
type="text"
value={(value as string) || ''}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
placeholder={field.placeholder}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
/>
</div>
);
case 'textarea':
return (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
{field.required && <span className="text-red-500 ml-1">*</span>}
</label>
{field.description && (
<p className="text-xs text-gray-400 mb-1.5">{field.description}</p>
)}
<textarea
value={(value as string) || ''}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
placeholder={field.placeholder}
rows={4}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent resize-y"
/>
</div>
);
case 'number':
return (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
{field.required && <span className="text-red-500 ml-1">*</span>}
</label>
<input
type="number"
value={(value as number) ?? ''}
onChange={(e) => handleFieldChange(field.name, parseFloat(e.target.value) || 0)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
/>
</div>
);
case 'boolean':
return (
<div key={key} className="flex items-center gap-3">
<input
type="checkbox"
checked={!!value}
onChange={(e) => handleFieldChange(field.name, e.target.checked)}
className="w-4 h-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900"
/>
<label className="text-sm font-medium text-gray-700">{field.label}</label>
{field.description && (
<span className="text-xs text-gray-400">{field.description}</span>
)}
</div>
);
case 'select':
case 'dropdown':
return (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
</label>
<select
value={(value as string) || ''}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
>
<option value="">请选择</option>
{field.options?.map((opt) => (
<option key={String(opt.value)} value={String(opt.value)}>
{opt.label}
</option>
))}
</select>
</div>
);
case 'image':
return (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
</label>
<input
type="text"
value={(value as string) || ''}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
placeholder="输入图片 URL 或从媒体库选择"
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
/>
{!!value && (
<img
src={String(value)}
alt="预览"
className="mt-2 max-h-32 rounded border border-gray-200"
/>
)}
</div>
);
case 'array':
case 'object':
return (
<div key={key} className="border border-gray-200 rounded-lg p-4">
<label className="block text-sm font-medium text-gray-700 mb-3">
{field.label}
</label>
{field.fields?.map((subField) => renderField(subField, `${field.name}.`))}
</div>
);
default:
return (
<div key={key}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
</label>
<input
type="text"
value={(value as string) || ''}
onChange={(e) => handleFieldChange(field.name, e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
/>
</div>
);
}
};
if (authLoading || loading) {
return (
<div className="flex items-center justify-center h-64">
<div className="animate-spin w-8 h-8 border-2 border-gray-900 border-t-transparent rounded-full" />
</div>
);
}
return (
<div className="space-y-6 max-w-3xl">
{/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<button
onClick={() => router.push(`/admin/content/${modelCode}`)}
className="p-2 rounded hover:bg-gray-100 transition-colors"
>
<ArrowLeft className="w-5 h-5" />
</button>
<div>
<h1 className="text-xl font-bold text-gray-900">
{isNew ? `新增${modelLabel}` : `编辑${modelLabel}`}
</h1>
<p className="text-sm text-gray-500 mt-1">{model?.name}</p>
</div>
</div>
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-2 bg-gray-900 text-white rounded-lg px-4 py-2 text-sm font-medium hover:bg-gray-800 disabled:opacity-50 transition-colors"
>
<Save className="w-4 h-4" />
{saving ? '保存中...' : '保存'}
</button>
</div>
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 rounded-lg px-4 py-3 text-sm">
{error}
</div>
)}
{/* Form */}
<div className="bg-white rounded-lg border border-gray-200 p-6 space-y-5">
{/* 标题 */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
标题 <span className="text-red-500">*</span>
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="请输入标题"
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
/>
</div>
{/* Slug */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Slug</label>
<input
type="text"
value={slug}
onChange={(e) => setSlug(e.target.value)}
placeholder="URL 友好标识(留空自动生成)"
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
/>
</div>
{/* 状态 */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
<select
value={status}
onChange={(e) => setStatus(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
>
<option value="draft">草稿</option>
<option value="published">已发布</option>
<option value="archived">已归档</option>
</select>
</div>
{/* 模型字段 */}
{model?.fields?.map((field) => renderField(field))}
</div>
{/* Bottom save */}
<div className="flex justify-end">
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-2 bg-gray-900 text-white rounded-lg px-6 py-2.5 text-sm font-medium hover:bg-gray-800 disabled:opacity-50 transition-colors"
>
<Save className="w-4 h-4" />
{saving ? '保存中...' : '保存'}
</button>
</div>
</div>
);
}