added services in application and create a categorylist page

This commit is contained in:
Suraj Birewar 2024-07-31 22:58:42 +05:30
parent 261cf4cfbd
commit b10f323455
17 changed files with 943 additions and 5942 deletions

2
.env Normal file
View File

@ -0,0 +1,2 @@
VITE_ENVIRONMENT=dev
VITE_API_URL=https://api.yourproductionurl.com

View File

@ -13,6 +13,7 @@ import { AuthProvider, AuthContext } from "./contexts/AuthContext";
import EmployeeList from "./components/admin/EmployeeList"; import EmployeeList from "./components/admin/EmployeeList";
import AddEmployee from "./components/admin/AddEmployee"; import AddEmployee from "./components/admin/AddEmployee";
import EmployeeProfile from "./components/admin/EmployeeProfile"; import EmployeeProfile from "./components/admin/EmployeeProfile";
import CategoryList from "./components/categories/CategoryList";
import { Refine } from "@refinedev/core"; import { Refine } from "@refinedev/core";
import { RefineKbarProvider } from "@refinedev/kbar"; import { RefineKbarProvider } from "@refinedev/kbar";
import { ToastContainer, toast } from "react-toastify"; import { ToastContainer, toast } from "react-toastify";
@ -44,6 +45,7 @@ const App = () => {
<Route path="/employees" element={<PrivateRoute><EmployeeList /></PrivateRoute>} /> <Route path="/employees" element={<PrivateRoute><EmployeeList /></PrivateRoute>} />
<Route path="/add-employee" element={<PrivateRoute><AddEmployee /></PrivateRoute>} /> <Route path="/add-employee" element={<PrivateRoute><AddEmployee /></PrivateRoute>} />
<Route path="/employee-profile" element={<PrivateRoute><EmployeeProfile /></PrivateRoute>} /> <Route path="/employee-profile" element={<PrivateRoute><EmployeeProfile /></PrivateRoute>} />
<Route path="/CategoryList" element={<PrivateRoute><CategoryList /></PrivateRoute>} />
</Routes> </Routes>
</Content> </Content>
</div> </div>

View File

@ -1,10 +1,15 @@
import axios from 'axios'; import axios from 'axios';
// Determine environment and set baseURL accordingly
const environment = import.meta.env.VITE_ENVIRONMENT;
const baseURL = environment === 'dev'
? import.meta.env.VITE_API_URL
: 'http://localhost:5000'; // Default for development
const axiosInstance = axios.create({ const axiosInstance = axios.create({
baseURL: 'http://localhost:5000', baseURL,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}); });
@ -16,4 +21,22 @@ axiosInstance.interceptors.request.use((config) => {
return config; return config;
}); });
axiosInstance.interceptors.response.use(
response => response,
error => {
// Handle errors globally
if (error.response) {
// Server responded with a status other than 2xx
console.error('Error response:', error.response.data);
} else if (error.request) {
// No response received from the server
console.error('Error request:', error.request);
} else {
// Something else caused the error
console.error('Error message:', error.message);
}
return Promise.reject(error);
}
);
export default axiosInstance; export default axiosInstance;

View File

@ -93,7 +93,7 @@ const AddEmployee = () => {
}); });
try { try {
await axiosInstance.get('http://localhost:5000/employees', formData, { await axiosInstance.post('http://localhost:5000/employees', formData, {
headers: { headers: {
'Content-Type': 'multipart/form-data', 'Content-Type': 'multipart/form-data',
}, },

View File

@ -0,0 +1,45 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import Sidebar from '../sidebar/Sidebar'; // Ensure the correct path to Sidebar
const CategoryList = () => {
const navigate = useNavigate();
const categories = [
{ name: 'shirts', image: 'https://www2.hm.com/en_in/productpage.1032522123.html' },
{ name: 'suits', image: 'https://www2.hm.com/en_in/productpage.1032522123.html' },
{ name: 'tuxedos', image: 'https://www2.hm.com/en_in/productpage.1032522123.html' },
{ name: 'jackets', image: 'https://image.coolblue.nl/422x390/products/1101120' },
];
const handleClick = (category) => {
navigate(`/products/${category}`);
};
return (
<div className="flex h-screen">
{/* Sidebar */}
<Sidebar />
{/* Main content */}
<div className="flex-grow p-8">
<h1 className="text-3xl font-bold mb-8 text-left pl-4">categories</h1>
<div className="grid grid-cols-2 gap-8">
{categories.map((category, index) => (
<div
key={index}
className="border border-gray-300 p-4 rounded-lg cursor-pointer hover:shadow-lg transition-shadow duration-300 ease-in-out flex flex-col items-center"
onClick={() => handleClick(category.name)}
>
<img src={category.image} alt={category.name} className="w-48 h-48 object-cover" />
<h2 className="text-xl font-bold text-center mt-2 capitalize">{category.name}</h2>
<p className="text-center text-sm text-gray-600">click to view products</p>
</div>
))}
</div>
</div>
</div>
);
};
export default CategoryList;

View File

@ -4,7 +4,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronLeft } from '@fortawesome/free-solid-svg-icons'; import { faChevronLeft } from '@fortawesome/free-solid-svg-icons';
import Sidebar from '../sidebar/Sidebar'; import Sidebar from '../sidebar/Sidebar';
import axiosInstance from '../../api/axiosConfig'; import axiosInstance from '../../api/axiosConfig';
import { addCustomer } from "../../services_1/customersService";
const CLASSES = { const CLASSES = {
container: 'flex flex-row', container: 'flex flex-row',
mainContent: 'w-full flex flex-col min-h-screen text-black', mainContent: 'w-full flex flex-col min-h-screen text-black',
@ -124,12 +124,8 @@ const AddCustomer = () => {
} }
try { try {
const response = await axiosInstance.post('/customers', formData, { const data = await customerService.createCustomer(customerData);
headers: { console.log('Customer added successfully:', data);
'Content-Type': 'multipart/form-data',
},
});
console.log('Customer added successfully:', response.data);
navigate('/customers'); navigate('/customers');
} catch (error) { } catch (error) {
console.error('Error adding customer:', error.response || error.message); console.error('Error adding customer:', error.response || error.message);

View File

@ -3,21 +3,22 @@ import { useNavigate } from 'react-router-dom';
import Sidebar from '../sidebar/Sidebar'; import Sidebar from '../sidebar/Sidebar';
import axiosInstance from '../../api/axiosConfig'; import axiosInstance from '../../api/axiosConfig';
import '../../styles/CustomerList.css'; import '../../styles/CustomerList.css';
import { getCustomers, addCustomer } from '@/services_1/customersService';
const CustomerList = () => { const CustomerList = () => {
const [customers, setCustomers] = useState([]); const [customers, setCustomers] = useState([]);
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
getCustomers(); getCustomers();
}, []); }, []);
const getCustomers = async () => { const getCustomers = async () => {
try { try {
const response = await axiosInstance.get('http://localhost:5000/customers'); const data = await customerService.getAllCustomers()
let customers_data = response.data; setCustomers(data);
setCustomers(customers_data);
} catch (error) { } catch (error) {
throw error; throw error;
} }

View File

@ -46,7 +46,7 @@ const AdminSidebar = () => {
<Link to="/admin" className={classNames.iconLink}> <Link to="/admin" className={classNames.iconLink}>
<img src={HomeIcon} alt="Home" className={classNames.icon} /> <img src={HomeIcon} alt="Home" className={classNames.icon} />
</Link> </Link>
<Link to="/admin/categories" className={classNames.iconLink}> <Link to="/CategoryList" className={classNames.iconLink}>
<img src={CategoriesIcon} alt="Categories" className={classNames.icon} /> <img src={CategoriesIcon} alt="Categories" className={classNames.icon} />
</Link> </Link>
<Link to="/admin/add-customer" className={classNames.iconLink}> <Link to="/admin/add-customer" className={classNames.iconLink}>

View File

@ -41,7 +41,7 @@ const EmployeeSidebar = () => {
<Link to="/employee/home" className={classNames.iconLink}> <Link to="/employee/home" className={classNames.iconLink}>
<img src={HomeIcon} alt="Home" className={classNames.icon} /> <img src={HomeIcon} alt="Home" className={classNames.icon} />
</Link> </Link>
<Link to="/employee/categories" className={classNames.iconLink}> <Link to="/CategoryList" className={classNames.iconLink}>
<img src={CategoriesIcon} alt="Categories" className={classNames.icon} /> <img src={CategoriesIcon} alt="Categories" className={classNames.icon} />
</Link> </Link>
<Link to="/customers" className={classNames.iconLink}> <Link to="/customers" className={classNames.iconLink}>

75
src/services_1/Orders.jsx Normal file
View File

@ -0,0 +1,75 @@
import React, { useState, useEffect } from 'react';
import ordersService from './ordersService';
const Orders = () => {
const [orders, setOrders] = useState([]);
const [order, setOrder] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetchOrders();
}, []);
const fetchOrders = async () => {
try {
const data = await ordersService.getAllOrders();
setOrders(data);
} catch (error) {
setError('Error fetching orders');
}
};
const fetchOrderById = async (id) => {
try {
const data = await ordersService.getOrderById(id);
setOrder(data);
} catch (error) {
setError('Error fetching order');
}
};
const addOrder = async (orderData) => {
try {
const data = await ordersService.createOrder(orderData);
setOrders([...orders, data]);
} catch (error) {
setError('Error adding order');
}
};
const updateOrder = async (id, updatedData) => {
try {
const data = await ordersService.updateOrder(id, updatedData);
setOrders(orders.map(o => (o.id === id ? data : o)));
} catch (error) {
setError('Error updating order');
}
};
const deleteOrder = async (id) => {
try {
await ordersService.deleteOrder(id);
setOrders(orders.filter(o => o.id !== id));
} catch (error) {
setError('Error deleting order');
}
};
return (
<div>
<h1>Orders</h1>
{error && <p>{error}</p>}
{/* Render orders list here */}
{/* Example of calling fetchOrderById */}
{/* <button onClick={() => fetchOrderById('order-id')}>Fetch Order</button> */}
{/* Example of calling addOrder */}
{/* <button onClick={() => addOrder({ subtotal: 100, tax_rate: 0.1, tax_amount: 10, total: 110, status: 'pending' })}>Add Order</button> */}
{/* Example of calling updateOrder */}
{/* <button onClick={() => updateOrder('order-id', { status: 'shipped' })}>Update Order</button> */}
{/* Example of calling deleteOrder */}
{/* <button onClick={() => deleteOrder('order-id')}>Delete Order</button> */}
</div>
);
};
export default Orders;

View File

@ -0,0 +1,90 @@
import axiosInstance from "../api/axiosConfig"; // Import the global axios instance
// Get all categories
export const getAllCategories = async () => {
try {
const response = await axiosInstance.get("/categories");
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Create a new category
export const createCategory = async (categoryPayload) => {
try {
const response = await axiosInstance.post("/categories", categoryPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Get a category by ID
export const getCategoryById = async (id) => {
try {
const response = await axiosInstance.get(`/categories/${id}`);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Update a category's details
export const updateCategory = async (id, categoryPayload) => {
try {
const response = await axiosInstance.patch(
`/categories/${id}`,
categoryPayload
);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Delete a category
export const deleteCategory = async (id) => {
try {
await axiosInstance.delete(`/categories/${id}`);
return; // No content to return on successful delete
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Example function to use the service
export const exampleUsage = async () => {
try {
// Example: Get all categories
const categories = await getAllCategories();
console.log("Categories:", categories);
// Example: Create a new category
const newCategory = {
name: "Electronics",
description: "Devices and gadgets",
};
const createdCategory = await createCategory(newCategory);
console.log("Created Category:", createdCategory);
// Example: Get a category by ID
const categoryId = "456";
const category = await getCategoryById(categoryId);
console.log("Category by ID:", category);
// Example: Update a category
const updatedCategoryPayload = { name: "Electronics & Gadgets" };
const updatedCategory = await updateCategory(
categoryId,
updatedCategoryPayload
);
console.log("Updated Category:", updatedCategory);
// Example: Delete a category
await deleteCategory(categoryId);
console.log("Category deleted successfully");
} catch (error) {
console.error("Error occurred while using categories service:", error);
}
};

View File

@ -0,0 +1,95 @@
import axiosInstance from "../api/axiosConfig"; // Import the global axios instance
// Get all customers
export const getAllCustomers = async () => {
try {
const response = await axiosInstance.get("/customers");
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
export const getCustomers = async () => {
// Implementation
};
export const addCustomer = async (customer) => {
// Implementation
};
// Create a new customer
export const createCustomer = async (customerPayload) => {
try {
const response = await axiosInstance.post("/customers", customerPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Get a customer by ID
export const getCustomerById = async (id) => {
try {
const response = await axiosInstance.get(`/customers/${id}`);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Update a customer's details
export const updateCustomer = async (id, customerPayload) => {
try {
const response = await axiosInstance.patch(
`/customers/${id}`,
customerPayload
);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Delete a customer
export const deleteCustomer = async (id) => {
try {
await axiosInstance.delete(`/customers/${id}`);
return; // No content to return on successful delete
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Example function to use the service
export const exampleUsage = async () => {
try {
// Example: Get all customers
const customers = await getAllCustomers();
console.log("Customers:", customers);
// Example: Create a new customer
const newCustomer = { name: "Alice Johnson", email: "alice@example.com" };
const createdCustomer = await createCustomer(newCustomer);
console.log("Created Customer:", createdCustomer);
// Example: Get a customer by ID
const customerId = "456";
const customer = await getCustomerById(customerId);
console.log("Customer by ID:", customer);
// Example: Update a customer
const updatedCustomerPayload = { email: "alice.johnson@example.com" };
const updatedCustomer = await updateCustomer(
customerId,
updatedCustomerPayload
);
console.log("Updated Customer:", updatedCustomer);
// Example: Delete a customer
await deleteCustomer(customerId);
console.log("Customer deleted successfully");
} catch (error) {
console.error("Error occurred while using customers service:", error);
}
};

View File

@ -0,0 +1,81 @@
import axiosInstance from '../api/axiosConfig'; // Import the global axios instance
// Get all orders with their metadata
export const getAllOrders = async () => {
try {
const response = await axiosInstance.get('/orders');
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Create a new order
export const createOrder = async (orderPayload) => {
try {
const response = await axiosInstance.post('/orders', orderPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Get an order by ID
export const getOrderById = async (id) => {
try {
const response = await axiosInstance.get(`/orders/${id}`);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Update an order's details
export const updateOrder = async (id, orderPayload) => {
try {
const response = await axiosInstance.patch(`/orders/${id}`, orderPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Delete an order
export const deleteOrder = async (id) => {
try {
await axiosInstance.delete(`/orders/${id}`);
return; // No content to return on successful delete
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Example function to use the service
export const exampleUsage = async () => {
try {
// Example: Get all orders
const orders = await getAllOrders();
console.log('Orders:', orders);
// Example: Create a new order
const newOrder = { productId: '123', quantity: 2, status: 'pending' };
const createdOrder = await createOrder(newOrder);
console.log('Created Order:', createdOrder);
// Example: Get an order by ID
const orderId = '456';
const order = await getOrderById(orderId);
console.log('Order by ID:', order);
// Example: Update an order
const updatedOrderPayload = { status: 'shipped' };
const updatedOrder = await updateOrder(orderId, updatedOrderPayload);
console.log('Updated Order:', updatedOrder);
// Example: Delete an order
await deleteOrder(orderId);
console.log('Order deleted successfully');
} catch (error) {
console.error('Error occurred while using orders service:', error);
}
};

View File

@ -0,0 +1,102 @@
import axiosInstance from "../api/axiosConfig"; // Import the global axios instance
// Get all products with their metadata
export const getAllProducts = async () => {
try {
const response = await axiosInstance.get("/products");
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Create a new product
export const createProduct = async (productPayload) => {
try {
const response = await axiosInstance.post("/products", productPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Get a product by ID
export const getProductById = async (id) => {
try {
const response = await axiosInstance.get(`/products/${id}`);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Update a product's details
export const updateProduct = async (id, productPayload) => {
try {
const response = await axiosInstance.patch(
`/products/${id}`,
productPayload
);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Delete a product
export const deleteProduct = async (id) => {
try {
await axiosInstance.delete(`/products/${id}`);
return; // No content to return on successful delete
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Get a product by SKU
export const getProductBySKU = async (sku) => {
try {
const response = await axiosInstance.get(`/products/${sku}`);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Example function to use the service
export const exampleUsage = async () => {
try {
// Example: Get all products
const products = await getAllProducts();
console.log("Products:", products);
// Example: Create a new product
const newProduct = { name: "Laptop", sku: "LPT123", price: 1200 };
const createdProduct = await createProduct(newProduct);
console.log("Created Product:", createdProduct);
// Example: Get a product by ID
const productId = "789";
const product = await getProductById(productId);
console.log("Product by ID:", product);
// Example: Update a product
const updatedProductPayload = { price: 1100 };
const updatedProduct = await updateProduct(
productId,
updatedProductPayload
);
console.log("Updated Product:", updatedProduct);
// Example: Delete a product
await deleteProduct(productId);
console.log("Product deleted successfully");
// Example: Get a product by SKU
const productSKU = "LPT123";
const productBySKU = await getProductBySKU(productSKU);
console.log("Product by SKU:", productBySKU);
} catch (error) {
console.error("Error occurred while using products service:", error);
}
};

View File

@ -0,0 +1,81 @@
import axiosInstance from "../api/axiosConfig"; // Import the global axios instance
// Get all users with their metadata
export const getAllUsers = async () => {
try {
const response = await axiosInstance.get("/users");
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Create a new user
export const createUser = async (userPayload) => {
try {
const response = await axiosInstance.post("/users", userPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Get a user by ID
export const getUserById = async (id) => {
try {
const response = await axiosInstance.get(`/users/${id}`);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Update a user's details
export const updateUser = async (id, userPayload) => {
try {
const response = await axiosInstance.patch(`/users/${id}`, userPayload);
return response.data;
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Delete a user
export const deleteUser = async (id) => {
try {
await axiosInstance.delete(`/users/${id}`);
return; // No content to return on successful delete
} catch (error) {
throw error; // The error is handled globally by the axiosInstance
}
};
// Example function to use the service
export const exampleUsage = async () => {
try {
// Example: Get all users
const users = await getAllUsers();
console.log("Users:", users);
// Example: Create a new user
const newUser = { name: "John Doe", email: "john@example.com" };
const createdUser = await createUser(newUser);
console.log("Created User:", createdUser);
// Example: Get a user by ID
const userId = "123";
const user = await getUserById(userId);
console.log("User by ID:", user);
// Example: Update a user
const updatedUserPayload = { name: "John Smith" };
const updatedUser = await updateUser(userId, updatedUserPayload);
console.log("Updated User:", updatedUser);
// Example: Delete a user
await deleteUser(userId);
console.log("User deleted successfully");
} catch (error) {
console.error("Error occurred while using users service:", error);
}
};

View File

@ -1,12 +1,12 @@
// vite.config.js
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
resolve: { resolve: {
alias: { alias: {
'@api': '/src/api', '@': path.resolve(__dirname, 'src'),
}, },
}, },
}); });

6256
yarn.lock

File diff suppressed because it is too large Load Diff