feat: history and calculate needs for user
CI / 🧪 Tests Laravel (push) Failing after 2m18s
CI / 🐳 Build & Push Images (push) Has been skipped

This commit is contained in:
2026-08-14 12:45:37 +02:00
parent ea5a5737ec
commit 69372a49ed
51 changed files with 2226 additions and 305 deletions
@@ -0,0 +1,79 @@
<?php
namespace App\Actions;
use App\Enums\NutritionPlanSource;
use App\Enums\WeeklyReviewStatus;
use App\Models\NutritionPlan;
use App\Models\WeeklyReview;
use Illuminate\Support\Facades\DB;
class AcceptWeeklyReviewAdjustment
{
public function execute(WeeklyReview $weeklyReview): NutritionPlan
{
return DB::transaction(function () use ($weeklyReview): NutritionPlan {
$lockedReview = WeeklyReview::query()->lockForUpdate()->findOrFail($weeklyReview->getKey());
abort_if($lockedReview->accepted_at !== null, 409, 'WEEKLY_ADJUSTMENT_ALREADY_ACCEPTED');
abort_unless(
$lockedReview->status === WeeklyReviewStatus::ADJUSTMENT_RECOMMENDED
&& $lockedReview->recommended_calorie_adjustment !== 0,
409,
'WEEKLY_ADJUSTMENT_UNAVAILABLE',
);
$user = $lockedReview->user()->lockForUpdate()->firstOrFail();
$currentPlan = $user->nutritionPlans()->where('is_active', true)->latest('effective_from')->firstOrFail();
abort_unless(
$lockedReview->nutrition_plan_id === $currentPlan->getKey(),
409,
'WEEKLY_ADJUSTMENT_STALE',
);
$now = now();
$targetCalories = max(1200, $currentPlan->calories + $lockedReview->recommended_calorie_adjustment);
$proteins = (int) round($currentPlan->proteins);
$fats = (int) round($currentPlan->fats);
$carbs = max(0, (int) round(($targetCalories - ($proteins * 4) - ($fats * 9)) / 4));
$calories = ($proteins * 4) + ($carbs * 4) + ($fats * 9);
abort_if(
$calories === $currentPlan->calories,
409,
'WEEKLY_ADJUSTMENT_UNAVAILABLE',
);
$currentPlan->update([
'is_active' => false,
'effective_until' => $now,
]);
$nextPlan = $user->nutritionPlans()->create([
'source' => NutritionPlanSource::WEEKLY_ADJUSTMENT,
'formula_version' => $currentPlan->formula_version,
'calories' => $calories,
'proteins' => $proteins,
'carbs' => $carbs,
'fats' => $fats,
'resting_metabolism' => $currentPlan->resting_metabolism,
'maintenance_calories' => $currentPlan->maintenance_calories,
'calorie_adjustment_percent' => ($calories - $currentPlan->maintenance_calories) / max(1, $currentPlan->maintenance_calories),
'calculation_details' => [
...$currentPlan->calculation_details,
'weeklyReviewId' => $lockedReview->getKey(),
'weeklyAdjustmentCalories' => $lockedReview->recommended_calorie_adjustment,
],
'effective_from' => $now,
]);
$lockedReview->update([
'accepted_at' => $now,
'accepted_nutrition_plan_id' => $nextPlan->getKey(),
]);
return $nextPlan;
}, attempts: 3);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Actions;
use App\Enums\NutritionPlanSource;
use App\Models\User;
class CompleteNutritionOnboarding
{
public function __construct(private RecalculateNutritionPlan $recalculateNutritionPlan) {}
/**
* @param array<string, mixed> $data
*/
public function execute(User $user, array $data): User
{
if ($user->hasCompletedNutritionOnboarding()) {
return $user->loadMissing(['activeNutritionPlan', 'latestWeightEntry']);
}
return $this->recalculateNutritionPlan->execute(
user: $user,
data: $data,
source: NutritionPlanSource::ONBOARDING,
completeOnboarding: true,
);
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Actions;
use App\Enums\NutritionPlanSource;
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use App\Models\User;
use App\Services\NutritionPlanCalculator;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
class RecalculateNutritionPlan
{
public function __construct(private NutritionPlanCalculator $calculator) {}
/**
* @param array<string, mixed> $data
*/
public function execute(
User $user,
array $data,
NutritionPlanSource $source,
bool $completeOnboarding = false,
): User {
return DB::transaction(function () use ($user, $data, $source, $completeOnboarding): User {
$lockedUser = User::query()->lockForUpdate()->findOrFail($user->getKey());
$now = now();
if ($completeOnboarding && $lockedUser->hasCompletedNutritionOnboarding()) {
return $lockedUser->load(['activeNutritionPlan', 'latestWeightEntry']);
}
$lockedUser->update([
'height' => $data['heightCm'],
'target_weight' => $data['targetWeightKg'] ?? null,
'date_of_birth' => $data['dateOfBirth'],
'sex' => $data['sex'],
'physical_activity_level' => $data['physicalActivityLevel'],
'weight_goal' => $data['weightGoal'],
'pace_preference' => $data['pacePreference'],
...($completeOnboarding ? [
'onboarding_completed_at' => $now,
'nutrition_estimate_accepted_at' => $now,
] : []),
]);
$weightKg = (float) $data['weightKg'];
$latestWeight = $lockedUser->weightEntries()->latest('measured_at')->first();
if ($latestWeight === null || abs($latestWeight->weight_kg - $weightKg) >= 0.01) {
$lockedUser->weightEntries()->create([
'weight_kg' => $weightKg,
'measured_at' => $now,
]);
}
$lockedUser->nutritionPlans()
->where('is_active', true)
->update([
'is_active' => false,
'effective_until' => $now,
]);
$calculation = $this->calculator->calculate(
weightKg: $weightKg,
heightCm: (int) $data['heightCm'],
dateOfBirth: CarbonImmutable::parse($data['dateOfBirth']),
sex: UserSex::from($data['sex']),
activityLevel: PhysicalActivityLevel::from($data['physicalActivityLevel']),
weightGoal: WeightGoal::from($data['weightGoal']),
pacePreference: PacePreference::from($data['pacePreference']),
);
$lockedUser->nutritionPlans()->create([
...$calculation,
'source' => $source,
'is_active' => true,
'effective_from' => $now,
]);
return $lockedUser->fresh()->load(['activeNutritionPlan', 'latestWeightEntry']);
}, attempts: 3);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App\Enums;
enum NutritionPlanSource: string
{
case ONBOARDING = 'onboarding';
case PROFILE_RECALCULATION = 'profile_recalculation';
case WEEKLY_ADJUSTMENT = 'weekly_adjustment';
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App\Enums;
enum WeeklyReviewStatus: string
{
case INSUFFICIENT_DATA = 'insufficient_data';
case ON_TRACK = 'on_track';
case ADJUSTMENT_RECOMMENDED = 'adjustment_recommended';
}
@@ -2,12 +2,7 @@
namespace App\Filament\Resources\Users\Schemas;
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserRole;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
@@ -65,82 +60,11 @@ class UserForm
->label(__('admin.users.fields.email_verified_at')),
]),
Section::make(__('admin.users.sections.profile'))
->columns(2)
->schema([
Textarea::make('bio')
->label(__('admin.users.fields.bio'))
->rows(4)
->columnSpanFull(),
TextInput::make('height')
->label(__('admin.users.fields.height'))
->integer()
->minValue(0)
->maxValue(300)
->suffix('cm'),
DatePicker::make('date_of_birth')
->label(__('admin.users.fields.date_of_birth'))
->minDate('1900-01-01')
->maxDate(now()->subDay()),
Select::make('sex')
->label(__('admin.users.fields.sex'))
->options(UserSex::class)
->default(UserSex::UNKNOWN->value)
->required(),
]),
Section::make(__('admin.users.sections.nutrition_goals'))
->columns(4)
->schema([
TextInput::make('daily_calorie_goal')
->label(__('admin.users.fields.daily_calorie_goal'))
->integer()
->minValue(0)
->maxValue(100000)
->suffix('kcal')
->default(2000)
->required(),
TextInput::make('daily_protein_goal')
->label(__('admin.users.fields.daily_protein_goal'))
->numeric()
->minValue(0)
->maxValue(10000)
->suffix('g')
->default(120)
->required(),
TextInput::make('daily_carbs_goal')
->label(__('admin.users.fields.daily_carbs_goal'))
->numeric()
->minValue(0)
->maxValue(10000)
->suffix('g')
->default(250)
->required(),
TextInput::make('daily_fats_goal')
->label(__('admin.users.fields.daily_fats_goal'))
->numeric()
->minValue(0)
->maxValue(10000)
->suffix('g')
->default(70)
->required(),
]),
Section::make(__('admin.users.sections.activity'))
->columns(3)
->schema([
Select::make('physical_activity_level')
->label(__('admin.users.fields.physical_activity_level'))
->options(PhysicalActivityLevel::class)
->default(PhysicalActivityLevel::SEDENTARY->value)
->required(),
Select::make('weight_goal')
->label(__('admin.users.fields.weight_goal'))
->options(WeightGoal::class)
->default(WeightGoal::LOSE_WEIGHT->value)
->required(),
Select::make('pace_preference')
->label(__('admin.users.fields.pace_preference'))
->options(PacePreference::class)
->default(PacePreference::SLOW->value)
->required(),
]),
]);
}
@@ -67,6 +67,16 @@ class UserInfolist
->numeric(decimalPlaces: 0)
->suffix(' cm')
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('latestWeightEntry.weight_kg')
->label(__('admin.users.fields.current_weight'))
->numeric(maxDecimalPlaces: 2)
->suffix(' kg')
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('target_weight')
->label(__('admin.users.fields.target_weight'))
->numeric(maxDecimalPlaces: 2)
->suffix(' kg')
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('date_of_birth')
->label(__('admin.users.fields.date_of_birth'))
->date()
@@ -75,25 +85,29 @@ class UserInfolist
->label(__('admin.users.fields.sex'))
->badge(),
]),
Section::make(__('admin.users.sections.nutrition_goals'))
Section::make(__('admin.users.sections.nutrition_plan'))
->columns(4)
->schema([
TextEntry::make('daily_calorie_goal')
->label(__('admin.users.fields.daily_calorie_goal'))
TextEntry::make('activeNutritionPlan.calories')
->label(__('admin.users.fields.calorie_goal'))
->numeric(decimalPlaces: 0)
->suffix(' kcal'),
TextEntry::make('daily_protein_goal')
->label(__('admin.users.fields.daily_protein_goal'))
->suffix(' kcal')
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('activeNutritionPlan.proteins')
->label(__('admin.users.fields.protein_goal'))
->numeric(maxDecimalPlaces: 2)
->suffix(' g'),
TextEntry::make('daily_carbs_goal')
->label(__('admin.users.fields.daily_carbs_goal'))
->suffix(' g')
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('activeNutritionPlan.carbs')
->label(__('admin.users.fields.carbs_goal'))
->numeric(maxDecimalPlaces: 2)
->suffix(' g'),
TextEntry::make('daily_fats_goal')
->label(__('admin.users.fields.daily_fats_goal'))
->suffix(' g')
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('activeNutritionPlan.fats')
->label(__('admin.users.fields.fats_goal'))
->numeric(maxDecimalPlaces: 2)
->suffix(' g'),
->suffix(' g')
->placeholder(__('admin.users.placeholders.empty')),
]),
Section::make(__('admin.users.sections.activity'))
->columns(3)
@@ -106,7 +120,12 @@ class UserInfolist
->badge(),
TextEntry::make('pace_preference')
->label(__('admin.users.fields.pace_preference'))
->badge(),
->badge()
->placeholder(__('admin.users.placeholders.empty')),
TextEntry::make('onboarding_completed_at')
->label(__('admin.users.fields.onboarding_completed_at'))
->dateTime()
->placeholder(__('admin.users.placeholders.empty')),
]),
Section::make(__('admin.users.sections.metadata'))
->columns(2)
@@ -95,29 +95,25 @@ class UsersTable
->badge()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('daily_calorie_goal')
->label(__('admin.users.fields.daily_calorie_goal'))
TextColumn::make('activeNutritionPlan.calories')
->label(__('admin.users.fields.calorie_goal'))
->numeric(decimalPlaces: 0)
->suffix(' kcal')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('daily_protein_goal')
->label(__('admin.users.fields.daily_protein_goal'))
TextColumn::make('activeNutritionPlan.proteins')
->label(__('admin.users.fields.protein_goal'))
->numeric(maxDecimalPlaces: 2)
->suffix(' g')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('daily_carbs_goal')
->label(__('admin.users.fields.daily_carbs_goal'))
TextColumn::make('activeNutritionPlan.carbs')
->label(__('admin.users.fields.carbs_goal'))
->numeric(maxDecimalPlaces: 2)
->suffix(' g')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('daily_fats_goal')
->label(__('admin.users.fields.daily_fats_goal'))
TextColumn::make('activeNutritionPlan.fats')
->label(__('admin.users.fields.fats_goal'))
->numeric(maxDecimalPlaces: 2)
->suffix(' g')
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('bio')
->label(__('admin.users.fields.bio'))
+21 -45
View File
@@ -43,7 +43,7 @@ class AuthController extends Controller
$this->startWebSession($request, $user);
return response()->json([
'message' => __('api.auth.registered_unverified'),
'code' => 'REGISTERED_UNVERIFIED',
'user' => new UserResource($user),
], 201);
}
@@ -73,7 +73,7 @@ class AuthController extends Controller
}
return response()->json([
'message' => __('api.auth.registered_unverified'),
'code' => 'REGISTERED_UNVERIFIED',
'token' => $this->createMobileToken($user, $request->validated('device_name')),
'user' => new UserResource($user),
], 201);
@@ -101,7 +101,7 @@ class AuthController extends Controller
if (! hash_equals($hash, sha1($user->getEmailForVerification()))) {
if ($request->expectsJson()) {
return response()->json([
'message' => __('api.auth.invalid_verification_link'),
'code' => 'INVALID_VERIFICATION_LINK',
], 403);
}
@@ -118,9 +118,9 @@ class AuthController extends Controller
if ($request->expectsJson()) {
return response()->json([
'message' => $alreadyVerified
? __('api.auth.already_verified')
: __('api.auth.verified'),
'code' => $alreadyVerified
? 'EMAIL_ALREADY_VERIFIED'
: 'EMAIL_VERIFIED',
'user' => new UserResource($user->fresh()),
]);
}
@@ -141,7 +141,7 @@ class AuthController extends Controller
}
return response()->json([
'message' => __('api.auth.verification_sent_if_unverified'),
'code' => 'VERIFICATION_EMAIL_SENT_IF_UNVERIFIED',
]);
}
@@ -152,12 +152,12 @@ class AuthController extends Controller
if ($status === Password::RESET_THROTTLED) {
return response()->json([
'message' => __($status),
'code' => 'PASSWORD_RESET_THROTTLED',
], 429);
}
return response()->json([
'message' => __('api.auth.password_reset_link_sent'),
'code' => 'PASSWORD_RESET_LINK_SENT',
]);
}
@@ -167,12 +167,12 @@ class AuthController extends Controller
if ($status !== Password::PASSWORD_RESET) {
return response()->json([
'message' => __($status),
'code' => 'PASSWORD_RESET_FAILED',
], 422);
}
return response()->json([
'message' => __('api.auth.password_reset'),
'code' => 'PASSWORD_RESET',
]);
}
@@ -228,7 +228,7 @@ class AuthController extends Controller
}
return response()->json([
'message' => __('api.auth.logout'),
'code' => 'LOGGED_OUT',
]);
}
@@ -237,7 +237,7 @@ class AuthController extends Controller
$user = auth()->user();
if (! $user) {
return response()->json(['message' => __('api.auth.unauthenticated')], 401);
return response()->json(['code' => 'UNAUTHENTICATED'], 401);
}
return new UserResource($user);
@@ -247,10 +247,9 @@ class AuthController extends Controller
{
$user = $request->user();
abort_if($user->isSuspended(), 403, __('api.auth.suspended'));
abort_if($user->isSuspended(), 403, 'ACCOUNT_SUSPENDED');
$data = $request->validated();
$nutritionGoals = $data['nutritionGoals'] ?? null;
if ($request->hasFile('avatar')) {
if ($user->avatar_url) {
@@ -263,13 +262,6 @@ class AuthController extends Controller
$userAttributes = $this->userAttributesFromRequestData($data);
if (is_array($nutritionGoals)) {
$userAttributes['daily_calorie_goal'] = $nutritionGoals['calories'];
$userAttributes['daily_protein_goal'] = $nutritionGoals['proteins'];
$userAttributes['daily_carbs_goal'] = $nutritionGoals['carbs'];
$userAttributes['daily_fats_goal'] = $nutritionGoals['fats'];
}
if (! empty($userAttributes)) {
$user->update($userAttributes);
}
@@ -281,7 +273,7 @@ class AuthController extends Controller
{
$user = $request->user();
abort_if($user->isSuspended(), 403, __('api.auth.suspended'));
abort_if($user->isSuspended(), 403, 'ACCOUNT_SUSPENDED');
$currentAccessToken = $user->currentAccessToken();
@@ -299,7 +291,7 @@ class AuthController extends Controller
}
return response()->json([
'message' => __('api.auth.password_updated'),
'code' => 'PASSWORD_UPDATED',
]);
}
@@ -350,7 +342,7 @@ class AuthController extends Controller
}
return response()->json([
'message' => __('api.auth.deleted'),
'code' => 'ACCOUNT_DELETED',
]);
}
@@ -382,7 +374,7 @@ class AuthController extends Controller
}
return response()->json([
'message' => __('api.auth.verification_email_failed'),
'code' => 'VERIFICATION_EMAIL_FAILED',
], 503);
}
@@ -398,13 +390,13 @@ class AuthController extends Controller
if (! $user || ! Hash::check((string) $data['password'], $user->password)) {
return response()->json([
'message' => __('api.auth.invalid_credentials'),
'code' => 'INVALID_CREDENTIALS',
], 401);
}
if ($user->isSuspended()) {
return response()->json([
'message' => __('api.auth.suspended'),
'code' => 'ACCOUNT_SUSPENDED',
], 403);
}
@@ -414,7 +406,7 @@ class AuthController extends Controller
if (! $user->hasVerifiedEmail()) {
return response()->json([
'message' => __('api.auth.email_not_verified'),
'code' => 'EMAIL_NOT_VERIFIED',
], 403);
}
@@ -480,25 +472,9 @@ class AuthController extends Controller
'name',
'avatar_url',
'locale',
'height',
'bio',
'sex',
'date_of_birth',
]);
$attributeMap = [
'physicalActivityLevel' => 'physical_activity_level',
'weightGoal' => 'weight_goal',
'pacePreference' => 'pace_preference',
'dateOfBirth' => 'date_of_birth',
];
foreach ($attributeMap as $requestKey => $attribute) {
if (array_key_exists($requestKey, $data)) {
$attributes[$attribute] = $data[$requestKey];
}
}
return $attributes;
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Controllers;
use App\Actions\CompleteNutritionOnboarding;
use App\Http\Requests\CompleteNutritionOnboardingRequest;
use App\Http\Resources\UserResource;
class NutritionOnboardingController extends Controller
{
public function __invoke(
CompleteNutritionOnboardingRequest $request,
CompleteNutritionOnboarding $completeNutritionOnboarding,
): UserResource {
return new UserResource(
$completeNutritionOnboarding->execute($request->user(), $request->validated())
);
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers;
use App\Http\Resources\NutritionPlanResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class NutritionPlanController extends Controller
{
public function index(Request $request): AnonymousResourceCollection
{
return NutritionPlanResource::collection(
$request->user()->nutritionPlans()->latest('effective_from')->limit(50)->get()
);
}
public function current(Request $request): NutritionPlanResource
{
$plan = $request->user()->nutritionPlans()->where('is_active', true)->latest('effective_from')->firstOrFail();
return new NutritionPlanResource($plan);
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers;
use App\Actions\RecalculateNutritionPlan;
use App\Enums\NutritionPlanSource;
use App\Http\Requests\UpdateNutritionProfileRequest;
use App\Http\Resources\UserResource;
class NutritionProfileController extends Controller
{
public function __invoke(
UpdateNutritionProfileRequest $request,
RecalculateNutritionPlan $recalculateNutritionPlan,
): UserResource {
return new UserResource($recalculateNutritionPlan->execute(
user: $request->user(),
data: $request->validated(),
source: NutritionPlanSource::PROFILE_RECALCULATION,
));
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers;
use App\Actions\AcceptWeeklyReviewAdjustment;
use App\Http\Resources\NutritionPlanResource;
use App\Http\Resources\WeeklyReviewResource;
use App\Models\WeeklyReview;
use App\Services\WeeklyReviewService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class WeeklyReviewController extends Controller
{
public function index(Request $request): AnonymousResourceCollection
{
return WeeklyReviewResource::collection(
$request->user()->weeklyReviews()->latest('period_start')->limit(52)->get()
);
}
public function current(Request $request, WeeklyReviewService $weeklyReviewService): JsonResponse
{
return (new WeeklyReviewResource($weeklyReviewService->generate($request->user())))
->response()
->setStatusCode(200);
}
public function accept(
Request $request,
WeeklyReview $weeklyReview,
AcceptWeeklyReviewAdjustment $acceptWeeklyReviewAdjustment,
): NutritionPlanResource {
abort_unless($weeklyReview->user_id === $request->user()->getKey(), 404);
return new NutritionPlanResource($acceptWeeklyReviewAdjustment->execute($weeklyReview));
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ListWeightEntriesRequest;
use App\Http\Requests\StoreWeightEntryRequest;
use App\Http\Resources\WeightEntryResource;
use App\Models\WeightEntry;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
class WeightEntryController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(ListWeightEntriesRequest $request): AnonymousResourceCollection
{
$from = now()->subDays($request->integer('days', 365))->startOfDay();
$entries = $request->user()
->weightEntries()
->where('measured_at', '>=', $from)
->latest('measured_at')
->get();
return WeightEntryResource::collection($entries);
}
/**
* Store a newly created resource in storage.
*/
public function store(StoreWeightEntryRequest $request): WeightEntryResource
{
$entry = $request->user()->weightEntries()->create([
'weight_kg' => $request->validated('weightKg'),
'measured_at' => CarbonImmutable::parse($request->validated('measuredAt') ?? now()),
]);
return new WeightEntryResource($entry);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Request $request, WeightEntry $weightEntry): Response
{
abort_unless($weightEntry->user_id === $request->user()->getKey(), 404);
$weightEntry->delete();
return response()->noContent();
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureNutritionOnboardingCompleted
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->hasCompletedNutritionOnboarding()) {
return response()->json([
'code' => 'ONBOARDING_REQUIRED',
], 409);
}
return $next($request);
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Http\Requests;
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
class CompleteNutritionOnboardingRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'dateOfBirth' => [
'required',
'date_format:Y-m-d',
'before_or_equal:'.now()->subYears(18)->toDateString(),
'after_or_equal:'.now()->subYears(100)->toDateString(),
],
'sex' => ['required', Rule::in([UserSex::MAN->value, UserSex::WOMAN->value])],
'heightCm' => ['required', 'integer', 'min:120', 'max:230'],
'weightKg' => ['required', 'numeric', 'min:35', 'max:300'],
'targetWeightKg' => ['nullable', 'numeric', 'min:35', 'max:300'],
'physicalActivityLevel' => ['required', Rule::enum(PhysicalActivityLevel::class)],
'weightGoal' => ['required', Rule::enum(WeightGoal::class)],
'pacePreference' => ['required', Rule::enum(PacePreference::class)],
'nutritionEstimateAccepted' => ['required', 'accepted'],
];
}
public function after(): array
{
return [
function (Validator $validator): void {
$weight = $this->float('weightKg');
$targetWeight = $this->input('targetWeightKg');
$goal = $this->string('weightGoal')->toString();
if ($targetWeight === null || $targetWeight === '') {
return;
}
$targetWeight = (float) $targetWeight;
if ($goal === WeightGoal::LOSE_WEIGHT->value && $targetWeight >= $weight) {
$validator->errors()->add('targetWeightKg', 'NUTRITION_TARGET_WEIGHT_MUST_BE_LOWER');
}
if ($goal === WeightGoal::GAIN_WEIGHT->value && $targetWeight <= $weight) {
$validator->errors()->add('targetWeightKg', 'NUTRITION_TARGET_WEIGHT_MUST_BE_HIGHER');
}
},
];
}
public function messages(): array
{
return [
'dateOfBirth.before_or_equal' => 'NUTRITION_ADULTS_ONLY',
'dateOfBirth.after_or_equal' => 'NUTRITION_BIRTH_DATE_OUT_OF_RANGE',
'sex.in' => 'NUTRITION_METABOLIC_SEX_REQUIRED',
'nutritionEstimateAccepted.accepted' => 'NUTRITION_ESTIMATE_ACCEPTANCE_REQUIRED',
];
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ListWeightEntriesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return $this->user()?->hasCompletedNutritionOnboarding() === true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'days' => ['sometimes', 'integer', 'min:7', 'max:3650'],
];
}
}
-9
View File
@@ -2,10 +2,6 @@
namespace App\Http\Requests;
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use App\Http\Requests\Concerns\ModeratesUserContent;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -56,11 +52,6 @@ class RegisterRequest extends FormRequest
'termsAccepted' => ['required', 'accepted'],
'avatar' => ['sometimes', 'nullable', 'image', 'max:2048'],
'bio' => ['nullable', 'string'],
'physicalActivityLevel' => ['sometimes', Rule::enum(PhysicalActivityLevel::class)],
'weightGoal' => ['sometimes', Rule::enum(WeightGoal::class)],
'pacePreference' => ['sometimes', Rule::enum(PacePreference::class)],
'sex' => ['sometimes', Rule::enum(UserSex::class)],
'dateOfBirth' => ['sometimes', 'nullable', 'date_format:Y-m-d', 'before:today', 'after:1900-01-01'],
];
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreWeightEntryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return $this->user()?->hasCompletedNutritionOnboarding() === true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'weightKg' => ['required', 'numeric', 'min:35', 'max:300'],
'measuredAt' => ['sometimes', 'nullable', 'date', 'before_or_equal:now'],
];
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Http\Requests;
class UpdateNutritionProfileRequest extends CompleteNutritionOnboardingRequest
{
public function rules(): array
{
$rules = parent::rules();
unset($rules['nutritionEstimateAccepted']);
return $rules;
}
}
+9 -20
View File
@@ -2,10 +2,6 @@
namespace App\Http\Requests;
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use App\Http\Requests\Concerns\ModeratesUserContent;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -22,27 +18,24 @@ class UpdateUserRequest extends FormRequest
public function rules(): array
{
return [
'name' => [
'sometimes',
'string',
'min:3',
'max:32',
'regex:/^[a-zA-Z0-9_.-]+$/',
Rule::unique('users', 'name')->ignore($this->user()),
],
'bio' => ['sometimes', 'nullable', 'string'],
'height' => ['sometimes', 'nullable', 'integer'],
'locale' => ['sometimes', 'string', Rule::in(config('app.supported_locales', ['fr', 'en']))],
'avatar' => ['sometimes', 'nullable', 'image', 'max:2048'],
'nutritionGoals' => ['sometimes', 'array'],
'nutritionGoals.calories' => ['required_with:nutritionGoals', 'integer', 'min:0', 'max:100000'],
'nutritionGoals.proteins' => ['required_with:nutritionGoals', 'numeric', 'min:0', 'max:10000'],
'nutritionGoals.carbs' => ['required_with:nutritionGoals', 'numeric', 'min:0', 'max:10000'],
'nutritionGoals.fats' => ['required_with:nutritionGoals', 'numeric', 'min:0', 'max:10000'],
'physicalActivityLevel' => ['sometimes', Rule::enum(PhysicalActivityLevel::class)],
'weightGoal' => ['sometimes', Rule::enum(WeightGoal::class)],
'pacePreference' => ['sometimes', Rule::enum(PacePreference::class)],
'sex' => ['sometimes', Rule::enum(UserSex::class)],
'dateOfBirth' => ['sometimes', 'nullable', 'date_format:Y-m-d', 'before:today', 'after:1900-01-01'],
];
}
public function after(): array
{
return $this->moderationChecks(
[$this->input('bio')],
[$this->input('name'), $this->input('bio')],
[$this->file('avatar')],
);
}
@@ -51,10 +44,6 @@ class UpdateUserRequest extends FormRequest
{
return [
'avatar.max' => __('api.validation.image_max_2mb'),
'nutritionGoals.calories.integer' => __('api.validation.calories_integer'),
'nutritionGoals.*.required_with' => __('api.validation.nutrition_goals_required'),
'nutritionGoals.*.min' => __('api.validation.nutrition_goals_positive'),
'nutritionGoals.*.max' => __('api.validation.nutrition_goals_max'),
];
}
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Resources;
use App\Models\NutritionPlan;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin NutritionPlan */
class NutritionPlanResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'source' => $this->source,
'formulaVersion' => $this->formula_version,
'calories' => $this->calories,
'proteins' => $this->proteins,
'carbs' => $this->carbs,
'fats' => $this->fats,
'restingMetabolism' => $this->resting_metabolism,
'maintenanceCalories' => $this->maintenance_calories,
'calorieAdjustmentPercent' => $this->calorie_adjustment_percent,
'calculationDetails' => $this->calculation_details,
'effectiveFrom' => $this->effective_from?->toISOString(),
'effectiveUntil' => $this->effective_until?->toISOString(),
'isActive' => $this->is_active,
];
}
}
+22 -10
View File
@@ -15,14 +15,19 @@ class UserResource extends JsonResource
*/
public function toArray(Request $request): array
{
$this->resource->loadMissing(['activeNutritionPlan', 'latestWeightEntry']);
$nutritionPlan = $this->activeNutritionPlan;
return [
'id' => $this->id, // à voir si suppression par la suite
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'locale' => $this->locale,
'emailVerified' => $this->hasVerifiedEmail(),
'emailVerifiedAt' => $this->email_verified_at?->toISOString(),
'height' => $this->height,
'currentWeight' => $this->latestWeightEntry?->weight_kg,
'targetWeight' => $this->target_weight,
'avatarUrl' => $this->avatar_url ? asset(Storage::url($this->avatar_url)) : null,
'bio' => $this->bio,
'role' => $this->role,
@@ -38,20 +43,27 @@ class UserResource extends JsonResource
'hasActiveSubscription' => $this->hasActiveSubscription(),
'suspendedAt' => $this->suspended_at?->toISOString(),
'physicalActivityLevel' => $this->physical_activity_level,
'physicalActivityLevelLabel' => $this->physical_activity_level?->getLabel(),
'weightGoal' => $this->weight_goal,
'weightGoalLabel' => $this->weight_goal?->getLabel(),
'pacePreference' => $this->pace_preference,
'pacePreferenceLabel' => $this->pace_preference?->getLabel(),
'sex' => $this->sex,
'sexLabel' => $this->sex?->getLabel(),
'dateOfBirth' => $this->date_of_birth?->toDateString(),
'nutritionGoals' => [
'calories' => (int) $this->daily_calorie_goal,
'proteins' => (float) $this->daily_protein_goal,
'carbs' => (float) $this->daily_carbs_goal,
'fats' => (float) $this->daily_fats_goal,
'onboardingStatus' => $this->hasCompletedNutritionOnboarding() ? 'completed' : 'required',
'missingOnboardingFields' => $this->hasCompletedNutritionOnboarding() ? [] : [
'dateOfBirth',
'sex',
'heightCm',
'weightKg',
'physicalActivityLevel',
'weightGoal',
'pacePreference',
],
'nutritionPlan' => NutritionPlanResource::make($nutritionPlan),
'nutritionGoals' => $nutritionPlan ? [
'calories' => $nutritionPlan->calories,
'proteins' => $nutritionPlan->proteins,
'carbs' => $nutritionPlan->carbs,
'fats' => $nutritionPlan->fats,
] : null,
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Http\Resources;
use App\Models\WeeklyReview;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin WeeklyReview */
class WeeklyReviewResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'periodStart' => $this->period_start?->toDateString(),
'periodEnd' => $this->period_end?->toDateString(),
'averages' => [
'calories' => $this->average_calories,
'proteins' => $this->average_proteins,
'carbs' => $this->average_carbs,
'fats' => $this->average_fats,
],
'loggedDaysCount' => $this->logged_days_count,
'weightEntriesCount' => $this->weight_entries_count,
'weightTrendKg' => $this->weight_trend_kg,
'targetWeightTrendKg' => $this->target_weight_trend_kg,
'status' => $this->status,
'recommendedCalorieAdjustment' => $this->recommended_calorie_adjustment,
'messageCode' => $this->message_code,
'metrics' => $this->metrics,
'generatedAt' => $this->generated_at?->toISOString(),
'acceptedAt' => $this->accepted_at?->toISOString(),
'acceptedNutritionPlanId' => $this->accepted_nutrition_plan_id,
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Resources;
use App\Models\WeightEntry;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin WeightEntry */
class WeightEntryResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'weightKg' => $this->weight_kg,
'source' => $this->source,
'measuredAt' => $this->measured_at?->toISOString(),
'createdAt' => $this->created_at?->toISOString(),
];
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Models;
use App\Enums\NutritionPlanSource;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class NutritionPlan extends Model
{
/** @use HasFactory<\Database\Factories\NutritionPlanFactory> */
use HasFactory, HasUlids;
protected $fillable = [
'user_id',
'source',
'formula_version',
'calories',
'proteins',
'carbs',
'fats',
'resting_metabolism',
'maintenance_calories',
'calorie_adjustment_percent',
'calculation_details',
'is_active',
'effective_from',
'effective_until',
];
protected $attributes = [
'is_active' => true,
];
protected function casts(): array
{
return [
'source' => NutritionPlanSource::class,
'calories' => 'integer',
'proteins' => 'float',
'carbs' => 'float',
'fats' => 'float',
'resting_metabolism' => 'integer',
'maintenance_calories' => 'integer',
'calorie_adjustment_percent' => 'float',
'calculation_details' => 'array',
'is_active' => 'boolean',
'effective_from' => 'immutable_datetime',
'effective_until' => 'immutable_datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function weeklyReviews(): HasMany
{
return $this->hasMany(WeeklyReview::class);
}
}
+39 -8
View File
@@ -51,6 +51,7 @@ class User extends Authenticatable implements FilamentUser, HasAvatar, HasLocale
'password',
'avatar_url',
'height',
'target_weight',
'bio',
'account_verified_at',
'certification_purchased_at',
@@ -58,15 +59,13 @@ class User extends Authenticatable implements FilamentUser, HasAvatar, HasLocale
'subscription_store',
'subscription_expires_at',
'subscription_is_trial',
'daily_calorie_goal',
'daily_protein_goal',
'daily_carbs_goal',
'daily_fats_goal',
'physical_activity_level',
'weight_goal',
'pace_preference',
'sex',
'date_of_birth',
'onboarding_completed_at',
'nutrition_estimate_accepted_at',
'terms_accepted_at',
'social_notifications_enabled',
'engagement_reminders_enabled',
@@ -97,16 +96,16 @@ class User extends Authenticatable implements FilamentUser, HasAvatar, HasLocale
'account_verified_at' => 'datetime',
'certification_purchased_at' => 'datetime',
'password' => 'hashed',
'daily_calorie_goal' => 'integer',
'daily_protein_goal' => 'float',
'daily_carbs_goal' => 'float',
'daily_fats_goal' => 'float',
'height' => 'integer',
'target_weight' => 'float',
'physical_activity_level' => PhysicalActivityLevel::class,
'weight_goal' => WeightGoal::class,
'pace_preference' => PacePreference::class,
'sex' => UserSex::class,
'role' => UserRole::class,
'date_of_birth' => 'immutable_date',
'onboarding_completed_at' => 'datetime',
'nutrition_estimate_accepted_at' => 'datetime',
'terms_accepted_at' => 'datetime',
'social_notifications_enabled' => 'boolean',
'engagement_reminders_enabled' => 'boolean',
@@ -146,6 +145,38 @@ class User extends Authenticatable implements FilamentUser, HasAvatar, HasLocale
return $this->hasMany(WorkoutSessions::class);
}
public function nutritionPlans(): HasMany
{
return $this->hasMany(NutritionPlan::class);
}
public function activeNutritionPlan(): HasOne
{
return $this->hasOne(NutritionPlan::class)
->where('is_active', true)
->latestOfMany('effective_from');
}
public function weightEntries(): HasMany
{
return $this->hasMany(WeightEntry::class);
}
public function latestWeightEntry(): HasOne
{
return $this->hasOne(WeightEntry::class)->latestOfMany('measured_at');
}
public function weeklyReviews(): HasMany
{
return $this->hasMany(WeeklyReview::class);
}
public function hasCompletedNutritionOnboarding(): bool
{
return $this->onboarding_completed_at !== null;
}
public function stravaConnection(): HasOne
{
return $this->hasOne(StravaConnection::class);
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Models;
use App\Enums\WeeklyReviewStatus;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class WeeklyReview extends Model
{
/** @use HasFactory<\Database\Factories\WeeklyReviewFactory> */
use HasFactory, HasUlids;
protected $fillable = [
'user_id',
'nutrition_plan_id',
'period_start',
'period_end',
'average_calories',
'average_proteins',
'average_carbs',
'average_fats',
'logged_days_count',
'weight_entries_count',
'weight_trend_kg',
'target_weight_trend_kg',
'status',
'recommended_calorie_adjustment',
'message_code',
'metrics',
'generated_at',
'accepted_at',
'accepted_nutrition_plan_id',
];
protected function casts(): array
{
return [
'period_start' => 'immutable_date',
'period_end' => 'immutable_date',
'average_calories' => 'float',
'average_proteins' => 'float',
'average_carbs' => 'float',
'average_fats' => 'float',
'logged_days_count' => 'integer',
'weight_entries_count' => 'integer',
'weight_trend_kg' => 'float',
'target_weight_trend_kg' => 'float',
'status' => WeeklyReviewStatus::class,
'recommended_calorie_adjustment' => 'integer',
'metrics' => 'array',
'generated_at' => 'immutable_datetime',
'accepted_at' => 'immutable_datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function nutritionPlan(): BelongsTo
{
return $this->belongsTo(NutritionPlan::class);
}
public function acceptedNutritionPlan(): BelongsTo
{
return $this->belongsTo(NutritionPlan::class, 'accepted_nutrition_plan_id');
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class WeightEntry extends Model
{
/** @use HasFactory<\Database\Factories\WeightEntryFactory> */
use HasFactory, HasUlids;
protected $fillable = [
'user_id',
'weight_kg',
'source',
'measured_at',
];
protected $attributes = [
'source' => 'manual',
];
protected function casts(): array
{
return [
'weight_kg' => 'float',
'measured_at' => 'immutable_datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
namespace App\Services;
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use Carbon\CarbonInterface;
use InvalidArgumentException;
class NutritionPlanCalculator
{
public const FORMULA_VERSION = 'mifflin_st_jeor_v1';
/**
* @return array{
* formula_version: string,
* calories: int,
* proteins: float,
* carbs: float,
* fats: float,
* resting_metabolism: int,
* maintenance_calories: int,
* calorie_adjustment_percent: float,
* calculation_details: array<string, float|int|string>
* }
*/
public function calculate(
float $weightKg,
int $heightCm,
CarbonInterface $dateOfBirth,
UserSex $sex,
PhysicalActivityLevel $activityLevel,
WeightGoal $weightGoal,
PacePreference $pacePreference,
): array {
$sexCoefficient = match ($sex) {
UserSex::MAN => 5,
UserSex::WOMAN => -161,
default => throw new InvalidArgumentException('A metabolic calculation reference is required.'),
};
$age = (int) $dateOfBirth->diffInYears(now());
$restingMetabolism = (int) round(
(10 * $weightKg) + (6.25 * $heightCm) - (5 * $age) + $sexCoefficient
);
$activityFactor = $this->activityFactor($activityLevel);
$maintenanceCalories = (int) (round(($restingMetabolism * $activityFactor) / 10) * 10);
$adjustmentPercent = $this->calorieAdjustmentPercent($weightGoal, $pacePreference);
$unboundedCalories = (int) (round(($maintenanceCalories * (1 + $adjustmentPercent)) / 10) * 10);
$minimumCalories = max(1200, (int) (ceil(($restingMetabolism * 0.8) / 10) * 10));
$calorieTarget = max($minimumCalories, $unboundedCalories);
$heightMeters = $heightCm / 100;
$proteinReferenceWeight = min($weightKg, 25 * ($heightMeters ** 2));
$proteinFactor = $this->proteinFactor($activityLevel, $weightGoal);
$proteins = max(1, (int) round($proteinReferenceWeight * $proteinFactor));
$fats = max(1, (int) round(($calorieTarget * 0.25) / 9));
$carbs = max(0, (int) round(($calorieTarget - ($proteins * 4) - ($fats * 9)) / 4));
$macroCalories = ($proteins * 4) + ($carbs * 4) + ($fats * 9);
return [
'formula_version' => self::FORMULA_VERSION,
'calories' => $macroCalories,
'proteins' => $proteins,
'carbs' => $carbs,
'fats' => $fats,
'resting_metabolism' => $restingMetabolism,
'maintenance_calories' => $maintenanceCalories,
'calorie_adjustment_percent' => $adjustmentPercent,
'calculation_details' => [
'activityFactor' => $activityFactor,
'ageAtCalculation' => $age,
'heightCm' => $heightCm,
'inputWeightKg' => round($weightKg, 2),
'minimumCalories' => $minimumCalories,
'pacePreference' => $pacePreference->value,
'proteinFactor' => $proteinFactor,
'proteinReferenceWeightKg' => round($proteinReferenceWeight, 2),
'sexReference' => $sex->value,
'weightGoal' => $weightGoal->value,
],
];
}
private function activityFactor(PhysicalActivityLevel $activityLevel): float
{
return match ($activityLevel) {
PhysicalActivityLevel::SEDENTARY => 1.2,
PhysicalActivityLevel::LIGHTLY_ACTIVE => 1.375,
PhysicalActivityLevel::MODERATELY_ACTIVE => 1.55,
PhysicalActivityLevel::VERY_ACTIVE => 1.725,
PhysicalActivityLevel::ATHLETE => 1.9,
};
}
private function calorieAdjustmentPercent(WeightGoal $weightGoal, PacePreference $pacePreference): float
{
if ($weightGoal === WeightGoal::MAINTAIN_WEIGHT) {
return 0;
}
$magnitude = match ($pacePreference) {
PacePreference::SLOW => $weightGoal === WeightGoal::LOSE_WEIGHT ? 0.10 : 0.05,
PacePreference::NORMAL => $weightGoal === WeightGoal::LOSE_WEIGHT ? 0.15 : 0.10,
PacePreference::FAST => $weightGoal === WeightGoal::LOSE_WEIGHT ? 0.20 : 0.15,
};
return $weightGoal === WeightGoal::LOSE_WEIGHT ? -$magnitude : $magnitude;
}
private function proteinFactor(PhysicalActivityLevel $activityLevel, WeightGoal $weightGoal): float
{
$factor = match ($activityLevel) {
PhysicalActivityLevel::SEDENTARY => 1.2,
PhysicalActivityLevel::LIGHTLY_ACTIVE => 1.4,
PhysicalActivityLevel::MODERATELY_ACTIVE => 1.6,
PhysicalActivityLevel::VERY_ACTIVE, PhysicalActivityLevel::ATHLETE => 1.8,
};
$factor += match ($weightGoal) {
WeightGoal::LOSE_WEIGHT => 0.2,
WeightGoal::GAIN_WEIGHT => 0.1,
WeightGoal::MAINTAIN_WEIGHT => 0,
};
return min($factor, 2.0);
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
namespace App\Services;
use App\Enums\PacePreference;
use App\Enums\WeeklyReviewStatus;
use App\Enums\WeightGoal;
use App\Models\MealPosts;
use App\Models\User;
use App\Models\WeeklyReview;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
class WeeklyReviewService
{
/**
* Generate or refresh a review for the last completed week.
*/
public function generate(User $user, ?CarbonImmutable $periodStart = null): WeeklyReview
{
$periodStart ??= CarbonImmutable::now()->subWeek()->startOfWeek(CarbonInterface::MONDAY);
$periodStart = $periodStart->startOfDay();
$periodEnd = $periodStart->endOfWeek(CarbonInterface::SUNDAY);
$existingReview = $user->weeklyReviews()->whereDate('period_start', $periodStart)->first();
if ($existingReview?->accepted_at !== null) {
return $existingReview;
}
$currentPlan = $user->nutritionPlans()->where('is_active', true)->latest('effective_from')->firstOrFail();
$nutritionPlan = $user->nutritionPlans()
->where('effective_from', '<=', $periodEnd)
->latest('effective_from')
->first()
?? $currentPlan;
$meals = MealPosts::query()
->where('user_id', $user->getKey())
->whereBetween('eaten_at', [$periodStart, $periodEnd])
->get(['calories', 'proteins', 'carbs', 'fats', 'eaten_at']);
$loggedDaysCount = $meals->pluck('eaten_at')
->map(fn (CarbonInterface $date): string => $date->toDateString())
->unique()
->count();
$averages = $this->nutritionAverages($meals, $loggedDaysCount);
$weights = $user->weightEntries()
->whereBetween('measured_at', [$periodStart->subWeek(), $periodEnd])
->oldest('measured_at')
->get();
$trend = $this->weightTrend($weights);
$latestWeight = $weights->last()?->weight_kg ?? $user->latestWeightEntry()->value('weight_kg');
$targetTrend = $latestWeight === null ? null : $this->targetWeightTrend(
(float) $latestWeight,
$user->weight_goal,
$user->pace_preference,
);
[$status, $adjustment, $messageCode] = $this->recommendation(
loggedDaysCount: $loggedDaysCount,
weightCount: $weights->count(),
trend: $trend,
targetTrend: $targetTrend,
averageCalories: $averages['calories'],
planCalories: $nutritionPlan->calories,
weightGoal: $user->weight_goal,
);
if ($nutritionPlan->getKey() !== $currentPlan->getKey()) {
$status = WeeklyReviewStatus::INSUFFICIENT_DATA;
$adjustment = 0;
$messageCode = 'WEEKLY_REVIEW_PLAN_CHANGED';
}
return $user->weeklyReviews()->updateOrCreate(
['period_start' => $periodStart->toDateString()],
[
'nutrition_plan_id' => $nutritionPlan->getKey(),
'period_end' => $periodEnd->toDateString(),
'average_calories' => $averages['calories'],
'average_proteins' => $averages['proteins'],
'average_carbs' => $averages['carbs'],
'average_fats' => $averages['fats'],
'logged_days_count' => $loggedDaysCount,
'weight_entries_count' => $weights->count(),
'weight_trend_kg' => $trend,
'target_weight_trend_kg' => $targetTrend,
'status' => $status,
'recommended_calorie_adjustment' => $adjustment,
'message_code' => $messageCode,
'metrics' => [
'analysisStart' => $periodStart->subWeek()->toDateString(),
'analysisEnd' => $periodEnd->toDateString(),
'firstWeightKg' => $weights->first()?->weight_kg,
'lastWeightKg' => $weights->last()?->weight_kg,
'nutritionPlanCalories' => $nutritionPlan->calories,
],
'generated_at' => now(),
],
);
}
/**
* @param Collection<int, MealPosts> $meals
* @return array{calories: float, proteins: float, carbs: float, fats: float}
*/
private function nutritionAverages(Collection $meals, int $loggedDaysCount): array
{
$divisor = max(1, $loggedDaysCount);
return [
'calories' => round((float) $meals->sum('calories') / $divisor, 2),
'proteins' => round((float) $meals->sum('proteins') / $divisor, 2),
'carbs' => round((float) $meals->sum('carbs') / $divisor, 2),
'fats' => round((float) $meals->sum('fats') / $divisor, 2),
];
}
private function weightTrend(Collection $weights): ?float
{
$first = $weights->first();
$last = $weights->last();
if ($weights->count() < 4 || $first === null || $last === null) {
return null;
}
$days = max(1, $first->measured_at->diffInDays($last->measured_at));
if ($days < 7) {
return null;
}
return round((($last->weight_kg - $first->weight_kg) / $days) * 7, 2);
}
private function targetWeightTrend(
float $weightKg,
WeightGoal $weightGoal,
PacePreference $pacePreference,
): float {
$percentage = match ($weightGoal) {
WeightGoal::LOSE_WEIGHT => match ($pacePreference) {
PacePreference::SLOW => -0.0025,
PacePreference::NORMAL => -0.005,
PacePreference::FAST => -0.0075,
},
WeightGoal::GAIN_WEIGHT => match ($pacePreference) {
PacePreference::SLOW => 0.00125,
PacePreference::NORMAL => 0.0025,
PacePreference::FAST => 0.00375,
},
WeightGoal::MAINTAIN_WEIGHT => 0,
};
return round($weightKg * $percentage, 2);
}
/**
* @return array{WeeklyReviewStatus, int, string}
*/
private function recommendation(
int $loggedDaysCount,
int $weightCount,
?float $trend,
?float $targetTrend,
float $averageCalories,
int $planCalories,
WeightGoal $weightGoal,
): array {
if ($loggedDaysCount < 5 || $weightCount < 4 || $trend === null || $targetTrend === null) {
return [
WeeklyReviewStatus::INSUFFICIENT_DATA,
0,
'WEEKLY_REVIEW_INSUFFICIENT_TRACKING',
];
}
$calorieDifferenceRatio = abs($averageCalories - $planCalories) / max(1, $planCalories);
if ($calorieDifferenceRatio > 0.15) {
return [
WeeklyReviewStatus::INSUFFICIENT_DATA,
0,
'WEEKLY_REVIEW_INSUFFICIENT_ADHERENCE',
];
}
$tolerance = $weightGoal === WeightGoal::MAINTAIN_WEIGHT
? 0.2
: max(0.1, abs($targetTrend) * 0.35);
$difference = $trend - $targetTrend;
if (abs($difference) <= $tolerance) {
return [
WeeklyReviewStatus::ON_TRACK,
0,
'WEEKLY_REVIEW_ON_TRACK',
];
}
$adjustment = match ($weightGoal) {
WeightGoal::LOSE_WEIGHT => $difference > 0 ? -100 : 100,
WeightGoal::GAIN_WEIGHT => $difference < 0 ? 100 : -100,
WeightGoal::MAINTAIN_WEIGHT => $trend > 0 ? -100 : 100,
};
return [
WeeklyReviewStatus::ADJUSTMENT_RECOMMENDED,
$adjustment,
$this->adjustmentMessage($weightGoal, $adjustment),
];
}
private function adjustmentMessage(WeightGoal $weightGoal, int $adjustment): string
{
return match ($weightGoal) {
WeightGoal::LOSE_WEIGHT => $adjustment < 0
? 'WEEKLY_REVIEW_LOSS_SLOWER'
: 'WEEKLY_REVIEW_LOSS_FASTER',
WeightGoal::GAIN_WEIGHT => $adjustment > 0
? 'WEEKLY_REVIEW_GAIN_SLOWER'
: 'WEEKLY_REVIEW_GAIN_FASTER',
WeightGoal::MAINTAIN_WEIGHT => $adjustment > 0
? 'WEEKLY_REVIEW_MAINTENANCE_DOWN'
: 'WEEKLY_REVIEW_MAINTENANCE_UP',
};
}
}