Compare commits
11 Commits
main
...
feature/ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bbec0ee2b | ||
|
|
1656739ecd | ||
|
|
95afd46406 | ||
|
|
0f56303d59 | ||
|
|
a4eebef321 | ||
|
|
a57566c1fe | ||
|
|
7e1ecf35b9 | ||
|
|
ae008fbc9c | ||
|
|
8ef4383bd9 | ||
|
|
b575b42f22 | ||
|
|
553637d8e2 |
0
.ai/mcp/mcp.json
Normal file
0
.ai/mcp/mcp.json
Normal file
2
.gitignore
vendored
2
.gitignore
vendored
@ -38,6 +38,8 @@ yarn-error.log
|
|||||||
testem.log
|
testem.log
|
||||||
/typings
|
/typings
|
||||||
__screenshots__/
|
__screenshots__/
|
||||||
|
*.cache
|
||||||
|
.php-cs-fixer.dist.php
|
||||||
|
|
||||||
# System files
|
# System files
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
@ -2,7 +2,8 @@
|
|||||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||||
"version": 1,
|
"version": 1,
|
||||||
"cli": {
|
"cli": {
|
||||||
"packageManager": "npm"
|
"packageManager": "npm",
|
||||||
|
"analytics": false
|
||||||
},
|
},
|
||||||
"newProjectRoot": "projects",
|
"newProjectRoot": "projects",
|
||||||
"projects": {
|
"projects": {
|
||||||
|
|||||||
@ -31,7 +31,7 @@ SESSION_DRIVER=database
|
|||||||
SESSION_LIFETIME=120
|
SESSION_LIFETIME=120
|
||||||
SESSION_ENCRYPT=false
|
SESSION_ENCRYPT=false
|
||||||
SESSION_PATH=/
|
SESSION_PATH=/
|
||||||
SESSION_DOMAIN=null
|
SESSION_DOMAIN=localhost
|
||||||
|
|
||||||
BROADCAST_CONNECTION=log
|
BROADCAST_CONNECTION=log
|
||||||
FILESYSTEM_DISK=local
|
FILESYSTEM_DISK=local
|
||||||
@ -64,3 +64,4 @@ AWS_USE_PATH_STYLE_ENDPOINT=false
|
|||||||
|
|
||||||
VITE_APP_NAME="${APP_NAME}"
|
VITE_APP_NAME="${APP_NAME}"
|
||||||
FRONTEND_URL=http://localhost:4200
|
FRONTEND_URL=http://localhost:4200
|
||||||
|
SANCTUM_STATEFUL_DOMAINS=localhost:4200
|
||||||
|
|||||||
46
backend/app/Actions/AddProductToCartAction.php
Normal file
46
backend/app/Actions/AddProductToCartAction.php
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Data\AddToCartDTO;
|
||||||
|
use App\Data\CartDTO;
|
||||||
|
use App\Enums\CartStatus;
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Models\User;
|
||||||
|
|
||||||
|
final readonly class AddProductToCartAction
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Execute the action.
|
||||||
|
*/
|
||||||
|
public function execute(AddToCartDTO $cartData, User $user)
|
||||||
|
{
|
||||||
|
$cart = $user->carts()->active()->firstOrCreate([
|
||||||
|
'status' => CartStatus::Active,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$price = Product::query()->whereId($cartData->productId)->value('actual_price');
|
||||||
|
|
||||||
|
$productInCart = $cart->products()->find($cartData->productId);
|
||||||
|
|
||||||
|
if ($productInCart) {
|
||||||
|
$newQuantity = $productInCart->pivot->quantity + $cartData->quantity;
|
||||||
|
|
||||||
|
$cart->products()->updateExistingPivot($cartData->productId, [
|
||||||
|
'quantity' => $newQuantity,
|
||||||
|
'price' => $price,
|
||||||
|
]);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
$cart->products()->attach($cartData->productId, [
|
||||||
|
'quantity' => $cartData->quantity,
|
||||||
|
'price' => $price,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return CartDTO::fromModel($cart->load(['products' => function ($query) {
|
||||||
|
$query->withPivot('quantity', 'price');
|
||||||
|
}]));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
17
backend/app/Actions/GetActiveUserCartAction.php
Normal file
17
backend/app/Actions/GetActiveUserCartAction.php
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Data\CartDTO;
|
||||||
|
use App\Models\User;
|
||||||
|
|
||||||
|
final readonly class GetActiveUserCartAction
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Execute the action.
|
||||||
|
*/
|
||||||
|
public function execute(User $user)
|
||||||
|
{
|
||||||
|
return CartDTO::fromModel($user->carts()->active()->withProducts()->first());
|
||||||
|
}
|
||||||
|
}
|
||||||
21
backend/app/Actions/RemoveProductFromCartAction.php
Normal file
21
backend/app/Actions/RemoveProductFromCartAction.php
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
|
||||||
|
final readonly class RemoveProductFromCartAction
|
||||||
|
{
|
||||||
|
public function __construct(private GetActiveUserCartAction $activeCartAction) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the action.
|
||||||
|
*/
|
||||||
|
public function execute(int $productId, User $user)
|
||||||
|
{
|
||||||
|
$cart = $user->carts()->active()->sole();
|
||||||
|
$cart->products()->detach($productId);
|
||||||
|
|
||||||
|
return $this->activeCartAction->execute($user);
|
||||||
|
}
|
||||||
|
}
|
||||||
34
backend/app/Actions/UpdateProductInCartAction.php
Normal file
34
backend/app/Actions/UpdateProductInCartAction.php
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Data\AddToCartDTO;
|
||||||
|
use App\Data\CartDTO;
|
||||||
|
use App\Models\User;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
|
||||||
|
final readonly class UpdateProductInCartAction
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Execute the action.
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException
|
||||||
|
*/
|
||||||
|
public function execute(AddToCartDTO $cartData, User $user)
|
||||||
|
{
|
||||||
|
$cart = $user->carts()->active()->sole();
|
||||||
|
|
||||||
|
$productInCart = $cart->products()->find($cartData->productId);
|
||||||
|
|
||||||
|
throw_if($productInCart === null, new InvalidArgumentException('Product not found'));
|
||||||
|
|
||||||
|
$cart->products()->updateExistingPivot($cartData->productId, [
|
||||||
|
'quantity' => $cartData->quantity,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return CartDTO::fromModel($cart->load(['products' => function ($query) {
|
||||||
|
$query->withPivot('quantity', 'price');
|
||||||
|
}]));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
33
backend/app/Data/AddToCartDTO.php
Normal file
33
backend/app/Data/AddToCartDTO.php
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Data;
|
||||||
|
|
||||||
|
use App\Contracts\InputDataTransferObject;
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
final readonly class AddToCartDTO implements InputDataTransferObject
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public int $productId,
|
||||||
|
public int $quantity
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'productId' => $this->productId,
|
||||||
|
'quantity' => $this->quantity,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function fromRequest(FormRequest $request): InputDataTransferObject
|
||||||
|
{
|
||||||
|
return new self(
|
||||||
|
productId: $request->productId,
|
||||||
|
quantity: $request->quantity
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
49
backend/app/Data/CartDTO.php
Normal file
49
backend/app/Data/CartDTO.php
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Data;
|
||||||
|
|
||||||
|
use App\Contracts\OutputDataTransferObject;
|
||||||
|
use App\Models\Cart;
|
||||||
|
|
||||||
|
final readonly class CartDTO implements OutputDataTransferObject
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param CartItemDTO[] $items
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public int $id,
|
||||||
|
public ?int $itemsCount = null,
|
||||||
|
public ?int $totalPrice = null,
|
||||||
|
public array $items = []
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->id,
|
||||||
|
'itemsCount' => $this->itemsCount,
|
||||||
|
'totalPrice' => $this->totalPrice,
|
||||||
|
'items' => $this->items,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function fromModel(Cart $cart)
|
||||||
|
{
|
||||||
|
return new self(
|
||||||
|
id: $cart->id,
|
||||||
|
itemsCount: $cart->products->count(),
|
||||||
|
totalPrice: $cart->products->sum(fn ($product) => $product->pivot->price * $product->pivot->quantity),
|
||||||
|
items: $cart->products->map(fn ($product) => new CartItemDTO(
|
||||||
|
id: $product->id,
|
||||||
|
title: $product->title,
|
||||||
|
quantity: $product->pivot->quantity,
|
||||||
|
price: $product->actual_price,
|
||||||
|
subtotal: $product->actual_price * $product->pivot->quantity,
|
||||||
|
image: $product->images->first()->path,
|
||||||
|
))->toArray()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
32
backend/app/Data/CartItemDTO.php
Normal file
32
backend/app/Data/CartItemDTO.php
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Data;
|
||||||
|
|
||||||
|
use App\Contracts\OutputDataTransferObject;
|
||||||
|
|
||||||
|
final readonly class CartItemDTO implements OutputDataTransferObject
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public int $id,
|
||||||
|
public string $title,
|
||||||
|
public int $quantity,
|
||||||
|
public float $price,
|
||||||
|
public float $subtotal,
|
||||||
|
public string $image
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->id,
|
||||||
|
'title' => $this->title,
|
||||||
|
'quantity' => $this->quantity,
|
||||||
|
'price' => $this->price,
|
||||||
|
'subtotal' => $this->subtotal,
|
||||||
|
'image' => $this->image,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -22,6 +22,7 @@ public function __construct(
|
|||||||
public array $productImages,
|
public array $productImages,
|
||||||
public ?string $updatedAt = null,
|
public ?string $updatedAt = null,
|
||||||
public ?string $createdAt = null,
|
public ?string $createdAt = null,
|
||||||
|
public ?bool $isFavorite = null
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -41,6 +42,7 @@ public function toArray(): array
|
|||||||
$this->productImages),
|
$this->productImages),
|
||||||
'updatedAt' => $this->updatedAt,
|
'updatedAt' => $this->updatedAt,
|
||||||
'createdAt' => $this->createdAt,
|
'createdAt' => $this->createdAt,
|
||||||
|
'isFavorite' => $this->isFavorite,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -57,6 +59,8 @@ public static function fromModel(Product $product): self
|
|||||||
productImages: $product->images->map(fn (ProductImage $productImage) => ProductImageDTO::fromModel($productImage))->all(),
|
productImages: $product->images->map(fn (ProductImage $productImage) => ProductImageDTO::fromModel($productImage))->all(),
|
||||||
updatedAt: $product->updated_at,
|
updatedAt: $product->updated_at,
|
||||||
createdAt: $product->created_at,
|
createdAt: $product->created_at,
|
||||||
|
// this column is added by where exists query
|
||||||
|
isFavorite: $product->favorited_by_exists,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
11
backend/app/Enums/CartStatus.php
Normal file
11
backend/app/Enums/CartStatus.php
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
enum CartStatus: string
|
||||||
|
{
|
||||||
|
case Active = 'active'; // freshly created
|
||||||
|
case Converted = 'converted'; // user ordered
|
||||||
|
case Abandoned = 'abandoned'; // older than 24hrs
|
||||||
|
case Expired = 'expired'; // left for a long period
|
||||||
|
}
|
||||||
83
backend/app/Http/Controllers/CartController.php
Normal file
83
backend/app/Http/Controllers/CartController.php
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Actions\AddProductToCartAction;
|
||||||
|
use App\Actions\GetActiveUserCartAction;
|
||||||
|
use App\Actions\RemoveProductFromCartAction;
|
||||||
|
use App\Actions\UpdateProductInCartAction;
|
||||||
|
use App\Data\AddToCartDTO;
|
||||||
|
use App\Http\Requests\AddProductToCartRequest;
|
||||||
|
use App\Http\Requests\RemoveProductFromCartRequest;
|
||||||
|
use App\Http\Requests\UpdateProductInCartRequest;
|
||||||
|
use App\Http\Resources\CartResource;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
||||||
|
class CartController extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Store a newly created resource in storage.
|
||||||
|
*/
|
||||||
|
public function store(AddProductToCartRequest $request, AddProductToCartAction $addProductAction)
|
||||||
|
{
|
||||||
|
$addToCartData = AddToCartDTO::fromRequest($request);
|
||||||
|
|
||||||
|
$cart = $addProductAction->execute($addToCartData, Auth::user());
|
||||||
|
|
||||||
|
return new CartResource($cart);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display the specified resource.
|
||||||
|
*/
|
||||||
|
public function show(GetActiveUserCartAction $action)
|
||||||
|
{
|
||||||
|
return new CartResource($action->execute(Auth::user()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the specified resource in storage.
|
||||||
|
*/
|
||||||
|
public function update(UpdateProductInCartRequest $request, UpdateProductInCartAction $action)
|
||||||
|
{
|
||||||
|
$updateCartData = AddToCartDTO::fromRequest($request);
|
||||||
|
$cart = $action->execute($updateCartData, $request->user());
|
||||||
|
|
||||||
|
return new CartResource($cart);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the specified resource from storage.
|
||||||
|
*/
|
||||||
|
public function destroy(RemoveProductFromCartRequest $request, RemoveProductFromCartAction $action)
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
try {
|
||||||
|
$cart = $action->execute($request->productId, $user);
|
||||||
|
|
||||||
|
return new CartResource($cart);
|
||||||
|
} catch (ModelNotFoundException $e) {
|
||||||
|
|
||||||
|
Log::error('No active cart found when removing a product from cart.', [
|
||||||
|
'user' => $user->id,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'No active cart found.',
|
||||||
|
], 404);
|
||||||
|
|
||||||
|
} catch (MultipleRecordsFoundException $e) {
|
||||||
|
Log::error('Multiple active carts found for the user', [
|
||||||
|
'user' => $user->id,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'Multiple Active carts found.',
|
||||||
|
], 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
36
backend/app/Http/Controllers/FavouriteProductController.php
Normal file
36
backend/app/Http/Controllers/FavouriteProductController.php
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Resources\FavouriteProductResource;
|
||||||
|
use App\Models\FavouriteProduct;
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
|
class FavouriteProductController extends Controller
|
||||||
|
{
|
||||||
|
public function index()
|
||||||
|
{
|
||||||
|
return FavouriteProductResource::collection(FavouriteProduct::all());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toggle(Request $request, Product $product)
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var User $user
|
||||||
|
*/
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
$changes = $user->favoriteProducts()->toggle($product);
|
||||||
|
Log::info('hi again');
|
||||||
|
// If changes has any item, that means a product has been attached.
|
||||||
|
$isFavorite = count($changes['attached']) > 0;
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => $isFavorite ? 'Product added to favorites' : 'Product removed from favorites',
|
||||||
|
'isFavorite' => $isFavorite,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,14 +6,16 @@
|
|||||||
use App\Http\Requests\CreateProductRequest;
|
use App\Http\Requests\CreateProductRequest;
|
||||||
use App\Http\Resources\ProductResource;
|
use App\Http\Resources\ProductResource;
|
||||||
use App\Models\Product;
|
use App\Models\Product;
|
||||||
|
use App\Queries\GetProductsQuery;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
||||||
class ProductController extends Controller
|
class ProductController extends Controller
|
||||||
{
|
{
|
||||||
public function index()
|
public function index(GetProductsQuery $getProductsQuery)
|
||||||
{
|
{
|
||||||
$paginator = Product::query()->with(['category:id,name,slug', 'images:id,path,product_id'])->paginate();
|
$products = $getProductsQuery->get(Auth::user());
|
||||||
$paginatedDtos = $paginator->through(fn ($product) => ProductDTO::fromModel($product));
|
$paginatedDtos = $products->through(fn ($product) => ProductDTO::fromModel($product));
|
||||||
|
|
||||||
return ProductResource::collection($paginatedDtos);
|
return ProductResource::collection($paginatedDtos);
|
||||||
}
|
}
|
||||||
@ -25,7 +27,10 @@ public function store(CreateProductRequest $request)
|
|||||||
|
|
||||||
public function show(string $slug)
|
public function show(string $slug)
|
||||||
{
|
{
|
||||||
$product = Product::where('slug', $slug)->with(['category:id,name,slug', 'images:id,path,product_id'])->firstOrFail();
|
$product = Product::where('slug', $slug)
|
||||||
|
->with(['category:id,name,slug', 'images:id,path,product_id'])
|
||||||
|
->withExists('favoritedBy')
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
return new ProductResource(ProductDTO::fromModel($product));
|
return new ProductResource(ProductDTO::fromModel($product));
|
||||||
}
|
}
|
||||||
|
|||||||
29
backend/app/Http/Requests/AddProductToCartRequest.php
Normal file
29
backend/app/Http/Requests/AddProductToCartRequest.php
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class AddProductToCartRequest extends FormRequest
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Determine if the user is authorized to make this request.
|
||||||
|
*/
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the validation rules that apply to the request.
|
||||||
|
*
|
||||||
|
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||||
|
*/
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'productId' => 'required|exists:products,id',
|
||||||
|
'quantity' => 'required|numeric|min:1',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
28
backend/app/Http/Requests/RemoveProductFromCartRequest.php
Normal file
28
backend/app/Http/Requests/RemoveProductFromCartRequest.php
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class RemoveProductFromCartRequest extends FormRequest
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Determine if the user is authorized to make this request.
|
||||||
|
*/
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the validation rules that apply to the request.
|
||||||
|
*
|
||||||
|
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||||
|
*/
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'productId' => ['required', 'exists:products,id'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
29
backend/app/Http/Requests/UpdateProductInCartRequest.php
Normal file
29
backend/app/Http/Requests/UpdateProductInCartRequest.php
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class UpdateProductInCartRequest extends FormRequest
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Determine if the user is authorized to make this request.
|
||||||
|
*/
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the validation rules that apply to the request.
|
||||||
|
*
|
||||||
|
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||||
|
*/
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'productId' => ['required', 'exists:products,id'],
|
||||||
|
'quantity' => ['required', 'min:0', 'max:10'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
19
backend/app/Http/Resources/CartItemCollection.php
Normal file
19
backend/app/Http/Resources/CartItemCollection.php
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||||
|
|
||||||
|
class CartItemCollection extends ResourceCollection
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Transform the resource collection into an array.
|
||||||
|
*
|
||||||
|
* @return array<int|string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return parent::toArray($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
31
backend/app/Http/Resources/CartItemResource.php
Normal file
31
backend/app/Http/Resources/CartItemResource.php
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use App\Data\CartItemDTO;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @property CartItemDTO $resource
|
||||||
|
*/
|
||||||
|
class CartItemResource extends JsonResource
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Transform the resource into an array.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->resource->id,
|
||||||
|
'title' => $this->resource->title,
|
||||||
|
'quantity' => $this->resource->quantity,
|
||||||
|
'price' => $this->resource->price,
|
||||||
|
'subtotal' => $this->resource->subtotal,
|
||||||
|
'image' => Storage::disk('public')->url($this->resource->image),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
30
backend/app/Http/Resources/CartResource.php
Normal file
30
backend/app/Http/Resources/CartResource.php
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use App\Data\CartDTO;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @property CartDTO $resource
|
||||||
|
*/
|
||||||
|
class CartResource extends JsonResource
|
||||||
|
{
|
||||||
|
public static $wrap = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform the resource into an array.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->resource->id,
|
||||||
|
'itemsCount' => $this->resource->itemsCount,
|
||||||
|
'totalPrice' => $this->resource->totalPrice,
|
||||||
|
'items' => CartItemResource::collection($this->resource->items),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
23
backend/app/Http/Resources/FavouriteProductResource.php
Normal file
23
backend/app/Http/Resources/FavouriteProductResource.php
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use App\Models\FavouriteProduct;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin FavouriteProduct */
|
||||||
|
class FavouriteProductResource extends JsonResource
|
||||||
|
{
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->id,
|
||||||
|
'created_at' => $this->created_at,
|
||||||
|
'updated_at' => $this->updated_at,
|
||||||
|
|
||||||
|
'user_id' => $this->user_id,
|
||||||
|
'product_id' => $this->product_id,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -30,6 +30,7 @@ public function toArray(Request $request): array
|
|||||||
return Storage::disk('public')->url($productImage->path);
|
return Storage::disk('public')->url($productImage->path);
|
||||||
}, $this->resource->productImages),
|
}, $this->resource->productImages),
|
||||||
'updatedAt' => $this->resource->updatedAt,
|
'updatedAt' => $this->resource->updatedAt,
|
||||||
|
'isFavorite' => $this->resource->isFavorite,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
46
backend/app/Models/Cart.php
Normal file
46
backend/app/Models/Cart.php
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Enums\CartStatus;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class Cart extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = ['user_id', 'status'];
|
||||||
|
|
||||||
|
protected function casts()
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'status' => CartStatus::class,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function products()
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Product::class)
|
||||||
|
->withPivot('price', 'quantity')
|
||||||
|
->withTimestamps();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function user()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Scope]
|
||||||
|
protected function active(Builder $query)
|
||||||
|
{
|
||||||
|
return $query->where('status', CartStatus::Active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Scope]
|
||||||
|
protected function withProducts(Builder $query)
|
||||||
|
{
|
||||||
|
return $query->with(['products' => function ($product) {
|
||||||
|
$product->withPivot('quantity', 'price');
|
||||||
|
}]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,8 +2,11 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
@ -28,6 +31,22 @@ public function images(): HasMany
|
|||||||
return $this->hasMany(ProductImage::class, 'product_id', 'id');
|
return $this->hasMany(ProductImage::class, 'product_id', 'id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function favoritedBy(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(User::class, 'favorite_products');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function carts()
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Cart::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Scope]
|
||||||
|
protected function active(Builder $query): Builder
|
||||||
|
{
|
||||||
|
return $query->where('is_active', true);
|
||||||
|
}
|
||||||
|
|
||||||
protected static function booted(): void
|
protected static function booted(): void
|
||||||
{
|
{
|
||||||
static::saving(function ($product) {
|
static::saving(function ($product) {
|
||||||
@ -36,4 +55,11 @@ protected static function booted(): void
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function casts()
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'is_active' => 'boolean',
|
||||||
|
];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,7 +11,9 @@
|
|||||||
class User extends Authenticatable
|
class User extends Authenticatable
|
||||||
{
|
{
|
||||||
/** @use HasFactory<\Database\Factories\UserFactory> */
|
/** @use HasFactory<\Database\Factories\UserFactory> */
|
||||||
use HasFactory, Notifiable;
|
use HasFactory;
|
||||||
|
|
||||||
|
use Notifiable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The attributes that are mass assignable.
|
* The attributes that are mass assignable.
|
||||||
@ -50,4 +52,19 @@ protected function casts(): array
|
|||||||
'role' => UserRoles::class,
|
'role' => UserRoles::class,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function favoriteProducts()
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Product::class, 'favorite_products', 'user_id', 'product_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasFavorited(Product $product): bool
|
||||||
|
{
|
||||||
|
return $this->favoriteProducts()->where('product_id', $product->id)->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function carts()
|
||||||
|
{
|
||||||
|
return $this->hasMany(Cart::class);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
27
backend/app/Queries/GetProductsQuery.php
Normal file
27
backend/app/Queries/GetProductsQuery.php
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Queries;
|
||||||
|
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
|
||||||
|
final readonly class GetProductsQuery
|
||||||
|
{
|
||||||
|
public function get(?User $user = null): LengthAwarePaginator
|
||||||
|
{
|
||||||
|
return Product::query()
|
||||||
|
->active()
|
||||||
|
->when($user, function (Builder $query) use ($user) {
|
||||||
|
$query->withExists(
|
||||||
|
[
|
||||||
|
'favoritedBy' => fn (Builder $query) => $query->where('user_id', $user->id),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
})
|
||||||
|
->with(['category:id,name,slug', 'images:id,path,product_id'])
|
||||||
|
->paginate();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Product;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('favorite_products', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignIdFor(User::class);
|
||||||
|
$table->foreignIdFor(Product::class);
|
||||||
|
$table->timestamps();
|
||||||
|
$table->unique(['user_id', 'product_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('favorite_products');
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('products', function (Blueprint $table) {
|
||||||
|
$table->boolean('is_active')->default(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('products', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('is_active');
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\CartStatus;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('carts', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignIdFor(User::class);
|
||||||
|
$table->enum('status', array_column(CartStatus::cases(), 'value'));
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('carts');
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Cart;
|
||||||
|
use App\Models\Product;
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('cart_product', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignIdFor(Cart::class);
|
||||||
|
$table->foreignIdFor(Product::class);
|
||||||
|
$table->decimal('price', 10, 2);
|
||||||
|
$table->integer('quantity');
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->unique(['cart_id', 'product_id']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('cart_product');
|
||||||
|
}
|
||||||
|
};
|
||||||
@ -1,6 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Http\Controllers\AuthenticatedUserController;
|
use App\Http\Controllers\AuthenticatedUserController;
|
||||||
|
use App\Http\Controllers\CartController;
|
||||||
|
use App\Http\Controllers\FavouriteProductController;
|
||||||
use App\Http\Controllers\ProductCategoryController;
|
use App\Http\Controllers\ProductCategoryController;
|
||||||
use App\Http\Controllers\ProductController;
|
use App\Http\Controllers\ProductController;
|
||||||
use App\Http\Controllers\ProductImagesController;
|
use App\Http\Controllers\ProductImagesController;
|
||||||
@ -15,6 +17,13 @@
|
|||||||
Route::get('/user', [AuthenticatedUserController::class, 'show']);
|
Route::get('/user', [AuthenticatedUserController::class, 'show']);
|
||||||
Route::post('/logout', [AuthenticatedUserController::class, 'destroy']);
|
Route::post('/logout', [AuthenticatedUserController::class, 'destroy']);
|
||||||
Route::post('/upload/images', action: [ProductImagesController::class, 'store']);
|
Route::post('/upload/images', action: [ProductImagesController::class, 'store']);
|
||||||
|
|
||||||
|
// Favorites
|
||||||
|
Route::post('/products/{product}/favorite', [FavouriteProductController::class, 'toggle']);
|
||||||
|
|
||||||
|
Route::apiSingleton('/cart', CartController::class)
|
||||||
|
->creatable()
|
||||||
|
->destroyable();
|
||||||
});
|
});
|
||||||
Route::get('/categories', [ProductCategoryController::class, 'index']);
|
Route::get('/categories', [ProductCategoryController::class, 'index']);
|
||||||
Route::apiResource('products', ProductController::class);
|
Route::apiResource('products', ProductController::class);
|
||||||
|
|||||||
@ -1,14 +1,14 @@
|
|||||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from "@angular/core";
|
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||||
import { provideRouter, withComponentInputBinding } from "@angular/router";
|
import { provideRouter, withComponentInputBinding } from '@angular/router';
|
||||||
|
|
||||||
import { routes } from "./app.routes";
|
import { routes } from './app.routes';
|
||||||
import { provideHttpClient, withFetch, withInterceptors } from "@angular/common/http";
|
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
|
||||||
import { csrfInterceptor } from "./core/interceptors/csrf-interceptor";
|
import { csrfInterceptor } from './core/interceptors/csrf-interceptor';
|
||||||
|
|
||||||
export const appConfig: ApplicationConfig = {
|
export const appConfig: ApplicationConfig = {
|
||||||
providers: [
|
providers: [
|
||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes, withComponentInputBinding()),
|
provideRouter(routes, withComponentInputBinding()),
|
||||||
provideHttpClient(withFetch(), withInterceptors([csrfInterceptor])),
|
provideHttpClient(withInterceptors([csrfInterceptor])),
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@ -11,6 +11,7 @@ export interface ProductModel {
|
|||||||
category: Category;
|
category: Category;
|
||||||
productImages: string[];
|
productImages: string[];
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
isFavorite: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProductCollection extends PaginatedResponse<ProductModel> {}
|
export interface ProductCollection extends PaginatedResponse<ProductModel> {}
|
||||||
|
|||||||
16
src/app/core/services/favorite-service.spec.ts
Normal file
16
src/app/core/services/favorite-service.spec.ts
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { TestBed } from "@angular/core/testing";
|
||||||
|
|
||||||
|
import { FavoriteService } from "./favorite-service";
|
||||||
|
|
||||||
|
describe("FavoriteService", () => {
|
||||||
|
let service: FavoriteService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({});
|
||||||
|
service = TestBed.inject(FavoriteService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be created", () => {
|
||||||
|
expect(service).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
20
src/app/core/services/favorite-service.ts
Normal file
20
src/app/core/services/favorite-service.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { HttpClient } from "@angular/common/http";
|
||||||
|
import { inject, Injectable } from "@angular/core";
|
||||||
|
import { API_URL } from "../tokens/api-url-tokens";
|
||||||
|
|
||||||
|
export interface FavoriteResponse {
|
||||||
|
message: string;
|
||||||
|
isFavorite: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: "root",
|
||||||
|
})
|
||||||
|
export class FavoriteService {
|
||||||
|
http = inject(HttpClient);
|
||||||
|
apiUrl = inject(API_URL);
|
||||||
|
|
||||||
|
toggle(productId: number) {
|
||||||
|
return this.http.post<FavoriteResponse>(`${this.apiUrl}/products/${productId}/favorite`, {});
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,21 +1,19 @@
|
|||||||
<div class="card flex flex-col relative cursor-pointer" (click)="goToProductDetails()">
|
<div class="card flex flex-col relative cursor-pointer" (click)="goToProductDetails()">
|
||||||
<!--Favorite button -->
|
<app-favorite-button
|
||||||
<button
|
[productId]="product.id"
|
||||||
class="absolute right-6 top-6 transition-all duration-300 ease active:scale-80 hover:bg-gray-100 p-1 rounded-full"
|
[isFavorite]="product.isFavorite"
|
||||||
>
|
class="absolute top-5 right-5"
|
||||||
<lucide-angular [img]="HeartIcon" class="w-4 h-4 text-gray-500" />
|
/>
|
||||||
</button>
|
|
||||||
|
|
||||||
<!--Product image-->
|
<!--Product image-->
|
||||||
<div class="bg-gray-200 rounded-xl h-40">
|
<div class="bg-gray-200 rounded-xl h-40">
|
||||||
<img [src]="product.productImages[0]" alt="" class="object-cover rounded-xl w-full h-full" />
|
<img [src]="product.productImages[0]" alt="" class="object-cover rounded-xl w-full h-full" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="text-gray-400 text-sm truncate">{{product.title}}</p>
|
<p class="text-gray-400 text-sm truncate">{{ product.title }}</p>
|
||||||
<p class="text-gray-400 text-xs">⭐4.5</p>
|
<p class="text-gray-400 text-xs">⭐4.5</p>
|
||||||
<p class="text-gray-400 text-xs">
|
<p class="text-gray-400 text-xs">
|
||||||
Price:
|
Price:
|
||||||
<span class="line-through italic mr-1">{{product.actualPrice}}</span>
|
<span class="line-through italic mr-1">{{ product.actualPrice }}</span>
|
||||||
<span class="font-bold">{{product.listPrice}}/-</span>
|
<span class="font-bold">{{ product.listPrice }}/-</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,17 +1,15 @@
|
|||||||
import { Component, inject, Input } from "@angular/core";
|
import { Component, inject, Input } from "@angular/core";
|
||||||
import { LucideAngularModule, Heart } from "lucide-angular";
|
|
||||||
import { ProductModel } from "../../../../core/models/product.model";
|
import { ProductModel } from "../../../../core/models/product.model";
|
||||||
import { BACKEND_URL } from "../../../../core/tokens/api-url-tokens";
|
|
||||||
import { Router } from "@angular/router";
|
import { Router } from "@angular/router";
|
||||||
|
import { FavoriteButton } from "../../../../src/app/shared/components/favorite-button/favorite-button";
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: "app-product-card",
|
selector: "app-product-card",
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [LucideAngularModule],
|
imports: [FavoriteButton],
|
||||||
templateUrl: "./product-card.html",
|
templateUrl: "./product-card.html",
|
||||||
})
|
})
|
||||||
export class ProductCard {
|
export class ProductCard {
|
||||||
readonly HeartIcon = Heart;
|
|
||||||
readonly router = inject(Router);
|
readonly router = inject(Router);
|
||||||
|
|
||||||
@Input() product!: ProductModel;
|
@Input() product!: ProductModel;
|
||||||
|
|||||||
@ -2,7 +2,6 @@ import { inject, Injectable } from "@angular/core";
|
|||||||
import { HttpClient } from "@angular/common/http";
|
import { HttpClient } from "@angular/common/http";
|
||||||
import { API_URL } from "../../../core/tokens/api-url-tokens";
|
import { API_URL } from "../../../core/tokens/api-url-tokens";
|
||||||
import { ProductCollection, ProductModel } from "../../../core/models/product.model";
|
import { ProductCollection, ProductModel } from "../../../core/models/product.model";
|
||||||
import { map } from "rxjs";
|
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: "root",
|
providedIn: "root",
|
||||||
|
|||||||
@ -0,0 +1,13 @@
|
|||||||
|
<!--Favorite button -->
|
||||||
|
<button
|
||||||
|
(click)="$event.stopPropagation(); toggleFavorite($event)"
|
||||||
|
class="transition-all duration-300 ease active:scale-80 hover:bg-gray-100 p-1 rounded-full flex items-center justify-center"
|
||||||
|
>
|
||||||
|
<lucide-angular
|
||||||
|
[img]="HeartIcon"
|
||||||
|
[class.text-gray-500]="!isFavorite"
|
||||||
|
[class.text-red-400]="isFavorite"
|
||||||
|
[class]="isFavorite ? 'fill-red-500' : 'fill-none'"
|
||||||
|
class="w-4 h-4 transition-colors duration-200"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
@ -0,0 +1,22 @@
|
|||||||
|
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||||
|
|
||||||
|
import { FavoriteButton } from "./favorite-button";
|
||||||
|
|
||||||
|
describe("FavoriteButton", () => {
|
||||||
|
let component: FavoriteButton;
|
||||||
|
let fixture: ComponentFixture<FavoriteButton>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await TestBed.configureTestingModule({
|
||||||
|
imports: [FavoriteButton],
|
||||||
|
}).compileComponents();
|
||||||
|
|
||||||
|
fixture = TestBed.createComponent(FavoriteButton);
|
||||||
|
component = fixture.componentInstance;
|
||||||
|
await fixture.whenStable();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should create", () => {
|
||||||
|
expect(component).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -0,0 +1,34 @@
|
|||||||
|
import { Component, inject, Input } from "@angular/core";
|
||||||
|
import { HeartIcon, LucideAngularModule } from "lucide-angular";
|
||||||
|
import { FavoriteService } from "../../../../../core/services/favorite-service";
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: "app-favorite-button",
|
||||||
|
imports: [LucideAngularModule],
|
||||||
|
templateUrl: "./favorite-button.html",
|
||||||
|
styleUrl: "./favorite-button.css",
|
||||||
|
})
|
||||||
|
export class FavoriteButton {
|
||||||
|
@Input({ required: true }) productId!: number;
|
||||||
|
@Input() isFavorite = false;
|
||||||
|
|
||||||
|
favoriteService = inject(FavoriteService);
|
||||||
|
|
||||||
|
HeartIcon = HeartIcon;
|
||||||
|
|
||||||
|
toggleFavorite(event: Event) {
|
||||||
|
event.stopPropagation();
|
||||||
|
this.isFavorite = !this.isFavorite;
|
||||||
|
|
||||||
|
this.favoriteService.toggle(this.productId).subscribe({
|
||||||
|
next: (response) => {
|
||||||
|
this.isFavorite = response.isFavorite;
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
console.error(err);
|
||||||
|
// Revert the state incase of error
|
||||||
|
this.isFavorite = !this.isFavorite;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user