SheBeiGuanLi/backend/src/controllers/settingsController.ts
2026-03-10 15:51:03 +08:00

109 lines
2.9 KiB
TypeScript

import type { Request, Response } from 'express'
import prisma from '../utils/prisma'
import { successResponse, errorResponse } from '../utils/response'
const DEFAULT_SITE_NAME = '摄影设备借还系统'
const DEFAULT_THEME_COLOR = '#409EFF'
const DEFAULT_LOGO_URL = 'https://s3.1080p.hk/shuzhou/2025/05/18/8ebadf0a7cc34eaea00e8619b8efb827.png'
const mapConfigResponse = (config: any) => {
if (!config) {
return {
site_name: DEFAULT_SITE_NAME,
logo_url: DEFAULT_LOGO_URL,
favicon_url: '',
theme_color: DEFAULT_THEME_COLOR,
updated_at: null,
updated_by: null
}
}
return {
site_name: config.site_name || DEFAULT_SITE_NAME,
logo_url: DEFAULT_LOGO_URL,
favicon_url: '',
theme_color: config.theme_color || DEFAULT_THEME_COLOR,
updated_at: config.updated_at,
updated_by: config.updatedBy
? {
id: config.updatedBy.id,
username: config.updatedBy.username,
name: config.updatedBy.name
}
: null
}
}
export const getSiteConfig = async (req: Request, res: Response) => {
try {
const config = await prisma.siteConfig.findFirst({
orderBy: { updated_at: 'desc' },
include: {
updatedBy: {
select: {
id: true,
username: true,
name: true
}
}
}
})
successResponse(res, mapConfigResponse(config), '获取成功')
} catch (error: any) {
errorResponse(res, error.message || '获取站点配置失败')
}
}
export const updateSiteConfig = async (req: Request, res: Response) => {
try {
const { site_name, theme_color } = req.body as { site_name?: string; theme_color?: string }
if (!site_name) {
return errorResponse(res, '网站名称不能为空', 422)
}
const existing = await prisma.siteConfig.findFirst({
orderBy: { updated_at: 'desc' }
})
const data: any = {
site_name: site_name.trim(),
theme_color: theme_color || DEFAULT_THEME_COLOR,
updated_at: new Date(),
updated_by: res.locals.user?.id ?? null,
logo_url: DEFAULT_LOGO_URL,
favicon_url: null
}
const result = existing
? await prisma.siteConfig.update({
where: { id: existing.id },
data
})
: await prisma.siteConfig.create({
data: {
site_name: data.site_name,
theme_color: data.theme_color,
logo_url: data.logo_url,
favicon_url: data.favicon_url,
updated_by: data.updated_by
}
})
const response = await prisma.siteConfig.findUnique({
where: { id: result.id },
include: {
updatedBy: {
select: { id: true, username: true, name: true }
}
}
})
successResponse(res, mapConfigResponse(response), '保存成功')
} catch (error: any) {
errorResponse(res, error.message || '更新站点配置失败')
}
}