72 行
3.2 KiB
JavaScript

import { count, eq, desc, sql, gte } from 'drizzle-orm'
import { useDB, schema } from '../../utils/db.js'
import { requireAdmin } from '../../utils/auth.js'
export default defineEventHandler(async (event) => {
requireAdmin(event)
const db = useDB()
const [newsRow] = db.select({ c: count() }).from(schema.articles).where(eq(schema.articles.type, 'news')).all()
const [blogRow] = db.select({ c: count() }).from(schema.articles).where(eq(schema.articles.type, 'blog')).all()
const [reviewsRow] = db.select({ c: count() }).from(schema.reviews).all()
const [faqsRow] = db.select({ c: count() }).from(schema.faqs).all()
const [galleryRow] = db.select({ c: count() }).from(schema.galleryItems).all()
const [storiesRow] = db.select({ c: count() }).from(schema.stories).all()
const [subTotalRow] = db.select({ c: count() }).from(schema.submissions).all()
const [subUnreadRow] = db.select({ c: count() }).from(schema.submissions).where(eq(schema.submissions.read, false)).all()
const [siteContentRow] = db.select({ c: count() }).from(schema.siteContent).all()
// 产品线数量(从 site_content 的 product-lines 键解析)
let productLines = 0
try {
const pl = db.select().from(schema.siteContent).where(eq(schema.siteContent.key, 'product-lines')).all()
if (pl[0]?.data) {
const arr = JSON.parse(pl[0].data)
if (Array.isArray(arr)) productLines = arr.length
}
} catch {}
// 近 7 天真实提交(仅统计用户表单,文章/评价为后台手动录入不计入)
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
const [recentSubRow] = db.select({ c: count() }).from(schema.submissions).where(gte(schema.submissions.createdAt, weekAgo)).all()
const [recentContactRow] = db.select({ c: count() }).from(schema.submissions).where(sql`${schema.submissions.type} = 'contact' AND ${schema.submissions.createdAt} >= ${weekAgo}`).all()
const [recentCustomizeRow] = db.select({ c: count() }).from(schema.submissions).where(sql`${schema.submissions.type} = 'customize' AND ${schema.submissions.createdAt} >= ${weekAgo}`).all()
// 最近 5 条提交 / 最近 5 条评价
const recentSubmissions = db.select({
id: schema.submissions.id, type: schema.submissions.type,
read: schema.submissions.read, createdAt: schema.submissions.createdAt,
}).from(schema.submissions).orderBy(desc(schema.submissions.id)).limit(5).all()
const recentReviews = db.select({
id: schema.reviews.id, author: schema.reviews.author, rating: schema.reviews.rating,
title: schema.reviews.title, createdAt: schema.reviews.createdAt,
}).from(schema.reviews).orderBy(desc(schema.reviews.id)).limit(5).all()
return {
articles: {
total: newsRow.c + blogRow.c,
news: newsRow.c,
blog: blogRow.c,
},
reviews: reviewsRow.c,
faqs: faqsRow.c,
gallery: galleryRow.c,
stories: storiesRow.c,
submissions: {
total: subTotalRow.c,
unread: subUnreadRow.c,
},
siteContent: siteContentRow.c,
productLines,
recent: {
submissions7d: recentSubRow.c,
contact7d: recentContactRow.c,
customize7d: recentCustomizeRow.c,
},
recentSubmissions,
recentReviews,
}
})