76 lines
2.1 KiB
JavaScript
76 lines
2.1 KiB
JavaScript
export const dynamic = "force-dynamic";
|
|
import getDb from '@/lib/db';
|
|
import { getUserFromRequest, unauthorizedResponse, forbiddenResponse, checkRole } from '@/lib/auth';
|
|
|
|
function normalizeConfig(configs) {
|
|
const result = {};
|
|
|
|
for (const config of configs) {
|
|
let value = config.config_value;
|
|
|
|
if (config.config_key === 'company_logo' && value) {
|
|
const match = value.match(/^\/uploads\/(.+)$/);
|
|
if (match) {
|
|
value = `/api/config/logo?file=${encodeURIComponent(match[1])}`;
|
|
}
|
|
}
|
|
|
|
result[config.config_key] = value;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// GET /api/config - 获取系统配置(公开,无需认证)
|
|
export async function GET() {
|
|
try {
|
|
const db = await getDb();
|
|
const configs = db.prepare('SELECT config_key, config_value FROM system_config').all();
|
|
const result = normalizeConfig(configs);
|
|
return Response.json(result);
|
|
} catch (error) {
|
|
console.error('获取系统配置失败:', error);
|
|
return Response.json(
|
|
{ error: '服务器内部错误' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
// PUT /api/config - 更新系统配置(仅管理员)
|
|
export async function PUT(request) {
|
|
try {
|
|
const user = getUserFromRequest(request);
|
|
if (!user) return unauthorizedResponse();
|
|
if (!checkRole(user, ['admin'])) return forbiddenResponse();
|
|
|
|
const body = await request.json();
|
|
const db = await getDb();
|
|
|
|
const updateStmt = db.prepare(
|
|
'UPDATE system_config SET config_value = ?, updated_at = CURRENT_TIMESTAMP WHERE config_key = ?'
|
|
);
|
|
|
|
const allowedKeys = ['company_name', 'company_logo', 'profit_percentage'];
|
|
|
|
const updateMany = db.transaction(() => {
|
|
for (const key of allowedKeys) {
|
|
if (body[key] !== undefined) {
|
|
updateStmt.run(String(body[key]), key);
|
|
}
|
|
}
|
|
});
|
|
updateMany();
|
|
|
|
const configs = db.prepare('SELECT config_key, config_value FROM system_config').all();
|
|
const result = normalizeConfig(configs);
|
|
return Response.json(result);
|
|
} catch (error) {
|
|
console.error('更新系统配置失败:', error);
|
|
return Response.json(
|
|
{ error: '服务器内部错误' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|