This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db, habits, users, habitLogs } from '@/lib/db';
|
||||
import { getTokenCookie } from '@/lib/auth/cookies';
|
||||
import { eq, and, desc, sql } from 'drizzle-orm';
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
|
||||
async function getUserFromToken() {
|
||||
const token = await getTokenCookie();
|
||||
@@ -18,48 +18,58 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Get all non-archived habits with their latest log and statistics
|
||||
const userHabits = await db
|
||||
.select({
|
||||
id: habits.id,
|
||||
name: habits.name,
|
||||
type: habits.type,
|
||||
targetFrequency: habits.targetFrequency,
|
||||
color: habits.color,
|
||||
icon: habits.icon,
|
||||
createdAt: habits.createdAt,
|
||||
// Get the latest log time
|
||||
lastLoggedAt: sql<Date>`(
|
||||
SELECT MAX(logged_at)
|
||||
FROM ${habitLogs}
|
||||
WHERE habit_id = ${habits.id}
|
||||
)`.as('lastLoggedAt'),
|
||||
// Get total logs count
|
||||
totalLogs: sql<number>`(
|
||||
SELECT COUNT(*)
|
||||
FROM ${habitLogs}
|
||||
WHERE habit_id = ${habits.id}
|
||||
)`.as('totalLogs'),
|
||||
// Get logs in last 7 days
|
||||
logsLastWeek: sql<number>`(
|
||||
SELECT COUNT(*)
|
||||
FROM ${habitLogs}
|
||||
WHERE habit_id = ${habits.id}
|
||||
AND logged_at >= NOW() - INTERVAL '7 days'
|
||||
)`.as('logsLastWeek'),
|
||||
// Get logs in last 30 days
|
||||
logsLastMonth: sql<number>`(
|
||||
SELECT COUNT(*)
|
||||
FROM ${habitLogs}
|
||||
WHERE habit_id = ${habits.id}
|
||||
AND logged_at >= NOW() - INTERVAL '30 days'
|
||||
)`.as('logsLastMonth'),
|
||||
})
|
||||
// Get current timestamp for date calculations
|
||||
const now = new Date();
|
||||
const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// First get all habits
|
||||
const userHabitsBase = await db
|
||||
.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.userId, user.id), eq(habits.isArchived, false)))
|
||||
.orderBy(desc(habits.createdAt));
|
||||
|
||||
return NextResponse.json({ habits: userHabits });
|
||||
// Then get aggregated log data for each habit
|
||||
const habitsWithStats = await Promise.all(
|
||||
userHabitsBase.map(async (habit) => {
|
||||
// Get all logs for this habit
|
||||
const logs = await db
|
||||
.select({
|
||||
loggedAt: habitLogs.loggedAt,
|
||||
})
|
||||
.from(habitLogs)
|
||||
.where(eq(habitLogs.habitId, habit.id));
|
||||
|
||||
// Calculate statistics
|
||||
const totalLogs = logs.length;
|
||||
const logsLastWeek = logs.filter((log) => log.loggedAt >= sevenDaysAgo).length;
|
||||
const logsLastMonth = logs.filter((log) => log.loggedAt >= thirtyDaysAgo).length;
|
||||
const lastLoggedAt =
|
||||
logs.length > 0
|
||||
? logs.reduce(
|
||||
(latest, log) => (log.loggedAt > latest ? log.loggedAt : latest),
|
||||
logs[0].loggedAt,
|
||||
)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: habit.id,
|
||||
name: habit.name,
|
||||
type: habit.type,
|
||||
targetFrequency: habit.targetFrequency,
|
||||
color: habit.color,
|
||||
icon: habit.icon,
|
||||
createdAt: habit.createdAt,
|
||||
lastLoggedAt,
|
||||
totalLogs,
|
||||
logsLastWeek,
|
||||
logsLastMonth,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return NextResponse.json({ habits: habitsWithStats });
|
||||
} catch (error) {
|
||||
console.error('Get habits error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
|
Reference in New Issue
Block a user