import { Controller, Get, Render, UseGuards, Req, Query } from '@nestjs/common'; import { AuthenticatedGuard } from '../auth/guards/authenticated.guard'; import { UtilsService } from '../utils/utils.service'; @Controller('progress') @UseGuards(AuthenticatedGuard) export class ProgressController { constructor(private utilsService: UtilsService) {} @Get() @Render('progress') async getProgress(@Req() req, @Query('days') daysQuery: string) { try { const days = parseInt(daysQuery) || 30; const weightTrend = await this.utilsService.getWeightTrend(req.user.id, days); const calorieTrend = await this.utilsService.getCalorieTrend(req.user.id, days); let avgCalories = 0, avgProtein = 0, avgCarbs = 0, avgFat = 0; if (calorieTrend.length > 0) { avgCalories = calorieTrend.reduce((sum, d) => sum + d.calories, 0) / calorieTrend.length; avgProtein = calorieTrend.reduce((sum, d) => sum + d.protein, 0) / calorieTrend.length; avgCarbs = calorieTrend.reduce((sum, d) => sum + d.carbs, 0) / calorieTrend.length; avgFat = calorieTrend.reduce((sum, d) => sum + d.fat, 0) / calorieTrend.length; } let weightChange = null; if (weightTrend.length >= 2) { weightChange = weightTrend[weightTrend.length - 1].weight_kg - weightTrend[0].weight_kg; } return { user: req.user, weight_trend: weightTrend, calorie_trend: calorieTrend, avg_calories: Math.round(avgCalories), avg_protein: Math.round(avgProtein), avg_carbs: Math.round(avgCarbs), avg_fat: Math.round(avgFat), weight_change: weightChange, days, }; } catch (err) { console.error(err); req.flash('error_msg', 'Error loading progress'); return { user: req.user, weight_trend: [], calorie_trend: [], avg_calories: 0, avg_protein: 0, avg_carbs: 0, avg_fat: 0, weight_change: null, days: 30, }; } } }