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
+16 -32
View File
@@ -1,9 +1,5 @@
<?php
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use App\Mail\VerifyAccount;
use App\Models\User;
use Illuminate\Auth\Notifications\VerifyEmail;
@@ -22,11 +18,6 @@ it('sends a verification email when a user registers', function () {
'email' => 'leon@example.com',
'password' => 'Motsdfdepasse123*',
'locale' => 'fr-FR',
'physicalActivityLevel' => PhysicalActivityLevel::LIGHTLY_ACTIVE->value,
'weightGoal' => WeightGoal::MAINTAIN_WEIGHT->value,
'pacePreference' => PacePreference::NORMAL->value,
'sex' => UserSex::WOMAN->value,
'dateOfBirth' => '2003-04-24',
'termsAccepted' => true,
])
->assertCreated()
@@ -35,11 +26,8 @@ it('sends a verification email when a user registers', function () {
->assertJsonPath('user.emailVerified', false)
->assertJsonPath('user.analysisAccessLevel', 'free')
->assertJsonPath('user.canAnalyzeMeals', false)
->assertJsonPath('user.physicalActivityLevel', PhysicalActivityLevel::LIGHTLY_ACTIVE->value)
->assertJsonPath('user.weightGoal', WeightGoal::MAINTAIN_WEIGHT->value)
->assertJsonPath('user.pacePreference', PacePreference::NORMAL->value)
->assertJsonPath('user.sex', UserSex::WOMAN->value)
->assertJsonPath('user.dateOfBirth', '2003-04-24')
->assertJsonPath('user.onboardingStatus', 'required')
->assertJsonPath('user.nutritionGoals', null)
->assertCookieMissing('token');
$user = User::where('email', 'leon@example.com')->firstOrFail();
@@ -51,13 +39,13 @@ it('sends a verification email when a user registers', function () {
$this->assertDatabaseHas('users', [
'id' => $user->id,
'locale' => 'fr',
'physical_activity_level' => PhysicalActivityLevel::LIGHTLY_ACTIVE->value,
'weight_goal' => WeightGoal::MAINTAIN_WEIGHT->value,
'pace_preference' => PacePreference::NORMAL->value,
'sex' => UserSex::WOMAN->value,
'physical_activity_level' => null,
'weight_goal' => null,
'pace_preference' => null,
'sex' => null,
]);
expect($user->date_of_birth?->toDateString())->toBe('2003-04-24');
expect($user->date_of_birth)->toBeNull();
Notification::assertSentTo($user, VerifyEmail::class);
});
@@ -75,7 +63,7 @@ it('returns a temporary error when the verification email cannot be sent during
'termsAccepted' => true,
])
->assertServiceUnavailable()
->assertJsonPath('message', __('api.auth.verification_email_failed'));
->assertJsonPath('code', 'VERIFICATION_EMAIL_FAILED');
$this->assertDatabaseMissing('users', [
'email' => 'leon@example.com',
@@ -91,16 +79,12 @@ it('registers mobile users with a bearer token', function () {
'password' => 'Motsdfdepasse123*',
'deviceName' => 'Bowli Android',
'locale' => 'fr-FR',
'physicalActivityLevel' => PhysicalActivityLevel::LIGHTLY_ACTIVE->value,
'weightGoal' => WeightGoal::MAINTAIN_WEIGHT->value,
'pacePreference' => PacePreference::NORMAL->value,
'sex' => UserSex::MAN->value,
'dateOfBirth' => '2003-04-24',
'termsAccepted' => true,
])
->assertCreated()
->assertJsonPath('user.email', 'mobile.leon@example.com')
->assertJsonPath('user.emailVerified', false)
->assertJsonPath('user.onboardingStatus', 'required')
->assertJsonStructure(['token'])
->assertCookieMissing('token');
@@ -183,7 +167,7 @@ it('generates verification links with a relative signature', function () {
->withServerVariables(['HTTP_HOST' => 'different-host.test'])
->getJson($requestUrl)
->assertOk()
->assertJsonPath('message', __('api.auth.verified'));
->assertJsonPath('code', 'EMAIL_VERIFIED');
expect($user->fresh()->hasVerifiedEmail())->toBeTrue();
});
@@ -197,7 +181,7 @@ it('verifies a user from a signed email link', function () {
$this->getJson($url)
->assertOk()
->assertJsonPath('message', __('api.auth.verified'))
->assertJsonPath('code', 'EMAIL_VERIFIED')
->assertJsonPath('user.emailVerified', true);
expect($user->fresh()->hasVerifiedEmail())->toBeTrue();
@@ -225,7 +209,7 @@ it('blocks login for unverified users', function () {
'password' => 'password',
])
->assertForbidden()
->assertJsonPath('message', __('api.auth.email_not_verified'))
->assertJsonPath('code', 'EMAIL_NOT_VERIFIED')
->assertCookieMissing('token');
$this->assertDatabaseMissing('personal_access_tokens', [
@@ -288,7 +272,7 @@ it('logs out mobile users by deleting the current bearer token', function () {
->withToken($token)
->postJson('/api/auth/logout')
->assertOk()
->assertJsonPath('message', __('api.auth.logout'));
->assertJsonPath('code', 'LOGGED_OUT');
$this->assertDatabaseMissing('personal_access_tokens', [
'name' => 'Bowli iOS',
@@ -305,7 +289,7 @@ it('resends a verification email for an unverified user without authentication',
'email' => $user->email,
])
->assertOk()
->assertJsonPath('message', __('api.auth.verification_sent_if_unverified'));
->assertJsonPath('code', 'VERIFICATION_EMAIL_SENT_IF_UNVERIFIED');
Notification::assertSentTo($user, VerifyEmail::class);
});
@@ -319,13 +303,13 @@ it('does not reveal whether an email can receive a verification email', function
'email' => $verifiedUser->email,
])
->assertOk()
->assertJsonPath('message', __('api.auth.verification_sent_if_unverified'));
->assertJsonPath('code', 'VERIFICATION_EMAIL_SENT_IF_UNVERIFIED');
$this->postJson('/api/auth/email/verification-notification', [
'email' => 'missing@example.com',
])
->assertOk()
->assertJsonPath('message', __('api.auth.verification_sent_if_unverified'));
->assertJsonPath('code', 'VERIFICATION_EMAIL_SENT_IF_UNVERIFIED');
Notification::assertNothingSent();
});
+93
View File
@@ -0,0 +1,93 @@
<?php
use App\Enums\PacePreference;
use App\Enums\PhysicalActivityLevel;
use App\Enums\UserSex;
use App\Enums\WeightGoal;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
uses(RefreshDatabase::class);
function onboardingPayload(array $overrides = []): array
{
return [
'dateOfBirth' => '1992-04-18',
'sex' => UserSex::WOMAN->value,
'heightCm' => 168,
'weightKg' => 72.4,
'targetWeightKg' => 66,
'physicalActivityLevel' => PhysicalActivityLevel::MODERATELY_ACTIVE->value,
'weightGoal' => WeightGoal::LOSE_WEIGHT->value,
'pacePreference' => PacePreference::NORMAL->value,
'nutritionEstimateAccepted' => true,
...$overrides,
];
}
it('returns an explicit onboarding state and blocks application endpoints', function () {
$user = User::factory()->withoutNutritionOnboarding()->create();
Sanctum::actingAs($user);
$this->getJson('/api/auth/me')
->assertOk()
->assertJsonPath('data.onboardingStatus', 'required')
->assertJsonPath('data.nutritionGoals', null)
->assertJsonPath('data.currentWeight', null);
$this->getJson('/api/meal-posts/stats?period=day&date=2026-08-14')
->assertStatus(409)
->assertJsonPath('code', 'ONBOARDING_REQUIRED')
->assertJsonMissingPath('message');
});
it('completes onboarding atomically and returns the calculated plan', function () {
$user = User::factory()->withoutNutritionOnboarding()->create();
Sanctum::actingAs($user);
$response = $this->postJson('/api/nutrition-onboarding', onboardingPayload());
$response
->assertOk()
->assertJsonPath('data.onboardingStatus', 'completed')
->assertJsonPath('data.height', 168)
->assertJsonPath('data.currentWeight', 72.4)
->assertJsonPath('data.targetWeight', 66)
->assertJsonPath('data.nutritionPlan.formulaVersion', 'mifflin_st_jeor_v1')
->assertJsonPath('data.nutritionPlan.source', 'onboarding');
expect($response->json('data.nutritionGoals.calories'))->toBeGreaterThan(1200);
$this->assertDatabaseCount('weight_entries', 1);
$this->assertDatabaseCount('nutrition_plans', 1);
expect($user->fresh()->onboarding_completed_at)->not->toBeNull();
});
it('is idempotent when the completion response is retried', function () {
$user = User::factory()->withoutNutritionOnboarding()->create();
Sanctum::actingAs($user);
$this->postJson('/api/nutrition-onboarding', onboardingPayload())->assertOk();
$this->postJson('/api/nutrition-onboarding', onboardingPayload())->assertOk();
$this->assertDatabaseCount('weight_entries', 1);
$this->assertDatabaseCount('nutrition_plans', 1);
});
it('validates adult age, formula reference and target direction', function () {
Sanctum::actingAs(User::factory()->withoutNutritionOnboarding()->create());
$this->postJson('/api/nutrition-onboarding', onboardingPayload([
'dateOfBirth' => now()->subYears(17)->toDateString(),
'sex' => UserSex::OTHER->value,
'targetWeightKg' => 80,
]))
->assertUnprocessable()
->assertJsonValidationErrors(['dateOfBirth', 'sex', 'targetWeightKg'])
->assertJsonPath('code', 'VALIDATION_ERROR')
->assertJsonPath('errors.dateOfBirth.0', 'NUTRITION_ADULTS_ONLY')
->assertJsonPath('errors.sex.0', 'NUTRITION_METABOLIC_SEX_REQUIRED')
->assertJsonPath('errors.targetWeightKg.0', 'NUTRITION_TARGET_WEIGHT_MUST_BE_LOWER')
->assertJsonMissingPath('message');
});
+41 -42
View File
@@ -11,11 +11,12 @@ use Laravel\Sanctum\Sanctum;
uses(RefreshDatabase::class);
it('returns nutrition goals with the authenticated user', function () {
$user = User::factory()->create([
'daily_calorie_goal' => 2400,
'daily_protein_goal' => 140,
'daily_carbs_goal' => 280,
'daily_fats_goal' => 80,
$user = User::factory()->create();
$user->nutritionPlans()->where('is_active', true)->update([
'calories' => 2400,
'proteins' => 140,
'carbs' => 280,
'fats' => 80,
]);
Sanctum::actingAs($user);
@@ -29,52 +30,48 @@ it('returns nutrition goals with the authenticated user', function () {
->assertJsonPath('data.nutritionGoals.fats', 80);
});
it('updates nutrition goals for the authenticated user', function () {
it('recalculates nutrition goals from the complete profile', function () {
$user = User::factory()->create();
Sanctum::actingAs($user);
$response = $this->patchJson('/api/auth/me', [
'nutritionGoals' => [
'calories' => 2200,
'proteins' => 135.5,
'carbs' => 260,
'fats' => 75.25,
],
$response = $this->patchJson('/api/nutrition-profile', [
'dateOfBirth' => '1991-06-12',
'sex' => UserSex::MAN->value,
'heightCm' => 182,
'weightKg' => 84,
'targetWeightKg' => 78,
'physicalActivityLevel' => PhysicalActivityLevel::VERY_ACTIVE->value,
'weightGoal' => WeightGoal::LOSE_WEIGHT->value,
'pacePreference' => PacePreference::NORMAL->value,
]);
$response
->assertOk()
->assertJsonPath('data.nutritionGoals.calories', 2200)
->assertJsonPath('data.nutritionGoals.proteins', 135.5)
->assertJsonPath('data.nutritionGoals.carbs', 260)
->assertJsonPath('data.nutritionGoals.fats', 75.25);
->assertJsonPath('data.nutritionPlan.source', 'profile_recalculation')
->assertJsonPath('data.currentWeight', 84)
->assertJsonPath('data.targetWeight', 78);
$this->assertDatabaseHas('users', [
'id' => $user->id,
'daily_calorie_goal' => 2200,
'daily_protein_goal' => 135.5,
'daily_carbs_goal' => 260,
'daily_fats_goal' => 75.25,
]);
expect($response->json('data.nutritionGoals.calories'))->toBeGreaterThan(1200);
$this->assertDatabaseCount('nutrition_plans', 2);
$this->assertDatabaseCount('weight_entries', 2);
$this->assertDatabaseHas('nutrition_plans', ['is_active' => false]);
});
it('validates nutrition goals', function () {
Sanctum::actingAs(User::factory()->create());
it('does not allow direct nutrition goal overrides through the account endpoint', function () {
$user = User::factory()->create();
Sanctum::actingAs($user);
$this->patchJson('/api/auth/me', [
'nutritionGoals' => [
'calories' => -1,
'proteins' => 'abc',
'calories' => 9000,
'proteins' => 1,
'carbs' => 1,
'fats' => 1,
],
])
->assertUnprocessable()
->assertJsonValidationErrors([
'nutritionGoals.calories',
'nutritionGoals.proteins',
'nutritionGoals.carbs',
'nutritionGoals.fats',
]);
->assertOk()
->assertJsonPath('data.nutritionGoals.calories', 2200);
});
it('returns profile preferences with the authenticated user', function () {
@@ -98,25 +95,25 @@ it('updates profile preferences for the authenticated user', function () {
Sanctum::actingAs($user);
$this->patchJson('/api/auth/me', [
$this->patchJson('/api/nutrition-profile', [
'physicalActivityLevel' => PhysicalActivityLevel::MODERATELY_ACTIVE->value,
'weightGoal' => WeightGoal::MAINTAIN_WEIGHT->value,
'pacePreference' => PacePreference::NORMAL->value,
'sex' => UserSex::MAN->value,
'dateOfBirth' => '2003-04-24',
'locale' => 'fr-FR',
'heightCm' => 180,
'weightKg' => 75,
'targetWeightKg' => null,
])
->assertOk()
->assertJsonPath('data.physicalActivityLevel', PhysicalActivityLevel::MODERATELY_ACTIVE->value)
->assertJsonPath('data.weightGoal', WeightGoal::MAINTAIN_WEIGHT->value)
->assertJsonPath('data.pacePreference', PacePreference::NORMAL->value)
->assertJsonPath('data.sex', UserSex::MAN->value)
->assertJsonPath('data.locale', 'fr')
->assertJsonPath('data.dateOfBirth', '2003-04-24');
$this->assertDatabaseHas('users', [
'id' => $user->id,
'locale' => 'fr',
'physical_activity_level' => PhysicalActivityLevel::MODERATELY_ACTIVE->value,
'weight_goal' => WeightGoal::MAINTAIN_WEIGHT->value,
'pace_preference' => PacePreference::NORMAL->value,
@@ -129,13 +126,14 @@ it('updates profile preferences for the authenticated user', function () {
it('validates profile preferences', function () {
Sanctum::actingAs(User::factory()->create());
$this->patchJson('/api/auth/me', [
$this->patchJson('/api/nutrition-profile', [
'physicalActivityLevel' => 'daily',
'weightGoal' => 'bulk',
'pacePreference' => 'urgent',
'sex' => 'x',
'locale' => 'es',
'dateOfBirth' => 'tomorrow',
'heightCm' => 20,
'weightKg' => 5,
])
->assertUnprocessable()
->assertJsonValidationErrors([
@@ -143,7 +141,8 @@ it('validates profile preferences', function () {
'weightGoal',
'pacePreference',
'sex',
'locale',
'dateOfBirth',
'heightCm',
'weightKg',
]);
});
+132
View File
@@ -0,0 +1,132 @@
<?php
use App\Enums\PacePreference;
use App\Enums\WeeklyReviewStatus;
use App\Enums\WeightGoal;
use App\Models\MealPosts;
use App\Models\NutritionPlan;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
uses(RefreshDatabase::class);
beforeEach(function () {
CarbonImmutable::setTestNow('2026-08-17 10:00:00');
});
afterEach(function () {
CarbonImmutable::setTestNow();
});
it('returns an insufficient data review without changing the plan', function () {
$user = User::factory()->create();
Sanctum::actingAs($user);
$this->getJson('/api/weekly-reviews/current')
->assertOk()
->assertJsonPath('data.periodStart', '2026-08-10')
->assertJsonPath('data.periodEnd', '2026-08-16')
->assertJsonPath('data.status', WeeklyReviewStatus::INSUFFICIENT_DATA->value)
->assertJsonPath('data.recommendedCalorieAdjustment', 0);
$this->assertDatabaseCount('nutrition_plans', 1);
});
it('proposes and applies a small confirmed adjustment', function () {
$user = User::factory()->create([
'weight_goal' => WeightGoal::LOSE_WEIGHT,
'pace_preference' => PacePreference::NORMAL,
]);
$user->weightEntries()->delete();
foreach ([
['2026-08-03 07:00:00', 70.0],
['2026-08-07 07:00:00', 69.98],
['2026-08-12 07:00:00', 69.95],
['2026-08-16 07:00:00', 69.90],
] as [$measuredAt, $weightKg]) {
$user->weightEntries()->create([
'weight_kg' => $weightKg,
'measured_at' => $measuredAt,
]);
}
foreach (range(10, 14) as $day) {
MealPosts::factory()->for($user, 'user')->create([
'calories' => 2200,
'proteins' => 112,
'carbs' => 286,
'fats' => 61,
'eaten_at' => "2026-08-{$day} 12:00:00",
]);
}
Sanctum::actingAs($user);
$reviewResponse = $this->getJson('/api/weekly-reviews/current')
->assertOk()
->assertJsonPath('data.status', WeeklyReviewStatus::ADJUSTMENT_RECOMMENDED->value)
->assertJsonPath('data.recommendedCalorieAdjustment', -100);
$reviewId = $reviewResponse->json('data.id');
$this->postJson("/api/weekly-reviews/{$reviewId}/accept")
->assertCreated()
->assertJsonPath('data.source', 'weekly_adjustment');
$this->assertDatabaseCount('nutrition_plans', 2);
$this->assertDatabaseHas('weekly_reviews', [
'id' => $reviewId,
'recommended_calorie_adjustment' => -100,
]);
expect($user->weeklyReviews()->findOrFail($reviewId)->accepted_at)->not->toBeNull();
});
it('does not allow accepting another users review', function () {
$user = User::factory()->create();
$otherUser = User::factory()->create();
$review = $otherUser->weeklyReviews()->create([
'period_start' => '2026-08-10',
'period_end' => '2026-08-16',
'status' => WeeklyReviewStatus::ADJUSTMENT_RECOMMENDED,
'recommended_calorie_adjustment' => -100,
'message_code' => 'WEEKLY_REVIEW_ADJUSTMENT',
'metrics' => [],
'generated_at' => now(),
]);
Sanctum::actingAs($user);
$this->postJson("/api/weekly-reviews/{$review->id}/accept")->assertNotFound();
});
it('rejects an adjustment generated for a plan that is no longer active', function () {
$user = User::factory()->create();
$previousPlan = $user->nutritionPlans()->where('is_active', true)->firstOrFail();
$review = $user->weeklyReviews()->create([
'nutrition_plan_id' => $previousPlan->getKey(),
'period_start' => '2026-08-10',
'period_end' => '2026-08-16',
'status' => WeeklyReviewStatus::ADJUSTMENT_RECOMMENDED,
'recommended_calorie_adjustment' => -100,
'message_code' => 'WEEKLY_REVIEW_ADJUSTMENT',
'metrics' => [],
'generated_at' => now(),
]);
$previousPlan->update([
'is_active' => false,
'effective_until' => now(),
]);
NutritionPlan::factory()->for($user)->create([
'is_active' => true,
'effective_from' => now()->addMinute(),
]);
Sanctum::actingAs($user);
$this->postJson("/api/weekly-reviews/{$review->id}/accept")
->assertStatus(409);
expect($review->fresh()->accepted_at)->toBeNull();
});
+46
View File
@@ -0,0 +1,46 @@
<?php
use App\Models\User;
use App\Models\WeightEntry;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
uses(RefreshDatabase::class);
it('stores and lists the authenticated user weight history', function () {
$user = User::factory()->create();
Sanctum::actingAs($user);
$this->postJson('/api/weight-entries', [
'weightKg' => 69.35,
'measuredAt' => '2026-08-10T07:30:00Z',
])
->assertCreated()
->assertJsonPath('data.weightKg', 69.35);
$this->getJson('/api/weight-entries?days=365')
->assertOk()
->assertJsonPath('data.0.weightKg', 70)
->assertJsonPath('data.1.weightKg', 69.35);
});
it('does not allow deleting another users weight entry', function () {
$user = User::factory()->create();
$otherUser = User::factory()->create();
$entry = WeightEntry::factory()->for($otherUser)->create();
Sanctum::actingAs($user);
$this->deleteJson("/api/weight-entries/{$entry->id}")->assertNotFound();
$this->assertModelExists($entry);
});
it('validates weight measurements', function () {
Sanctum::actingAs(User::factory()->create());
$this->postJson('/api/weight-entries', [
'weightKg' => 10,
'measuredAt' => now()->addDay()->toISOString(),
])
->assertUnprocessable()
->assertJsonValidationErrors(['weightKg', 'measuredAt']);
});