feat: nextjs setup and configuration (lib, store, css, assets)

This commit is contained in:
parsa committed 2026-06-12 01:00:54 +03:30
1 parent eff6c00a9c
commit c5a1b8e5d2
17 files changed
+1933 -17

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
import axios from 'axios';
const api = axios.create({
baseURL: '/api',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Interceptor to add auth token in the future
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
export default api;
@@ -0,0 +1,102 @@
import api from './api';
export interface User {
id: string;
firstName: string;
lastName: string;
email: string;
mobile: string | null;
role: string;
walletBalance: number;
charityDonationTotal: number;
createdAt: string;
updatedAt: string;
pets?: any[];
orders?: any[];
}
export interface AuthResponse {
success: boolean;
data: {
user: User;
accessToken: string;
};
}
export class AuthService {
private static instance: AuthService;
private constructor() {}
public static getInstance(): AuthService {
if (!AuthService.instance) {
AuthService.instance = new AuthService();
}
return AuthService.instance;
}
/**
* Send SMS verification code (OTP)
*/
public async sendOtp(phoneNumber: string): Promise<{ success: boolean; message: string }> {
try {
const response = await api.post('/auth/send-otp', { phoneNumber });
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ارسال کد تایید';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Verify SMS verification code and login/register
*/
public async verifyOtp(phoneNumber: string, code: string): Promise<AuthResponse> {
try {
const response = await api.post('/auth/verify-otp', { phoneNumber, code });
const { data } = response.data;
if (data?.accessToken) {
localStorage.setItem('accessToken', data.accessToken);
}
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'کد تایید نامعتبر است';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get current user profile
*/
public async getProfile(): Promise<User> {
try {
const response = await api.get('/users/profile');
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Update current user profile
*/
public async updateProfile(profileData: Partial<User>): Promise<User> {
try {
const response = await api.patch('/users/profile', profileData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ویرایش اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Logout user and clear tokens
*/
public logout(): void {
localStorage.removeItem('accessToken');
}
}
export const authService = AuthService.getInstance();
@@ -0,0 +1,79 @@
import api from './api';
import { CartItem } from '../store/cartStore';
export interface OrderItem {
id: string;
orderId: string;
productId: string | null;
quantity: number;
product?: any;
}
export interface Order {
id: string;
userId: string;
couponId: string | null;
totalAmount: number;
charityDonation: number;
status: string;
trackingNumber: string | null;
createdAt: string;
orderItems: OrderItem[];
}
export class OrderService {
private static instance: OrderService;
private constructor() {}
public static getInstance(): OrderService {
if (!OrderService.instance) {
OrderService.instance = new OrderService();
}
return OrderService.instance;
}
/**
* Create a new order on the backend
*/
public async createOrder(orderData: {
petId?: string;
items: { productId: string; quantity: number }[];
}): Promise<Order> {
try {
const response = await api.post('/orders', orderData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ثبت سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get all orders for the current user
*/
public async getUserOrders(): Promise<Order[]> {
try {
const response = await api.get('/orders');
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت لیست سفارش‌ها';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get order details by ID
*/
public async getOrderById(id: string): Promise<Order> {
try {
const response = await api.get(`/orders/${id}`);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت جزئیات سفارش';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
}
export const orderService = OrderService.getInstance();
@@ -0,0 +1,106 @@
import api from './api';
import { PRODUCTS, Product, PetType } from "../data/products";
export class ProductService {
private static instance: ProductService;
private constructor() {}
public static getInstance(): ProductService {
if (!ProductService.instance) {
ProductService.instance = new ProductService();
}
return ProductService.instance;
}
private mapBackendToFrontend(data: any): Product {
// Find the local static product to inherit functions like calculateDosage
const local = PRODUCTS.find(p => p.artNo === data.artNo);
const safeParse = (val: any, fallback: any) => {
if (!val) return fallback;
if (typeof val === 'string') {
try { return JSON.parse(val); } catch (e) { return fallback; }
}
return val;
};
return {
id: data.id,
artNo: data.artNo,
name: data.name,
scientificTagline: data.scientificTagline,
description: data.description,
shortDescription: data.shortDescription,
price: data.priceDisplay || `${data.priceValue.toLocaleString('fa-IR')} تومان`,
priceValue: Number(data.priceValue),
category: data.category,
categorySlug: data.categorySlug,
unit: data.unit,
packageSize: data.packageSize,
dosage_logic: data.dosageLogic,
benefits: data.benefits,
suitableFor: data.suitableFor as PetType,
storage: data.storage,
specialBadge: data.specialBadge,
onSetOfAction: data.onSetOfAction,
optimisticTemplate: data.optimisticTemplate,
feedingAdvice: data.feedingAdvice,
image: data.image,
main_ingredients: data.ingredients?.map((i: any) => i.ingredient) || [],
symptoms: data.symptoms?.map((s: any) => s.symptom) || [],
keyBenefits: safeParse(data.keyBenefits, []),
expectedResults: safeParse(data.expectedResults, []),
benefitsList: safeParse(data.benefitsList, []),
faqs: safeParse(data.faqs, []),
analysis: safeParse(data.analysis, {}),
specialist: safeParse(data.specialist, null),
relatedProducts: safeParse(data.relatedProducts, []),
contraindications: safeParse(data.contraindications, []),
calculateDosage: local?.calculateDosage || (() => ({ quantity: 0, unit: '', description: '' }))
};
}
public async getProducts(filters?: {
category?: string;
petType?: PetType | "all";
query?: string;
}): Promise<Product[]> {
const params = new URLSearchParams();
if (filters?.category && filters.category !== "all") params.append('category', filters.category);
if (filters?.petType && filters.petType !== "all") params.append('petType', filters.petType);
if (filters?.query) params.append('query', filters.query);
try {
const response = await api.get(`/products?${params.toString()}`);
return response.data.map((item: any) => this.mapBackendToFrontend(item));
} catch (error) {
console.error("[ProductService] Failed to fetch products:", error);
return [];
}
}
public async getProductById(id: string): Promise<Product | null> {
try {
const response = await api.get(`/products/${id}`);
return this.mapBackendToFrontend(response.data);
} catch (error) {
console.error(`[ProductService] Failed to fetch product ${id}:`, error);
return null;
}
}
public async getFeaturedProducts(): Promise<Product[]> {
try {
const response = await api.get('/products');
return response.data.slice(0, 4).map((item: any) => this.mapBackendToFrontend(item));
} catch (error) {
console.error("[ProductService] Failed to fetch featured products:", error);
return [];
}
}
}
export const productService = ProductService.getInstance();