提交正式官网
This commit is contained in:
@@ -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