提交正式官网
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { requireAuth, nowStr } from '~/server/utils/auth'
|
||||
import { query, queryOne } from '~/server/utils/mysql'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
function todayPrefix(): string {
|
||||
return nowStr().slice(0, 10)
|
||||
}
|
||||
|
||||
async function countBy(sql: string, ...params: unknown[]): Promise<number> {
|
||||
const row = await queryOne<{ c: number }>(sql, params)
|
||||
return row?.c ?? 0
|
||||
}
|
||||
|
||||
function mapAssessment(row: Record<string, unknown>) {
|
||||
return {
|
||||
id: row.id,
|
||||
lang: row.lang,
|
||||
firstName: row.first_name,
|
||||
lastName: row.last_name,
|
||||
email: row.email,
|
||||
status: row.status,
|
||||
createdAt: row.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
function mapPartner(row: Record<string, unknown>) {
|
||||
return {
|
||||
id: row.id,
|
||||
lang: row.lang,
|
||||
firstName: row.first_name,
|
||||
lastName: row.last_name,
|
||||
companyName: row.company_name,
|
||||
email: row.email,
|
||||
status: row.status,
|
||||
createdAt: row.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const today = todayPrefix()
|
||||
|
||||
const assessmentStats = {
|
||||
total: await countBy('SELECT COUNT(*) AS c FROM assessment_submissions'),
|
||||
unread: await countBy("SELECT COUNT(*) AS c FROM assessment_submissions WHERE status = 'unread'"),
|
||||
today: await countBy('SELECT COUNT(*) AS c FROM assessment_submissions WHERE created_at >= ?', `${today} 00:00:00`),
|
||||
zh: await countBy("SELECT COUNT(*) AS c FROM assessment_submissions WHERE lang = 'zh'"),
|
||||
en: await countBy("SELECT COUNT(*) AS c FROM assessment_submissions WHERE lang = 'en'"),
|
||||
}
|
||||
|
||||
const partnerStats = {
|
||||
total: await countBy('SELECT COUNT(*) AS c FROM partner_submissions'),
|
||||
unread: await countBy("SELECT COUNT(*) AS c FROM partner_submissions WHERE status = 'unread'"),
|
||||
today: await countBy('SELECT COUNT(*) AS c FROM partner_submissions WHERE created_at >= ?', `${today} 00:00:00`),
|
||||
zh: await countBy("SELECT COUNT(*) AS c FROM partner_submissions WHERE lang = 'zh'"),
|
||||
en: await countBy("SELECT COUNT(*) AS c FROM partner_submissions WHERE lang = 'en'"),
|
||||
}
|
||||
|
||||
const recentAssessments = (
|
||||
await query<Record<string, unknown>>(
|
||||
'SELECT id, lang, first_name, last_name, email, status, created_at FROM assessment_submissions ORDER BY id DESC LIMIT 5'
|
||||
)
|
||||
).map(mapAssessment)
|
||||
|
||||
const recentPartners = (
|
||||
await query<Record<string, unknown>>(
|
||||
'SELECT id, lang, first_name, last_name, company_name, email, status, created_at FROM partner_submissions ORDER BY id DESC LIMIT 5'
|
||||
)
|
||||
).map(mapPartner)
|
||||
|
||||
return ok({
|
||||
assessments: assessmentStats,
|
||||
partners: partnerStats,
|
||||
recentAssessments,
|
||||
recentPartners,
|
||||
generatedAt: nowStr(),
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
import { generateToken, md5 } from '~/server/utils/auth'
|
||||
import { getUserByUsername } from '~/server/utils/db'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody<{ username?: string; password?: string }>(event)
|
||||
const { username, password } = body || {}
|
||||
|
||||
if (!username?.trim() || !password) {
|
||||
return fail('用户名和密码不能为空')
|
||||
}
|
||||
|
||||
const user = await getUserByUsername(username.trim())
|
||||
if (!user || user.password !== md5(password)) {
|
||||
return fail('用户名或密码错误')
|
||||
}
|
||||
|
||||
if (user.status === 'inactive') {
|
||||
return fail('用户已被禁用,无法登录')
|
||||
}
|
||||
|
||||
return ok({ token: generateToken(user.id) }, '登录成功')
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { execute } from '~/server/utils/mysql'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const id = getRouterParam(event, 'id')
|
||||
if (!id) return fail('缺少 id 参数')
|
||||
|
||||
const body = await readBody<{ status?: string }>(event)
|
||||
if (!body.status) return fail('缺少 status 参数')
|
||||
|
||||
await execute('UPDATE assessment_submissions SET status = ? WHERE id = ?', [body.status, id])
|
||||
return ok(null, '更新成功')
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { execute, query } from '~/server/utils/mysql'
|
||||
import { fail, ok, pageOk } from '~/server/utils/response'
|
||||
|
||||
function mapAssessment(row: Record<string, unknown>) {
|
||||
return {
|
||||
id: row.id,
|
||||
lang: row.lang,
|
||||
firstName: row.first_name,
|
||||
lastName: row.last_name,
|
||||
email: row.email,
|
||||
condition: row.condition_text,
|
||||
reports: row.reports,
|
||||
message: row.message,
|
||||
status: row.status,
|
||||
createdAt: row.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const method = event.method
|
||||
|
||||
if (method === 'GET') {
|
||||
const queryParams = getQuery(event)
|
||||
const page = Math.max(1, parseInt(String(queryParams.page || '1'), 10))
|
||||
const pageSize = Math.max(1, parseInt(String(queryParams.pageSize || '10'), 10))
|
||||
const lang = String(queryParams.lang || 'all')
|
||||
const email = String(queryParams.email || '')
|
||||
|
||||
let sql = 'SELECT * FROM assessment_submissions WHERE 1=1'
|
||||
const params: unknown[] = []
|
||||
|
||||
if (lang === 'zh' || lang === 'en') {
|
||||
sql += ' AND lang = ?'
|
||||
params.push(lang)
|
||||
}
|
||||
if (email) {
|
||||
sql += ' AND email LIKE ?'
|
||||
params.push(`%${email}%`)
|
||||
}
|
||||
|
||||
sql += ' ORDER BY id DESC'
|
||||
|
||||
const rows = await query<Record<string, unknown>>(sql, params)
|
||||
const total = rows.length
|
||||
const list = rows.slice((page - 1) * pageSize, page * pageSize).map(mapAssessment)
|
||||
return pageOk(list, total, page, pageSize)
|
||||
}
|
||||
|
||||
if (method === 'DELETE') {
|
||||
const ids = await readBody<number[]>(event)
|
||||
if (!Array.isArray(ids) || !ids.length) return fail('请选择要删除的记录')
|
||||
for (const id of ids) {
|
||||
await execute('DELETE FROM assessment_submissions WHERE id = ?', [id])
|
||||
}
|
||||
return ok(null, '删除成功')
|
||||
}
|
||||
|
||||
setResponseStatus(event, 405)
|
||||
return fail('Method Not Allowed', 405)
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { execute } from '~/server/utils/mysql'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const id = getRouterParam(event, 'id')
|
||||
if (!id) return fail('ID不能为空')
|
||||
|
||||
if (event.method === 'PATCH') {
|
||||
const body = await readBody<{ status?: string }>(event)
|
||||
if (body.status !== 'read' && body.status !== 'unread') {
|
||||
return fail('状态无效')
|
||||
}
|
||||
await execute('UPDATE partner_submissions SET status = ? WHERE id = ?', [body.status, id])
|
||||
return ok(null, '更新成功')
|
||||
}
|
||||
|
||||
setResponseStatus(event, 405)
|
||||
return fail('Method Not Allowed', 405)
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { execute, query } from '~/server/utils/mysql'
|
||||
import { fail, ok, pageOk } from '~/server/utils/response'
|
||||
|
||||
function mapPartner(row: Record<string, unknown>) {
|
||||
return {
|
||||
id: row.id,
|
||||
lang: row.lang,
|
||||
firstName: row.first_name,
|
||||
lastName: row.last_name,
|
||||
companyName: row.company_name,
|
||||
country: row.country,
|
||||
email: row.email,
|
||||
category: row.category,
|
||||
collaborate: row.collaborate,
|
||||
status: row.status,
|
||||
createdAt: row.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const method = event.method
|
||||
|
||||
if (method === 'GET') {
|
||||
const queryParams = getQuery(event)
|
||||
const page = Math.max(1, parseInt(String(queryParams.page || '1'), 10))
|
||||
const pageSize = Math.max(1, parseInt(String(queryParams.pageSize || '10'), 10))
|
||||
const lang = String(queryParams.lang || 'all')
|
||||
const email = String(queryParams.email || '')
|
||||
|
||||
let sql = 'SELECT * FROM partner_submissions WHERE 1=1'
|
||||
const params: unknown[] = []
|
||||
|
||||
if (lang === 'zh' || lang === 'en') {
|
||||
sql += ' AND lang = ?'
|
||||
params.push(lang)
|
||||
}
|
||||
if (email) {
|
||||
sql += ' AND email LIKE ?'
|
||||
params.push(`%${email}%`)
|
||||
}
|
||||
|
||||
sql += ' ORDER BY id DESC'
|
||||
|
||||
const rows = await query<Record<string, unknown>>(sql, params)
|
||||
const total = rows.length
|
||||
const list = rows.slice((page - 1) * pageSize, page * pageSize).map(mapPartner)
|
||||
return pageOk(list, total, page, pageSize)
|
||||
}
|
||||
|
||||
if (method === 'DELETE') {
|
||||
const ids = await readBody<number[]>(event)
|
||||
if (!Array.isArray(ids) || !ids.length) return fail('请选择要删除的记录')
|
||||
for (const id of ids) {
|
||||
await execute('DELETE FROM partner_submissions WHERE id = ?', [id])
|
||||
}
|
||||
return ok(null, '删除成功')
|
||||
}
|
||||
|
||||
setResponseStatus(event, 405)
|
||||
return fail('Method Not Allowed', 405)
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import {
|
||||
createNewsArticle,
|
||||
deleteNewsArticles,
|
||||
getNewsArticleById,
|
||||
listNewsArticles,
|
||||
updateNewsArticle,
|
||||
type MediaType,
|
||||
type NewsArticleInput,
|
||||
} from '~/server/utils/news'
|
||||
import { fail, ok, pageOk } from '~/server/utils/response'
|
||||
|
||||
function authOrFail(event: Parameters<typeof requireAuth>[0]) {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return null
|
||||
}
|
||||
return auth
|
||||
}
|
||||
|
||||
function parseMediaType(value: unknown): MediaType | null {
|
||||
return value === 'video' ? 'video' : value === 'article' ? 'article' : null
|
||||
}
|
||||
|
||||
function parseInput(body: Partial<NewsArticleInput>): NewsArticleInput | null {
|
||||
const locale = body.locale === 'zh' ? 'zh' : body.locale === 'en' ? 'en' : null
|
||||
const mediaType = parseMediaType(body.mediaType)
|
||||
const title = body.title?.trim()
|
||||
const summary = body.summary?.trim()
|
||||
const thumbnail = body.thumbnail?.trim()
|
||||
|
||||
if (!locale || !mediaType || !title || !summary || !thumbnail) return null
|
||||
|
||||
if (mediaType === 'article') {
|
||||
const url = body.url?.trim()
|
||||
if (!url) return null
|
||||
return {
|
||||
locale,
|
||||
mediaType,
|
||||
title,
|
||||
summary,
|
||||
thumbnail,
|
||||
thumbnailAlt: body.thumbnailAlt?.trim(),
|
||||
url,
|
||||
sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined,
|
||||
status: body.status === 'draft' ? 'draft' : 'published',
|
||||
}
|
||||
}
|
||||
|
||||
const youtubeUrl = body.youtubeUrl?.trim()
|
||||
const tiktokUrl = body.tiktokUrl?.trim()
|
||||
if (!youtubeUrl && !tiktokUrl) return null
|
||||
|
||||
return {
|
||||
locale,
|
||||
mediaType,
|
||||
title,
|
||||
summary,
|
||||
thumbnail,
|
||||
thumbnailAlt: body.thumbnailAlt?.trim(),
|
||||
youtubeUrl: youtubeUrl || undefined,
|
||||
tiktokUrl: tiktokUrl || undefined,
|
||||
sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined,
|
||||
status: body.status === 'draft' ? 'draft' : 'published',
|
||||
}
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = authOrFail(event)
|
||||
if (!auth) return fail('未授权,请先登录', 401)
|
||||
|
||||
const method = event.method
|
||||
|
||||
if (method === 'GET') {
|
||||
const query = getQuery(event)
|
||||
const page = Math.max(1, parseInt(String(query.page || '1'), 10))
|
||||
const pageSize = Math.max(1, parseInt(String(query.pageSize || '10'), 10))
|
||||
const localeRaw = String(query.locale || '')
|
||||
const mediaTypeRaw = String(query.mediaType || query.media_type || '')
|
||||
const keyword = String(query.keyword || '').trim()
|
||||
const statusRaw = String(query.status || '')
|
||||
|
||||
const { list, total } = await listNewsArticles({
|
||||
page,
|
||||
pageSize,
|
||||
locale: localeRaw === 'en' || localeRaw === 'zh' ? localeRaw : undefined,
|
||||
mediaType: parseMediaType(mediaTypeRaw) || undefined,
|
||||
keyword: keyword || undefined,
|
||||
status: statusRaw === 'published' || statusRaw === 'draft' ? statusRaw : undefined,
|
||||
})
|
||||
|
||||
return pageOk(list, total, page, pageSize)
|
||||
}
|
||||
|
||||
if (method === 'POST') {
|
||||
const body = await readBody<Partial<NewsArticleInput>>(event)
|
||||
const input = parseInput(body)
|
||||
if (!input) {
|
||||
return fail(
|
||||
body.mediaType === 'video'
|
||||
? '请填写完整信息(语言、标题、简介、缩略图,以及 YouTube 或 TikTok 链接至少一项)'
|
||||
: '请填写完整信息(语言、标题、简介、缩略图、原文链接)'
|
||||
)
|
||||
}
|
||||
|
||||
const record = await createNewsArticle(input)
|
||||
return ok(record, '创建成功')
|
||||
}
|
||||
|
||||
if (method === 'PUT') {
|
||||
const body = await readBody<Partial<NewsArticleInput> & { id?: string }>(event)
|
||||
if (!body.id) return fail('内容 ID 不能为空')
|
||||
|
||||
const existing = await getNewsArticleById(body.id)
|
||||
if (!existing) return fail('内容不存在')
|
||||
|
||||
const input = parseInput({
|
||||
locale: body.locale ?? existing.locale,
|
||||
mediaType: body.mediaType ?? existing.mediaType,
|
||||
title: body.title ?? existing.title,
|
||||
summary: body.summary ?? existing.summary,
|
||||
thumbnail: body.thumbnail ?? existing.thumbnail,
|
||||
thumbnailAlt: body.thumbnailAlt ?? existing.thumbnailAlt,
|
||||
url: body.url ?? existing.url,
|
||||
youtubeUrl: body.youtubeUrl ?? existing.youtubeUrl,
|
||||
tiktokUrl: body.tiktokUrl ?? existing.tiktokUrl,
|
||||
sortOrder: body.sortOrder ?? existing.sortOrder,
|
||||
status: body.status ?? existing.status,
|
||||
})
|
||||
if (!input) return fail('请填写完整的内容信息')
|
||||
|
||||
const record = await updateNewsArticle(body.id, input)
|
||||
return ok(record, '更新成功')
|
||||
}
|
||||
|
||||
if (method === 'DELETE') {
|
||||
const ids = await readBody<string[]>(event)
|
||||
if (!Array.isArray(ids) || !ids.length) return fail('请选择要删除的内容')
|
||||
|
||||
await deleteNewsArticles(ids)
|
||||
return ok(null, '删除成功')
|
||||
}
|
||||
|
||||
setResponseStatus(event, 405)
|
||||
return fail('Method Not Allowed', 405)
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { rowToRole, type AdminRoleRow } from '~/server/utils/db'
|
||||
import { query } from '~/server/utils/mysql'
|
||||
import { fail, pageOk } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const queryParams = getQuery(event)
|
||||
const page = Math.max(1, parseInt(String(queryParams.page || '1'), 10))
|
||||
const pageSize = Math.max(1, parseInt(String(queryParams.pageSize || '10'), 10))
|
||||
const name = String(queryParams.name || '')
|
||||
const code = String(queryParams.code || '')
|
||||
const status = queryParams.status ? String(queryParams.status) : ''
|
||||
|
||||
let rows = await query<AdminRoleRow>('SELECT * FROM admin_roles ORDER BY create_time DESC')
|
||||
|
||||
if (name) rows = rows.filter((r) => r.name.includes(name))
|
||||
if (code) rows = rows.filter((r) => r.code.includes(code))
|
||||
if (status) rows = rows.filter((r) => r.status === status)
|
||||
|
||||
const total = rows.length
|
||||
const list = rows.slice((page - 1) * pageSize, page * pageSize).map(rowToRole)
|
||||
return pageOk(list, total, page, pageSize)
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { getPageSeoById, updatePageSeo, type PageSeoUpdateInput } from '~/server/utils/page-seo'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const id = getRouterParam(event, 'id')
|
||||
if (!id) {
|
||||
setResponseStatus(event, 400)
|
||||
return fail('缺少 id 参数', 400)
|
||||
}
|
||||
|
||||
if (event.method === 'GET') {
|
||||
const record = await getPageSeoById(id)
|
||||
if (!record) {
|
||||
setResponseStatus(event, 404)
|
||||
return fail('未找到 SEO 配置', 404)
|
||||
}
|
||||
return ok(record)
|
||||
}
|
||||
|
||||
if (event.method === 'PUT') {
|
||||
const body = await readBody<PageSeoUpdateInput>(event)
|
||||
if (!body?.title?.trim() || !body?.description?.trim()) {
|
||||
return fail('标题和描述不能为空')
|
||||
}
|
||||
|
||||
const updated = await updatePageSeo(
|
||||
id,
|
||||
{
|
||||
title: body.title.trim(),
|
||||
description: body.description.trim(),
|
||||
keywords: body.keywords?.trim() || undefined,
|
||||
ogTitle: body.ogTitle?.trim() || undefined,
|
||||
ogDescription: body.ogDescription?.trim() || undefined,
|
||||
ogImage: body.ogImage?.trim() || undefined,
|
||||
robots: body.robots?.trim() || 'index,follow',
|
||||
ogType: body.ogType === 'article' ? 'article' : 'website',
|
||||
},
|
||||
auth.userId
|
||||
)
|
||||
|
||||
if (!updated) {
|
||||
setResponseStatus(event, 404)
|
||||
return fail('未找到 SEO 配置', 404)
|
||||
}
|
||||
|
||||
return ok(updated, '保存成功')
|
||||
}
|
||||
|
||||
setResponseStatus(event, 405)
|
||||
return fail('Method Not Allowed', 405)
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { listPageSeo } from '~/server/utils/page-seo'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const queryParams = getQuery(event)
|
||||
const locale = String(queryParams.locale || '')
|
||||
const keyword = String(queryParams.keyword || '')
|
||||
|
||||
const list = await listPageSeo({
|
||||
locale: locale === 'en' || locale === 'zh' ? locale : undefined,
|
||||
keyword: keyword || undefined,
|
||||
})
|
||||
|
||||
return ok(list)
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { updatePageSeo, type PageSeoUpdateInput } from '~/server/utils/page-seo'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
type SeoUpdateBody = PageSeoUpdateInput & { id: string }
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const body = await readBody<SeoUpdateBody>(event)
|
||||
if (!body?.id?.trim()) {
|
||||
setResponseStatus(event, 400)
|
||||
return fail('缺少 id 参数', 400)
|
||||
}
|
||||
if (!body.title?.trim() || !body.description?.trim()) {
|
||||
return fail('标题和描述不能为空')
|
||||
}
|
||||
|
||||
const updated = await updatePageSeo(
|
||||
body.id.trim(),
|
||||
{
|
||||
title: body.title.trim(),
|
||||
description: body.description.trim(),
|
||||
keywords: body.keywords?.trim() || undefined,
|
||||
ogTitle: body.ogTitle?.trim() || undefined,
|
||||
ogDescription: body.ogDescription?.trim() || undefined,
|
||||
ogImage: body.ogImage?.trim() || undefined,
|
||||
robots: body.robots?.trim() || 'index,follow',
|
||||
ogType: body.ogType === 'article' ? 'article' : 'website',
|
||||
},
|
||||
auth.userId
|
||||
)
|
||||
|
||||
if (!updated) {
|
||||
setResponseStatus(event, 404)
|
||||
return fail('未找到 SEO 配置', 404)
|
||||
}
|
||||
|
||||
return ok(updated, '保存成功')
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { getUserById } from '~/server/utils/db'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const id = getRouterParam(event, 'id')
|
||||
if (!id) return fail('用户ID不能为空')
|
||||
|
||||
const user = await getUserById(id)
|
||||
if (!user) return fail('用户不存在')
|
||||
|
||||
return ok(user, '获取成功')
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
import { md5, nowStr, requireAuth } from '~/server/utils/auth'
|
||||
import { getUserById, rowToUser, type AdminUserRow } from '~/server/utils/db'
|
||||
import { execute, query, queryOne } from '~/server/utils/mysql'
|
||||
import { fail, ok, pageOk } from '~/server/utils/response'
|
||||
|
||||
function authOrFail(event: Parameters<typeof requireAuth>[0]) {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return null
|
||||
}
|
||||
return auth
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = authOrFail(event)
|
||||
if (!auth) return fail('未授权,请先登录', 401)
|
||||
|
||||
const method = event.method
|
||||
|
||||
if (method === 'GET') {
|
||||
const queryParams = getQuery(event)
|
||||
const page = Math.max(1, parseInt(String(queryParams.page || '1'), 10))
|
||||
const pageSize = Math.max(1, parseInt(String(queryParams.pageSize || '10'), 10))
|
||||
const username = String(queryParams.username || '')
|
||||
const name = String(queryParams.name || '')
|
||||
const status = queryParams.status ? String(queryParams.status) : ''
|
||||
|
||||
let rows = await query<AdminUserRow>('SELECT * FROM admin_users ORDER BY create_time DESC')
|
||||
|
||||
if (username) rows = rows.filter((r) => r.username.includes(username))
|
||||
if (name) rows = rows.filter((r) => (r.name || '').includes(name))
|
||||
if (status) rows = rows.filter((r) => r.status === status)
|
||||
|
||||
const total = rows.length
|
||||
const list = rows.slice((page - 1) * pageSize, page * pageSize).map(rowToUser)
|
||||
return pageOk(list, total, page, pageSize)
|
||||
}
|
||||
|
||||
if (method === 'POST') {
|
||||
const body = await readBody<{
|
||||
username?: string
|
||||
password?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
roleId?: string
|
||||
status?: 'active' | 'inactive'
|
||||
}>(event)
|
||||
|
||||
if (!body.username?.trim() || !body.password) {
|
||||
return fail('用户名和密码不能为空')
|
||||
}
|
||||
|
||||
const exists = await queryOne<{ id: number }>(
|
||||
'SELECT id FROM admin_users WHERE username = ?',
|
||||
[body.username.trim()]
|
||||
)
|
||||
if (exists) return fail('用户名已存在')
|
||||
|
||||
const now = nowStr()
|
||||
await execute(
|
||||
`INSERT INTO admin_users (username, password, name, phone, email, role_id, status, is_built_in, create_time, update_time)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
|
||||
[
|
||||
body.username.trim(),
|
||||
md5(body.password),
|
||||
body.name || null,
|
||||
body.phone || null,
|
||||
body.email || null,
|
||||
body.roleId ? Number(body.roleId) || null : null,
|
||||
body.status || 'active',
|
||||
now,
|
||||
now,
|
||||
]
|
||||
)
|
||||
|
||||
return ok(null, '创建成功')
|
||||
}
|
||||
|
||||
if (method === 'PUT') {
|
||||
const body = await readBody<{
|
||||
id?: string
|
||||
username?: string
|
||||
password?: string
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
roleId?: string
|
||||
status?: 'active' | 'inactive'
|
||||
}>(event)
|
||||
|
||||
if (!body.id) return fail('用户ID不能为空')
|
||||
const existing = await getUserById(body.id)
|
||||
if (!existing) return fail('用户不存在')
|
||||
|
||||
const now = nowStr()
|
||||
const password = body.password ? md5(body.password) : existing.password
|
||||
|
||||
await execute(
|
||||
`UPDATE admin_users
|
||||
SET username = ?, password = ?, name = ?, phone = ?, email = ?, role_id = ?, status = ?, update_time = ?
|
||||
WHERE id = ?`,
|
||||
[
|
||||
body.username?.trim() || existing.username,
|
||||
password,
|
||||
body.name ?? existing.name ?? null,
|
||||
body.phone ?? existing.phone ?? null,
|
||||
body.email ?? existing.email ?? null,
|
||||
body.roleId ? Number(body.roleId) || null : existing.roleId ? Number(existing.roleId) || null : null,
|
||||
body.status || existing.status,
|
||||
now,
|
||||
body.id,
|
||||
]
|
||||
)
|
||||
|
||||
return ok(null, '更新成功')
|
||||
}
|
||||
|
||||
if (method === 'DELETE') {
|
||||
const ids = await readBody<string[]>(event)
|
||||
if (!Array.isArray(ids) || !ids.length) return fail('请选择要删除的用户')
|
||||
|
||||
for (const id of ids) {
|
||||
await execute('DELETE FROM admin_users WHERE id = ? AND is_built_in = 0', [id])
|
||||
}
|
||||
return ok(null, '删除成功')
|
||||
}
|
||||
|
||||
setResponseStatus(event, 405)
|
||||
return fail('Method Not Allowed', 405)
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { getUserById } from '~/server/utils/db'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const user = await getUserById(auth.userId)
|
||||
if (!user) return fail('用户不存在')
|
||||
|
||||
return ok(user, '获取成功')
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
/** 记录登录日志(当前仅接收并返回成功,避免前端报错) */
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
await readBody(event).catch(() => null)
|
||||
return ok(null, '添加登录日志成功')
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { md5, nowStr, requireAuth } from '~/server/utils/auth'
|
||||
import { getUserById } from '~/server/utils/db'
|
||||
import { execute } from '~/server/utils/mysql'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
/** 当前登录用户修改密码 */
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const user = await getUserById(auth.userId)
|
||||
if (!user) return fail('用户不存在')
|
||||
|
||||
const body = await readBody<{
|
||||
oldPassword?: string
|
||||
newPassword?: string
|
||||
confirmPassword?: string
|
||||
}>(event)
|
||||
|
||||
const { oldPassword, newPassword, confirmPassword } = body
|
||||
|
||||
if (!oldPassword || !newPassword || !confirmPassword) {
|
||||
return fail('旧密码、新密码和确认密码不能为空')
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
return fail('新密码长度至少6位')
|
||||
}
|
||||
|
||||
if (newPassword !== confirmPassword) {
|
||||
return fail('新密码和确认密码不一致')
|
||||
}
|
||||
|
||||
if (user.password !== md5(oldPassword)) {
|
||||
return fail('旧密码错误')
|
||||
}
|
||||
|
||||
const now = nowStr()
|
||||
await execute('UPDATE admin_users SET password = ?, update_time = ? WHERE id = ?', [
|
||||
md5(newPassword),
|
||||
now,
|
||||
auth.userId,
|
||||
])
|
||||
|
||||
return ok(null, '密码修改成功')
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { requireAuth } from '~/server/utils/auth'
|
||||
import { getRoleById, getUserById } from '~/server/utils/db'
|
||||
import { getPermissionsForRole } from '~/server/utils/menus'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const user = await getUserById(auth.userId)
|
||||
if (!user) return fail('用户不存在')
|
||||
|
||||
if (!user.roleId) {
|
||||
return ok({ menus: [], buttonPermissions: [] }, '获取成功')
|
||||
}
|
||||
|
||||
const role = await getRoleById(user.roleId)
|
||||
if (!role?.menuIds?.length) {
|
||||
return ok({ menus: [], buttonPermissions: [] }, '获取成功')
|
||||
}
|
||||
|
||||
return ok(getPermissionsForRole(role.menuIds), '获取成功')
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { nowStr, requireAuth } from '~/server/utils/auth'
|
||||
import { getUserById } from '~/server/utils/db'
|
||||
import { execute } from '~/server/utils/mysql'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
/** 当前登录用户更新个人资料 */
|
||||
export default defineEventHandler(async (event) => {
|
||||
const auth = requireAuth(event)
|
||||
if (!auth) {
|
||||
setResponseStatus(event, 401)
|
||||
return fail('未授权,请先登录', 401)
|
||||
}
|
||||
|
||||
const user = await getUserById(auth.userId)
|
||||
if (!user) return fail('用户不存在')
|
||||
|
||||
const body = await readBody<{
|
||||
name?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
avatar?: string
|
||||
bio?: string
|
||||
tags?: string
|
||||
}>(event)
|
||||
|
||||
const now = nowStr()
|
||||
await execute(
|
||||
`UPDATE admin_users
|
||||
SET name = ?, phone = ?, email = ?, avatar = ?, bio = ?, tags = ?, update_time = ?
|
||||
WHERE id = ?`,
|
||||
[
|
||||
body.name ?? user.name ?? null,
|
||||
body.phone ?? user.phone ?? null,
|
||||
body.email ?? user.email ?? null,
|
||||
body.avatar ?? user.avatar ?? null,
|
||||
body.bio ?? user.bio ?? null,
|
||||
body.tags ?? user.tags ?? null,
|
||||
now,
|
||||
auth.userId,
|
||||
]
|
||||
)
|
||||
|
||||
const updated = await getUserById(auth.userId)
|
||||
if (!updated) return fail('用户不存在')
|
||||
|
||||
const { password: _password, ...safeUser } = updated
|
||||
return ok(safeUser, '更新成功')
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { nowStr } from '~/server/utils/auth'
|
||||
import { execute } from '~/server/utils/mysql'
|
||||
import { notifyAssessmentSubmission } from '~/server/utils/form-notification'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody<{
|
||||
lang?: string
|
||||
firstName?: string
|
||||
lastName?: string
|
||||
email?: string
|
||||
condition?: string
|
||||
reports?: string
|
||||
message?: string
|
||||
}>(event)
|
||||
|
||||
const lang = body.lang === 'zh' ? 'zh' : 'en'
|
||||
const firstName = body.firstName?.trim()
|
||||
const email = body.email?.trim()
|
||||
const condition = body.condition?.trim()
|
||||
|
||||
if (!firstName) return fail('请填写患者名')
|
||||
if (!email) return fail('请填写联系邮箱')
|
||||
if (!condition) return fail('请填写主要病情/诊断')
|
||||
|
||||
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!emailPattern.test(email)) return fail('邮箱格式不正确')
|
||||
|
||||
const createdAt = nowStr()
|
||||
|
||||
await execute(
|
||||
`INSERT INTO assessment_submissions
|
||||
(lang, first_name, last_name, email, condition_text, reports, message, status, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'unread', ?)`,
|
||||
[
|
||||
lang,
|
||||
firstName,
|
||||
body.lastName?.trim() || null,
|
||||
email,
|
||||
condition,
|
||||
body.reports || null,
|
||||
body.message?.trim() || null,
|
||||
createdAt,
|
||||
]
|
||||
)
|
||||
|
||||
void notifyAssessmentSubmission({
|
||||
lang,
|
||||
firstName,
|
||||
lastName: body.lastName?.trim() || null,
|
||||
email,
|
||||
condition,
|
||||
reports: body.reports || null,
|
||||
message: body.message?.trim() || null,
|
||||
createdAt,
|
||||
}).catch((error) => {
|
||||
console.error('[mail] 免费评估表通知发送失败:', error)
|
||||
})
|
||||
|
||||
return ok(null, '提交成功')
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { nowStr } from '~/server/utils/auth'
|
||||
import { execute } from '~/server/utils/mysql'
|
||||
import { notifyPartnerSubmission } from '~/server/utils/form-notification'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody<{
|
||||
lang?: string
|
||||
firstName?: string
|
||||
lastName?: string
|
||||
companyName?: string
|
||||
country?: string
|
||||
email?: string
|
||||
category?: string
|
||||
collaborate?: string
|
||||
}>(event)
|
||||
|
||||
const lang = body.lang === 'zh' ? 'zh' : 'en'
|
||||
const firstName = body.firstName?.trim()
|
||||
const lastName = body.lastName?.trim()
|
||||
const companyName = body.companyName?.trim()
|
||||
const country = body.country?.trim()
|
||||
const email = body.email?.trim()
|
||||
const category = body.category?.trim()
|
||||
const collaborate = body.collaborate?.trim()
|
||||
|
||||
if (!firstName) return fail('请填写名')
|
||||
if (!lastName) return fail('请填写姓')
|
||||
if (!companyName) return fail('请填写公司名称')
|
||||
if (!country) return fail('请填写国家/地区')
|
||||
if (!email) return fail('请填写电子邮箱')
|
||||
if (!category) return fail('请选择合作类别')
|
||||
if (!collaborate) return fail('请填写合作说明')
|
||||
|
||||
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!emailPattern.test(email)) return fail('邮箱格式不正确')
|
||||
|
||||
const createdAt = nowStr()
|
||||
|
||||
await execute(
|
||||
`INSERT INTO partner_submissions
|
||||
(lang, first_name, last_name, company_name, country, email, category, collaborate, status, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'unread', ?)`,
|
||||
[lang, firstName, lastName, companyName, country, email, category, collaborate, createdAt]
|
||||
)
|
||||
|
||||
void notifyPartnerSubmission({
|
||||
lang,
|
||||
firstName,
|
||||
lastName,
|
||||
companyName,
|
||||
country,
|
||||
email,
|
||||
category,
|
||||
collaborate,
|
||||
createdAt,
|
||||
}).catch((error) => {
|
||||
console.error('[mail] 合作申请通知发送失败:', error)
|
||||
})
|
||||
|
||||
return ok(null, '提交成功')
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import { listPublishedMedia } from '~/server/utils/news'
|
||||
import { ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const localeRaw = String(query.locale || 'en').trim()
|
||||
const locale = localeRaw === 'zh' ? 'zh' : 'en'
|
||||
|
||||
const media = await listPublishedMedia(locale)
|
||||
return ok(media)
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
import { getPageSeoByRoute } from '~/server/utils/page-seo'
|
||||
import { fail, ok } from '~/server/utils/response'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const routeKey = String(query.routeKey || query.route_key || '').trim()
|
||||
const localeRaw = String(query.locale || 'en').trim()
|
||||
|
||||
if (!routeKey) {
|
||||
setResponseStatus(event, 400)
|
||||
return fail('缺少 routeKey 参数', 400)
|
||||
}
|
||||
|
||||
const locale = localeRaw === 'zh' ? 'zh' : 'en'
|
||||
const record = await getPageSeoByRoute(routeKey, locale)
|
||||
|
||||
if (!record) {
|
||||
setResponseStatus(event, 404)
|
||||
return fail('未找到 SEO 配置', 404)
|
||||
}
|
||||
|
||||
return ok(record)
|
||||
})
|
||||
@@ -0,0 +1,319 @@
|
||||
import { formatPageTitle, SITE_BRAND_TITLE } from '../../utils/seo'
|
||||
|
||||
export type SeoRegistryEntry = {
|
||||
routeKey: string
|
||||
locale: 'en' | 'zh'
|
||||
pageLabel: string
|
||||
title: string
|
||||
description: string
|
||||
keywords?: string
|
||||
ogTitle?: string
|
||||
ogDescription?: string
|
||||
ogImage?: string
|
||||
robots?: string
|
||||
ogType?: 'website' | 'article'
|
||||
}
|
||||
|
||||
function page(
|
||||
routeKey: string,
|
||||
pageLabel: string,
|
||||
en: Omit<SeoRegistryEntry, 'routeKey' | 'locale' | 'pageLabel'>,
|
||||
zh: Omit<SeoRegistryEntry, 'routeKey' | 'locale' | 'pageLabel'>
|
||||
): SeoRegistryEntry[] {
|
||||
return [
|
||||
{ routeKey, locale: 'en', pageLabel, ...en },
|
||||
{ routeKey, locale: 'zh', pageLabel, ...zh }
|
||||
]
|
||||
}
|
||||
|
||||
function titled(
|
||||
routeKey: string,
|
||||
pageLabel: string,
|
||||
enPart: string,
|
||||
zhPart: string,
|
||||
enDesc: string,
|
||||
zhDesc: string,
|
||||
extra?: { en?: Partial<SeoRegistryEntry>; zh?: Partial<SeoRegistryEntry> }
|
||||
): SeoRegistryEntry[] {
|
||||
return page(routeKey, pageLabel, {
|
||||
title: formatPageTitle(enPart, 'en'),
|
||||
description: enDesc,
|
||||
...extra?.en
|
||||
}, {
|
||||
title: formatPageTitle(zhPart, 'zh'),
|
||||
description: zhDesc,
|
||||
...extra?.zh
|
||||
})
|
||||
}
|
||||
|
||||
/** 官网全部页面 SEO 默认值(中英文),启动时写入数据库 */
|
||||
export const SEO_REGISTRY: SeoRegistryEntry[] = [
|
||||
...page('/', '首页', {
|
||||
title: SITE_BRAND_TITLE.en,
|
||||
description:
|
||||
'UMedGlobal is a professional medical concierge based in Guangzhou, helping international patients access executive health screenings, specialist consultations, remote second opinions, visa & travel logistics and TCM care at JCI-accredited and Grade 3A hospitals in China.',
|
||||
keywords:
|
||||
'Orthopedics, Orthopaedics, Joint replacement, Tumor, Lung cancer, Liver cancer, Nasopharyngeal carcinoma (NPC), Ophthalmology, Stomatology, Department of Stomatology, Dentistry, Endocrine diseases, Kidney disease, Nephropathy, Cardiovascular diseases, Neurology, Neurosurgery, Diabetes mellitus, Diabetes, Physical examination, High-end physical examination, Premium health checkup, Computed Tomography, CT, Magnetic Resonance Imaging, MRI, Positron Emission Tomography–Computed Tomography, PET-CT, Traditional Chinese Medicine, TCM',
|
||||
ogTitle: 'UMedGlobal | Medical Tourism China',
|
||||
ogDescription: 'Fast-Track Access to Advanced Specialized Care in China for international patients.',
|
||||
ogImage: '/images/hero.jpg'
|
||||
}, {
|
||||
title: SITE_BRAND_TITLE.zh,
|
||||
description:
|
||||
'优医是位于广州的专业医疗服务机构,帮助国际患者对接中国 JCI 认证及三甲医院的健康体检、专家会诊、远程二次诊疗、签证与出行安排,以及中医药康复服务。',
|
||||
keywords:
|
||||
'骨科, 关节置换, 肿瘤, 肺癌, 肝癌, 鼻咽癌, 眼科, 口腔科, 牙科, 内分泌疾病, 肾病, 心血管疾病, 神经内科, 神经外科, 糖尿病, 体检, 高端体检, CT, MRI, PET-CT, 中医',
|
||||
ogTitle: '优医 | 中国医疗旅游',
|
||||
ogDescription: '为国际患者提供快速对接中国先进专科诊疗的服务。',
|
||||
ogImage: '/images/hero.jpg'
|
||||
}),
|
||||
|
||||
...titled(
|
||||
'/about-us',
|
||||
'关于我们',
|
||||
'About Us — Your Bridge to Advanced Medical Care in China',
|
||||
'关于我们 — 您通往中国先进医疗的桥梁',
|
||||
'Learn about UMedGlobal: Guangzhou-based medical concierge connecting international patients to Class 3A and JCI-accredited hospitals in China—with visa support, translation, and end-to-end care coordination.',
|
||||
'了解优医:广州医疗服务,为国际患者对接三甲及 JCI 认证医院,提供签证支持、翻译与全程协调。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/services',
|
||||
'服务',
|
||||
'Services | Medical Treatment Facilitation in China',
|
||||
'服务 | 在华医疗治疗协调',
|
||||
'UMedGlobal coordinates international medical travel to China under China business standards: specialist matching, S1/S2 visa support, translation, lodging, and post-treatment care.',
|
||||
'优医在中国商业法规标准下协调国际医疗出行:专家匹配、S1/S2 签证支持、医学翻译、住宿安排及治疗后照护。',
|
||||
{ en: { ogImage: '/images/services-hero.jpg' }, zh: { ogImage: '/images/services-hero.jpg' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/free-assessment',
|
||||
'免费医疗评估',
|
||||
'Free Medical Assessment Application',
|
||||
'免费医疗评估申请',
|
||||
'Request a free medical feasibility assessment for treatment in China. UMedGlobal reviews your case within 1-2 business days—specialist matching, timeline, and treatment viability.',
|
||||
'申请中国治疗的免费医疗可行性评估。优医将在 1–2 个工作日内审核您的病例——专家匹配、时间预估与治疗可行性。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/partner-with-us',
|
||||
'与我们合作',
|
||||
'Partner With Us — Global Healthcare Alliance',
|
||||
'与我们合作 — 全球医疗联盟',
|
||||
'Partner with UMedGlobal: join our cross-border medical network—hospitals, referral partners, travel concierge, and insurers—connecting global patients to care in China.',
|
||||
'与优医携手:加入跨境医疗网络——医院、转诊伙伴、出行服务与保险公司,连接全球患者与中国优质医疗。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/cases',
|
||||
'患者案例',
|
||||
'Patient Success Stories | Navigating Medical Tourism in China',
|
||||
'患者成功案例 | 中国医疗旅游导航',
|
||||
'Patient success stories and case studies from UMedGlobal — expert cross-border medical concierge support, specialist coordination, and advanced care pathways at leading Chinese hospitals.',
|
||||
'优医患者成功案例与病例研究——跨境医疗服务、专家协调及中国领先医院的先进治疗路径。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/news',
|
||||
'媒体中心',
|
||||
'Media Center | Navigating Medical Tourism in China',
|
||||
'媒体中心 | 中国医疗旅游导航',
|
||||
'UMedGlobal Media Center — articles and videos on cross-border healthcare for international patients.',
|
||||
'优医媒体中心——跨境医疗文章与视频,为国际患者提供来华就医参考。'
|
||||
),
|
||||
|
||||
...page('/faq', '常见问题', {
|
||||
title: formatPageTitle('Frequently Asked Questions', 'en'),
|
||||
description:
|
||||
'Answers about medical tourism to China: hospital matching, visas, bilingual support, fees, insurance documents, and UMedGlobal concierge logistics.',
|
||||
ogTitle: 'FAQ | UMedGlobal'
|
||||
}, {
|
||||
title: formatPageTitle('常见问题解答', 'zh'),
|
||||
description:
|
||||
'中国医疗旅游常见问题:医院匹配、签证、双语支持、费用、保险单据及 优医 后勤服务。',
|
||||
ogTitle: '常见问题 | 优医'
|
||||
}),
|
||||
|
||||
...titled(
|
||||
'/hospitals',
|
||||
'特色医院',
|
||||
'Featured Hospitals',
|
||||
'特色医院',
|
||||
'Browse JCI-accredited and Grade 3A partner hospitals in China. Search by name and view profiles with official website links.',
|
||||
'浏览中国 JCI 认证及三甲合作医院,按名称搜索并查看简介与官网。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/doctors',
|
||||
'精选专家',
|
||||
'Featured Specialists',
|
||||
'精选专家',
|
||||
'Leading department heads and chief physicians from UMedGlobal partner hospitals in China. Filter by hospital and department.',
|
||||
'优医合作医院科室主任与首席医师,可按医院与科室筛选。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/sitemap',
|
||||
'站点地图',
|
||||
'Sitemap',
|
||||
'站点地图',
|
||||
'UMedGlobal sitemap: browse all main pages, health screening packages, and patient guides.',
|
||||
'优医官网站点地图:浏览全部主要页面、健康体检套餐与患者指南。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/health-screenings',
|
||||
'健康体检',
|
||||
'Health Screenings in China | Transparent Pricing & VIP Access',
|
||||
'中国健康体检 | 透明定价与 VIP 通道',
|
||||
"World-class executive health screenings in China with UMedGlobal's zero-markup guarantee, VIP English concierge, priority booking, and direct hospital payment at official public rates.",
|
||||
'中国世界级健康体检,优医零加价保证、VIP 英语服务、优先预约,直接向医院支付官方公示价格。'
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/privacy-policy',
|
||||
'隐私政策',
|
||||
'Privacy Policy',
|
||||
'隐私政策',
|
||||
'UMedGlobal Privacy Policy: how we collect, use, protect, and share your personal and medical information for cross-border healthcare coordination in China.',
|
||||
'优医隐私政策:我们如何收集、使用、保护与共享您的个人及医疗信息,以支持中国跨境医疗协调服务。',
|
||||
{ en: { robots: 'noindex,follow' }, zh: { robots: 'noindex,follow' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/terms-of-use',
|
||||
'使用条款',
|
||||
'Terms of Use',
|
||||
'使用条款',
|
||||
'UMedGlobal Terms and Conditions: scope of medical concierge services, patient responsibilities, liability, privacy, and governing law for cross-border healthcare coordination.',
|
||||
'优医条款与条件:医疗服务范围、患者责任、责任限制、隐私及跨境医疗协调适用法律。',
|
||||
{ en: { robots: 'noindex,follow' }, zh: { robots: 'noindex,follow' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/accessibility-statement',
|
||||
'无障碍声明',
|
||||
'Accessibility Statement',
|
||||
'无障碍声明',
|
||||
'UMedGlobal accessibility commitment: WCAG 2.1 Level AA practices, inclusive design features, and how to request accessible support.',
|
||||
'优医无障碍承诺:WCAG 2.1 AA 级实践、包容性设计功能及如何申请无障碍支持。',
|
||||
{ en: { robots: 'noindex,follow' }, zh: { robots: 'noindex,follow' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/why-choose-china-for-medical-tourism',
|
||||
'为何选择中国医疗旅游',
|
||||
'Why Choose China for Medical Tourism',
|
||||
'为何选择中国医疗旅游',
|
||||
"Explore China's cost-effective Class III hospitals, short waiting times, advanced clinical technology, TCM integration, and international patient support for medical tourism.",
|
||||
'了解中国高性价比三级医院、较短等候时间、先进临床技术、中医药整合及国际患者支持等医疗旅游优势。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/china-medical-tourism-visa-guide',
|
||||
'中国医疗旅游签证指南',
|
||||
'China Medical Tourism Visa Guide',
|
||||
'中国医疗旅游签证指南',
|
||||
'Guide to China medical tourism visas: L, S2, and S1 visa categories, visa-free entry policies, and administrative support for international patients seeking treatment in China.',
|
||||
'中国医疗旅游签证指南:L、S2、S1 签证类别、免签入境政策及国际患者行政支持。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/how-to-get-china-medical-s1-s2-visa',
|
||||
'S1/S2 医疗签证',
|
||||
'How To Get China Medical S1/S2 Visa',
|
||||
'如何申请中国医疗 S1/S2 签证',
|
||||
'Step-by-step guide to China S1 and S2 medical visas: eligibility, documentation, application procedures, extensions, and UMedGlobal concierge support for international patients.',
|
||||
'中国 S1/S2 医疗签证分步指南:资格、材料、申请流程、延期及优医支持。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/explore-china-visa-free',
|
||||
'中国免签入境',
|
||||
'Explore China Visa-Free: Your Gateway to Medical Care',
|
||||
'探索中国免签:医疗出行门户',
|
||||
"Guide to China's 30-day visa-free entry policy for international medical patients: eligibility by country, entry requirements, accessible treatments, and UMedGlobal concierge support.",
|
||||
'中国 30 天免签入境政策指南:各国资格、入境要求、可及治疗及优医支持。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/china-healthcare-a-foreigners-definitive-guide',
|
||||
'国际患者中国医疗指南',
|
||||
"China Healthcare: A Foreigner's Definitive Guide",
|
||||
'国际患者中国医疗旅游指南',
|
||||
"Definitive guide for foreigners navigating China's healthcare system: triage, hospital selection, appointments, clinical workflow, payments, follow-up, and concierge support for medical tourism.",
|
||||
'外籍人士使用中国医疗体系的完整指南:分诊、选院、预约、临床流程、支付、随访及医疗协调支持。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/secure-convenient-wechat-pay-for-medical-tourism',
|
||||
'微信支付指南',
|
||||
'Secure & Convenient WeChat Pay for Medical Tourism',
|
||||
'微信支付指南(医疗旅游)',
|
||||
'Guide to setting up and using WeChat Pay for medical tourism in China: card linking, transaction limits, TourCard, fees, security, and UMedGlobal concierge support.',
|
||||
'医疗旅游微信支付指南:绑卡、交易限额、TourCard、费用、安全及优医支持。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/patient-guide/how-to-set-up-use-alipay-for-medical-tourism',
|
||||
'支付宝指南',
|
||||
'How to Set Up & Use Alipay for Medical Tourism',
|
||||
'支付宝设置与使用指南(医疗旅游)',
|
||||
'Guide to setting up and using Alipay for medical tourism in China: registration, KYC, international card linking, TourCard, QR payments, limits, and UMedGlobal concierge support.',
|
||||
'医疗旅游支付宝指南:注册、实名认证、绑定国际卡、TourCard、扫码支付、限额及后勤支持。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/health-screenings/imc-mens-health-checkup-package-gold',
|
||||
'IMC 男性金卡套餐',
|
||||
"IMC Men's Health Checkup Package (Gold)",
|
||||
'IMC 男性健康体检套餐(金卡)',
|
||||
"IMC Men's Health Checkup Package (Gold) at The Hong Kong University-Shenzhen Hospital International Medical Center — coordinated by UMedGlobal with transparent hospital pricing and VIP English concierge support.",
|
||||
'IMC 男性健康体检套餐(金卡) — 香港大学深圳医院国际医疗中心,由 优医 协调,透明院内定价与 VIP 英语服务。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/health-screenings/imc-mens-health-checkup-package-diamond',
|
||||
'IMC 男性钻石套餐',
|
||||
"IMC Men's Health Checkup Package (Diamond)",
|
||||
'IMC 男性健康体检套餐(钻石)',
|
||||
"IMC Men's Health Checkup Package (Diamond) at The Hong Kong University-Shenzhen Hospital International Medical Center — coordinated by UMedGlobal with transparent hospital pricing and VIP English concierge support.",
|
||||
'IMC 男性健康体检套餐(钻石) — 香港大学深圳医院国际医疗中心,由 优医 协调,透明院内定价与 VIP 英语服务。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/health-screenings/imc-womens-health-checkup-package-gold',
|
||||
'IMC 女性金卡套餐',
|
||||
"IMC Women's Health Checkup Package (Gold)",
|
||||
'IMC 女性健康体检套餐(金卡)',
|
||||
"IMC Women's Health Checkup Package (Gold) at The Hong Kong University-Shenzhen Hospital International Medical Center — coordinated by UMedGlobal with transparent hospital pricing and VIP English concierge support.",
|
||||
'IMC 女性健康体检套餐(金卡) — 香港大学深圳医院国际医疗中心,由 优医 协调,透明院内定价与 VIP 英语服务。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
),
|
||||
|
||||
...titled(
|
||||
'/health-screenings/imc-womens-health-checkup-package-diamond',
|
||||
'IMC 女性钻石套餐',
|
||||
"IMC Women's Health Checkup Package (Diamond)",
|
||||
'IMC 女性健康体检套餐(钻石)',
|
||||
"IMC Women's Health Checkup Package (Diamond) at The Hong Kong University-Shenzhen Hospital International Medical Center — coordinated by UMedGlobal with transparent hospital pricing and VIP English concierge support.",
|
||||
'IMC 女性健康体检套餐(钻石) — 香港大学深圳医院国际医疗中心,由 优医 协调,透明院内定价与 VIP 英语服务。',
|
||||
{ en: { ogType: 'article' }, zh: { ogType: 'article' } }
|
||||
)
|
||||
]
|
||||
|
||||
/** URL 安全的主键,避免 id 中的 / 导致 API 路由 404 */
|
||||
export function seoRegistryKey(routeKey: string, locale: 'en' | 'zh') {
|
||||
const normalized = routeKey === '/' ? '_root_' : routeKey.replace(/^\//, '')
|
||||
return `${normalized}::${locale}`
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { isAdminSpaRoute, serveAdminSpa } from '~/server/utils/admin-spa'
|
||||
|
||||
/**
|
||||
* 管理后台为 Vue SPA(history 模式)。
|
||||
* 刷新 /admin/xxx 时须回退 index.html,否则 Nuxt 会当成官网路由返回 404。
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const pathname = getRequestURL(event).pathname
|
||||
if (!isAdminSpaRoute(pathname)) return
|
||||
|
||||
return serveAdminSpa(event)
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { isAdminSpaRoute, serveAdminSpa } from '~/server/utils/admin-spa'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const pathname = getRequestURL(event).pathname
|
||||
if (!isAdminSpaRoute(pathname)) return
|
||||
|
||||
return serveAdminSpa(event)
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
import { serveAdminSpa } from '~/server/utils/admin-spa'
|
||||
|
||||
export default defineEventHandler((event) => serveAdminSpa(event))
|
||||
@@ -0,0 +1,20 @@
|
||||
import { getSiteUrlFromEvent } from '~/server/utils/site-url'
|
||||
import { toAbsoluteUrl } from '~/utils/seo'
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const siteUrl = getSiteUrlFromEvent(event, String(config.public.siteUrl))
|
||||
const sitemapUrl = toAbsoluteUrl(siteUrl, '/sitemap.xml')
|
||||
|
||||
setHeader(event, 'content-type', 'text/plain; charset=utf-8')
|
||||
setHeader(event, 'cache-control', 'public, max-age=3600')
|
||||
|
||||
return [
|
||||
'User-agent: *',
|
||||
'Allow: /',
|
||||
'Disallow: /admin',
|
||||
'',
|
||||
`Sitemap: ${sitemapUrl}`,
|
||||
''
|
||||
].join('\n')
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import { send } from 'h3'
|
||||
import { sitemapRoutes } from '~/data/sitemap-routes'
|
||||
import { getSiteUrlFromEvent } from '~/server/utils/site-url'
|
||||
import { toLocalePath } from '~/utils/locale-path'
|
||||
import { toAbsoluteUrl } from '~/utils/seo'
|
||||
import type { SiteLocale } from '~/types/locale'
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''')
|
||||
}
|
||||
|
||||
function buildAlternateLinks(siteUrl: string, basePath: string): string {
|
||||
const enUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'en')))
|
||||
const zhUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'zh')))
|
||||
|
||||
return [
|
||||
` <xhtml:link rel="alternate" hreflang="en" href="${enUrl}" />`,
|
||||
` <xhtml:link rel="alternate" hreflang="zh-CN" href="${zhUrl}" />`,
|
||||
` <xhtml:link rel="alternate" hreflang="x-default" href="${enUrl}" />`
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const siteUrl = getSiteUrlFromEvent(event, String(config.public.siteUrl))
|
||||
const lastmod = new Date().toISOString().slice(0, 10)
|
||||
const locales: SiteLocale[] = ['en', 'zh']
|
||||
|
||||
const urls = sitemapRoutes
|
||||
.flatMap((route) =>
|
||||
locales.map((locale) => {
|
||||
const loc = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(route.path, locale)))
|
||||
return [
|
||||
' <url>',
|
||||
` <loc>${loc}</loc>`,
|
||||
buildAlternateLinks(siteUrl, route.path),
|
||||
` <lastmod>${lastmod}</lastmod>`,
|
||||
` <changefreq>${route.changefreq}</changefreq>`,
|
||||
` <priority>${route.priority.toFixed(1)}</priority>`,
|
||||
' </url>'
|
||||
].join('\n')
|
||||
})
|
||||
)
|
||||
.join('\n')
|
||||
|
||||
const body = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>',
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">',
|
||||
urls,
|
||||
'</urlset>',
|
||||
''
|
||||
].join('\n')
|
||||
|
||||
setResponseHeaders(event, {
|
||||
'content-type': 'application/xml; charset=utf-8',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'cache-control': 'public, max-age=3600'
|
||||
})
|
||||
|
||||
return send(event, body)
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import type { H3Event } from 'h3'
|
||||
|
||||
/** 是否为需要回退到 admin/index.html 的 SPA 路由(非静态资源) */
|
||||
export function isAdminSpaRoute(pathname: string): boolean {
|
||||
if (!pathname.startsWith('/admin')) return false
|
||||
|
||||
const rest = pathname.slice('/admin'.length)
|
||||
if (!rest || rest === '/') return true
|
||||
|
||||
const last = rest.split('/').pop() || ''
|
||||
// 带扩展名的路径交给 Nitro 静态资源处理,如 /admin/assets/*.js
|
||||
if (/\.[a-z0-9]+$/i.test(last)) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/** 解析 admin 构建产物目录(兼容 dev / preview / production 多种 cwd) */
|
||||
function resolveAdminIndexPath(): string | null {
|
||||
const candidates = [
|
||||
join(process.cwd(), 'public', 'admin', 'index.html'),
|
||||
join(process.cwd(), '.output', 'public', 'admin', 'index.html'),
|
||||
]
|
||||
|
||||
for (const filePath of candidates) {
|
||||
if (existsSync(filePath)) return filePath
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function serveAdminSpa(event: H3Event) {
|
||||
const indexPath = resolveAdminIndexPath()
|
||||
if (!indexPath) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Admin not built. Run: cd admin && npm run build-only',
|
||||
})
|
||||
}
|
||||
|
||||
const html = readFileSync(indexPath, 'utf-8')
|
||||
|
||||
setHeader(event, 'Content-Type', 'text/html; charset=utf-8')
|
||||
setHeader(event, 'Cache-Control', 'no-cache')
|
||||
return html
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import type { H3Event } from 'h3'
|
||||
|
||||
export function md5(text: string): string {
|
||||
return createHash('md5').update(text).digest('hex')
|
||||
}
|
||||
|
||||
export function generateToken(userId: string | number): string {
|
||||
return `token_${userId}_${Date.now()}_${Math.random().toString(36).slice(2, 15)}`
|
||||
}
|
||||
|
||||
export function getUserIdFromToken(token: string | null): string | null {
|
||||
if (!token?.startsWith('token_')) return null
|
||||
const rest = token.slice('token_'.length)
|
||||
const timestampIndex = rest.search(/_\d+_/)
|
||||
if (timestampIndex <= 0) return null
|
||||
return rest.slice(0, timestampIndex)
|
||||
}
|
||||
|
||||
export function extractToken(event: H3Event): string | null {
|
||||
const authHeader = getHeader(event, 'authorization')
|
||||
if (!authHeader) return null
|
||||
if (authHeader.startsWith('Bearer ')) return authHeader.slice(7)
|
||||
return authHeader
|
||||
}
|
||||
|
||||
export function requireAuth(event: H3Event): { userId: string } | null {
|
||||
const token = extractToken(event)
|
||||
if (!token || !token.startsWith('token_')) return null
|
||||
const userId = getUserIdFromToken(token)
|
||||
if (!userId) return null
|
||||
return { userId }
|
||||
}
|
||||
|
||||
/** 当前时间字符串(固定东八区,与官网用户/后台展示一致) */
|
||||
export function nowStr(): string {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
}).formatToParts(new Date())
|
||||
|
||||
const get = (type: Intl.DateTimeFormatPartTypes) =>
|
||||
parts.find((part) => part.type === type)?.value ?? '00'
|
||||
|
||||
return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}:${get('second')}`
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { md5, nowStr } from './auth'
|
||||
import { execInit, queryInit, queryOneInit } from './mysql'
|
||||
|
||||
const DEFAULT_ADMIN_PASSWORD_MD5 = md5('admin888')
|
||||
const LEGACY_ADMIN_PASSWORD_MD5 = [md5('admin123'), md5('admin')]
|
||||
|
||||
const WORKBENCH_MENU_IDS = ['menu_dash_dir', 'menu_dash_home']
|
||||
const SEO_MENU_IDS = ['menu_seo_dir', 'menu_seo_list', 'menu_seo_edit']
|
||||
|
||||
export async function initSchema() {
|
||||
await execInit(`
|
||||
CREATE TABLE IF NOT EXISTS admin_roles (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
code VARCHAR(64) NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
is_built_in TINYINT NOT NULL DEFAULT 0,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||
menu_ids TEXT NOT NULL,
|
||||
create_time VARCHAR(32) NOT NULL,
|
||||
update_time VARCHAR(32) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`)
|
||||
|
||||
await execInit(`
|
||||
CREATE TABLE IF NOT EXISTS admin_users (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
name VARCHAR(255),
|
||||
avatar TEXT,
|
||||
phone VARCHAR(64),
|
||||
email VARCHAR(255),
|
||||
role_id BIGINT,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||
is_built_in TINYINT NOT NULL DEFAULT 0,
|
||||
bio TEXT,
|
||||
tags TEXT,
|
||||
create_time VARCHAR(32) NOT NULL,
|
||||
update_time VARCHAR(32) NOT NULL,
|
||||
CONSTRAINT fk_admin_users_role FOREIGN KEY (role_id) REFERENCES admin_roles(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`)
|
||||
|
||||
await execInit(`
|
||||
CREATE TABLE IF NOT EXISTS assessment_submissions (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
lang VARCHAR(8) NOT NULL,
|
||||
first_name VARCHAR(255) NOT NULL,
|
||||
last_name VARCHAR(255),
|
||||
email VARCHAR(255) NOT NULL,
|
||||
condition_text TEXT NOT NULL,
|
||||
reports TEXT,
|
||||
message TEXT,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'unread',
|
||||
created_at VARCHAR(32) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`)
|
||||
|
||||
await execInit(`
|
||||
CREATE TABLE IF NOT EXISTS partner_submissions (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
lang VARCHAR(8) NOT NULL,
|
||||
first_name VARCHAR(255) NOT NULL,
|
||||
last_name VARCHAR(255) NOT NULL,
|
||||
company_name VARCHAR(255) NOT NULL,
|
||||
country VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
category VARCHAR(255) NOT NULL,
|
||||
collaborate TEXT NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'unread',
|
||||
created_at VARCHAR(32) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`)
|
||||
}
|
||||
|
||||
export async function seedIfEmpty() {
|
||||
const roleCount = await queryOneInit<{ c: number }>('SELECT COUNT(*) AS c FROM admin_roles')
|
||||
if ((roleCount?.c ?? 0) > 0) return
|
||||
|
||||
const now = nowStr()
|
||||
const menuIds = JSON.stringify([
|
||||
'menu_dash_dir',
|
||||
'menu_dash_home',
|
||||
'menu_msg_dir',
|
||||
'menu_msg_assessment',
|
||||
'menu_msg_assessment_view',
|
||||
'menu_msg_assessment_delete',
|
||||
'menu_msg_partner',
|
||||
'menu_msg_partner_view',
|
||||
'menu_msg_partner_delete',
|
||||
'menu_sys_dir',
|
||||
'menu_sys_role',
|
||||
'menu_sys_role_view',
|
||||
'menu_sys_user',
|
||||
'menu_sys_user_add',
|
||||
'menu_sys_user_edit',
|
||||
'menu_sys_user_delete',
|
||||
'menu_sys_user_view',
|
||||
'menu_seo_dir',
|
||||
'menu_seo_list',
|
||||
'menu_seo_edit',
|
||||
'menu_content_dir',
|
||||
'menu_news_list',
|
||||
'menu_news_add',
|
||||
'menu_news_edit',
|
||||
'menu_news_delete',
|
||||
'menu_news_view',
|
||||
])
|
||||
|
||||
const roleResult = await execInit(
|
||||
`INSERT INTO admin_roles (name, code, description, is_built_in, status, menu_ids, create_time, update_time)
|
||||
VALUES (?, ?, ?, 1, 'active', ?, ?, ?)`,
|
||||
['超级管理员', 'super_admin', '拥有系统所有权限', menuIds, now, now]
|
||||
)
|
||||
|
||||
await execInit(
|
||||
`INSERT INTO admin_users (username, password, name, email, role_id, status, is_built_in, create_time, update_time)
|
||||
VALUES (?, ?, ?, ?, ?, 'active', 1, ?, ?)`,
|
||||
['admin', DEFAULT_ADMIN_PASSWORD_MD5, '超级管理员', 'admin@umedglobal.com', roleResult.insertId, now, now]
|
||||
)
|
||||
}
|
||||
|
||||
export async function migrateBuiltinAdminPassword() {
|
||||
const admin = await queryOneInit<{ password: string }>(
|
||||
'SELECT password FROM admin_users WHERE username = ? AND is_built_in = 1',
|
||||
['admin']
|
||||
)
|
||||
|
||||
if (!admin || !LEGACY_ADMIN_PASSWORD_MD5.includes(admin.password)) return
|
||||
|
||||
await execInit('UPDATE admin_users SET password = ?, update_time = ? WHERE username = ? AND is_built_in = 1', [
|
||||
DEFAULT_ADMIN_PASSWORD_MD5,
|
||||
nowStr(),
|
||||
'admin',
|
||||
])
|
||||
}
|
||||
|
||||
export async function migrateSeoMenu() {
|
||||
const roles = await queryInit<{ id: number; menu_ids: string }>('SELECT id, menu_ids FROM admin_roles')
|
||||
|
||||
for (const role of roles) {
|
||||
const ids = JSON.parse(role.menu_ids || '[]') as string[]
|
||||
if (!ids.includes('menu_sys_dir')) continue
|
||||
const missing = SEO_MENU_IDS.filter((id) => !ids.includes(id))
|
||||
if (!missing.length) continue
|
||||
|
||||
await execInit('UPDATE admin_roles SET menu_ids = ?, update_time = ? WHERE id = ?', [
|
||||
JSON.stringify([...ids, ...missing]),
|
||||
nowStr(),
|
||||
role.id,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
export async function migrateWorkbenchMenu() {
|
||||
const roles = await queryInit<{ id: number; menu_ids: string }>('SELECT id, menu_ids FROM admin_roles')
|
||||
|
||||
for (const role of roles) {
|
||||
const ids = JSON.parse(role.menu_ids || '[]') as string[]
|
||||
const missing = WORKBENCH_MENU_IDS.filter((id) => !ids.includes(id))
|
||||
if (!missing.length) continue
|
||||
|
||||
await execInit('UPDATE admin_roles SET menu_ids = ?, update_time = ? WHERE id = ?', [
|
||||
JSON.stringify([...WORKBENCH_MENU_IDS, ...ids]),
|
||||
nowStr(),
|
||||
role.id,
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { queryOne } from './mysql'
|
||||
|
||||
export type AdminUserRow = {
|
||||
id: number
|
||||
username: string
|
||||
password: string
|
||||
name: string | null
|
||||
avatar: string | null
|
||||
phone: string | null
|
||||
email: string | null
|
||||
role_id: number | null
|
||||
status: string
|
||||
is_built_in: number
|
||||
bio: string | null
|
||||
tags: string | null
|
||||
create_time: string
|
||||
update_time: string
|
||||
}
|
||||
|
||||
export type AdminRoleRow = {
|
||||
id: number
|
||||
name: string
|
||||
code: string
|
||||
description: string | null
|
||||
is_built_in: number
|
||||
status: string
|
||||
menu_ids: string
|
||||
create_time: string
|
||||
update_time: string
|
||||
}
|
||||
|
||||
export function rowToUser(row: AdminUserRow) {
|
||||
return {
|
||||
id: String(row.id),
|
||||
username: row.username,
|
||||
password: row.password,
|
||||
name: row.name ?? undefined,
|
||||
avatar: row.avatar ?? undefined,
|
||||
phone: row.phone ?? undefined,
|
||||
email: row.email ?? undefined,
|
||||
roleId: row.role_id != null ? String(row.role_id) : undefined,
|
||||
status: row.status as 'active' | 'inactive',
|
||||
isBuiltIn: row.is_built_in === 1,
|
||||
bio: row.bio ?? undefined,
|
||||
tags: row.tags ?? undefined,
|
||||
createTime: row.create_time,
|
||||
updateTime: row.update_time,
|
||||
}
|
||||
}
|
||||
|
||||
export function rowToRole(row: AdminRoleRow) {
|
||||
return {
|
||||
id: String(row.id),
|
||||
name: row.name,
|
||||
code: row.code,
|
||||
description: row.description ?? undefined,
|
||||
isBuiltIn: row.is_built_in === 1,
|
||||
status: row.status as 'active' | 'inactive',
|
||||
menuIds: JSON.parse(row.menu_ids || '[]') as string[],
|
||||
createTime: row.create_time,
|
||||
updateTime: row.update_time,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getUserById(id: string | number) {
|
||||
const row = await queryOne<AdminUserRow>('SELECT * FROM admin_users WHERE id = ?', [id])
|
||||
return row ? rowToUser(row) : null
|
||||
}
|
||||
|
||||
export async function getUserByUsername(username: string) {
|
||||
const row = await queryOne<AdminUserRow>('SELECT * FROM admin_users WHERE username = ?', [username])
|
||||
return row ? rowToUser(row) : null
|
||||
}
|
||||
|
||||
export async function getRoleById(id: string | number) {
|
||||
const row = await queryOne<AdminRoleRow>('SELECT * FROM admin_roles WHERE id = ?', [id])
|
||||
return row ? rowToRole(row) : null
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
type SiteLang = 'en' | 'zh'
|
||||
|
||||
const assessmentReportsLabels: Record<string, Record<SiteLang, string>> = {
|
||||
yes: { zh: '是,我有近期报告/影像', en: 'Yes, I have recent reports/scans' },
|
||||
no: { zh: '否,暂时没有', en: 'No, not yet' },
|
||||
pending: { zh: '我即将获取', en: 'I will obtain them soon' }
|
||||
}
|
||||
|
||||
const partnerCategoryLabels: Record<string, Record<SiteLang, string>> = {
|
||||
'medical-institution': { zh: '医疗机构', en: 'Medical Institution' },
|
||||
'referral-partner': { zh: '转诊合作伙伴', en: 'Referral Partner' },
|
||||
'travel-concierge': { zh: '旅行服务', en: 'Travel & Concierge' },
|
||||
insurance: { zh: '保险', en: 'Insurance' },
|
||||
other: { zh: '其他', en: 'Other' }
|
||||
}
|
||||
|
||||
export function formatAssessmentReports(value: string | null | undefined, lang: SiteLang): string {
|
||||
if (!value) return lang === 'zh' ? '(未选择)' : '(Not selected)'
|
||||
return assessmentReportsLabels[value]?.[lang] ?? value
|
||||
}
|
||||
|
||||
export function formatPartnerCategory(value: string, lang: SiteLang): string {
|
||||
return partnerCategoryLabels[value]?.[lang] ?? value
|
||||
}
|
||||
|
||||
export function formatLangLabel(lang: SiteLang): string {
|
||||
return lang === 'zh' ? '中文' : 'English'
|
||||
}
|
||||
|
||||
export function formatOptional(value: string | null | undefined, lang: SiteLang): string {
|
||||
const trimmed = value?.trim()
|
||||
if (trimmed) return trimmed
|
||||
return lang === 'zh' ? '(未填写)' : '(Not provided)'
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
formatAssessmentReports,
|
||||
formatLangLabel,
|
||||
formatOptional,
|
||||
formatPartnerCategory
|
||||
} from '~/server/utils/form-mail-labels'
|
||||
import { buildMailHtml, buildMailText, sendMail } from '~/server/utils/mail'
|
||||
|
||||
type SiteLang = 'en' | 'zh'
|
||||
|
||||
export async function notifyAssessmentSubmission(input: {
|
||||
lang: SiteLang
|
||||
firstName: string
|
||||
lastName?: string | null
|
||||
email: string
|
||||
condition: string
|
||||
reports?: string | null
|
||||
message?: string | null
|
||||
createdAt: string
|
||||
}) {
|
||||
const rows = [
|
||||
{ label: '表单类型', value: '免费评估表' },
|
||||
{ label: '提交语言', value: formatLangLabel(input.lang) },
|
||||
{ label: '提交时间', value: input.createdAt },
|
||||
{ label: '患者名', value: input.firstName },
|
||||
{ label: '患者姓', value: formatOptional(input.lastName, input.lang) },
|
||||
{ label: '联系邮箱', value: input.email },
|
||||
{ label: '主要病情/诊断', value: input.condition },
|
||||
{
|
||||
label: '是否有近期医疗报告/影像?',
|
||||
value: formatAssessmentReports(input.reports, input.lang)
|
||||
},
|
||||
{ label: '简要留言/具体问题', value: formatOptional(input.message, input.lang) }
|
||||
]
|
||||
|
||||
const title = '【优医官网】免费评估表新提交'
|
||||
const subject = `${title} - ${input.firstName}`
|
||||
|
||||
await sendMail({
|
||||
subject,
|
||||
text: buildMailText(title, rows),
|
||||
html: buildMailHtml(title, rows),
|
||||
replyTo: input.email
|
||||
})
|
||||
}
|
||||
|
||||
export async function notifyPartnerSubmission(input: {
|
||||
lang: SiteLang
|
||||
firstName: string
|
||||
lastName: string
|
||||
companyName: string
|
||||
country: string
|
||||
email: string
|
||||
category: string
|
||||
collaborate: string
|
||||
createdAt: string
|
||||
}) {
|
||||
const rows = [
|
||||
{ label: '表单类型', value: '加入我们' },
|
||||
{ label: '提交语言', value: formatLangLabel(input.lang) },
|
||||
{ label: '提交时间', value: input.createdAt },
|
||||
{ label: '名', value: input.firstName },
|
||||
{ label: '姓', value: input.lastName },
|
||||
{ label: '公司名称', value: input.companyName },
|
||||
{ label: '国家/地区', value: input.country },
|
||||
{ label: '电子邮箱', value: input.email },
|
||||
{ label: '合作类别', value: formatPartnerCategory(input.category, input.lang) },
|
||||
{ label: '我们如何合作?', value: input.collaborate }
|
||||
]
|
||||
|
||||
const title = '【优医官网】合作申请新提交'
|
||||
const subject = `${title} - ${input.companyName}`
|
||||
|
||||
await sendMail({
|
||||
subject,
|
||||
text: buildMailText(title, rows),
|
||||
html: buildMailHtml(title, rows),
|
||||
replyTo: input.email
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
import type { Transporter } from 'nodemailer'
|
||||
|
||||
type MailPayload = {
|
||||
subject: string
|
||||
text: string
|
||||
html: string
|
||||
replyTo?: string
|
||||
}
|
||||
|
||||
let transporter: Transporter | null = null
|
||||
let transporterKey = ''
|
||||
|
||||
function getMailConfig() {
|
||||
const config = useRuntimeConfig()
|
||||
return {
|
||||
enabled: String(config.mailEnabled) !== 'false',
|
||||
host: String(config.mailSmtpHost || 'smtp.exmail.qq.com'),
|
||||
port: Number(config.mailSmtpPort || 465),
|
||||
secure: String(config.mailSmtpSecure) !== 'false',
|
||||
user: String(config.mailUser || ''),
|
||||
pass: String(config.mailPass || ''),
|
||||
from: String(config.mailFrom || config.mailUser || ''),
|
||||
to: String(config.mailTo || 'umedglobal@umedglobal.cn')
|
||||
}
|
||||
}
|
||||
|
||||
function getTransporter(): Transporter | null {
|
||||
const mail = getMailConfig()
|
||||
if (!mail.enabled || !mail.user || !mail.pass || !mail.to) return null
|
||||
|
||||
const key = `${mail.host}:${mail.port}:${mail.user}`
|
||||
if (!transporter || transporterKey !== key) {
|
||||
transporter = nodemailer.createTransport({
|
||||
host: mail.host,
|
||||
port: mail.port,
|
||||
secure: mail.secure,
|
||||
auth: {
|
||||
user: mail.user,
|
||||
pass: mail.pass
|
||||
}
|
||||
})
|
||||
transporterKey = key
|
||||
}
|
||||
|
||||
return transporter
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
}
|
||||
|
||||
export async function sendMail(payload: MailPayload): Promise<boolean> {
|
||||
const mail = getMailConfig()
|
||||
const transport = getTransporter()
|
||||
|
||||
if (!transport) {
|
||||
console.warn('[mail] SMTP 未配置,跳过发送邮件')
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
await transport.sendMail({
|
||||
from: mail.from,
|
||||
to: mail.to,
|
||||
replyTo: payload.replyTo,
|
||||
subject: payload.subject,
|
||||
text: payload.text,
|
||||
html: payload.html
|
||||
})
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('[mail] 发送失败:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function buildMailHtml(title: string, rows: Array<{ label: string; value: string }>): string {
|
||||
const body = rows
|
||||
.map(
|
||||
(row) =>
|
||||
`<tr><td style="padding:8px 12px;border:1px solid #e5e7eb;background:#f8fafc;width:180px;font-weight:600;">${escapeHtml(row.label)}</td><td style="padding:8px 12px;border:1px solid #e5e7eb;white-space:pre-wrap;">${escapeHtml(row.value)}</td></tr>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
return `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="font-family:system-ui,sans-serif;color:#111827;"><h2 style="margin:0 0 16px;">${escapeHtml(title)}</h2><table style="border-collapse:collapse;width:100%;max-width:720px;">${body}</table></body></html>`
|
||||
}
|
||||
|
||||
export function buildMailText(title: string, rows: Array<{ label: string; value: string }>): string {
|
||||
const lines = rows.map((row) => `${row.label}:${row.value}`)
|
||||
return [title, '', ...lines].join('\n')
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
export interface AdminMenu {
|
||||
id: string
|
||||
type: 'directory' | 'menu' | 'button'
|
||||
path: string
|
||||
title: string
|
||||
icon?: string
|
||||
parentId?: string | null
|
||||
order?: number
|
||||
status?: 'active' | 'inactive'
|
||||
permission?: string
|
||||
isBuiltIn?: boolean
|
||||
createTime?: string
|
||||
updateTime?: string
|
||||
children?: AdminMenu[]
|
||||
}
|
||||
|
||||
const NOW = '2026-06-26 00:00:00'
|
||||
|
||||
export const ALL_MENUS: AdminMenu[] = [
|
||||
{
|
||||
id: 'menu_dash_dir',
|
||||
type: 'directory',
|
||||
path: '',
|
||||
title: '数据概览',
|
||||
icon: 'HOutline:HomeIcon',
|
||||
parentId: null,
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_dash_home',
|
||||
type: 'menu',
|
||||
path: '/dashboard/home',
|
||||
title: '数据概览',
|
||||
icon: 'HOutline:ComputerDesktopIcon',
|
||||
parentId: 'menu_dash_dir',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'menu_msg_dir',
|
||||
type: 'directory',
|
||||
path: '',
|
||||
title: '留言管理',
|
||||
icon: 'HOutline:ChatBubbleLeftRightIcon',
|
||||
parentId: null,
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_msg_assessment',
|
||||
type: 'menu',
|
||||
path: '/messages/assessment',
|
||||
title: '评估表',
|
||||
icon: 'HOutline:ClipboardDocumentListIcon',
|
||||
parentId: 'menu_msg_dir',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_msg_assessment_view',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '查看',
|
||||
permission: 'assessment:view',
|
||||
parentId: 'menu_msg_assessment',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_msg_assessment_delete',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '删除',
|
||||
permission: 'assessment:delete',
|
||||
parentId: 'menu_msg_assessment',
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'menu_msg_partner',
|
||||
type: 'menu',
|
||||
path: '/messages/partner',
|
||||
title: '加入我们',
|
||||
icon: 'HOutline:UserGroupIcon',
|
||||
parentId: 'menu_msg_dir',
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_msg_partner_view',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '查看',
|
||||
permission: 'partner:view',
|
||||
parentId: 'menu_msg_partner',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_msg_partner_delete',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '删除',
|
||||
permission: 'partner:delete',
|
||||
parentId: 'menu_msg_partner',
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'menu_content_dir',
|
||||
type: 'directory',
|
||||
path: '',
|
||||
title: '内容管理',
|
||||
icon: 'HOutline:NewspaperIcon',
|
||||
parentId: null,
|
||||
order: 2,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_news_list',
|
||||
type: 'menu',
|
||||
path: '/content/news',
|
||||
title: '媒体中心',
|
||||
icon: 'HOutline:DocumentTextIcon',
|
||||
parentId: 'menu_content_dir',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_news_add',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '新增',
|
||||
permission: 'news:add',
|
||||
parentId: 'menu_news_list',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_news_edit',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '编辑',
|
||||
permission: 'news:edit',
|
||||
parentId: 'menu_news_list',
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_news_delete',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '删除',
|
||||
permission: 'news:delete',
|
||||
parentId: 'menu_news_list',
|
||||
order: 2,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_news_view',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '查看',
|
||||
permission: 'news:view',
|
||||
parentId: 'menu_news_list',
|
||||
order: 3,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'menu_seo_dir',
|
||||
type: 'directory',
|
||||
path: '',
|
||||
title: 'SEO 管理',
|
||||
icon: 'HOutline:MagnifyingGlassCircleIcon',
|
||||
parentId: null,
|
||||
order: 3,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_seo_list',
|
||||
type: 'menu',
|
||||
path: '/seo',
|
||||
title: '页面 SEO',
|
||||
icon: 'HOutline:DocumentMagnifyingGlassIcon',
|
||||
parentId: 'menu_seo_dir',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_seo_edit',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '编辑',
|
||||
permission: 'seo:edit',
|
||||
parentId: 'menu_seo_list',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'menu_sys_dir',
|
||||
type: 'directory',
|
||||
path: '',
|
||||
title: '系统管理',
|
||||
icon: 'HOutline:Cog6ToothIcon',
|
||||
parentId: null,
|
||||
order: 4,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_sys_role',
|
||||
type: 'menu',
|
||||
path: '/system/role',
|
||||
title: '角色管理',
|
||||
icon: 'HOutline:ShieldCheckIcon',
|
||||
parentId: 'menu_sys_dir',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_sys_role_view',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '查看',
|
||||
permission: 'role:view',
|
||||
parentId: 'menu_sys_role',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'menu_sys_user',
|
||||
type: 'menu',
|
||||
path: '/system/user',
|
||||
title: '账号管理',
|
||||
icon: 'HOutline:UsersIcon',
|
||||
parentId: 'menu_sys_dir',
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [
|
||||
{
|
||||
id: 'menu_sys_user_add',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '添加',
|
||||
permission: 'user:add',
|
||||
parentId: 'menu_sys_user',
|
||||
order: 0,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_sys_user_edit',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '编辑',
|
||||
permission: 'user:edit',
|
||||
parentId: 'menu_sys_user',
|
||||
order: 1,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_sys_user_delete',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '删除',
|
||||
permission: 'user:delete',
|
||||
parentId: 'menu_sys_user',
|
||||
order: 2,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'menu_sys_user_view',
|
||||
type: 'button',
|
||||
path: '',
|
||||
title: '查看',
|
||||
permission: 'user:view',
|
||||
parentId: 'menu_sys_user',
|
||||
order: 3,
|
||||
status: 'active',
|
||||
isBuiltIn: true,
|
||||
createTime: NOW,
|
||||
updateTime: NOW,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
function flattenMenus(menus: AdminMenu[]): AdminMenu[] {
|
||||
const result: AdminMenu[] = []
|
||||
for (const menu of menus) {
|
||||
result.push(menu)
|
||||
if (menu.children?.length) result.push(...flattenMenus(menu.children))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const FLAT_MENUS = flattenMenus(ALL_MENUS)
|
||||
|
||||
function getMenuAncestors(menuId: string, allMenus: AdminMenu[]): string[] {
|
||||
const ancestors: string[] = []
|
||||
let current = allMenus.find((m) => m.id === menuId)
|
||||
while (current?.parentId) {
|
||||
ancestors.push(current.parentId)
|
||||
current = allMenus.find((m) => m.id === current!.parentId)
|
||||
}
|
||||
return ancestors
|
||||
}
|
||||
|
||||
function buildMenuTree(menuIds: Set<string>): AdminMenu[] {
|
||||
const expandedIds = new Set(menuIds)
|
||||
for (const id of menuIds) {
|
||||
for (const ancestor of getMenuAncestors(id, FLAT_MENUS)) {
|
||||
expandedIds.add(ancestor)
|
||||
}
|
||||
}
|
||||
|
||||
const filtered = FLAT_MENUS.filter((m) => expandedIds.has(m.id) && m.status === 'active')
|
||||
|
||||
function build(parentId: string | null): AdminMenu[] {
|
||||
return filtered
|
||||
.filter((m) => (m.parentId ?? null) === parentId && m.type !== 'button')
|
||||
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
||||
.map((m) => ({
|
||||
...m,
|
||||
children: build(m.id),
|
||||
}))
|
||||
}
|
||||
|
||||
return build(null)
|
||||
}
|
||||
|
||||
export function getPermissionsForRole(menuIds: string[]) {
|
||||
const idSet = new Set(menuIds)
|
||||
const buttonPermissions = FLAT_MENUS.filter((m) => m.type === 'button' && m.permission && idSet.has(m.id))
|
||||
.map((m) => m.permission!)
|
||||
const menus = buildMenuTree(idSet)
|
||||
return { menus, buttonPermissions }
|
||||
}
|
||||
|
||||
export function getAllMenusTree(): AdminMenu[] {
|
||||
return ALL_MENUS
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import mysql, { type Pool, type ResultSetHeader, type RowDataPacket } from 'mysql2/promise'
|
||||
|
||||
let pool: Pool | null = null
|
||||
let initPromise: Promise<void> | null = null
|
||||
let dbReady = false
|
||||
|
||||
function mysqlConfig() {
|
||||
return {
|
||||
host: process.env.NUXT_MYSQL_HOST || '127.0.0.1',
|
||||
port: Number(process.env.NUXT_MYSQL_PORT || 3306),
|
||||
user: process.env.NUXT_MYSQL_USER || 'root',
|
||||
password: process.env.NUXT_MYSQL_PASSWORD || '',
|
||||
database: process.env.NUXT_MYSQL_DATABASE || 'umedglobal',
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
timezone: '+08:00',
|
||||
}
|
||||
}
|
||||
|
||||
export function getPool(): Pool {
|
||||
if (!pool) {
|
||||
pool = mysql.createPool(mysqlConfig())
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
async function queryRaw<T extends RowDataPacket>(sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
const [rows] = await getPool().query<T[]>(sql, params)
|
||||
return rows
|
||||
}
|
||||
|
||||
async function executeRaw(sql: string, params: unknown[] = []): Promise<ResultSetHeader> {
|
||||
const [result] = await getPool().execute<ResultSetHeader>(sql, params)
|
||||
return result
|
||||
}
|
||||
|
||||
export async function query<T extends RowDataPacket>(
|
||||
sql: string,
|
||||
params: unknown[] = []
|
||||
): Promise<T[]> {
|
||||
await ensureDb()
|
||||
return queryRaw<T>(sql, params)
|
||||
}
|
||||
|
||||
export async function queryOne<T extends RowDataPacket>(
|
||||
sql: string,
|
||||
params: unknown[] = []
|
||||
): Promise<T | null> {
|
||||
const rows = await query<T>(sql, params)
|
||||
return rows[0] ?? null
|
||||
}
|
||||
|
||||
export async function execute(sql: string, params: unknown[] = []): Promise<ResultSetHeader> {
|
||||
await ensureDb()
|
||||
return executeRaw(sql, params)
|
||||
}
|
||||
|
||||
export async function ensureDb(): Promise<void> {
|
||||
if (dbReady) return
|
||||
if (!initPromise) {
|
||||
initPromise = initDatabase()
|
||||
}
|
||||
await initPromise
|
||||
}
|
||||
|
||||
async function initDatabase() {
|
||||
const { initSchema, seedIfEmpty, migrateBuiltinAdminPassword, migrateWorkbenchMenu, migrateSeoMenu } =
|
||||
await import('./db-init')
|
||||
const { initPageSeoSchema, seedPageSeoIfEmpty, syncMissingPageSeo } = await import('./page-seo')
|
||||
const { initNewsSchema, migrateNewsMenu } = await import('./news')
|
||||
|
||||
await initSchema()
|
||||
await initPageSeoSchema()
|
||||
await initNewsSchema()
|
||||
await seedIfEmpty()
|
||||
await seedPageSeoIfEmpty()
|
||||
await syncMissingPageSeo()
|
||||
await migrateBuiltinAdminPassword()
|
||||
await migrateWorkbenchMenu()
|
||||
await migrateSeoMenu()
|
||||
await migrateNewsMenu()
|
||||
|
||||
dbReady = true
|
||||
}
|
||||
|
||||
export async function execInit(sql: string, params: unknown[] = []): Promise<ResultSetHeader> {
|
||||
return executeRaw(sql, params)
|
||||
}
|
||||
|
||||
export async function queryInit<T extends RowDataPacket>(
|
||||
sql: string,
|
||||
params: unknown[] = []
|
||||
): Promise<T[]> {
|
||||
return queryRaw<T>(sql, params)
|
||||
}
|
||||
|
||||
export async function queryOneInit<T extends RowDataPacket>(
|
||||
sql: string,
|
||||
params: unknown[] = []
|
||||
): Promise<T | null> {
|
||||
const rows = await queryInit<T>(sql, params)
|
||||
return rows[0] ?? null
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
import type { MediaPublicItem } from '~/data/news-content'
|
||||
import { newsItems as seedNewsEn, seedVideosEn } from '~/data/news-content'
|
||||
import { newsItemsZh, seedVideosZh } from '~/data/locale/zh/news.zh'
|
||||
import { nowStr } from './auth'
|
||||
import { execInit, execute, query, queryInit, queryOne, queryOneInit } from './mysql'
|
||||
|
||||
export type MediaType = 'article' | 'video'
|
||||
|
||||
export type NewsArticleRow = {
|
||||
id: number
|
||||
locale: string
|
||||
media_type: string
|
||||
title: string
|
||||
summary: string
|
||||
thumbnail: string
|
||||
thumbnail_alt: string | null
|
||||
url: string | null
|
||||
youtube_url: string | null
|
||||
tiktok_url: string | null
|
||||
sort_order: number
|
||||
status: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export type NewsArticleRecord = {
|
||||
id: string
|
||||
locale: 'en' | 'zh'
|
||||
mediaType: MediaType
|
||||
title: string
|
||||
summary: string
|
||||
thumbnail: string
|
||||
thumbnailAlt?: string
|
||||
url?: string
|
||||
youtubeUrl?: string
|
||||
tiktokUrl?: string
|
||||
sortOrder: number
|
||||
status: 'published' | 'draft'
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export type NewsArticleInput = {
|
||||
locale: 'en' | 'zh'
|
||||
mediaType: MediaType
|
||||
title: string
|
||||
summary: string
|
||||
thumbnail: string
|
||||
thumbnailAlt?: string
|
||||
url?: string
|
||||
youtubeUrl?: string
|
||||
tiktokUrl?: string
|
||||
sortOrder?: number
|
||||
status?: 'published' | 'draft'
|
||||
}
|
||||
|
||||
export type ArticlePublic = {
|
||||
title: string
|
||||
summary: string
|
||||
thumbnail: string
|
||||
thumbnailAlt: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export type VideoPublic = {
|
||||
title: string
|
||||
summary: string
|
||||
thumbnail: string
|
||||
thumbnailAlt: string
|
||||
youtubeUrl?: string
|
||||
tiktokUrl?: string
|
||||
}
|
||||
|
||||
export type PublishedMedia = {
|
||||
items: MediaPublicItem[]
|
||||
articles: ArticlePublic[]
|
||||
videos: VideoPublic[]
|
||||
}
|
||||
|
||||
function rowToRecord(row: NewsArticleRow): NewsArticleRecord {
|
||||
return {
|
||||
id: String(row.id),
|
||||
locale: row.locale as 'en' | 'zh',
|
||||
mediaType: (row.media_type === 'video' ? 'video' : 'article') as MediaType,
|
||||
title: row.title,
|
||||
summary: row.summary,
|
||||
thumbnail: row.thumbnail,
|
||||
thumbnailAlt: row.thumbnail_alt ?? undefined,
|
||||
url: row.url ?? undefined,
|
||||
youtubeUrl: row.youtube_url ?? undefined,
|
||||
tiktokUrl: row.tiktok_url ?? undefined,
|
||||
sortOrder: row.sort_order,
|
||||
status: row.status as 'published' | 'draft',
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
function rowToMediaPublic(row: NewsArticleRow): MediaPublicItem {
|
||||
const base = {
|
||||
title: row.title,
|
||||
summary: row.summary,
|
||||
thumbnail: row.thumbnail,
|
||||
thumbnailAlt: row.thumbnail_alt || row.title,
|
||||
}
|
||||
|
||||
if (row.media_type === 'video') {
|
||||
return {
|
||||
...base,
|
||||
mediaType: 'video',
|
||||
youtubeUrl: row.youtube_url ?? undefined,
|
||||
tiktokUrl: row.tiktok_url ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
mediaType: 'article',
|
||||
url: row.url || '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function initNewsSchema() {
|
||||
await execInit(`
|
||||
CREATE TABLE IF NOT EXISTS news_articles (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
locale VARCHAR(8) NOT NULL,
|
||||
media_type VARCHAR(32) NOT NULL DEFAULT 'article',
|
||||
title TEXT NOT NULL,
|
||||
summary TEXT NOT NULL,
|
||||
thumbnail TEXT NOT NULL,
|
||||
thumbnail_alt TEXT,
|
||||
url TEXT,
|
||||
youtube_url TEXT,
|
||||
tiktok_url TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'published',
|
||||
created_at VARCHAR(32) NOT NULL,
|
||||
updated_at VARCHAR(32) NOT NULL,
|
||||
INDEX idx_news_locale_sort (locale, sort_order, id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`)
|
||||
}
|
||||
|
||||
export async function seedNewsIfEmpty() {
|
||||
const count = await queryOneInit<{ c: number }>('SELECT COUNT(*) AS c FROM news_articles')
|
||||
if ((count?.c ?? 0) > 0) return
|
||||
|
||||
await seedArticles()
|
||||
await seedVideos()
|
||||
}
|
||||
|
||||
async function seedArticles() {
|
||||
const now = nowStr()
|
||||
|
||||
for (const [index, item] of seedNewsEn.entries()) {
|
||||
await execInit(
|
||||
`INSERT INTO news_articles (
|
||||
locale, media_type, title, summary, thumbnail, thumbnail_alt, url, youtube_url, tiktok_url,
|
||||
sort_order, status, created_at, updated_at
|
||||
) VALUES (?, 'article', ?, ?, ?, ?, ?, NULL, NULL, ?, 'published', ?, ?)`,
|
||||
['en', item.title, item.summary, item.thumbnail, item.thumbnailAlt, item.url, seedNewsEn.length - index + 3, now, now]
|
||||
)
|
||||
}
|
||||
|
||||
for (const [index, item] of newsItemsZh.entries()) {
|
||||
await execInit(
|
||||
`INSERT INTO news_articles (
|
||||
locale, media_type, title, summary, thumbnail, thumbnail_alt, url, youtube_url, tiktok_url,
|
||||
sort_order, status, created_at, updated_at
|
||||
) VALUES (?, 'article', ?, ?, ?, ?, ?, NULL, NULL, ?, 'published', ?, ?)`,
|
||||
['zh', item.title, item.summary, item.thumbnail, item.thumbnailAlt, item.url, newsItemsZh.length - index + 3, now, now]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function seedVideos() {
|
||||
const now = nowStr()
|
||||
|
||||
for (const [index, item] of seedVideosEn.entries()) {
|
||||
await execInit(
|
||||
`INSERT INTO news_articles (
|
||||
locale, media_type, title, summary, thumbnail, thumbnail_alt, url, youtube_url, tiktok_url,
|
||||
sort_order, status, created_at, updated_at
|
||||
) VALUES (?, 'video', ?, ?, ?, ?, '', ?, ?, ?, 'published', ?, ?)`,
|
||||
[
|
||||
'en',
|
||||
item.title,
|
||||
item.summary,
|
||||
item.thumbnail,
|
||||
item.thumbnailAlt,
|
||||
item.youtubeUrl ?? null,
|
||||
item.tiktokUrl ?? null,
|
||||
seedVideosEn.length - index + 2,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
for (const [index, item] of seedVideosZh.entries()) {
|
||||
await execInit(
|
||||
`INSERT INTO news_articles (
|
||||
locale, media_type, title, summary, thumbnail, thumbnail_alt, url, youtube_url, tiktok_url,
|
||||
sort_order, status, created_at, updated_at
|
||||
) VALUES (?, 'video', ?, ?, ?, ?, '', ?, ?, ?, 'published', ?, ?)`,
|
||||
[
|
||||
'zh',
|
||||
item.title,
|
||||
item.summary,
|
||||
item.thumbnail,
|
||||
item.thumbnailAlt,
|
||||
item.youtubeUrl ?? null,
|
||||
item.tiktokUrl ?? null,
|
||||
seedVideosZh.length - index + 2,
|
||||
now,
|
||||
now,
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function seedVideosIfEmpty() {
|
||||
const count = await queryOneInit<{ c: number }>(
|
||||
`SELECT COUNT(*) AS c FROM news_articles WHERE media_type = 'video'`
|
||||
)
|
||||
if ((count?.c ?? 0) > 0) return
|
||||
|
||||
await seedVideos()
|
||||
}
|
||||
|
||||
export const NEWS_MENU_IDS = [
|
||||
'menu_content_dir',
|
||||
'menu_news_list',
|
||||
'menu_news_add',
|
||||
'menu_news_edit',
|
||||
'menu_news_delete',
|
||||
'menu_news_view',
|
||||
]
|
||||
|
||||
export async function migrateNewsMenu() {
|
||||
const roles = await queryInit<{ id: number; menu_ids: string }>('SELECT id, menu_ids FROM admin_roles')
|
||||
|
||||
for (const role of roles) {
|
||||
const ids = JSON.parse(role.menu_ids || '[]') as string[]
|
||||
if (!ids.includes('menu_sys_dir')) continue
|
||||
const missing = NEWS_MENU_IDS.filter((id) => !ids.includes(id))
|
||||
if (!missing.length) continue
|
||||
|
||||
await execInit('UPDATE admin_roles SET menu_ids = ?, update_time = ? WHERE id = ?', [
|
||||
JSON.stringify([...ids, ...missing]),
|
||||
nowStr(),
|
||||
role.id,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
export async function listNewsArticles(options?: {
|
||||
locale?: 'en' | 'zh'
|
||||
mediaType?: MediaType
|
||||
keyword?: string
|
||||
status?: 'published' | 'draft'
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}) {
|
||||
let rows = await query<NewsArticleRow>(
|
||||
'SELECT * FROM news_articles ORDER BY sort_order DESC, created_at DESC'
|
||||
)
|
||||
|
||||
if (options?.locale) rows = rows.filter((r) => r.locale === options.locale)
|
||||
if (options?.mediaType) rows = rows.filter((r) => r.media_type === options.mediaType)
|
||||
if (options?.status) rows = rows.filter((r) => r.status === options.status)
|
||||
if (options?.keyword) {
|
||||
const kw = options.keyword.toLowerCase()
|
||||
rows = rows.filter(
|
||||
(r) => r.title.toLowerCase().includes(kw) || r.summary.toLowerCase().includes(kw)
|
||||
)
|
||||
}
|
||||
|
||||
const total = rows.length
|
||||
if (options?.page && options?.pageSize) {
|
||||
const page = Math.max(1, options.page)
|
||||
const pageSize = Math.max(1, options.pageSize)
|
||||
rows = rows.slice((page - 1) * pageSize, page * pageSize)
|
||||
}
|
||||
|
||||
return { list: rows.map(rowToRecord), total }
|
||||
}
|
||||
|
||||
export async function listPublishedMedia(locale: 'en' | 'zh'): Promise<PublishedMedia> {
|
||||
const rows = await query<NewsArticleRow>(
|
||||
`SELECT * FROM news_articles
|
||||
WHERE locale = ? AND status = 'published'
|
||||
ORDER BY sort_order DESC, created_at DESC`,
|
||||
[locale]
|
||||
)
|
||||
|
||||
const items = rows.map(rowToMediaPublic)
|
||||
|
||||
return {
|
||||
items,
|
||||
articles: items.filter((item) => item.mediaType === 'article').map((item) => ({
|
||||
title: item.title,
|
||||
summary: item.summary,
|
||||
thumbnail: item.thumbnail,
|
||||
thumbnailAlt: item.thumbnailAlt,
|
||||
url: item.url || '',
|
||||
})),
|
||||
videos: items.filter((item) => item.mediaType === 'video').map((item) => ({
|
||||
title: item.title,
|
||||
summary: item.summary,
|
||||
thumbnail: item.thumbnail,
|
||||
thumbnailAlt: item.thumbnailAlt,
|
||||
youtubeUrl: item.youtubeUrl,
|
||||
tiktokUrl: item.tiktokUrl,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getNewsArticleById(id: string | number) {
|
||||
const row = await queryOne<NewsArticleRow>('SELECT * FROM news_articles WHERE id = ?', [id])
|
||||
return row ? rowToRecord(row) : null
|
||||
}
|
||||
|
||||
export async function createNewsArticle(input: NewsArticleInput) {
|
||||
const now = nowStr()
|
||||
const maxSort = await queryOne<{ m: number }>(
|
||||
'SELECT COALESCE(MAX(sort_order), 0) AS m FROM news_articles WHERE locale = ?',
|
||||
[input.locale]
|
||||
)
|
||||
|
||||
const result = await execute(
|
||||
`INSERT INTO news_articles (
|
||||
locale, media_type, title, summary, thumbnail, thumbnail_alt, url, youtube_url, tiktok_url,
|
||||
sort_order, status, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
input.locale,
|
||||
input.mediaType,
|
||||
input.title.trim(),
|
||||
input.summary.trim(),
|
||||
input.thumbnail.trim(),
|
||||
input.thumbnailAlt?.trim() || null,
|
||||
input.mediaType === 'article' ? input.url?.trim() || '' : '',
|
||||
input.mediaType === 'video' ? input.youtubeUrl?.trim() || null : null,
|
||||
input.mediaType === 'video' ? input.tiktokUrl?.trim() || null : null,
|
||||
input.sortOrder ?? (maxSort?.m ?? 0) + 1,
|
||||
input.status ?? 'published',
|
||||
now,
|
||||
now,
|
||||
]
|
||||
)
|
||||
|
||||
return (await getNewsArticleById(result.insertId))!
|
||||
}
|
||||
|
||||
export async function updateNewsArticle(id: string | number, input: Partial<NewsArticleInput>) {
|
||||
const existing = await getNewsArticleById(id)
|
||||
if (!existing) return null
|
||||
|
||||
const mediaType = input.mediaType ?? existing.mediaType
|
||||
const now = nowStr()
|
||||
|
||||
await execute(
|
||||
`UPDATE news_articles SET
|
||||
locale = ?,
|
||||
media_type = ?,
|
||||
title = ?,
|
||||
summary = ?,
|
||||
thumbnail = ?,
|
||||
thumbnail_alt = ?,
|
||||
url = ?,
|
||||
youtube_url = ?,
|
||||
tiktok_url = ?,
|
||||
sort_order = ?,
|
||||
status = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?`,
|
||||
[
|
||||
input.locale ?? existing.locale,
|
||||
mediaType,
|
||||
input.title?.trim() ?? existing.title,
|
||||
input.summary?.trim() ?? existing.summary,
|
||||
input.thumbnail?.trim() ?? existing.thumbnail,
|
||||
input.thumbnailAlt !== undefined ? input.thumbnailAlt.trim() || null : existing.thumbnailAlt ?? null,
|
||||
mediaType === 'article' ? (input.url?.trim() ?? existing.url ?? '') : '',
|
||||
mediaType === 'video' ? (input.youtubeUrl?.trim() ?? existing.youtubeUrl ?? null) : null,
|
||||
mediaType === 'video' ? (input.tiktokUrl?.trim() ?? existing.tiktokUrl ?? null) : null,
|
||||
input.sortOrder ?? existing.sortOrder,
|
||||
input.status ?? existing.status,
|
||||
now,
|
||||
id,
|
||||
]
|
||||
)
|
||||
|
||||
return getNewsArticleById(id)
|
||||
}
|
||||
|
||||
export async function deleteNewsArticles(ids: Array<string | number>) {
|
||||
for (const id of ids) {
|
||||
await execute('DELETE FROM news_articles WHERE id = ?', [id])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { SEO_REGISTRY, type SeoRegistryEntry } from '../data/seo-registry'
|
||||
import { nowStr } from './auth'
|
||||
import { execInit, execute, query, queryInit, queryOne, queryOneInit } from './mysql'
|
||||
|
||||
export type PageSeoRow = {
|
||||
id: number
|
||||
route_key: string
|
||||
locale: string
|
||||
page_label: string
|
||||
title: string
|
||||
description: string
|
||||
keywords: string | null
|
||||
og_title: string | null
|
||||
og_description: string | null
|
||||
og_image: string | null
|
||||
robots: string | null
|
||||
og_type: string | null
|
||||
updated_at: string
|
||||
updated_by: number | null
|
||||
}
|
||||
|
||||
export type PageSeoRecord = {
|
||||
id: string
|
||||
routeKey: string
|
||||
locale: 'en' | 'zh'
|
||||
pageLabel: string
|
||||
title: string
|
||||
description: string
|
||||
keywords?: string
|
||||
ogTitle?: string
|
||||
ogDescription?: string
|
||||
ogImage?: string
|
||||
robots?: string
|
||||
ogType?: 'website' | 'article'
|
||||
updatedAt: string
|
||||
updatedBy?: string
|
||||
}
|
||||
|
||||
export type PageSeoUpdateInput = {
|
||||
title: string
|
||||
description: string
|
||||
keywords?: string
|
||||
ogTitle?: string
|
||||
ogDescription?: string
|
||||
ogImage?: string
|
||||
robots?: string
|
||||
ogType?: 'website' | 'article'
|
||||
}
|
||||
|
||||
function rowToRecord(row: PageSeoRow): PageSeoRecord {
|
||||
return {
|
||||
id: String(row.id),
|
||||
routeKey: row.route_key,
|
||||
locale: row.locale as 'en' | 'zh',
|
||||
pageLabel: row.page_label,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
keywords: row.keywords ?? undefined,
|
||||
ogTitle: row.og_title ?? undefined,
|
||||
ogDescription: row.og_description ?? undefined,
|
||||
ogImage: row.og_image ?? undefined,
|
||||
robots: row.robots ?? undefined,
|
||||
ogType: (row.og_type as 'website' | 'article' | null) ?? undefined,
|
||||
updatedAt: row.updated_at,
|
||||
updatedBy: row.updated_by != null ? String(row.updated_by) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function entryToValues(entry: SeoRegistryEntry, now: string) {
|
||||
return [
|
||||
entry.routeKey,
|
||||
entry.locale,
|
||||
entry.pageLabel,
|
||||
entry.title,
|
||||
entry.description,
|
||||
entry.keywords ?? null,
|
||||
entry.ogTitle ?? null,
|
||||
entry.ogDescription ?? null,
|
||||
entry.ogImage ?? null,
|
||||
entry.robots ?? 'index,follow',
|
||||
entry.ogType ?? 'website',
|
||||
now,
|
||||
null,
|
||||
]
|
||||
}
|
||||
|
||||
export async function initPageSeoSchema() {
|
||||
await execInit(`
|
||||
CREATE TABLE IF NOT EXISTS page_seo (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
route_key VARCHAR(512) NOT NULL,
|
||||
locale VARCHAR(8) NOT NULL,
|
||||
page_label VARCHAR(255) NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
keywords TEXT,
|
||||
og_title TEXT,
|
||||
og_description TEXT,
|
||||
og_image TEXT,
|
||||
robots VARCHAR(64) DEFAULT 'index,follow',
|
||||
og_type VARCHAR(32) DEFAULT 'website',
|
||||
updated_at VARCHAR(32) NOT NULL,
|
||||
updated_by BIGINT,
|
||||
UNIQUE KEY uk_page_seo_route_locale (route_key, locale)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
`)
|
||||
}
|
||||
|
||||
export async function seedPageSeoIfEmpty() {
|
||||
const count = await queryOneInit<{ c: number }>('SELECT COUNT(*) AS c FROM page_seo')
|
||||
if ((count?.c ?? 0) > 0) return
|
||||
|
||||
const now = nowStr()
|
||||
for (const entry of SEO_REGISTRY) {
|
||||
await execInit(
|
||||
`INSERT INTO page_seo (
|
||||
route_key, locale, page_label, title, description,
|
||||
keywords, og_title, og_description, og_image, robots, og_type,
|
||||
updated_at, updated_by
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
entryToValues(entry, now)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncMissingPageSeo() {
|
||||
const now = nowStr()
|
||||
const existingRows = await queryInit<{ route_key: string; locale: string }>(
|
||||
'SELECT route_key, locale FROM page_seo'
|
||||
)
|
||||
const existing = new Set(existingRows.map((r) => `${r.route_key}::${r.locale}`))
|
||||
|
||||
for (const entry of SEO_REGISTRY) {
|
||||
const routeLocaleKey = `${entry.routeKey}::${entry.locale}`
|
||||
if (existing.has(routeLocaleKey)) continue
|
||||
|
||||
await execInit(
|
||||
`INSERT INTO page_seo (
|
||||
route_key, locale, page_label, title, description,
|
||||
keywords, og_title, og_description, og_image, robots, og_type,
|
||||
updated_at, updated_by
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
entryToValues(entry, now)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function listPageSeo(params?: { locale?: string; keyword?: string }) {
|
||||
let sql = 'SELECT * FROM page_seo WHERE 1=1'
|
||||
const args: unknown[] = []
|
||||
|
||||
if (params?.locale === 'en' || params?.locale === 'zh') {
|
||||
sql += ' AND locale = ?'
|
||||
args.push(params.locale)
|
||||
}
|
||||
|
||||
if (params?.keyword) {
|
||||
sql += ' AND (page_label LIKE ? OR route_key LIKE ? OR title LIKE ?)'
|
||||
const kw = `%${params.keyword}%`
|
||||
args.push(kw, kw, kw)
|
||||
}
|
||||
|
||||
sql += ' ORDER BY route_key ASC, locale ASC'
|
||||
const rows = await query<PageSeoRow>(sql, args)
|
||||
return rows.map(rowToRecord)
|
||||
}
|
||||
|
||||
export async function getPageSeoByRoute(routeKey: string, locale: 'en' | 'zh') {
|
||||
const row = await queryOne<PageSeoRow>(
|
||||
'SELECT * FROM page_seo WHERE route_key = ? AND locale = ?',
|
||||
[routeKey, locale]
|
||||
)
|
||||
return row ? rowToRecord(row) : null
|
||||
}
|
||||
|
||||
export async function getPageSeoById(id: string | number) {
|
||||
const row = await queryOne<PageSeoRow>('SELECT * FROM page_seo WHERE id = ?', [id])
|
||||
return row ? rowToRecord(row) : null
|
||||
}
|
||||
|
||||
export async function updatePageSeo(id: string | number, input: PageSeoUpdateInput, updatedBy?: string) {
|
||||
const existing = await getPageSeoById(id)
|
||||
if (!existing) return null
|
||||
|
||||
const now = nowStr()
|
||||
await execute(
|
||||
`UPDATE page_seo SET
|
||||
title = ?,
|
||||
description = ?,
|
||||
keywords = ?,
|
||||
og_title = ?,
|
||||
og_description = ?,
|
||||
og_image = ?,
|
||||
robots = ?,
|
||||
og_type = ?,
|
||||
updated_at = ?,
|
||||
updated_by = ?
|
||||
WHERE id = ?`,
|
||||
[
|
||||
input.title,
|
||||
input.description,
|
||||
input.keywords ?? null,
|
||||
input.ogTitle ?? null,
|
||||
input.ogDescription ?? null,
|
||||
input.ogImage ?? null,
|
||||
input.robots ?? 'index,follow',
|
||||
input.ogType ?? 'website',
|
||||
now,
|
||||
updatedBy ? Number(updatedBy) || null : null,
|
||||
id,
|
||||
]
|
||||
)
|
||||
|
||||
return getPageSeoById(id)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export function ok<T>(data: T, message = '成功') {
|
||||
return { code: 200, message, data }
|
||||
}
|
||||
|
||||
export function fail(message: string, code = 500) {
|
||||
return { code, message, data: null }
|
||||
}
|
||||
|
||||
export function pageOk<T>(list: T[], total: number, page: number, pageSize: number, message = '获取成功') {
|
||||
return { code: 200, message, data: { list, total, page, pageSize } }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { getRequestURL, type H3Event } from 'h3'
|
||||
import { resolveSiteUrl } from '~/utils/seo'
|
||||
|
||||
/** 反向代理后读取真实域名(支持 umedglobal.cn / umedglobal.com.cn 等多域名) */
|
||||
export const REQUEST_SITE_URL_OPTS = {
|
||||
xForwardedHost: true,
|
||||
xForwardedProto: true
|
||||
} as const
|
||||
|
||||
export function getSiteUrlFromEvent(event: H3Event, fallback: string) {
|
||||
return resolveSiteUrl(fallback, getRequestURL(event, REQUEST_SITE_URL_OPTS).origin)
|
||||
}
|
||||
Reference in New Issue
Block a user