update,
This commit is contained in:
99
tsc1877/task1/aws/workspace/admin/src/contexts/auth.js
Normal file
99
tsc1877/task1/aws/workspace/admin/src/contexts/auth.js
Normal file
@@ -0,0 +1,99 @@
|
||||
import { useRouter } from 'next/router';
|
||||
import React, { createContext, useEffect, useState } from 'react';
|
||||
import CheckSession from 'src/api/checkSession';
|
||||
import Loading from 'src/components/Loading';
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
const AuthProvider = ({ children }) => {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const [username, setUsername] = useState(null);
|
||||
const router = useRouter();
|
||||
|
||||
const performLogin = ({ values }) => {
|
||||
return fetch('/api/auth/login', { method: 'POST', body: JSON.stringify(values) })
|
||||
.then(res => res.json())
|
||||
.then(res_json => {
|
||||
let { status, username: username_found } = res_json;
|
||||
setUsername(username_found);
|
||||
|
||||
if (status == 'admin login OK') {
|
||||
localStorage.setItem('session', JSON.stringify(res_json));
|
||||
|
||||
router.replace('/admin');
|
||||
} else if (status == 'customer login OK') {
|
||||
localStorage.setItem('session', JSON.stringify(res_json));
|
||||
router.replace('/shopfront/customer/profile');
|
||||
} else {
|
||||
alert('Invalid username or password');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
});
|
||||
};
|
||||
|
||||
const performLogout = () => {
|
||||
setUsername(null);
|
||||
localStorage.clear('session');
|
||||
};
|
||||
|
||||
const performChangePassword = ({ old_password, new_password }) => {
|
||||
return fetch('/api/auth/change_password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ username, old_password, new_password }),
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(res_json => {
|
||||
let { status } = res_json;
|
||||
|
||||
if (status == 'password change ok') {
|
||||
performLogout();
|
||||
router.replace('/shopfront');
|
||||
} else {
|
||||
alert('password change failed');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
});
|
||||
};
|
||||
|
||||
let [loading, setLoading] = useState(true);
|
||||
useEffect(() => {
|
||||
let session_string = localStorage.getItem('session');
|
||||
if (session_string) {
|
||||
let { session } = JSON.parse(session_string);
|
||||
|
||||
CheckSession({ session }).then(data => {
|
||||
let { username: username_found } = data;
|
||||
setUsername(username_found);
|
||||
});
|
||||
setLoading(false);
|
||||
} else {
|
||||
setLoading(false);
|
||||
router.replace('/shopfront');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const helloworld = () => {
|
||||
console.log('helloworld');
|
||||
};
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<>
|
||||
<Loading />
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ username, setUsername, isAuthenticated, performLogin, performLogout, performChangePassword, helloworld }}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export { AuthContext, AuthProvider };
|
149
tsc1877/task1/aws/workspace/admin/src/contexts/cart.js
Normal file
149
tsc1877/task1/aws/workspace/admin/src/contexts/cart.js
Normal file
@@ -0,0 +1,149 @@
|
||||
import { useRouter } from 'next/router';
|
||||
import React, { createContext, useEffect, useState } from 'react';
|
||||
import checkoutCart from 'src/api/checkoutCart';
|
||||
import fetchProducts from 'src/api/fetchProducts';
|
||||
|
||||
const CartContext = createContext();
|
||||
const CartConsumer = CartContext.Consumer;
|
||||
|
||||
const CartProvider = ({ children }) => {
|
||||
const [cart, setCart] = useState([]);
|
||||
const [total_price, setTotalPrice] = useState(0);
|
||||
const [products, setProducts] = useState([]);
|
||||
|
||||
const changeCartItemQty = (pid, quantity, unit_price) => {
|
||||
if (quantity < 1) {
|
||||
alert('please enter a number greater than 0');
|
||||
} else {
|
||||
const productExistInCart = cart.find(item => item.pid === pid);
|
||||
|
||||
if (productExistInCart) {
|
||||
const max_item_allowed = products.filter(p => p.pid === pid)[0].count;
|
||||
|
||||
const item = cart.find(item => item.pid === pid);
|
||||
const allow_to_add_item = quantity <= max_item_allowed;
|
||||
|
||||
if (allow_to_add_item) {
|
||||
const final_item = quantity;
|
||||
setCart(cart.map(item => (item.pid === pid ? { ...item, quantity: final_item, unit_price } : item)));
|
||||
} else {
|
||||
// display alert ?
|
||||
alert('sorry but the item to add is over the max item allowed');
|
||||
}
|
||||
} else {
|
||||
console.log('newly insert in cart');
|
||||
setCart([...cart, { pid, quantity, unit_price }]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addToCart = (pid, quantity, unit_price) => {
|
||||
if (cart) {
|
||||
const productExistInCart = cart.find(item => item.pid === pid);
|
||||
|
||||
if (productExistInCart) {
|
||||
const max_item_allowed = products.filter(p => p.pid === pid)[0].unsold_count;
|
||||
|
||||
// extract item from cart
|
||||
const item = cart.find(item => item.pid === pid);
|
||||
const allow_to_add_item = item.quantity + quantity <= max_item_allowed;
|
||||
|
||||
if (allow_to_add_item) {
|
||||
const final_item = item.quantity + quantity;
|
||||
setCart(cart.map(item => (item.pid === pid ? { ...item, quantity: final_item, unit_price } : item)));
|
||||
} else {
|
||||
// display alert ?
|
||||
alert('sorry but the item to add is over the max item allowed');
|
||||
}
|
||||
} else {
|
||||
setCart([...cart, { pid, quantity, unit_price }]);
|
||||
}
|
||||
} else {
|
||||
setCart([{ pid, quantity, unit_price }]);
|
||||
}
|
||||
};
|
||||
|
||||
const emptyCart = () => {
|
||||
setCart([]);
|
||||
};
|
||||
|
||||
const proceedCheckOutCart = async () => {
|
||||
try {
|
||||
let { data } = await checkoutCart(cart);
|
||||
|
||||
if (data.status === 'OK') {
|
||||
// clear cart after done
|
||||
localStorage.setItem('cart', JSON.stringify([]));
|
||||
} else {
|
||||
console.error({ data });
|
||||
throw new Error('error during checkout');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.error('checkout error');
|
||||
}
|
||||
};
|
||||
|
||||
// localStorage for saving and loading across sessions
|
||||
// loading, on each fresh site arriving
|
||||
useEffect(() => {
|
||||
setCart(JSON.parse(localStorage.getItem('cart')));
|
||||
}, []);
|
||||
|
||||
// saving, trigger on each cart update
|
||||
useEffect(() => {
|
||||
if (cart?.length > 0) {
|
||||
let temp = 0;
|
||||
cart.forEach(c_i => {
|
||||
temp = temp + c_i.unit_price * c_i.quantity;
|
||||
console.log(c_i.unit_price * c_i.quantity);
|
||||
});
|
||||
setTotalPrice(temp);
|
||||
} else {
|
||||
setTotalPrice(0);
|
||||
}
|
||||
|
||||
localStorage.setItem('cart', JSON.stringify(cart));
|
||||
}, [cart]);
|
||||
|
||||
const removeFromCart = pid => {
|
||||
const productToRemove = cart.find(item => item.pid === pid);
|
||||
if (productToRemove.quantity > 1) {
|
||||
setCart(cart.map(item => (item.pid === pid ? { ...item, quantity: item.quantity - 1 } : item)));
|
||||
} else {
|
||||
setCart(cart.filter(item => item.pid !== pid));
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const update = async () => {
|
||||
let temp = await fetchProducts();
|
||||
setProducts(temp);
|
||||
};
|
||||
update();
|
||||
}, []);
|
||||
|
||||
const helloworld = () => {
|
||||
console.log('hello cart');
|
||||
};
|
||||
|
||||
return (
|
||||
<CartContext.Provider
|
||||
value={{
|
||||
addToCart,
|
||||
removeFromCart,
|
||||
helloworld,
|
||||
emptyCart,
|
||||
cart,
|
||||
total_price,
|
||||
changeCartItemQty,
|
||||
products,
|
||||
proceedCheckOutCart,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</CartContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export { CartProvider, CartConsumer, CartContext };
|
Reference in New Issue
Block a user