[CLEAR-38] Grouping by day and month
This commit is contained in:
parent
b17d515a9c
commit
30d017a44f
@ -110,10 +110,12 @@ class UsersController extends Controller
|
||||
return response()->json(['success' => true, 'message' => 'Recipe saved successfully in history']);
|
||||
}
|
||||
|
||||
public function getRecipeHistory()
|
||||
public function getRecipeHistory(Request $request)
|
||||
{
|
||||
$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);
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ namespace App\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\UsersRecipes;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class UsersRepository implements UsersRepositoryInterface
|
||||
{
|
||||
@ -46,13 +47,35 @@ class UsersRepository implements UsersRepositoryInterface
|
||||
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();
|
||||
$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) {
|
||||
$recipeHistory[] = array_merge(['date' => $userRecipe->created_at], $userRecipe->recipe->nutrition);
|
||||
foreach ($userRecipes as $date => $dateRecipes) {
|
||||
$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;
|
||||
|
@ -21,5 +21,5 @@ interface UsersRepositoryInterface
|
||||
|
||||
public function saveRecipe(int $userID, int $recipeID);
|
||||
|
||||
public function getRecipeHistory(int $userID);
|
||||
public function getRecipeHistory(int $userID, string $groupBy);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user