Compare commits

...

5 Commits

3 changed files with 102 additions and 2 deletions

View File

@ -3,7 +3,8 @@
use Lycoreco\Apps\Recipes\Models\{
IngredientModel,
RecipeModel,
RecipeUserMenu
RecipeUserMenu,
FavoriteModel
};
function get_ajax_error($message, $error_code = 500)
@ -133,5 +134,57 @@ function ajax_search_ingredient()
$result['count'] = count($ingredients);
$result['result'] = $ingredients;
return $result;
}
function ajax_favorites()
{
$recipe_id = $_POST['recipe_id'] ?? null;
$type = $_POST['type'] ?? 'add'; // add, remove
if (!CURRENT_USER) {
return get_ajax_error('You are not authorized', 401);
}
if (!isset($recipe_id)) {
return get_ajax_error("Missing 'recipe_id' parameter.", 400);
}
if($type != 'add' && $type != 'remove')
{
return get_ajax_error("'type' parameter can be only 'add' or 'remove'", 400);
}
$result = array();
$favorite = FavoriteModel::get(array(
[
'name' => 'obj.recipe_id',
'type' => '=',
'value' => $recipe_id
],
[
'name' => 'obj.user_id',
'type' => '=',
'value' => CURRENT_USER->get_id()
]
));
if($type == 'remove') {
if($favorite) {
$favorite->delete();
$result['success'] = 'This recipe was removed from your favorite list';
return $result;
}
else {
return get_ajax_error("This recipe from your favorites list does not exist.", 400);
}
}
if(!$favorite)
$favorite = new FavoriteModel();
$favorite->field_user_id = CURRENT_USER->get_id();
$favorite->field_recipe_id = $recipe_id;
$favorite->save();
$result['success'] = 'You have successfully added the recipe to your favorites list';
return $result;
}

View File

@ -0,0 +1,47 @@
<?php
namespace Lycoreco\Apps\Recipes\Models;
use Lycoreco\Includes\Model\BaseModel;
class FavoriteModel extends BaseModel
{
public $field_recipe_id;
public $field_user_id;
static protected $table_name = 'recipe_favorites';
static protected $table_fields = [
'id' => 'int',
'recipe_id' => 'int',
'user_id' => 'int',
];
public static function init_table()
{
$result = db_query('CREATE TABLE ' . static::$table_name . ' (
id INT AUTO_INCREMENT PRIMARY KEY,
recipe_id INT NOT NULL,
user_id INT NOT NULL,
FOREIGN KEY (recipe_id) REFERENCES recipes(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);');
return $result;
}
public function valid()
{
$recipe = RecipeModel::get(array(
[
'name' => 'obj.id',
'type' => '=',
'value' => $this->field_recipe_id
]
));
if(!$recipe)
return ['Recipe does not exist'];
return true;
}
}

View File

@ -50,7 +50,7 @@ class RecipeUserMenu extends BaseModel
]
));
if(!$recipe)
return ['Recipe is not exists'];
return ['Recipe does not exist'];
return true;
}