feat(whole project): huge changes, huge updates
This commit is contained in:
196 files changed
+9146
-4316
No files matched your search
@@ -0,0 +1,116 @@
|
||||
import React, { createContext, useState, useContext, useEffect } from 'react';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { STORAGE_KEYS } from '../constants/storageKeys';
|
||||
import api from '../api';
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
checkUser();
|
||||
}, []);
|
||||
|
||||
const checkUser = async () => {
|
||||
try {
|
||||
const token = await AsyncStorage.getItem(STORAGE_KEYS.AUTH_TOKEN);
|
||||
const userData = await AsyncStorage.getItem(STORAGE_KEYS.USER_DATA);
|
||||
|
||||
if (token && userData) {
|
||||
setUser(JSON.parse(userData));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error checking user:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const login = async (email, password) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await api.login(email, password);
|
||||
|
||||
if (response.token) {
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.AUTH_TOKEN, response.token);
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.USER_DATA, JSON.stringify(response.user));
|
||||
setUser(response.user);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (err) {
|
||||
console.error('Login error:', err);
|
||||
setError(err.message);
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.AUTH_TOKEN);
|
||||
await AsyncStorage.removeItem(STORAGE_KEYS.USER_DATA);
|
||||
setUser(null);
|
||||
} catch (err) {
|
||||
console.error('Logout error:', err);
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (userData) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await api.register(userData);
|
||||
|
||||
if (response.token) {
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.AUTH_TOKEN, response.token);
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.USER_DATA, JSON.stringify(response.user));
|
||||
setUser(response.user);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (err) {
|
||||
console.error('Registration error:', err);
|
||||
setError(err.message);
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{
|
||||
user,
|
||||
loading,
|
||||
error,
|
||||
login,
|
||||
logout,
|
||||
register,
|
||||
isAuthenticated: !!user
|
||||
}}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export default AuthContext;
|
||||
@@ -1,23 +1,79 @@
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { getCart } from '../api';
|
||||
import { getCart, validateCoupon } from '../api';
|
||||
import { setGlobalRefreshCart } from '../api';
|
||||
|
||||
const CartContext = createContext();
|
||||
|
||||
export const CartProvider = ({ children }) => {
|
||||
const [cartCount, setCartCount] = useState(0);
|
||||
const [cartTotal, setCartTotal] = useState(0);
|
||||
const [appliedCoupon, setAppliedCoupon] = useState(null);
|
||||
const [couponDiscount, setCouponDiscount] = useState(0);
|
||||
const [discount, setDiscount] = useState(0);
|
||||
const navigation = useNavigation();
|
||||
|
||||
const updateCartCount = useCallback(async () => {
|
||||
try {
|
||||
const cart = await getCart();
|
||||
setCartCount(cart?.items?.length || 0);
|
||||
|
||||
// Calculate cart total
|
||||
const total = cart?.items?.reduce((sum, item) => {
|
||||
const price = parseFloat(item.product_price || item.price || 0);
|
||||
const quantity = parseInt(item.quantity || 1);
|
||||
return sum + (price * quantity);
|
||||
}, 0) || 0;
|
||||
|
||||
setCartTotal(total);
|
||||
|
||||
// Calculate discount (6% of total)
|
||||
const calculatedDiscount = (total * 6) / 100;
|
||||
setDiscount(calculatedDiscount);
|
||||
|
||||
// If there's an applied coupon, recalculate the discount
|
||||
if (appliedCoupon) {
|
||||
applyCoupon(appliedCoupon.code);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating cart count:', error);
|
||||
// Don't set cart count to 0 on error, keep previous value
|
||||
}
|
||||
}, []);
|
||||
}, [appliedCoupon]);
|
||||
|
||||
const applyCoupon = async (code) => {
|
||||
try {
|
||||
if (!code) return;
|
||||
|
||||
const result = await validateCoupon(code, cartTotal);
|
||||
|
||||
if (result.valid) {
|
||||
setAppliedCoupon(result.coupon);
|
||||
setCouponDiscount(result.discount);
|
||||
return { success: true, discount: result.discount };
|
||||
} else {
|
||||
setAppliedCoupon(null);
|
||||
setCouponDiscount(0);
|
||||
return { success: false, message: result.message };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error applying coupon:', error);
|
||||
setAppliedCoupon(null);
|
||||
setCouponDiscount(0);
|
||||
|
||||
// Extract the error message from the response if available
|
||||
const errorMessage = error.response?.data?.message || 'Failed to apply coupon';
|
||||
return { success: false, message: errorMessage };
|
||||
}
|
||||
};
|
||||
|
||||
const removeCoupon = useCallback(() => {
|
||||
// Clear all coupon-related state
|
||||
setAppliedCoupon(null);
|
||||
setCouponDiscount(0);
|
||||
|
||||
// Force a cart refresh to update totals
|
||||
updateCartCount();
|
||||
}, [updateCartCount]);
|
||||
|
||||
useEffect(() => {
|
||||
// Set the global refresh function
|
||||
@@ -38,7 +94,16 @@ export const CartProvider = ({ children }) => {
|
||||
}, [navigation, updateCartCount]);
|
||||
|
||||
return (
|
||||
<CartContext.Provider value={{ cartCount, refreshCart: updateCartCount }}>
|
||||
<CartContext.Provider value={{
|
||||
cartCount,
|
||||
cartTotal,
|
||||
appliedCoupon,
|
||||
couponDiscount,
|
||||
discount,
|
||||
refreshCart: updateCartCount,
|
||||
applyCoupon,
|
||||
removeCoupon
|
||||
}}>
|
||||
{children}
|
||||
</CartContext.Provider>
|
||||
);
|
||||
@@ -50,4 +115,6 @@ export const useCart = () => {
|
||||
throw new Error('useCart must be used within a CartProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
};
|
||||
|
||||
export default CartContext;
|
||||
@@ -0,0 +1,106 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { Alert } from 'react-native';
|
||||
import {
|
||||
getNotifications,
|
||||
markNotificationAsRead as markNotificationAsReadApi,
|
||||
deleteNotification as deleteNotificationApi,
|
||||
clearAllNotifications as clearAllNotificationsApi,
|
||||
} from '../api';
|
||||
import axios from 'axios';
|
||||
import { API_URL } from '../config';
|
||||
|
||||
const NotificationContext = createContext();
|
||||
|
||||
export const NotificationProvider = ({ children }) => {
|
||||
const [notifications, setNotifications] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const fetchNotifications = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const data = await getNotifications();
|
||||
setNotifications(Array.isArray(data) ? data : []);
|
||||
} catch (err) {
|
||||
setError('Failed to fetch notifications');
|
||||
console.error('Error fetching notifications:', err);
|
||||
setNotifications([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const markAsRead = async (notificationId) => {
|
||||
try {
|
||||
await markNotificationAsReadApi(notificationId);
|
||||
setNotifications((prev) =>
|
||||
prev.map((notification) =>
|
||||
notification.id === notificationId
|
||||
? { ...notification, read: true }
|
||||
: notification
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Error marking notification as read:', err);
|
||||
Alert.alert('Error', 'Failed to mark notification as read');
|
||||
}
|
||||
};
|
||||
|
||||
const clearNotification = async (notificationId) => {
|
||||
try {
|
||||
await deleteNotificationApi(notificationId);
|
||||
setNotifications((prev) =>
|
||||
prev.filter((notification) => notification.id !== notificationId)
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Error deleting notification:', err);
|
||||
Alert.alert('Error', 'Failed to delete notification');
|
||||
}
|
||||
};
|
||||
|
||||
const clearAllNotifications = async () => {
|
||||
try {
|
||||
await clearAllNotificationsApi();
|
||||
setNotifications([]);
|
||||
} catch (err) {
|
||||
console.error('Error clearing notifications:', err);
|
||||
Alert.alert('Error', 'Failed to clear notifications');
|
||||
}
|
||||
};
|
||||
|
||||
const getUnreadCount = () => {
|
||||
return notifications.filter((notification) => !notification.read).length;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchNotifications();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<NotificationContext.Provider
|
||||
value={{
|
||||
notifications,
|
||||
loading,
|
||||
error,
|
||||
fetchNotifications,
|
||||
markAsRead,
|
||||
clearNotification,
|
||||
clearAllNotifications,
|
||||
getUnreadCount,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</NotificationContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useNotifications = () => {
|
||||
const context = useContext(NotificationContext);
|
||||
if (!context) {
|
||||
throw new Error('useNotifications must be used within a NotificationProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export default NotificationContext;
|
||||
Reference in new issue
Block a user