[CLEAR-38] Grouping by day and month

This commit is contained in:
Artur Nowakowski 2020-01-19 14:53:23 +01:00
parent b17d515a9c
commit 30d017a44f
3 changed files with 31 additions and 6 deletions

View File

@ -110,10 +110,12 @@ class UsersController extends Controller
return response()->json(['success' => true, 'message' => 'Recipe saved successfully in history']); return response()->json(['success' => true, 'message' => 'Recipe saved successfully in history']);
} }
public function getRecipeHistory() public function getRecipeHistory(Request $request)
{ {
$userID = auth()->id(); $userID = auth()->id();
$recipeHistory = $this->usersRepository->getRecipeHistory($userID); $groupBy = $request->input('groupBy') ?? 'day';
$recipeHistory = $this->usersRepository->getRecipeHistory($userID, $groupBy);
return response()->json(['success' => true, 'data' => ['history' => $recipeHistory]], 200); return response()->json(['success' => true, 'data' => ['history' => $recipeHistory]], 200);
} }

View File

@ -6,6 +6,7 @@ namespace App\Repositories;
use App\Models\User; use App\Models\User;
use App\UsersRecipes; use App\UsersRecipes;
use Carbon\Carbon;
class UsersRepository implements UsersRepositoryInterface class UsersRepository implements UsersRepositoryInterface
{ {
@ -46,13 +47,35 @@ class UsersRepository implements UsersRepositoryInterface
return UsersRecipes::create(['user_id' => $userID, 'recipe_id' => $recipeID]); return UsersRecipes::create(['user_id' => $userID, 'recipe_id' => $recipeID]);
} }
public function getRecipeHistory(int $userID) public function getRecipeHistory(int $userID, string $groupBy = 'day')
{ {
$userRecipes = UsersRecipes::where('user_id', $userID)->get(); $userRecipes = UsersRecipes::where('user_id', $userID)->get();
$recipeHistory = []; $recipeHistory = [];
if ($groupBy == 'month') {
$userRecipes = $userRecipes->groupBy(function ($d) {
return Carbon::parse($d->created_at)->format('Y-m');
});
} else {
$userRecipes = $userRecipes->groupBy(function ($d) {
return Carbon::parse($d->created_at)->format('Y-m-d');
});
}
foreach ($userRecipes as $userRecipe) { foreach ($userRecipes as $date => $dateRecipes) {
$recipeHistory[] = array_merge(['date' => $userRecipe->created_at], $userRecipe->recipe->nutrition); $nutritionSum = [
'kcal' => 0,
'carbohydrates' => 0,
'protein' => 0,
'fat' => 0,
];
foreach($dateRecipes as $userRecipe){
$nutritionValues = $userRecipe->recipe->nutrition;
foreach($nutritionValues as $name => $value){
$nutritionSum[$name] += $value;
}
}
$recipeHistory[] = array_merge(['date' => $date], $nutritionSum);
} }
return $recipeHistory; return $recipeHistory;

View File

@ -21,5 +21,5 @@ interface UsersRepositoryInterface
public function saveRecipe(int $userID, int $recipeID); public function saveRecipe(int $userID, int $recipeID);
public function getRecipeHistory(int $userID); public function getRecipeHistory(int $userID, string $groupBy);
} }