[CLEAR-37] saving users recipes history

This commit is contained in:
Artur Nowakowski 2020-01-07 19:45:45 +01:00
parent 80f4aab76f
commit 11471894f7
11 changed files with 101 additions and 35 deletions

View File

@ -4,7 +4,7 @@ namespace App\Helpers;
class NutritionCalculator class NutritionCalculator
{ {
public static function calculateNutritionForRecipe(object $ingredients) public static function calculateNutritionForProducts($products)
{ {
$nutrition = [ $nutrition = [
'kcal' => 0, 'kcal' => 0,
@ -13,10 +13,10 @@ class NutritionCalculator
'fat' => 0, 'fat' => 0,
]; ];
foreach($ingredients as $ingredient) foreach($products as $product)
{ {
foreach(array_keys($nutrition) as $nutritionValue) { foreach(array_keys($nutrition) as $nutritionValue) {
$nutrition[$nutritionValue] += $ingredient['weight'] / 100 * $ingredient['product'][$nutritionValue]; $nutrition[$nutritionValue] += $product['weight'] / 100 * $product['product'][$nutritionValue];
} }
} }

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Helpers\NutritionCalculator;
use App\Http\Requests\AddProductRequest; use App\Http\Requests\AddProductRequest;
use App\Repositories\ProductsRepositoryInterface; use App\Repositories\ProductsRepositoryInterface;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@ -29,4 +30,12 @@ class ProductsController extends Controller
return response()->json(['success' => true, 'data' => ['products' => $products]], 200); return response()->json(['success' => true, 'data' => ['products' => $products]], 200);
} }
public function calculate(Request $request)
{
$products = $this->productsRepository->fillProductsInfo($request->input('products'));
$nutrition = NutritionCalculator::calculateNutritionForProducts($products);
return response()->json(['success' => true, 'data' => ['nutrition' => $nutrition]]);
}
} }

View File

@ -82,7 +82,6 @@ class UsersController extends Controller
auth()->invalidate($request->input('token')); auth()->invalidate($request->input('token'));
return response()->json(['success' => true, 'message' => "You have successfully logged out."]); return response()->json(['success' => true, 'message' => "You have successfully logged out."]);
} catch (JWTException $e) { } catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['success' => false, 'error' => 'Failed to logout, please try again.'], 500); return response()->json(['success' => false, 'error' => 'Failed to logout, please try again.'], 500);
} }
} }
@ -97,4 +96,18 @@ class UsersController extends Controller
]); ]);
} }
public function saveRecipe(Request $request)
{
$userID = auth()->id();
$recipeID = $request->input('recipeID');
$savedRecipe = $this->usersRepository->saveRecipe($userID, $recipeID);
if (!$savedRecipe) {
return response()->json(['success' => false, 'error' => 'Failed to save recipe, please try again.'], 400);
}
return response()->json(['success' => true, 'message' => 'Recipe saved successfully in history']);
}
} }

View File

@ -27,6 +27,6 @@ class Recipe extends Model
public function getNutritionAttribute() public function getNutritionAttribute()
{ {
return NutritionCalculator::calculateNutritionForRecipe($this->ingredients); return NutritionCalculator::calculateNutritionForProducts($this->ingredients);
} }
} }

View File

@ -0,0 +1,10 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UsersRecipes extends Model
{
//
}

View File

@ -23,4 +23,13 @@ class ProductsRepository implements ProductsRepositoryInterface
return $query->paginate($filters['limit']); return $query->paginate($filters['limit']);
} }
public function fillProductsInfo(array $products)
{
foreach ($products as $k => $product){
$products[$k]['product'] = Product::find($product['id']);
}
return $products;
}
} }

View File

@ -7,4 +7,5 @@ interface ProductsRepositoryInterface
{ {
public function create($data); public function create($data);
public function paginate(array $filters); public function paginate(array $filters);
public function fillProductsInfo(array $products);
} }

View File

@ -5,6 +5,7 @@ namespace App\Repositories;
use App\Models\User; use App\Models\User;
use App\UsersRecipes;
class UsersRepository implements UsersRepositoryInterface class UsersRepository implements UsersRepositoryInterface
{ {
@ -39,4 +40,9 @@ class UsersRepository implements UsersRepositoryInterface
{ {
return User::where($field, $actual); return User::where($field, $actual);
} }
public function saveRecipe(int $userID, int $recipeID)
{
return UsersRecipes::create(['user_id' => $userID, 'recipe_id' => $recipeID]);
}
} }

View File

@ -7,45 +7,17 @@ use Illuminate\Database\Eloquent\Collection;
interface UsersRepositoryInterface interface UsersRepositoryInterface
{ {
/**
* Get all Users.
* @return User[]|Collection
*/
public function getAll(); public function getAll();
/**
* Paginate Users, chunkSize is the size of one page.
* @param $chunkSize
* @return mixed
*/
public function paginate($chunkSize); public function paginate($chunkSize);
/**
* Create user with given data.
* @param $data
* @return mixed
*/
public function create($data); public function create($data);
/**
* Delete user with given id.
* @param $id
* @return mixed
*/
public function delete($id); public function delete($id);
/**
* Get user by id.
* @param $userId
* @return mixed
*/
public function getById($userId); public function getById($userId);
/**
* Get the users where $field is equal to $actual.
* @param $field
* @param $actual
* @return mixed
*/
public function getWhereEquals($field, $actual); public function getWhereEquals($field, $actual);
public function saveRecipe(int $userID, int $recipeID);
} }

View File

@ -0,0 +1,43 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersRecipesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users_recipes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('recipe_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->foreign('recipe_id')
->references('id')
->on('recipes')
->onUpdate('cascade')
->onDelete('cascade');
$table->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users_recipes');
}
}

View File

@ -6,6 +6,7 @@ Route::group(['prefix' => 'user', 'middleware' => ['assign.guard:users']], funct
Route::post('/register', 'UsersController@register'); Route::post('/register', 'UsersController@register');
Route::post('/login', 'UsersController@login'); Route::post('/login', 'UsersController@login');
Route::get('/me', 'UsersController@me'); Route::get('/me', 'UsersController@me');
Route::post('/save-recipe', 'UsersController@saveRecipe');
}); });
Route::prefix('product')->group(function () { Route::prefix('product')->group(function () {
@ -17,3 +18,5 @@ Route::prefix('recipe')->group(function () {
Route::post('/', 'RecipesController@add')->middleware(['jwt.auth']); Route::post('/', 'RecipesController@add')->middleware(['jwt.auth']);
Route::get('/', 'RecipesController@index'); Route::get('/', 'RecipesController@index');
}); });
Route::post('calculate', 'ProductsController@calculate');