Compare commits

...

31 Commits

Author SHA1 Message Date
kusowl
63b3d06d3a BREAKING CHANGE: remove wrapping for individual address resource 2026-03-17 11:00:32 +05:30
kusowl
3ae3374eec chore: formatting
- updated format via pint
2026-03-13 18:09:06 +05:30
kusowl
c27ae1969f feature: add address api
- users can save, edi and delete addresses
- each user can have multiple address
- used shallow routes for address
2026-03-13 18:08:45 +05:30
kusowl
61ecbec994 chore: add command to generate dto
- add make:dto command which generates dto in App\Data namespace
- varient: --input (default), --output
2026-03-13 11:28:22 +05:30
kusowl
03f044b8d3 chore: add ide helper
- add laravel ide helper package for better LSP support
- update dependencies
2026-03-13 10:08:55 +05:30
kusowl
5bbec0ee2b feature: update quantity and remove product from cart
add endpoint for update quantity of products (min:1, max:10)
add endpoint for removing product from cart
2026-03-10 19:01:52 +05:30
kusowl
1656739ecd feature: add and fetch products in cart api
- schema for cart and product
- define relationship, DTO, Resource and API collections
- Add post and get endpoint for cart api
2026-03-09 19:07:27 +05:30
kusowl
95afd46406 fix: add isFavorite on Product show response 2026-03-05 18:07:46 +05:30
kusowl
0f56303d59 fix sanctum and session environment variables 2026-03-05 14:43:21 +05:30
kusowl
a4eebef321 Merge branch 'feature/products' into staging 2026-03-05 13:48:30 +05:30
kusowl
a57566c1fe Merge branch 'backend' into staging 2026-03-05 13:48:24 +05:30
kusowl
7e1ecf35b9 make favorite state persistant with api 2026-03-05 13:34:37 +05:30
kusowl
ae008fbc9c chore: add isFavorite in produtcs response
- refactor code to use query
- add active column in products
2026-03-05 13:32:49 +05:30
kusowl
8ef4383bd9 feature: endpoint to favorite product 2026-03-05 10:32:40 +05:30
kusowl
b575b42f22 Merge remote-tracking branch 'origin/feature/products' into fix/history-issue
# Conflicts:
#	src/app/features/product/components/product-card/product-card.html
#	src/app/features/product/components/product-card/product-card.ts
#	src/app/features/product/services/product-service.ts
2026-03-03 17:40:12 +05:30
kusowl
553637d8e2 fix: commit whole changes 2026-03-03 17:27:30 +05:30
kusowl
f5393f5110 feature: show products on the home page and add individual product page 2026-03-02 18:47:43 +05:30
kusowl
068975d3b0 Merge branch 'backend' 2026-02-27 18:22:36 +05:30
kusowl
a34bea34d4 Merge branch 'feature/add-product' 2026-02-27 18:17:35 +05:30
kusowl
8b1b831ea2 feature: authorization - add role guard and protect products route 2026-02-27 13:22:02 +05:30
kusowl
617053c0ee feature: upload images and show alert after successfull product creation 2026-02-26 19:02:39 +05:30
kusowl
bb05fb7747 feature: add product page
- add UI
- add dialog for preview selected images
2026-02-25 19:04:00 +05:30
kusowl
03525280db Merge branch 'feature/main/login' 2026-02-24 18:49:45 +05:30
kusowl
6e2fd45803 Merge branch 'backend' 2026-02-24 18:49:33 +05:30
kusowl
4a4c8bd4e3 feature: user logout and auth states
added s authState which helps conditonaly render components based on this state

stored user details in localStoarge so that server side end point does not get hit in every page load.

add a guard which protects routes and redirects to login if user is not logged in.

create a logout route
2026-02-24 18:14:21 +05:30
kusowl
043d54bcd0 user can login via frontend 2026-02-23 18:53:54 +05:30
kusowl
0427d1c62d feature: user can login to backend 2026-02-23 18:46:23 +05:30
kusowl
aee7e4fd89 navigate user after successful registration.
- data is passed via state
2026-02-23 16:10:59 +05:30
kusowl
4aba99fcb5 chore: format 2026-02-23 15:08:06 +05:30
kusowl
78bf326622 add client side validation errors 2026-02-23 15:07:43 +05:30
kusowl
77532aaac2 Show server side validation errors 2026-02-23 12:17:14 +05:30
131 changed files with 34453 additions and 356 deletions

0
.ai/mcp/mcp.json Normal file
View File

2
.gitignore vendored
View File

@ -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

3
.oxfmtrc.json Normal file
View File

@ -0,0 +1,3 @@
{
"ignorePatterns": ["backend/**", "*.min.js"]
}

1
.rgignore Normal file
View File

@ -0,0 +1 @@
backend/

View File

@ -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": {

View File

@ -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

2346
backend/.phpstorm.meta.php Normal file

File diff suppressed because it is too large Load Diff

28541
backend/_ide_helper.php Normal file

File diff suppressed because it is too large Load Diff

View 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');
}]));
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Actions;
use App\Models\Address;
final readonly class DeleteUserAddressAction
{
/**
* Execute the action.
*/
public function execute(Address $address)
{
$address->users()->detach();
$address->delete();
return response()->noContent();
}
}

View 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());
}
}

View 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);
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Actions;
use App\Data\AddUserAddressRequestDTO;
use App\Data\UserAddressResponseDTO;
use App\Models\User;
final readonly class SaveUserAddressAction
{
/**
* Execute the action.
*/
public function execute(AddUserAddressRequestDTO $data, User $user)
{
return UserAddressResponseDTO::fromModel(
$user
->addresses()
->create($data->toArray())
);
}
}

View 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');
}]));
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Actions;
use App\Data\UpdateUserAddressRequestDTO;
use App\Data\UserAddressResponseDTO;
use App\Models\Address;
final readonly class UpdateUserAddressAction
{
/**
* Execute the action.
*/
public function execute(UpdateUserAddressRequestDTO $data, Address $address)
{
$address->update($data->toArray());
$address->refresh();
return UserAddressResponseDTO::fromModel($address);
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class MakeDtoCommand extends GeneratorCommand
{
/**
* The console command name and signature.
*
* @var string
*/
protected $name = 'make:dto';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Data Transfer Object class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'DTO';
/**
* Get the stub file for the generator.
*/
protected function getStub(): string
{
if ($this->option('output')) {
return base_path('stubs/dto.output.stub');
}
return base_path('stubs/dto.input.stub');
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
*/
protected function getDefaultNamespace($rootNamespace): string
{
return $rootNamespace.'\Data';
}
/**
* Get the console command options.
*/
protected function getOptions(): array
{
return [
['input', 'i', InputOption::VALUE_NONE, 'Generate an Input DTO (default)'],
['output', 'o', InputOption::VALUE_NONE, 'Generate an Output DTO'],
];
}
}

View 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
);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Data;
use App\Contracts\InputDataTransferObject;
use Illuminate\Foundation\Http\FormRequest;
final readonly class AddUserAddressRequestDTO implements InputDataTransferObject
{
public function __construct(
public string $firstName,
public string $lastName,
public string $street,
public string $city,
public string $state,
public string $pinCode
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'street' => $this->street,
'city' => $this->city,
'state' => $this->state,
'pin' => $this->pinCode,
];
}
public static function fromRequest(FormRequest $request): InputDataTransferObject
{
return new self(
firstName: $request->firstName,
lastName: $request->lastName,
street: $request->street,
city: $request->city,
state: $request->state,
pinCode: $request->pinCode
);
}
}

View 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()
);
}
}

View 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,
];
}
}

View File

@ -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,
); );
} }
} }

View File

@ -0,0 +1,47 @@
<?php
namespace App\Data;
use App\Contracts\InputDataTransferObject;
use Illuminate\Foundation\Http\FormRequest;
final readonly class UpdateUserAddressRequestDTO implements InputDataTransferObject
{
public function __construct(
public ?string $firstName = null,
public ?string $lastName = null,
public ?string $street = null,
public ?string $city = null,
public ?string $state = null,
public ?string $pinCode = null,
) {}
/**
* @return array<string = null = null, mixed>
*/
public function toArray(): array
{
$data = [
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'street' => $this->street,
'city' => $this->city,
'state' => $this->state,
'pin' => $this->pinCode,
];
return array_filter($data, fn ($value) => $value !== null);
}
public static function fromRequest(FormRequest $request): InputDataTransferObject
{
return new self(
firstName: $request->input('firstName'),
lastName: $request->input('lastName'),
street: $request->input('street'),
city: $request->input('city'),
state: $request->input('state'),
pinCode: $request->input('pinCode'),
);
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Data;
use App\Contracts\OutputDataTransferObject;
use App\Models\Address;
final readonly class UserAddressResponseDTO implements OutputDataTransferObject
{
public function __construct(
public int $id,
public string $firstName,
public string $lastName,
public string $street,
public string $city,
public string $state,
public string $pinCode
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'id' => $this->id,
'firstName' => $this->firstName,
'lastName' => $this->lastName,
'street' => $this->street,
'city' => $this->city,
'state' => $this->state,
'pinCode' => $this->pinCode,
];
}
public static function fromModel(Address $address): OutputDataTransferObject
{
return new self(
id: $address->id,
firstName: $address->first_name,
lastName: $address->last_name,
street: $address->street,
city: $address->city,
state: $address->state,
pinCode: $address->pin
);
}
}

View 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
}

View 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);
}
}
}

View 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,
]);
}
}

View File

@ -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));
} }

View File

@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers;
use App\Actions\DeleteUserAddressAction;
use App\Actions\SaveUserAddressAction;
use App\Actions\UpdateUserAddressAction;
use App\Data\AddUserAddressRequestDTO;
use App\Data\UpdateUserAddressRequestDTO;
use App\Data\UserAddressResponseDTO;
use App\Http\Requests\AddUserAddressRequest;
use App\Http\Requests\UpdateUserAddressRequest;
use App\Http\Resources\AddressResource;
use App\Models\Address;
use Illuminate\Http\Request;
class UserAddressController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request)
{
$addresses = $request->user()->addresses;
$data = $addresses->map(fn ($address) => UserAddressResponseDTO::fromModel($address));
return AddressResource::collection($data);
}
/**
* Store a newly created resource in storage.
*/
public function store(AddUserAddressRequest $request, SaveUserAddressAction $action)
{
return new AddressResource($action->execute(AddUserAddressRequestDTO::fromRequest($request), $request->user()));
}
/**
* Display the specified resource.
*/
public function show(Address $address)
{
return new AddressResource(UserAddressResponseDTO::fromModel($address));
}
/**
* Update the specified resource in storage.
*/
public function update(UpdateUserAddressRequest $request, Address $address, UpdateUserAddressAction $action)
{
return new AddressResource($action->execute(UpdateUserAddressRequestDTO::fromRequest($request), $address));
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Address $address, DeleteUserAddressAction $action)
{
return $action->execute($address);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
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, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'productId' => 'required|exists:products,id',
'quantity' => 'required|numeric|min:1',
];
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
class AddUserAddressRequest 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, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'firstName' => 'required|string|min:3|max:50',
'lastName' => 'required|string|min:3|max:50',
'street' => 'required|string|min:3|max:100',
'city' => 'required|string|min:3|max:20',
'state' => 'required|string|min:3|max:40',
'pinCode' => 'required|string|min:3|max:10',
];
}
}

View File

@ -2,6 +2,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
@ -18,7 +19,7 @@ public function authorize(): bool
/** /**
* Get the validation rules that apply to the request. * Get the validation rules that apply to the request.
* *
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> * @return array<string, ValidationRule|array<mixed>|string>
*/ */
public function rules(): array public function rules(): array
{ {

View File

@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
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, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'productId' => ['required', 'exists:products,id'],
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
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, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'productId' => ['required', 'exists:products,id'],
'quantity' => ['required', 'min:0', 'max:10'],
];
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserAddressRequest 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, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'firstName' => 'sometimes|string|min:3|max:50',
'lastName' => 'sometimes|string|min:3|max:50',
'street' => 'sometimes|string|min:3|max:100',
'city' => 'sometimes|string|min:3|max:20',
'state' => 'sometimes|string|min:3|max:40',
'pinCode' => 'sometimes|string|min:3|max:10',
];
}
}

View File

@ -2,6 +2,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
class UploadImageRequest extends FormRequest class UploadImageRequest extends FormRequest
@ -17,7 +18,7 @@ public function authorize(): bool
/** /**
* Get the validation rules that apply to the request. * Get the validation rules that apply to the request.
* *
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> * @return array<string, ValidationRule|array<mixed>|string>
*/ */
public function rules(): array public function rules(): array
{ {

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
class AddressCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @return array<int|string, mixed>
*/
public function toArray(Request $request): array
{
return parent::toArray($request);
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Http\Resources;
use App\Data\UserAddressResponseDTO;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @property UserAddressResponseDTO $resource
*/
class AddressResource 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,
'firstName' => $this->resource->firstName,
'lastName' => $this->resource->lastName,
'street' => $this->resource->street,
'city' => $this->resource->city,
'state' => $this->resource->state,
'pinCode' => $this->resource->pinCode,
];
}
}

View 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);
}
}

View 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),
];
}
}

View 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),
];
}
}

View 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,
];
}
}

View File

@ -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,
]; ];
} }
} }

View File

@ -0,0 +1,49 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
/**
* @property-read User|null $user
*
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address query()
*
* @property-read Collection<int, User> $users
* @property-read int|null $users_count
* @property int $id
* @property string $first_name
* @property string $last_name
* @property string $street
* @property string $city
* @property string $state
* @property string $pin
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereCity($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereFirstName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereLastName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address wherePin($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereState($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereStreet($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Address whereUpdatedAt($value)
*
* @mixin \Eloquent
*/
class Address extends Model
{
protected $fillable = ['first_name', 'last_name', 'street', 'city', 'state', 'pin'];
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Models;
use App\Enums\CartStatus;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property int $user_id
* @property CartStatus $status
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Collection<int, Product> $products
* @property-read int|null $products_count
* @property-read User|null $user
*
* @method static Builder<static>|Cart active()
* @method static Builder<static>|Cart newModelQuery()
* @method static Builder<static>|Cart newQuery()
* @method static Builder<static>|Cart query()
* @method static Builder<static>|Cart whereCreatedAt($value)
* @method static Builder<static>|Cart whereId($value)
* @method static Builder<static>|Cart whereStatus($value)
* @method static Builder<static>|Cart whereUpdatedAt($value)
* @method static Builder<static>|Cart whereUserId($value)
* @method static Builder<static>|Cart withProducts()
*
* @mixin \Eloquent
*/
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');
}]);
}
}

View File

@ -2,11 +2,52 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
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\Carbon;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/**
* @property int $id
* @property string $title
* @property string|null $slug
* @property string $description
* @property numeric $actual_price
* @property numeric $list_price
* @property int $product_category_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property bool $is_active
* @property-read Collection<int, Cart> $carts
* @property-read int|null $carts_count
* @property-read ProductCategory|null $category
* @property-read Collection<int, User> $favoritedBy
* @property-read int|null $favorited_by_count
* @property-read Collection<int, ProductImage> $images
* @property-read int|null $images_count
*
* @method static Builder<static>|Product active()
* @method static Builder<static>|Product newModelQuery()
* @method static Builder<static>|Product newQuery()
* @method static Builder<static>|Product query()
* @method static Builder<static>|Product whereActualPrice($value)
* @method static Builder<static>|Product whereCreatedAt($value)
* @method static Builder<static>|Product whereDescription($value)
* @method static Builder<static>|Product whereId($value)
* @method static Builder<static>|Product whereIsActive($value)
* @method static Builder<static>|Product whereListPrice($value)
* @method static Builder<static>|Product whereProductCategoryId($value)
* @method static Builder<static>|Product whereSlug($value)
* @method static Builder<static>|Product whereTitle($value)
* @method static Builder<static>|Product whereUpdatedAt($value)
*
* @mixin \Eloquent
*/
class Product extends Model class Product extends Model
{ {
protected $fillable = [ protected $fillable = [
@ -28,6 +69,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 +93,11 @@ protected static function booted(): void
} }
}); });
} }
protected function casts()
{
return [
'is_active' => 'boolean',
];
}
} }

View File

@ -3,7 +3,26 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property string $name
* @property string $slug
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory whereSlug($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductCategory whereUpdatedAt($value)
*
* @mixin \Eloquent
*/
class ProductCategory extends Model class ProductCategory extends Model
{ {
// //

View File

@ -4,7 +4,27 @@
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property string $path
* @property int $product_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Product|null $product
*
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage wherePath($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage whereProductId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ProductImage whereUpdatedAt($value)
*
* @mixin \Eloquent
*/
class ProductImage extends Model class ProductImage extends Model
{ {
protected $fillable = [ protected $fillable = [

View File

@ -4,14 +4,59 @@
// use Illuminate\Contracts\Auth\MustVerifyEmail; // use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\UserRoles; use App\Enums\UserRoles;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Notifications\DatabaseNotificationCollection;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
/**
* @property int $id
* @property string $name
* @property string $email
* @property Carbon|null $email_verified_at
* @property string $password
* @property string|null $remember_token
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string $mobile_number
* @property string $city
* @property UserRoles $role
* @property-read Collection<int, Cart> $carts
* @property-read int|null $carts_count
* @property-read Collection<int, Product> $favoriteProducts
* @property-read int|null $favorite_products_count
* @property-read DatabaseNotificationCollection<int, DatabaseNotification> $notifications
* @property-read int|null $notifications_count
*
* @method static \Database\Factories\UserFactory factory($count = null, $state = [])
* @method static \Illuminate\Database\Eloquent\Builder<static>|User newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereCity($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereEmail($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereEmailVerifiedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereMobileNumber($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User wherePassword($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereRememberToken($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereRole($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereUpdatedAt($value)
*
* @mixin \Eloquent
*/
class User extends Authenticatable class User extends Authenticatable
{ {
/** @use HasFactory<\Database\Factories\UserFactory> */ /** @use HasFactory<UserFactory> */
use HasFactory, Notifiable; use HasFactory;
use Notifiable;
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
@ -50,4 +95,24 @@ protected function casts(): array
'role' => UserRoles::class, 'role' => UserRoles::class,
]; ];
} }
public function favoriteProducts(): BelongsToMany
{
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);
}
public function addresses(): BelongsToMany
{
return $this->belongsToMany(Address::class);
}
} }

View 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();
}
}

View File

@ -1,5 +1,7 @@
<?php <?php
use App\Providers\AppServiceProvider;
return [ return [
App\Providers\AppServiceProvider::class, AppServiceProvider::class,
]; ];

View File

@ -15,6 +15,7 @@
"laravel/tinker": "^2.10.1" "laravel/tinker": "^2.10.1"
}, },
"require-dev": { "require-dev": {
"barryvdh/laravel-ide-helper": "^3.6",
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2", "laravel/pail": "^1.2.2",
"laravel/pint": "^1.24", "laravel/pint": "^1.24",
@ -55,7 +56,10 @@
"@php artisan package:discover --ansi" "@php artisan package:discover --ansi"
], ],
"post-update-cmd": [ "post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force" "@php artisan vendor:publish --tag=laravel-assets --ansi --force",
"@php artisan vendor:publish --tag=laravel-assets --ansi --force",
"@php artisan ide-helper:generate",
"@php artisan ide-helper:meta"
], ],
"post-root-package-install": [ "post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""

679
backend/composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,7 @@
<?php <?php
use App\Models\User;
return [ return [
/* /*
@ -62,7 +64,7 @@
'providers' => [ 'providers' => [
'users' => [ 'users' => [
'driver' => 'eloquent', 'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class), 'model' => env('AUTH_MODEL', User::class),
], ],
// 'users' => [ // 'users' => [

View File

@ -1,6 +1,7 @@
<?php <?php
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Pdo\Mysql;
return [ return [
@ -59,7 +60,7 @@
'strict' => true, 'strict' => true,
'engine' => null, 'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([ 'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'), (PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [], ]) : [],
], ],
@ -79,7 +80,7 @@
'strict' => true, 'strict' => true,
'engine' => null, 'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([ 'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? \Pdo\Mysql::ATTR_SSL_CA : \PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'), (PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [], ]) : [],
], ],

View File

@ -1,5 +1,8 @@
<?php <?php
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
use Laravel\Sanctum\Sanctum; use Laravel\Sanctum\Sanctum;
return [ return [
@ -76,9 +79,9 @@
*/ */
'middleware' => [ 'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class, 'authenticate_session' => AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class, 'encrypt_cookies' => EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, 'validate_csrf_token' => ValidateCsrfToken::class,
], ],
]; ];

View File

@ -2,12 +2,13 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str; use Illuminate\Support\Str;
/** /**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User> * @extends Factory<User>
*/ */
class UserFactory extends Factory class UserFactory extends Factory
{ {

View File

@ -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');
}
};

View File

@ -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');
});
}
};

View File

@ -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');
}
};

View File

@ -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');
}
};

View File

@ -0,0 +1,33 @@
<?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::create('addresses', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->string('street');
$table->string('city');
$table->string('state');
$table->string('pin');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('addresses');
}
};

View File

@ -0,0 +1,29 @@
<?php
use App\Models\Address;
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('address_user', function (Blueprint $table) {
$table->foreignIdFor(User::class)->constrained()->cascadeOnDelete();
$table->foreignIdFor(Address::class)->constrained()->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('address_user');
}
};

View File

@ -1,10 +1,13 @@
<?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;
use App\Http\Controllers\RegisteredUserController; use App\Http\Controllers\RegisteredUserController;
use App\Http\Controllers\UserAddressController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::middleware('guest')->group(function () { Route::middleware('guest')->group(function () {
@ -15,6 +18,15 @@
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::apiResource('user.addresses', UserAddressController::class)->shallow();
}); });
Route::get('/categories', [ProductCategoryController::class, 'index']); Route::get('/categories', [ProductCategoryController::class, 'index']);
Route::apiResource('products', ProductController::class); Route::apiResource('products', ProductController::class);

View File

@ -0,0 +1,30 @@
<?php
namespace {{ namespace }};
use App\Contracts\InputDataTransferObject;
use Illuminate\Foundation\Http\FormRequest;
final readonly class {{ class }} implements InputDataTransferObject
{
public function __construct(
// TODO: Define your properties here
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
// TODO: Map properties to array
];
}
public static function fromRequest(FormRequest $request): InputDataTransferObject
{
return new self(
// TODO: Map request data to properties
);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace {{ namespace }};
use App\Contracts\OutputDataTransferObject;
use Illuminate\Database\Eloquent\Model;
final readonly class {{ class }} implements OutputDataTransferObject
{
public function __construct(
// TODO: Define your properties here
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
// TODO: Map properties to array
];
}
public static function fromModel(Model $model): OutputDataTransferObject
{
return new self(
// TODO: Map model data to properties
);
}
}

View File

@ -1,5 +1,7 @@
<?php <?php
use Tests\TestCase;
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Test Case | Test Case
@ -11,7 +13,7 @@
| |
*/ */
pest()->extend(Tests\TestCase::class) pest()->extend(TestCase::class)
// ->use(Illuminate\Foundation\Testing\RefreshDatabase::class) // ->use(Illuminate\Foundation\Testing\RefreshDatabase::class)
->in('Feature'); ->in('Feature');

View File

@ -1,8 +1,14 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from "@angular/core"; import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } 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 { csrfInterceptor } from './core/interceptors/csrf-interceptor';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes)], providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(withInterceptors([csrfInterceptor])),
],
}; };

View File

@ -1,3 +1,7 @@
<div class="flex min-h-screen flex-col antialiased m-0">
<app-header /> <app-header />
<main class="flex-1">
<router-outlet></router-outlet> <router-outlet></router-outlet>
</main>
<app-footer /> <app-footer />
</div>

View File

@ -1,13 +1,23 @@
import { Routes } from "@angular/router"; import { Routes } from "@angular/router";
import { Home } from "./features/home/home"; import { Home } from "./features/home/home";
import { authGuard } from "./core/guards/auth-guard";
import { roleGuard } from "./core/guards/role-guard";
export const routes: Routes = [ export const routes: Routes = [
{ {
path: "", path: "",
component: Home, component: Home,
canActivate: [authGuard],
}, },
{ {
path: "", path: "",
loadChildren: () => import("./features/auth/auth.routes").then((routes) => routes.AuthRoutes), loadChildren: () => import("./features/auth/auth.routes").then((routes) => routes.AuthRoutes),
}, },
{
path: "products",
loadChildren: () =>
import("./features/product/product.routes").then((routes) => routes.productRoutes),
canActivate: [authGuard, roleGuard],
data: { roles: ["admin", "broker"] },
},
]; ];

View File

@ -1,6 +1,6 @@
import { Component, signal } from "@angular/core"; import { Component, signal } from "@angular/core";
import { RouterOutlet } from "@angular/router"; import { RouterOutlet } from "@angular/router";
import { Products } from "./features/home/products/products"; import { Product } from "./features/product/product";
import { Footer } from "./core/layouts/footer/footer"; import { Footer } from "./core/layouts/footer/footer";
import { Header } from "./core/layouts/header/header"; import { Header } from "./core/layouts/header/header";

View File

@ -0,0 +1,17 @@
import { TestBed } from "@angular/core/testing";
import { CanActivateFn } from "@angular/router";
import { authGuard } from "./auth-guard";
describe("authGuard", () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => authGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it("should be created", () => {
expect(executeGuard).toBeTruthy();
});
});

View File

@ -0,0 +1,11 @@
import { CanActivateFn, Router } from "@angular/router";
import { inject } from "@angular/core";
import { AuthService } from "../../features/auth/services/auth-service";
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated()) return true;
return router.navigate(["/login"]);
};

View File

@ -0,0 +1,17 @@
import { TestBed } from "@angular/core/testing";
import { CanActivateFn } from "@angular/router";
import { roleGuard } from "./role-guard";
describe("roleGuard", () => {
const executeGuard: CanActivateFn = (...guardParameters) =>
TestBed.runInInjectionContext(() => roleGuard(...guardParameters));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it("should be created", () => {
expect(executeGuard).toBeTruthy();
});
});

View File

@ -0,0 +1,12 @@
import { CanActivateFn } from "@angular/router";
import { inject } from "@angular/core";
import { AuthService } from "../../features/auth/services/auth-service";
export const roleGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
// get role from route data passed in route config.
const roles = route.data["roles"] as string[];
return roles && authService.hasRoles(roles);
};

View File

@ -0,0 +1,17 @@
import { TestBed } from "@angular/core/testing";
import { HttpInterceptorFn } from "@angular/common/http";
import { csrfInterceptor } from "./csrf-interceptor";
describe("authInterceptor", () => {
const interceptor: HttpInterceptorFn = (req, next) =>
TestBed.runInInjectionContext(() => csrfInterceptor(req, next));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it("should be created", () => {
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,20 @@
import { HttpInterceptorFn } from "@angular/common/http";
export const csrfInterceptor: HttpInterceptorFn = (req, next) => {
const getCookie = (name: string): string | null => {
const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return match ? decodeURIComponent(match[3]) : null;
};
let headers = req.headers.set("Accept", "application/json");
const xsrfToken = getCookie("XSRF-TOKEN");
if (xsrfToken) {
headers = headers.set("X-XSRF-TOKEN", xsrfToken);
}
const clonedRequest = req.clone({
withCredentials: true,
headers: headers,
});
return next(clonedRequest);
};

View File

@ -18,7 +18,7 @@
<div class="footer-links"> <div class="footer-links">
<a href="">Home</a> <a href="">Home</a>
<a href="">Products</a> <a href="">Product</a>
<a href="">About Us</a> <a href="">About Us</a>
<a href="">Contact Us</a> <a href="">Contact Us</a>
</div> </div>

View File

@ -3,14 +3,14 @@
class="bg-gray-50 wrapper py-4 flex gap-x-5 sm:gap-x-10 items-center shadow-lg shadow-gray-400/20" class="bg-gray-50 wrapper py-4 flex gap-x-5 sm:gap-x-10 items-center shadow-lg shadow-gray-400/20"
> >
<div class=""> <div class="">
<a href="/" class="px-3 py-1 bg-gray-800 text-white">eKart</a> <a class="px-3 py-1 bg-gray-800 text-white" href="/">eKart</a>
</div> </div>
<div class="flex-1 grid grid-cols-[1fr_auto]"> <div class="flex-1 grid grid-cols-[1fr_auto]">
<input <input
type="text"
class="w-full border border-gray-300 text-sm rounded-full rounded-r-none px-6 py-1" class="w-full border border-gray-300 text-sm rounded-full rounded-r-none px-6 py-1"
placeholder="Search watches, brands, products..." placeholder="Search watches, brands, products..."
type="text"
/> />
<button class="btn btn-ghost rounded-l-none! py-1 px-3 border-l-0!"> <button class="btn btn-ghost rounded-l-none! py-1 px-3 border-l-0!">
<lucide-angular [img]="SearchIcon" class="w-5" /> <lucide-angular [img]="SearchIcon" class="w-5" />
@ -20,9 +20,9 @@
<div class="flex space-x-4"> <div class="flex space-x-4">
<div class="flex text-gray-600"> <div class="flex text-gray-600">
<button <button
class="btn btn-ghost py-1 px-2 rounded-r-none!"
popovertarget="popover-1" popovertarget="popover-1"
style="anchor-name: --anchor-1" style="anchor-name: --anchor-1"
class="btn btn-ghost py-1 px-2 rounded-r-none!"
> >
<lucide-angular [img]="UserIcon" class="w-5" /> <lucide-angular [img]="UserIcon" class="w-5" />
</button> </button>
@ -32,8 +32,14 @@
</div> </div>
</div> </div>
</nav> </nav>
<ul class="dropdown" popover id="popover-1" style="position-anchor: --anchor-1"> <ul class="dropdown" id="popover-1" popover style="position-anchor: --anchor-1">
<li><a class="block h-full w-full" href="">Login</a></li> @if (authService.authState() === AuthState.Unauthenticated) {
<li><a class="block h-full w-full" routerLink="/login">Login</a></li>
} @else if (authService.authState() === AuthState.Loading) {
<li><a class="block h-full w-full">Loading</a></li>
} @else {
<li><a class="block h-full w-full" routerLink="/logout">Logout</a></li>
}
<li><a class="block h-full w-full" href="">My Account</a></li> <li><a class="block h-full w-full" href="">My Account</a></li>
<li><a class="block h-full w-full" href="">Orders</a></li> <li><a class="block h-full w-full" href="">Orders</a></li>
<li><a class="block h-full w-full" href="">Wishlist</a></li> <li><a class="block h-full w-full" href="">Wishlist</a></li>

View File

@ -1,8 +1,11 @@
import { Component } from "@angular/core"; import { Component, inject } from "@angular/core";
import { LucideAngularModule, User, ShoppingCart, Search } from "lucide-angular"; import { LucideAngularModule, Search, ShoppingCart, User } from "lucide-angular";
import { RouterLink } from "@angular/router";
import { AuthService, AuthState } from "../../../features/auth/services/auth-service";
@Component({ @Component({
selector: "app-header", selector: "app-header",
imports: [LucideAngularModule], imports: [LucideAngularModule, RouterLink],
templateUrl: "./header.html", templateUrl: "./header.html",
styleUrl: "./header.css", styleUrl: "./header.css",
}) })
@ -10,4 +13,6 @@ export class Header {
readonly UserIcon = User; readonly UserIcon = User;
readonly CartIcon = ShoppingCart; readonly CartIcon = ShoppingCart;
readonly SearchIcon = Search; readonly SearchIcon = Search;
readonly authService = inject(AuthService);
protected readonly AuthState = AuthState;
} }

View File

@ -0,0 +1,25 @@
export interface PaginatedResponse<T> {
data: T[];
links: {
next: string | null;
prev: string | null;
last: string | null;
first: string | null;
};
meta: {
total: number;
per_page: number;
current_page: number;
last_page: number;
from: number;
to: number;
links: links[];
};
}
interface links {
url: string | null;
label: string;
active: boolean;
page: number | null;
}

View File

@ -0,0 +1,17 @@
import { PaginatedResponse } from "./paginated.model";
import { Category } from "../../features/product/services/category-service";
export interface ProductModel {
id: number;
title: string;
slug: string;
description: string;
actualPrice: number;
listPrice: number;
category: Category;
productImages: string[];
updatedAt: string;
isFavorite: boolean;
}
export interface ProductCollection extends PaginatedResponse<ProductModel> {}

View File

@ -6,3 +6,12 @@ export interface RegisterUserRequest{
password_confirmation: string | null; password_confirmation: string | null;
city: string | null; city: string | null;
} }
export interface User {
id: number;
name: string;
email: string;
mobileNumber: string;
city: string;
role: string;
}

View 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();
});
});

View 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`, {});
}
}

View File

@ -0,0 +1,39 @@
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root",
})
export class LocalStorageService {
setItem<T>(key: string, value: T) {
try {
const item = JSON.stringify(value);
localStorage.setItem(key, item);
} catch (e) {
console.error("Error storing item in local storage: ", e);
}
}
getItem<T>(key: string): T | null {
try {
const item = localStorage.getItem(key);
return item ? (JSON.parse(item) as T) : null;
} catch (err) {
console.error("Error getting item from local storage: ", err);
return null;
}
}
/**
* @throws Error if item is not found
*/
removeItem(key: string) {
localStorage.removeItem(key);
}
/**
* @Throws Error if localstorage API is not available
*/
clear() {
localStorage.clear();
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from "@angular/core/testing";
import { LocalStorageService } from "./local-storage.service";
describe("LocalStorage", () => {
let service: LocalStorageService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(LocalStorageService);
});
it("should be created", () => {
expect(service).toBeTruthy();
});
});

View File

@ -1,7 +1,12 @@
import { InjectionToken } from "@angular/core"; import { InjectionToken } from "@angular/core";
import {environment} from '../../../environments/environment'; import { environment } from "../../../environments/environment";
export const API_URL = new InjectionToken<string>('API_URL', { export const API_URL = new InjectionToken<string>("API_URL", {
providedIn: "root", providedIn: "root",
factory: () => environment.apiUrl factory: () => environment.apiUrl,
}) });
export const BACKEND_URL = new InjectionToken<string>("API_URL", {
providedIn: "root",
factory: () => environment.backendUrl,
});

View File

@ -1,6 +1,8 @@
import { Routes } from "@angular/router"; import { Router, Routes } from "@angular/router";
import { Login } from "./components/login/login"; import { Login } from "./components/login/login";
import { Register } from "./components/register/register"; import { Register } from "./components/register/register";
import { inject } from "@angular/core";
import { AuthService } from "./services/auth-service";
export const AuthRoutes: Routes = [ export const AuthRoutes: Routes = [
{ {
@ -14,6 +16,19 @@ export const AuthRoutes: Routes = [
path: "register", path: "register",
component: Register, component: Register,
}, },
{
path: "logout",
component: Login,
canActivate: [
() => {
const authService = inject(AuthService);
const router = inject(Router);
authService.logout().subscribe(() => router.navigate(["/login"]));
return false;
},
],
},
], ],
}, },
]; ];

View File

@ -1,4 +1,11 @@
<section class="my-10 sm:my-20 flex justify-center items-center"> @if (successMessage) {
<div
class="px-4 py-3 mb-8 bg-teal-100 rounded-lg text-teal-800 text-sm mt-10 max-w-11/12 sm:max-w-8/12 mx-auto"
>
<p>{{successMessage}}</p>
</div>
}
<section class="my-5 sm:my-10 flex justify-center items-center">
<article class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 lg:grid-cols-3 gap-4"> <article class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 lg:grid-cols-3 gap-4">
<div class="md:col-span-1 lg:col-span-2"> <div class="md:col-span-1 lg:col-span-2">
<img <img
@ -13,21 +20,25 @@
<h2 class="text-xl text-gray-600">Get access to your Orders, Wishlist and Recommendations</h2> <h2 class="text-xl text-gray-600">Get access to your Orders, Wishlist and Recommendations</h2>
<form class="flex flex-col space-y-5"> <form [formGroup]="loginForm" (ngSubmit)="loginUser()" class="flex flex-col space-y-5">
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Email</legend> <legend class="fieldset-legend">Email</legend>
<input type="text" class="input" placeholder="Enter email here" /> <input formControlName="email" type="text" class="input" placeholder="Enter email here" />
<p class="label">your-email-address@email.com</p> <p class="label">your-email-address@email.com</p>
<app-error fieldName="email" [control]="loginForm.get('email')" />
</fieldset> </fieldset>
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Password</legend> <legend class="fieldset-legend">Password</legend>
<input type="password" class="input" placeholder="Type here" /> <input formControlName="password" type="password" class="input" placeholder="Type here" />
<app-error fieldName="password" [control]="loginForm.get('password')" />
</fieldset> </fieldset>
<button type="submit" class="btn btn-black py-2">Login</button> <button type="submit" class="btn btn-black py-2">Login</button>
</form> </form>
<a href="" class="text-xs text-gray-800 text-center w-full block hover:text-teal-600" <a
routerLink="/register"
class="text-xs text-gray-800 text-center w-full block hover:text-teal-600"
>New User ? Sign Up</a >New User ? Sign Up</a
> >
</article> </article>

View File

@ -1,9 +1,38 @@
import { Component } from "@angular/core"; import { Component, inject } from "@angular/core";
import { Router, RouterLink } from "@angular/router";
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
import { AuthService } from "../../services/auth-service";
import { Error } from "../../../../shared/components/error/error";
@Component({ @Component({
selector: "app-login", selector: "app-login",
imports: [], imports: [RouterLink, ReactiveFormsModule, Error],
templateUrl: "./login.html", templateUrl: "./login.html",
styleUrl: "./login.css", styleUrl: "./login.css",
}) })
export class Login {} export class Login {
successMessage: string | undefined;
authService = inject(AuthService);
loginForm = new FormGroup({
email: new FormControl("", { validators: [Validators.required, Validators.email] }),
password: new FormControl("", { validators: [Validators.required] }),
});
constructor(private router: Router) {
const navigator = this.router.currentNavigation();
const state = navigator?.extras.state as { message?: string };
this.successMessage = state?.message;
}
loginUser() {
if (this.loginForm.invalid) {
this.loginForm.markAllAsTouched();
return;
}
this.authService.login(this.loginForm.value as { email: string; password: string }).subscribe({
next: () => this.router.navigate(["/"]),
});
}
}

View File

@ -1,44 +1,82 @@
<section class="my-10 sm:my-30 flex flex-col sm:flex-row space-x-20 justify-center items-center"> <section
class="my-10 md:my-30 flex flex-col md:flex-row space-x-20 space-y-10 justify-center items-center"
>
<article class="space-y-6"> <article class="space-y-6">
<h1 class="text-3xl text-gray-800 font-space font-bold">Register</h1> <h1 class="text-3xl text-gray-800 font-space font-bold">Register</h1>
<h2 class="text-xl text-gray-600">Sign up with your<br />email address to get started</h2> <h2 class="text-xl text-gray-600">Sign up with your<br />email address to get started</h2>
<div class="text-xs text-red-600 space-y-2">
@for (error of errors(); track error) {
<p>{{ error }}</p>
}
</div>
</article> </article>
<form [formGroup]="registerForm" (ngSubmit)="registerUser()" class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 gap-4"> <form
<article class="space-y-4"> [formGroup]="registerForm"
(ngSubmit)="registerUser()"
class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 gap-4"
>
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Name</legend> <legend class="fieldset-legend">Name*</legend>
<input type="text" class="input" formControlName="name" placeholder="Jhon Doe" /> <input type="text" name="name" class="input" formControlName="name" placeholder="Jhon Doe" />
<app-error fieldName="name" [control]="registerForm.get('name')" />
</fieldset> </fieldset>
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Mobile Number</legend> <legend class="fieldset-legend">Mobile Number*</legend>
<input type="text" class="input" formControlName="mobile_number" placeholder="+X1 XXXXXXXXXX" /> <input
type="text"
name="mobile_number"
class="input"
formControlName="mobile_number"
placeholder="+X1 XXXXXXXXXX"
/>
<app-error fieldName="mobile number" [control]="registerForm.get('mobile_number')" />
</fieldset> </fieldset>
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Email</legend> <legend class="fieldset-legend">Email*</legend>
<input type="text" class="input" formControlName="email" placeholder="Enter email here" /> <input type="text" class="input" formControlName="email" placeholder="Enter email here" />
<p class="label">your-email-address@email.com</p> <p class="label">your-email-address@email.com</p>
<app-error fieldName="email" [control]="registerForm.get('email')" />
</fieldset> </fieldset>
</article>
<article class="space-y-4">
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Password</legend> <legend class="fieldset-legend">City*</legend>
<input
type="text"
name="city"
class="input"
formControlName="city"
placeholder="Your city name"
/>
<app-error fieldName="city" [control]="registerForm.get('city')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Password*</legend>
<input type="password" class="input" formControlName="password" placeholder="Type here" /> <input type="password" class="input" formControlName="password" placeholder="Type here" />
<app-error fieldName="password" [control]="registerForm.get('password')" />
</fieldset> </fieldset>
<fieldset class="fieldset"> <fieldset class="fieldset">
<legend class="fieldset-legend">Confirm Password</legend> <legend class="fieldset-legend">Confirm Password*</legend>
<input type="text" class="input" formControlName="password_confirmation" placeholder="Type here" /> <input
type="text"
class="input"
formControlName="password_confirmation"
placeholder="Type here"
/>
<app-error [control]="registerForm.get('password_confirmation')" />
</fieldset> </fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">City</legend>
<input type="text" class="input" formControlName="city" placeholder="Your city name" />
</fieldset>
</article>
<div class="flex flex-col col-span-2 gap-y-2"> <div class="flex flex-col col-span-2 gap-y-2">
<button type="submit" class="btn btn-black py-2 w-full">Register</button> <button type="submit" [disabled]="registerForm.invalid" class="btn btn-black py-2 w-full">
<a href="" class="text-xs text-gray-800 text-center w-full block hover:text-teal-600" Register
</button>
<a
routerLink="/login"
class="text-xs text-gray-800 text-center w-full block hover:text-teal-600"
>Already have an account ? Login</a >Already have an account ? Login</a
> >
</div> </div>

View File

@ -1,30 +1,45 @@
import { Component, inject } from "@angular/core"; import { Component, inject, signal } from "@angular/core";
import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms"; import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
import { AuthService } from "../../services/auth-service"; import { AuthService } from "../../services/auth-service";
import { RegisterUserRequest } from "../../../../core/models/user.model"; import { RegisterUserRequest } from "../../../../core/models/user.model";
import { Error } from "../../../../shared/components/error/error";
import { Router, RouterLink } from "@angular/router";
@Component({ @Component({
selector: "app-register", selector: "app-register",
imports: [ReactiveFormsModule], imports: [ReactiveFormsModule, Error, RouterLink],
templateUrl: "./register.html", templateUrl: "./register.html",
styleUrl: "./register.css", styleUrl: "./register.css",
}) })
export class Register { export class Register {
authService = inject(AuthService); authService = inject(AuthService);
router = inject(Router);
errors = signal<string[]>([]);
registerForm = new FormGroup({ registerForm = new FormGroup({
name :new FormControl(''), name: new FormControl("", { validators: [Validators.required] }),
email :new FormControl(''), email: new FormControl("", { validators: [Validators.required, Validators.email] }),
mobile_number : new FormControl(''), mobile_number: new FormControl("", { validators: [Validators.required] }),
password : new FormControl(''), password: new FormControl("", { validators: [Validators.required] }),
password_confirmation : new FormControl(''), password_confirmation: new FormControl("", { validators: [Validators.required] }),
city : new FormControl(''), city: new FormControl("", { validators: [Validators.required] }),
}); });
registerUser() { registerUser() {
this.authService.register(this.registerForm.value as RegisterUserRequest) // validation errors if user submit early
.subscribe(); if (this.registerForm.invalid) {
this.registerForm.markAllAsTouched();
return;
} }
this.authService.register(this.registerForm.value as RegisterUserRequest).subscribe({
next: () =>
this.router.navigate(["/login"], { state: { message: "Registration successful!" } }),
error: (error) => {
const errors: Record<number, string[]> = error?.error?.errors || {};
const errorMessages: string[] = Object.values(errors).flat();
this.errors.set(errorMessages);
},
});
}
} }

View File

@ -1,8 +1,8 @@
import { TestBed } from '@angular/core/testing'; import { TestBed } from "@angular/core/testing";
import { AuthService } from './auth-service'; import { AuthService } from "./auth-service";
describe('AuthService', () => { describe("AuthService", () => {
let service: AuthService; let service: AuthService;
beforeEach(() => { beforeEach(() => {
@ -10,7 +10,7 @@ describe('AuthService', () => {
service = TestBed.inject(AuthService); service = TestBed.inject(AuthService);
}); });
it('should be created', () => { it("should be created", () => {
expect(service).toBeTruthy(); expect(service).toBeTruthy();
}); });
}); });

View File

@ -1,19 +1,112 @@
import { Injectable, inject } from '@angular/core'; import { computed, inject, Injectable, Signal, signal, WritableSignal } from "@angular/core";
import { RegisterUserRequest } from '../../../core/models/user.model'; import { RegisterUserRequest, User } from "../../../core/models/user.model";
import { HttpClient } from '@angular/common/http'; import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { API_URL } from '../../../core/tokens/api-url-tokens'; import { API_URL, BACKEND_URL } from "../../../core/tokens/api-url-tokens";
import { switchMap, tap } from "rxjs";
import { LocalStorageService } from "../../../core/services/local-storage.service";
export enum AuthState {
Loading = "loading",
Authenticated = "authenticated",
Unauthenticated = "unauthenticated",
}
/**
* UserService - manages user related operations
*
* ## Auth States
* - loading: user is being fetched from the server
* - authenticated: user is authenticated
* - unauthenticated: user is not authenticated
*/
@Injectable({ @Injectable({
providedIn: 'root', providedIn: "root",
}) })
export class AuthService { export class AuthService {
// User states
readonly authState: WritableSignal<AuthState>;
readonly user: WritableSignal<User | null>;
readonly userRole: Signal<string | null>;
// Computed state for easy checking
readonly isAuthenticated: Signal<boolean>;
// Dependent services
private localStorage = inject(LocalStorageService);
private http: HttpClient = inject(HttpClient); private http: HttpClient = inject(HttpClient);
// Constants
private readonly userKey = "ekart_user";
private apiUrl = inject(API_URL); private apiUrl = inject(API_URL);
private backendURL = inject(BACKEND_URL);
constructor() {
const cachedUser = this.localStorage.getItem<User>(this.userKey);
this.authState = signal<AuthState>(
cachedUser ? AuthState.Authenticated : AuthState.Unauthenticated,
);
this.user = signal<User | null>(cachedUser);
this.isAuthenticated = computed(() => !!this.user());
this.userRole = computed(() => this.user()?.role || null);
}
register(userRequest: RegisterUserRequest) { register(userRequest: RegisterUserRequest) {
console.log(this.apiUrl);
return this.http.post(`${this.apiUrl}/register`, userRequest); return this.http.post(`${this.apiUrl}/register`, userRequest);
} }
/**
* Laravel API expects the csrf cookie to be set before making a request.
* First set the cookie then attempt to login.
* If the login is successful, set the user in the state.
*/
login(credentials: { email: string; password: string }) {
return this.getCsrfCookie().pipe(
switchMap(() =>
this.http.post(`${this.backendURL}/login`, credentials, { observe: "response" }),
),
switchMap(() => this.getCurrentUser()),
);
}
getCurrentUser() {
return this.http.get<User>(`${this.apiUrl}/user`).pipe(
tap({
next: (user) => this.setAuth(user),
error: (error: HttpErrorResponse) => this.purgeAuth(),
}),
);
}
/**
* Check if current user has the role.
* Mostly used in role guard.
*/
hasRoles(roles: string[]) {
const role = this.userRole();
if (!role) return false;
return roles.includes(role);
}
logout() {
return this.http.post(`${this.backendURL}/logout`, {}).pipe(
tap({
next: () => this.purgeAuth(),
}),
);
}
private getCsrfCookie() {
return this.http.get(`${this.backendURL}/sanctum/csrf-cookie`);
}
private setAuth(user: User) {
this.localStorage.setItem<User>(this.userKey, user);
this.user.set(user);
this.authState.set(AuthState.Authenticated);
}
private purgeAuth() {
this.localStorage.removeItem(this.userKey);
this.user.set(null);
this.authState.set(AuthState.Unauthenticated);
}
} }

View File

@ -1,9 +1,9 @@
import { Component } from "@angular/core"; import { Component } from "@angular/core";
import { Products } from "./products/products"; import { Product } from "../product/product";
@Component({ @Component({
selector: "app-home", selector: "app-home",
imports: [Products], imports: [Product],
templateUrl: "./home.html", templateUrl: "./home.html",
styleUrl: "./home.css", styleUrl: "./home.css",
}) })

View File

@ -1,17 +0,0 @@
<div class="card flex flex-col relative">
<!--Favorite button -->
<button
class="absolute right-6 top-6 transition-all duration-300 ease active:scale-80 hover:bg-gray-100 p-1 rounded-full"
>
<lucide-angular [img]="HeartIcon" class="w-4 h-4 text-gray-500" />
</button>
<!--Product image-->
<div class="bg-gray-200 rounded-xl h-40">
<img src="https://placehold.co/400x600" alt="" class="object-cover rounded-xl w-full h-full" />
</div>
<p class="text-gray-400 text-sm">Product Name</p>
<p class="text-gray-400 text-xs">⭐4.5</p>
<p class="text-gray-400 text-xs">Price: 4999/-</p>
</div>

View File

@ -1,12 +0,0 @@
import { Component } from "@angular/core";
import { LucideAngularModule, Heart } from "lucide-angular";
@Component({
selector: "app-product-card",
standalone: true,
imports: [LucideAngularModule],
templateUrl: "./product-card.html",
})
export class ProductCard {
readonly HeartIcon = Heart;
}

View File

@ -1,9 +0,0 @@
import { Component } from "@angular/core";
import { ProductCard } from "./componets/product-card/product-card";
@Component({
selector: "app-products",
imports: [ProductCard],
templateUrl: "./products.html",
})
export class Products {}

View File

@ -0,0 +1,157 @@
<section class="wrapper">
@if (successMessage()) {
<div
class="fixed top-5 right-5 z-50 flex items-center p-4 mb-4 text-green-800 rounded-lg bg-green-50 border border-green-200 shadow-lg animate-bounce-in"
role="alert"
>
<svg
aria-hidden="true"
class="flex-shrink-0 w-4 h-4"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5Zm3.707 8.207-4 4a1 1 0 0 1-1.414 0l-2-2a1 1 0 0 1 1.414-1.414L9 10.586l3.293-3.293a1 1 0 0 1 1.414 1.414Z"
/>
</svg>
<div class="ms-3 text-sm font-medium">{{ successMessage() }}</div>
<button
(click)="successMessage.set(null)"
class="ms-auto -mx-1.5 -my-1.5 bg-green-50 text-green-500 rounded-lg p-1.5 hover:bg-green-200 inline-flex items-center justify-center h-8 w-8"
type="button"
>
<span class="sr-only">Close</span>
</button>
</div>
}
<h1 class="h1">Add Product</h1>
<section class="card">
<form
(ngSubmit)="submitProductForm()"
[formGroup]="productAddFrom"
class="flex flex-col sm:flex-row gap-4"
>
<fieldset class="flex flex-col space-y-4 min-w-0 flex-1">
<fieldset class="fieldset">
<legend class="fieldset-legend">Title</legend>
<input
class="input"
formControlName="title"
id="title"
placeholder="Enter product title"
type="text"
/>
<app-error [control]="productAddFrom.get('title')" fieldName="title" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Description</legend>
<textarea
class="input"
formControlName="description"
id="description"
rows="5"
></textarea>
<app-error [control]="productAddFrom.get('description')" fieldName="description" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Select category</legend>
<select class="input" formControlName="product_category_id" id="category">
<option disabled selected value="">Select Category</option>
@for (category of categories(); track category?.id) {
<option [value]="category?.id">{{ category.name }}</option>
}
</select>
<app-error [control]="productAddFrom.get('product_category_id')" fieldName="category" />
</fieldset>
</fieldset>
<fieldset class="flex flex-col space-y-4 min-w-0 flex-1">
<div class="flex gap-4">
<fieldset class="fieldset flex-1">
<legend class="fieldset-legend">List Price</legend>
<input
class="input"
formControlName="list_price"
id="list-price"
placeholder="$0"
type="number"
/>
<label class="label" for="list-price">Price to be shown as MRP</label>
<app-error [control]="productAddFrom.get('list_price')" fieldName="List Price" />
</fieldset>
<fieldset class="fieldset flex-1">
<legend class="fieldset-legend">Actual Price</legend>
<input
class="input"
formControlName="actual_price"
id="actual-price"
placeholder="$0"
type="number"
/>
<label class="label" for="actual-price">Price to be calculated when billing</label>
<app-error [control]="productAddFrom.get('actual_price')" fieldName="Actual Price" />
</fieldset>
</div>
<fieldset class="fieldset">
<legend class="fieldset-legend">Image</legend>
<div class="grid grid-cols-1 sm:grid-cols-3 sm:h-36 gap-4">
<app-image-input
(imageSelected)="openPreview($event)"
[bgImageUrl]="selectedImages()['image_1']?.url"
id="image_1"
/>
<app-image-input
(imageSelected)="openPreview($event)"
[bgImageUrl]="selectedImages()['image_2']?.url"
id="image_2"
/>
<app-image-input
(imageSelected)="openPreview($event)"
[bgImageUrl]="selectedImages()['image_3']?.url"
id="image_3"
/>
<dialog
#imageDialog
class="relative min-w-11/12 min-h-11/12 m-auto p-4 rounded-xl bg-gray-50 overflow-x-hidden backdrop:bg-black/50 backdrop:backdrop-blur-xs"
>
<div class="flex flex-col gap-4 overflow-hidden">
<div class="flex self-end gap-4 fixed top-10 right-10">
<button
(click)="closeDialog()"
class="btn btn-ghost bg-gray-50 py-1 px-4 shadow-xl"
type="button"
>
✕ Close
</button>
<button
(click)="confirmImage()"
class="btn btn-black py-1 px-4 shadow-xl"
type="button"
>
✓ Select
</button>
</div>
<div class="overflow-y-scroll rounded-lg">
<img
[src]="activeImage()?.url"
alt="Product Preview"
class="w-full h-auto object-contain"
/>
</div>
</div>
</dialog>
</div>
</fieldset>
<button class="btn btn-black py-2" type="submit">Add Product</button>
</fieldset>
</form>
</section>
</section>

Some files were not shown because too many files have changed in this diff Show More