Merge branch 'feature/add-product'

This commit is contained in:
kusowl 2026-02-27 18:17:35 +05:30
commit a34bea34d4
26 changed files with 538 additions and 14 deletions

View File

@ -3,12 +3,12 @@ import { provideRouter } from "@angular/router";
import { routes } from "./app.routes";
import { provideHttpClient, withFetch, withInterceptors } from "@angular/common/http";
import { authInterceptor } from "./core/interceptors/auth-interceptor";
import { csrfInterceptor } from "./core/interceptors/csrf-interceptor";
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
provideHttpClient(withFetch(), withInterceptors([csrfInterceptor])),
],
};

View File

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

View File

@ -1,6 +1,7 @@
import { Routes } from "@angular/router";
import { Home } from "./features/home/home";
import { authGuard } from "./core/guards/auth-guard";
import { roleGuard } from "./core/guards/role-guard";
export const routes: Routes = [
{
@ -12,4 +13,11 @@ export const routes: Routes = [
path: "",
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: ["broker"] },
},
];

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

@ -1,11 +1,11 @@
import { TestBed } from "@angular/core/testing";
import { HttpInterceptorFn } from "@angular/common/http";
import { authInterceptor } from "./auth-interceptor";
import { csrfInterceptor } from "./csrf-interceptor";
describe("authInterceptor", () => {
const interceptor: HttpInterceptorFn = (req, next) =>
TestBed.runInInjectionContext(() => authInterceptor(req, next));
TestBed.runInInjectionContext(() => csrfInterceptor(req, next));
beforeEach(() => {
TestBed.configureTestingModule({});

View File

@ -1,6 +1,6 @@
import { HttpInterceptorFn } from "@angular/common/http";
export const authInterceptor: HttpInterceptorFn = (req, next) => {
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;

View File

@ -13,4 +13,5 @@ export interface User {
email: string;
mobileNumber: string;
city: string;
role: string;
}

View File

@ -27,6 +27,7 @@ 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>;
@ -45,6 +46,7 @@ export class AuthService {
);
this.user = signal<User | null>(cachedUser);
this.isAuthenticated = computed(() => !!this.user());
this.userRole = computed(() => this.user()?.role || null);
}
register(userRequest: RegisterUserRequest) {
@ -74,6 +76,16 @@ export class AuthService {
);
}
/**
* 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({

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>

View File

@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { AddProduct } from "./add-product";
describe("AddProduct", () => {
let component: AddProduct;
let fixture: ComponentFixture<AddProduct>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AddProduct],
}).compileComponents();
fixture = TestBed.createComponent(AddProduct);
component = fixture.componentInstance;
await fixture.whenStable();
});
it("should create", () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,112 @@
import { Component, ElementRef, inject, signal, ViewChild } from "@angular/core";
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
import { ImageInput } from "../../../shared/components/image-input/image-input";
import { HttpClient } from "@angular/common/http";
import { API_URL } from "../../../core/tokens/api-url-tokens";
import { Error } from "../../../shared/components/error/error";
import { Category, CategoryService } from "../services/category-service";
import { forkJoin, switchMap } from "rxjs";
export interface ImageSelection {
id: string;
url: string;
file: File;
}
@Component({
selector: "app-add-product",
imports: [ReactiveFormsModule, ImageInput, Error],
templateUrl: "./add-product.html",
styleUrl: "./add-product.css",
})
export class AddProduct {
http = inject(HttpClient);
apiUrl = inject<string>(API_URL);
categoryService = inject(CategoryService);
@ViewChild("imageDialog") imageDialog!: ElementRef<HTMLDialogElement>;
activeImage = signal<ImageSelection | null>(null);
selectedImages = signal<Record<string, { url: string; file: File }>>({});
categories = signal<Category[]>([]);
successMessage = signal<string | null>(null);
productAddFrom = new FormGroup({
title: new FormControl("", {
validators: [Validators.required, Validators.minLength(3)],
}),
description: new FormControl("", {
validators: [Validators.required, Validators.minLength(10)],
}),
actual_price: new FormControl(0, { validators: [Validators.required, Validators.min(0)] }),
list_price: new FormControl(0, { validators: [Validators.required, Validators.min(0)] }),
product_category_id: new FormControl("", { validators: [Validators.required] }),
});
ngOnInit() {
this.categoryService.getCategories().subscribe({
next: (categories) => this.categories.set(categories),
error: (error) => console.log(error),
});
}
openPreview(image: ImageSelection) {
this.activeImage.set(image);
this.imageDialog.nativeElement.showModal();
}
confirmImage() {
// Add the current image to the selected images
const current = this.activeImage();
if (current) {
this.selectedImages.update((images) => ({ ...images, [current.id]: current }));
}
this.closeDialog();
}
closeDialog() {
this.activeImage.set(null);
this.imageDialog.nativeElement.close();
}
submitProductForm() {
if (this.productAddFrom.invalid) {
this.productAddFrom.markAllAsTouched();
return;
}
this.http
.post<{ id: string | number }>(`${this.apiUrl}/products`, this.productAddFrom.value)
.pipe(
switchMap((response) => {
const productId = response.id;
const images = Object.values(this.selectedImages());
if (images.length === 0) {
return [response];
}
const uploadRequests = images.map((img) => this.uploadImage(img.file, productId));
return forkJoin(uploadRequests);
}),
)
.subscribe({
next: (results) => {
this.successMessage.set("Product and images uploaded successfully!");
console.log("Product and all images uploaded successfully", results);
this.productAddFrom.reset();
this.selectedImages.set({});
setTimeout(() => this.successMessage.set(null), 3000);
},
error: (err) => console.error("Upload failed", err),
});
}
private uploadImage(file: File, productId: string | number) {
const formData = new FormData();
formData.append("image", file);
formData.append("product_id", productId.toString());
return this.http.post(`${this.apiUrl}/upload/images`, formData);
}
}

View File

View File

@ -0,0 +1 @@
<p>product works!</p>

View File

@ -0,0 +1,9 @@
import { Routes } from "@angular/router";
import { AddProduct } from "./add-product/add-product";
export const productRoutes: Routes = [
{
path: "create",
component: AddProduct,
},
];

View File

@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { Product } from "./product";
describe("Product", () => {
let component: Product;
let fixture: ComponentFixture<Product>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Product],
}).compileComponents();
fixture = TestBed.createComponent(Product);
component = fixture.componentInstance;
await fixture.whenStable();
});
it("should create", () => {
expect(component).toBeTruthy();
});
});

View File

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

View File

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

View File

@ -0,0 +1,21 @@
import { inject, Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { API_URL } from "../../../core/tokens/api-url-tokens";
export interface Category {
id: number;
name: string;
slug: string;
}
@Injectable({
providedIn: "root",
})
export class CategoryService {
private http = inject(HttpClient);
private apiUrl = inject(API_URL);
getCategories() {
return this.http.get<Category[]>(`${this.apiUrl}/categories`);
}
}

View File

@ -6,11 +6,13 @@ import { UpperCaseFirstPipe } from "../../pipes/upper-case-first-pipe";
selector: "app-error",
imports: [UpperCaseFirstPipe],
template: `
<div class="min-h-4">
@if (this.control && this.control.touched) {
@for (error of getErrorMessages(); track error) {
<p class="ml-2 text-xs text-red-400">{{ error | upperCaseFirst }}</p>
}
}
</div>
`,
})
export class Error {

View File

@ -0,0 +1,29 @@
<div class="relative input-image input-image-ghost h-full w-full">
@if (bgImageUrl) {
<label
[for]="id"
[style.backgroundImage]="'url(' + bgImageUrl + ')'"
class="absolute inset-0 bg-cover bg-center bg-no-repeat p-4 w-full h-full flex flex-col space-y-4 justify-center items-center cursor-pointer rounded-xl"
>
<div class="absolute inset-0 bg-black/40 h-full rounded-xl"></div>
<lucide-angular [img]="cameraIcon" class="w-10 h-10 text-white stroke-1 z-10" />
<p class="text-white text-sm font-semibold z-10">Change image</p>
</label>
} @else {
<label
[for]="id"
class="absolute inset-0 p-4 w-full h-full flex flex-col space-y-4 justify-center items-center cursor-pointer hover:bg-gray-50 rounded-xl"
>
<lucide-angular [img]="cameraIcon" class="w-10 h-10 text-gray-400 stroke-1" />
<p class="text-gray-500 text-sm">Click to upload</p>
</label>
}
<input
(change)="handleFileSelect($event)"
[id]="id"
class="absolute opacity-0 w-full h-full top-0 right-0"
placeholder="Upload image"
type="file"
/>
</div>

View File

@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { ImageInput } from "./image-input";
describe("ImageInput", () => {
let component: ImageInput;
let fixture: ComponentFixture<ImageInput>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ImageInput],
}).compileComponents();
fixture = TestBed.createComponent(ImageInput);
component = fixture.componentInstance;
await fixture.whenStable();
});
it("should create", () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,26 @@
import { Component, EventEmitter, Input, Output } from "@angular/core";
import { Camera, LucideAngularModule } from "lucide-angular";
import { ImageSelection } from "../../../features/product/add-product/add-product";
@Component({
selector: "app-image-input",
imports: [LucideAngularModule],
templateUrl: "./image-input.html",
styleUrl: "./image-input.css",
})
export class ImageInput {
cameraIcon = Camera;
@Output() imageSelected = new EventEmitter<ImageSelection>();
@Input() id!: string;
@Input() bgImageUrl: string | undefined;
handleFileSelect(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files && input.files[0]) {
const file = input.files[0];
const url = URL.createObjectURL(file);
this.imageSelected.emit({ id: this.id, url: url, file: file });
}
}
}

View File

@ -13,7 +13,7 @@
}
body {
@apply bg-gray-100;
@apply bg-gray-100 antialiased m-0;
}
.wrapper {
@ -21,7 +21,7 @@ body {
}
.btn {
@apply rounded-full transition-all duration-200 font-medium ease-out flex justify-center active:translate-y-px disabled:opacity-50 disabled:cursor-not-allowed;
@apply rounded-xl py-2 transition-all duration-200 font-medium ease-out flex justify-center active:translate-y-px disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-ghost {
@ -39,6 +39,7 @@ body {
.fieldset {
@apply space-y-1;
}
.fieldset-legend {
@apply text-xs font-bold ml-2 text-gray-800;
}
@ -51,6 +52,14 @@ body {
@apply p-3 border border-gray-300 rounded-xl text-sm w-full;
}
.input-image {
@apply rounded-xl border bg-teal-100 border-teal-500 border-dashed;
}
.input-image-ghost {
@apply bg-gray-100 border-gray-300;
}
.dropdown {
position-area: span-left bottom;
@apply p-4 mt-2 border border-gray-300 shadow-lg rounded-xl space-y-2 text-gray-800;
@ -59,3 +68,16 @@ body {
.dropdown li {
@apply rounded-lg hover:bg-linear-to-r hover:from-teal-300 hover:to-transparent px-5 py-1;
}
h1,
h2,
h3,
h4,
h5,
h6 {
@apply font-space text-gray-800;
}
h1 {
@apply text-3xl my-4 ml-2;
}