93 lines
2.7 KiB
TypeScript
93 lines
2.7 KiB
TypeScript
import { NextResponse } from 'next/server';
|
||
import { getServerSession } from 'next-auth';
|
||
import { authOptions } from '@/lib/auth';
|
||
import { prisma } from '@/lib/prisma';
|
||
import { buildMaterialPrivacyWhere } from '@/lib/task-detail-privacy';
|
||
|
||
// GET - 获取素材统计数据(只统计未删除的素材)
|
||
export async function GET() {
|
||
try {
|
||
const session = await getServerSession(authOptions);
|
||
if (!session?.user) {
|
||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||
}
|
||
const privacyWhere = await buildMaterialPrivacyWhere((session.user as any).id);
|
||
|
||
// 获取总数(只统计未删除的素材)
|
||
let total: number;
|
||
let materials: Array<{ createdAt: Date }>;
|
||
|
||
try {
|
||
total = await prisma.material.count({
|
||
where: {
|
||
deletedAt: null,
|
||
AND: [privacyWhere],
|
||
} as any,
|
||
});
|
||
|
||
// 获取所有未删除素材的创建时间
|
||
materials = await prisma.material.findMany({
|
||
where: {
|
||
deletedAt: null,
|
||
AND: [privacyWhere],
|
||
} as any,
|
||
select: {
|
||
createdAt: true,
|
||
},
|
||
orderBy: {
|
||
createdAt: 'desc',
|
||
},
|
||
});
|
||
} catch (e: any) {
|
||
// 兼容旧版本数据库(没有deletedAt字段)
|
||
if (e?.meta?.column?.includes('deletedAt')) {
|
||
console.warn('[Materials Stats] deletedAt field not found, using all materials');
|
||
total = await prisma.material.count({ where: privacyWhere });
|
||
materials = await prisma.material.findMany({
|
||
where: privacyWhere,
|
||
select: {
|
||
createdAt: true,
|
||
},
|
||
orderBy: {
|
||
createdAt: 'desc',
|
||
},
|
||
});
|
||
} else {
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
// 按月份统计
|
||
const monthMap = new Map<string, number>();
|
||
|
||
materials.forEach(material => {
|
||
const date = new Date(material.createdAt);
|
||
const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
|
||
monthMap.set(monthKey, (monthMap.get(monthKey) || 0) + 1);
|
||
});
|
||
|
||
// 格式化月份数据
|
||
const months = Array.from(monthMap.entries())
|
||
.map(([value, count]) => {
|
||
const [year, month] = value.split('-');
|
||
return {
|
||
value,
|
||
label: `${year}年${parseInt(month)}月`,
|
||
count,
|
||
};
|
||
})
|
||
.sort((a, b) => b.value.localeCompare(a.value)); // 降序排列
|
||
|
||
return NextResponse.json({
|
||
total,
|
||
months,
|
||
}, { headers: { 'Cache-Control': 'private, no-store' } });
|
||
} catch (error) {
|
||
console.error('Error fetching material stats:', error);
|
||
return NextResponse.json(
|
||
{ error: '获取统计数据失败' },
|
||
{ status: 500 }
|
||
);
|
||
}
|
||
}
|