From 0581cf77fed28a27d4ffe8a5e27c7175e24a5104 Mon Sep 17 00:00:00 2001 From: roshangarg Date: Fri, 3 May 2024 10:34:47 +0530 Subject: [PATCH] added employee section --- package.json | 4 +- src/_nav.js | 16 +- src/components/AppContent.js | 21 +- src/components/AppSidebar.js | 55 +- src/index.js | 4 +- src/routes.js | 58 +- src/views/EmployeeAccess/Employee.js | 284 ++--- src/views/EmployeeAccess/addEmployee.js | 115 +- src/views/EmployeeAccess/editEmployee.js | 99 +- src/views/dashboard/Dashboard.js | 2 +- src/views/exportExcel.js | 73 ++ src/views/orders/AddOrder.js | 1387 +++++++++++----------- src/views/orders/EditOrder.js | 2 +- src/views/pages/login/Login.js | 4 +- 14 files changed, 1170 insertions(+), 954 deletions(-) create mode 100644 src/views/exportExcel.js diff --git a/package.json b/package.json index 18a472f..42c60d4 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "draft-js": "^0.11.7", "draft-js-export-html": "^1.4.1", "draft-js-import-html": "^1.4.1", + "file-saver": "^2.0.5", "md5": "^2.3.0", "moment": "^2.30.1", "prop-types": "^15.7.2", @@ -76,7 +77,8 @@ "styled-components": "^6.0.8", "sweetalert": "^2.1.2", "sweetalert2": "^11.4.0", - "uuid": "^9.0.1" + "uuid": "^9.0.1", + "xlsx": "^0.18.5" }, "devDependencies": { "auto-changelog": "~2.3.0", diff --git a/src/_nav.js b/src/_nav.js index ca0faf1..13e578e 100644 --- a/src/_nav.js +++ b/src/_nav.js @@ -323,17 +323,17 @@ const _nav = [ // Employee { component: CNavItem, - name: "Employee", + name: " Employees & Access", icon: , to: "/employee", }, -//Point of Sale start -{ - component: CNavItem, - name: "Point of Sale", - icon: , - to: "/pos", -}, + //Point of Sale start + { + component: CNavItem, + name: "Point of Sale", + icon: , + to: "/pos", + }, // { // component: CNavGroup, // name: "Blog", diff --git a/src/components/AppContent.js b/src/components/AppContent.js index f3c74be..715dbd6 100644 --- a/src/components/AppContent.js +++ b/src/components/AppContent.js @@ -1,16 +1,17 @@ -import React, { Suspense } from 'react' -import { Navigate, Route, Routes } from 'react-router-dom' -import { CContainer, CSpinner } from '@coreui/react' +import React, { Suspense, useState } from "react"; +import { Navigate, Route, Routes } from "react-router-dom"; +import { CContainer, CSpinner } from "@coreui/react"; // routes config -import routes from '../routes' +import routes from "../routes"; const AppContent = () => { + const [appRoutes, setAppRoutes] = useState(routes); return ( }> - {routes.map((route, idx) => { + {appRoutes.map((route, idx) => { return ( route.element && ( { element={} /> ) - ) + ); })} } /> - ) -} + ); +}; - - -export default React.memo(AppContent) +export default React.memo(AppContent); diff --git a/src/components/AppSidebar.js b/src/components/AppSidebar.js index 79ec9c5..6f921d9 100644 --- a/src/components/AppSidebar.js +++ b/src/components/AppSidebar.js @@ -27,12 +27,61 @@ const AppSidebar = () => { const dispatch = useDispatch(); const unfoldable = useSelector((state) => state.sidebarUnfoldable); const sidebarShow = useSelector((state) => state.sidebarShow); + const [navigationItem, setNavigationItem] = useState(navigation); + + const [userdata, setUserData] = useState(null); + const token = isAutheticated(); + console.log("userDatt", userdata); + + useEffect(() => { + const getUser = async () => { + let existanceData = localStorage.getItem("authToken"); + if (!existanceData) { + // console.log(existanceData.userData) + setUserData(false); + } else { + try { + // console.log('requesting user data from server') + let response = await axios.get(`/api/v1/user/details`, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + // console.log(response.data) + const data = response.data; + if ( + (data.success && data.user.role === "admin") || + data.user.role === "Employee" + ) { + setUserData(data.user); + } else { + setUserData(false); + } + } catch (err) { + setUserData(false); + console.log(err); + } + } + }; + getUser(); + }, []); + useEffect(() => { + if (userdata && userdata.accessTo) { + const filteredNavigation = navigation.filter((item) => { + if (userdata.accessTo[item.name]) { + return true; + } + return false; + }); + setNavigationItem(filteredNavigation); + } else { + setNavigationItem(navigation); + } + }, [userdata]); ///----------------------// const [loading, setLoading] = useState(false); - const token = isAutheticated(); - // urlcreated images const [AppName, setAppName] = useState(""); const [HeaderlogoUrl, setHeaderlogoUrl] = useState(""); @@ -87,7 +136,7 @@ const AppSidebar = () => { - + { - // axios.defaults.baseURL = "http://localhost:5000"; - axios.defaults.baseURL = "https://api.smellika.com"; + axios.defaults.baseURL = "http://localhost:5000"; + // axios.defaults.baseURL = "https://api.smellika.com"; axios.defaults.headers = { "Cache-Control": "no-cache,no-store", diff --git a/src/routes.js b/src/routes.js index 6c8307a..c9db5aa 100644 --- a/src/routes.js +++ b/src/routes.js @@ -146,6 +146,7 @@ import RegistrationEmail from "./views/CustomerSupport/EmailCMS/RegistrationEmai import Employee from "./views/EmployeeAccess/Employee"; import AddEmployee from "./views/EmployeeAccess/addEmployee"; import EditEmployee from "./views/EmployeeAccess/editEmployee"; +import ExportToExcel from "./views/exportExcel"; const routes = [ { path: "/", exact: true, name: "Home" }, { @@ -187,17 +188,17 @@ const routes = [ { path: "/customers-details", - name: "User Table", + name: "Customers", element: CustomerTable, }, { path: "/customers-details/:_id", - name: "User Table", + name: "Customers", element: SingleUserAllDetails, }, { path: "/add-customer", - name: "User Table", + name: "Customers", element: AddCustomer, }, // { @@ -212,7 +213,7 @@ const routes = [ // }, { path: "/users-address/view", - name: "view address", + name: "Customers", element: viewDetails, }, @@ -275,12 +276,12 @@ const routes = [ { path: "/contact/request", - name: "Contact Requests", + name: "Customer Service", element: ContactRequests, }, { path: "/contact/request/new", - name: "AddContact Request", + name: "Customer Service", element: AddContactRequest, }, //Support Requests @@ -297,54 +298,54 @@ const routes = [ { path: "/support/request", - name: "CustomerSupport Requests", + name: "Customer Service", element: SupportRequest, }, { path: "/support/request/closed", - name: "Closed CustomerSupport Requests", + name: "Customer Service", element: SupportRequestClosed, }, { path: "/support/request/closed/:ticketID", - name: "Closed CustomerSupport Request view", + name: "Customer Service", element: CloseRequestView, }, { path: "/support/request/reply/:ticketID", - name: "CustomerSupport Reply", + name: "Customer Service", element: SupportReply, }, // Content ---- > { path: "/content", - name: "Content", + name: "Website Relatedt", element: Content, }, { path: "/content/terms-and-conditions", - name: "Content", + name: "Website Related", element: EditTermsConditions, }, { path: "/content/privacy-policy", - name: "Content", + name: "Website Related", element: EditPrivacyPolicy, }, { path: "/content/shipping-policy", - name: "Content", + name: "Website Related", element: EditShippingPolicy, }, { path: "/content/refund-policy", - name: "Content", + name: "Website Related", element: EditRefundpolicy, }, { path: "/content/about-us", - name: "Content", + name: "Website Related", element: EditAboutUs, }, @@ -459,9 +460,21 @@ const routes = [ element: ReturnedOrders, }, //Point of sale orders - { path: "/inStoreCashOrders/new", name: "In Store Cash Orders", element:InStoreCashOrders }, - { path: "/InStoreQRCodeOrders/new", name: "In Store QR Code Orders", element:InStoreQRCodeOrders }, - { path: "/inStoreOrders/:status/:id", name: "View In Store Cash Orders", element: POSViewOrders }, + { + path: "/inStoreCashOrders/new", + name: "In Store Cash Orders", + element: InStoreCashOrders, + }, + { + path: "/InStoreQRCodeOrders/new", + name: "In Store QR Code Orders", + element: InStoreQRCodeOrders, + }, + { + path: "/inStoreOrders/:status/:id", + name: "View In Store Cash Orders", + element: POSViewOrders, + }, // { path: "/order/:status/:id", name: "View Order", element: ViewOdr }, //dashboard @@ -639,6 +652,13 @@ const routes = [ name: "Point of Sale", element: Pos, }, + + // Export to excel + { + path: "/exp", + name: "Point of Sale", + element: ExportToExcel, + }, ]; export default routes; diff --git a/src/views/EmployeeAccess/Employee.js b/src/views/EmployeeAccess/Employee.js index 9b7a18d..2650f39 100644 --- a/src/views/EmployeeAccess/Employee.js +++ b/src/views/EmployeeAccess/Employee.js @@ -25,26 +25,35 @@ const Employee = () => { const [loading, setLoading] = useState(true); const [loading1, setLoading1] = useState(true); const [success, setSuccess] = useState(true); - const [users, setUsers] = useState([]); + const [employee, setemployee] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [itemPerPage, setItemPerPage] = useState(10); - const [showData, setShowData] = useState(users); + const [showData, setShowData] = useState(employee); const handleShowEntries = (e) => { setCurrentPage(1); setItemPerPage(e.target.value); }; + useEffect(() => { + const loadData = () => { + const indexOfLastPost = currentPage * itemPerPage; + const indexOfFirstPost = indexOfLastPost - itemPerPage; + setShowData(employee.slice(indexOfFirstPost, indexOfLastPost)); + }; + loadData(); + }, [currentPage, itemPerPage, employee]); + console.log(employee); - // const getUsers = async () => { + // const getemployee = async () => { // axios - // .get(`/api/v1/admin/users`, { + // .get(`/api/v1/admin/employee`, { // headers: { // Authorization: `Bearer ${token}`, // }, // }) // .then((res) => { - // setUsers(res.data.users); + // setemployee(res.data.employee); // setLoading(false); // }) // .catch((error) => { @@ -60,19 +69,19 @@ const Employee = () => { // }; // useEffect(() => { - // getUsers(); + // getemployee(); // }, [success]); - // console.log(users); + // console.log(employee); // useEffect(() => { // const loadData = () => { // const indexOfLastPost = currentPage * itemPerPage; // const indexOfFirstPost = indexOfLastPost - itemPerPage; - // setShowData(users.slice(indexOfFirstPost, indexOfLastPost)); + // setShowData(employee.slice(indexOfFirstPost, indexOfLastPost)); // }; // loadData(); - // }, [currentPage, itemPerPage, users]); - // console.log(users); + // }, [currentPage, itemPerPage, employee]); + // console.log(employee); // const handleDelete = (id) => { // swal({ @@ -113,6 +122,70 @@ const Employee = () => { // }); // }; + // get All employee + const getemployee = async () => { + axios + .get(`/api/v1/admin/employee`, { + headers: { + Authorization: `Bearer ${token}`, + }, + }) + .then((res) => { + setemployee(res.data.employee); + setLoading(false); + }) + .catch((error) => { + swal({ + title: error, + text: "please login to access the resource or refresh the page ", + icon: "error", + button: "Retry", + dangerMode: true, + }); + setLoading(false); + }); + }; + useEffect(() => { + getemployee(); + }, [success]); + console.log(employee); + console.log("showdata", showData); + // const trueEntries = Object.entries(showData.).filter( + // ([key, value]) => value === true + // ); + const renderAccessTo = (accessTo) => { + return Object.entries(accessTo) + .filter(([key, value]) => value === true) + .map(([key, value]) => key) + .join(", "); + }; + const handleDelete = async (id) => { + try { + // Send a DELETE request to your API to delete the employee by ID + const res = await axios.delete(`/api/v1/admin/delete-employee/${id}`, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + // If deletion is successful, update the employee list + swal({ + title: "Congratulations!!", + text: res?.data?.message, + icon: "success", + buttons: "OK", + }); + setemployee(employee.filter((employee) => employee._id !== id)); + } catch (error) { + console.error("Error deleting employee:", error); + swal({ + title: "", + text: "Something went wrong!", + icon: "error", + button: "Retry", + dangerMode: true, + }); + } + }; return (
@@ -207,168 +280,67 @@ const Employee = () => { )} - {!loading ? ( + {loading ? ( Loading... ) : ( - // showData.map((user, i) => { - // return ( - // - // {user.name} - // {user._id} + showData.map((employee, i) => { + return ( + + {employee.name} + {employee.email} - // - // {new Date(user.createdAt).toLocaleString( - // "en-IN", - // { - // weekday: "short", - // month: "short", - // day: "numeric", - // year: "numeric", - // hour: "numeric", - // minute: "numeric", - // hour12: true, - // } - // )} - // - // {loading1 && ( - // <> - // loading... - // loading... - // - // )} + + {renderAccessTo(employee.accessTo)} + - // - - // - // {/* - // - // - // - // - // - // - // - // */} - // - // - // - // - // - // ); - // }) - - Roshan Garg - roshan@gmail.com - {/* Profile Image */} - dashboard - - {/* Last Purchase - Orders */} - - - - - + > + Delete + + + + ); + }) )} @@ -383,8 +355,8 @@ const Employee = () => { aria-live="polite" > Showing {currentPage * itemPerPage - itemPerPage + 1} to{" "} - {Math.min(currentPage * itemPerPage, users.length)} of{" "} - {users.length} entries + {Math.min(currentPage * itemPerPage, employee.length)}{" "} + of {employee.length} entries
@@ -432,7 +404,7 @@ const Employee = () => { {!( (currentPage + 1) * itemPerPage - itemPerPage > - users.length - 1 + employee.length - 1 ) && (
  • { className={ !( (currentPage + 1) * itemPerPage - itemPerPage > - users.length - 1 + employee.length - 1 ) ? "paginate_button page-item next" : "paginate_button page-item next disabled" diff --git a/src/views/EmployeeAccess/addEmployee.js b/src/views/EmployeeAccess/addEmployee.js index b0efd0d..4c9fb9e 100644 --- a/src/views/EmployeeAccess/addEmployee.js +++ b/src/views/EmployeeAccess/addEmployee.js @@ -5,32 +5,109 @@ import FormControlLabel from "@mui/material/FormControlLabel"; import Checkbox from "@mui/material/Checkbox"; import { useNavigate } from "react-router-dom"; import _nav from "src/_nav"; +import toast from "react-hot-toast"; +import axios from "axios"; const AddEmployee = () => { const [employeeName, setEmployeeName] = useState(""); + const [phone, setPhone] = useState(""); const [email, setEmail] = useState(""); const navigate = useNavigate(); - const [checkedItems, setCheckedItems] = useState({}); + const filteredNav = _nav.filter((item) => item.name !== "Employee"); + const [checkedItems, setCheckedItems] = useState( + filteredNav.reduce((acc, item) => { + acc[item.name] = false; + return acc; + }, {}) + ); + + // const filteredEntries = Object.fromEntries( + // Object.entries(checkedItems).filter(([key, value]) => value === true) + // ); + // console.log(filteredEntries); const handleCheckboxChange = (name) => (event) => { setCheckedItems({ ...checkedItems, [name]: event.target.checked, }); }; + console.log(checkedItems); + const generatePassword = (name, email) => { + const combinedStr = (name + email).toLowerCase(); // Convert to lowercase for consistency + const specialChars = "@#*!$%^&"; // Define the set of special characters + const alphaChars = combinedStr.match(/[a-zA-Z]/g); // Filter out alphabetic characters + const digitChars = combinedStr.match(/\d/g); // Filter out digits + const filteredChars = combinedStr.match(/[^\W_]/g); // Filter out non-alphanumeric characters + let passwordChars = alphaChars.concat(filteredChars); // Combine alphabetic and filtered characters + + // Ensure at least one uppercase letter + if (!passwordChars.some((char) => char === char.toUpperCase())) { + const uppercaseChar = String.fromCharCode( + 65 + Math.floor(Math.random() * 26) + ); + passwordChars.push(uppercaseChar); + } + + // Ensure at least one digit + if (!digitChars || digitChars.length === 0) { + const digitChar = Math.floor(Math.random() * 10).toString(); + passwordChars.push(digitChar); + } + + // Insert a random special character at a random position in the password characters array + const specialChar = specialChars.charAt( + Math.floor(Math.random() * specialChars.length) + ); + const randomIndex = Math.floor(Math.random() * (passwordChars.length + 1)); + passwordChars.splice(randomIndex, 0, specialChar); + + passwordChars = passwordChars.sort(() => Math.random() - 0.5); // Shuffle the characters + // passwordString.charAt(0).toUpperCase() + passwordString.slice(1) + "@"; + const normalpassword = passwordChars.join("").slice(0, 8); // Take the first 8 characters + const passwordWithspecialChar = + normalpassword.charAt(0).toUpperCase() + normalpassword.slice(1) + "1@2"; + return passwordWithspecialChar; + }; + + const handleFormSubmit = async (e) => { + e.preventDefault(); + console.log("request made"); + try { + if (!employeeName || !email || !phone) { + throw new Error("Fill all fields!"); + } + + // Generate password based on name and email + const generatedPassword = generatePassword(employeeName, email); + console.log(generatedPassword); // Use generatedPassword instead of generatePassword + // Set generated password to user state + + const response = await axios.post("/api/v1/user/register", { + // Send user details + name: employeeName, + email: email, + phone: phone, + role: "Employee", + accessTo: checkedItems, + password: generatedPassword, // Send generated password to the backend + }); + console.log(response); + if (response.status === 201) { + toast.success("Employee Added Successful"); + // setUserId(response.data.userId); + navigate("/employee"); + } + } catch (error) { + console.log(error?.response); + // toast.error(error?.response); + } + }; return (
    - {/* setTitle(e.target.value)} - variant="outlined" - size="small" - fullWidth - /> */} { onChange={(e) => setEmployeeName(e.target.value)} />
    +
    + + + setPhone(e.target.value)} + /> +
    + ); +} + +export default ExportToExcel; diff --git a/src/views/orders/AddOrder.js b/src/views/orders/AddOrder.js index f6b217d..c546963 100644 --- a/src/views/orders/AddOrder.js +++ b/src/views/orders/AddOrder.js @@ -1,738 +1,717 @@ - - - -import React, { useState, useEffect, useRef } from 'react' -import axios from 'axios' -import { Link, useNavigate, useParams } from 'react-router-dom' -import QRCode from 'react-qr-code' -import { isAutheticated } from 'src/auth' -import { useDispatch, useSelector } from 'react-redux' -import { addItemsToCart } from 'src/redux/Actions/cartAction' -import toast from 'react-hot-toast' -import { cibBlackberry } from '@coreui/icons' -import Button from '@material-ui/core/Button' +import React, { useState, useEffect, useRef } from "react"; +import axios from "axios"; +import { Link, useNavigate, useParams } from "react-router-dom"; +import QRCode from "react-qr-code"; +import { isAutheticated } from "src/auth"; +import { useDispatch, useSelector } from "react-redux"; +import { addItemsToCart } from "src/redux/Actions/cartAction"; +import toast from "react-hot-toast"; +import { cibBlackberry } from "@coreui/icons"; +import Button from "@material-ui/core/Button"; function AddOrder() { - const { status, id } = useParams() + const { status, id } = useParams(); - const { cartItems, subTotal, shippingCharge, tax, shipingInfo, total } = useSelector( - (state) => state.cart - ); + const { cartItems, subTotal, shippingCharge, tax, shipingInfo, total } = + useSelector((state) => state.cart); + const AllStates = useSelector((state) => state); + const getValue = useRef(); + const getFranchiseeID = useRef(); + const dispatch = useDispatch(); + const navigate = useNavigate(); + const printOrderRef = useRef(); + const token = isAutheticated(); + const [productData, setProductData] = useState([]); + const [allFranchisee, setAllFranchisee] = useState([]); + const [allTax, setAllTax] = useState([]); - const AllStates = useSelector( - (state) => state - ); - const getValue = useRef() - const getFranchiseeID = useRef() - const dispatch = useDispatch(); - const navigate = useNavigate() - const printOrderRef = useRef() - const token = isAutheticated() - const [productData, setProductData] = useState([]) - const [allFranchisee, setAllFranchisee] = useState([]) - const [allTax, setAllTax] = useState([]) - - - - const [productDetails, setProductDetails] = useState() - const [loading, setLoading] = useState(true) - const [orderStatus, setOrderStatus] = useState('') - const [data, setData] = useState({ - product_Name: '', - address: '', - quantity: '', - contact_Number: '', - total_Price: '', - }) - useEffect(() => { - const getAllTax = async () => { - const res = await axios.get(`/api/tax/view_tax`, { - headers: { 'Access-Control-Allow-Origin': '*', Authorization: `Bearer ${token}` }, - }) - if (res.data) { - // console.log(res.data) - setAllTax(res.data) - } - } - getAllTax() - - }, [token]) - - useEffect(() => { - function getProductDetails() { - setLoading(true) - axios - .get(`/api/product/getAll/`, { - headers: { 'Access-Control-Allow-Origin': '*', Authorization: `Bearer ${token}` }, - }) - .then((res) => { - setLoading(false) - // console.log(res.data.product) - setProductData(res.data.product) - }) - .catch((err) => { - setLoading(false) - // getBack() - }) - } - function getFranchiseeDetails() { - setLoading(true) - axios - .get(`/api/franchisee`, { - headers: { 'Access-Control-Allow-Origin': '*', Authorization: `Bearer ${token}` }, - }) - .then((res) => { - setLoading(false) - console.log(res.data.data) - setAllFranchisee(res.data.data) - }) - .catch((err) => { - setLoading(false) - // getBack() - }) - } - getProductDetails() - getFranchiseeDetails() - }, []) - - const handleChange = (e) => { - if (e.target.type === 'text') { - setData((prev) => ({ ...prev, [e.target.id]: e.target.value })) - } else { - setOrderStatus(e.target.value) - } - } - const handleQuantityChange = (e) => { - - setData((prev) => ({ - ...prev, - quantity: e.target.value, - total_Price: (productDetails?.base_Price * e.target.value) - })) - - } - - // ------------------------Frenchisee handle------------------------------// - - const handleGetSingleFrenchisee = async () => { - console.log(getFranchiseeID.current.value) - - axios - .get(`/api/franchisee/arrayspopulate/${getFranchiseeID.current.value}`, { - headers: { - 'Access-Control-Allow-Origin': '*', - Authorization: `Bearer ${token}`, - }, - }) - .then((res) => { - setLoading(false) - console.log(res.data.data) - let options = { - Franchisee: res?.data?.data?._id, - name: res?.data?.data?.name, - - - contact_Number: res?.data?.data?.contact_Number, - contact_Person_Name: res?.data?.data?.contact_Person_Name, - address: (res?.data?.data?.address_line_1 + ' ' + res?.data?.data?.address_line_2), - city: res?.data?.data?.city?.city_name, - price_Lable: res?.data?.data?.price_Lable, - state: res?.data?.data?.city?.state?.state_name, - banner: res?.data?.data?.banner?.url, - Franchisee_Url: res?.data?.data?.url - } - - dispatch({ type: "addShippingInfo", payload: options }); - - // localStorage.setItem("shippingInfo", JSON.stringify(AllStates.shipingInfo)); - - toast.success("Franchisee Added"); - - }) - .catch((err) => { - setLoading(false) - - }) - } - const FranchiseeRemove = (id) => { - dispatch({ - type: "deleteFromshippingInfo", - payload: { Franchisee: id }, - }); - toast.success("Franchisee Removed"); - + const [productDetails, setProductDetails] = useState(); + const [loading, setLoading] = useState(true); + const [orderStatus, setOrderStatus] = useState(""); + const [data, setData] = useState({ + product_Name: "", + address: "", + quantity: "", + contact_Number: "", + total_Price: "", + }); + useEffect(() => { + const getAllTax = async () => { + const res = await axios.get(`/api/tax/view_tax`, { + headers: { + "Access-Control-Allow-Origin": "*", + Authorization: `Bearer ${token}`, + }, + }); + if (res.data) { + // console.log(res.data) + setAllTax(res.data); + } }; - // ------------------------Frenchisee handle End------------------------------// - // ------------------------product handle------------------------------// + getAllTax(); + }, [token]); - const handleGetSingleProduct = async (e) => { - - - axios - .get(`/api/product/getOne/${getValue.current.value}`, { - headers: { 'Access-Control-Allow-Origin': '*', Authorization: `Bearer ${token}` }, - }) - .then((res) => { - setLoading(false) - const productAllkey = Object.keys(res?.data?.product); - const productAllValue = Object.values(res?.data?.product); - const findIndex1 = (productAllkey.indexOf(shipingInfo?.price_Lable)) - const findIndex2 = (productAllkey.indexOf(`${shipingInfo?.price_Lable}_With_Tax`)) - - - - let options = { - name: res?.data?.product?.name, - price: productAllValue[findIndex1], - product: res?.data?.product?._id, - quantity: 1, - - image: res?.data?.product?.image?.url, - - taxId: res?.data?.product?.taxId, - price_With_Tax: productAllValue[findIndex2], - } - dispatch({ type: "addToCart", payload: options }); - - dispatch({ type: "calculatePrice" }); - - toast.success("Product Added"); - - }) - .catch((err) => { - setLoading(false) - - }) + useEffect(() => { + function getProductDetails() { + setLoading(true); + axios + .get(`/api/product/getAll/admin`, { + headers: { + "Access-Control-Allow-Origin": "*", + Authorization: `Bearer ${token}`, + }, + }) + .then((res) => { + setLoading(false); + // console.log(res.data.product) + setProductData(res.data.product); + }) + .catch((err) => { + setLoading(false); + // getBack() + }); } - - - const handleRemove = (id) => { - dispatch({ - type: "deleteFromCart", - payload: { product: id }, + function getFranchiseeDetails() { + setLoading(true); + axios + .get(`/api/franchisee`, { + headers: { + "Access-Control-Allow-Origin": "*", + Authorization: `Bearer ${token}`, + }, + }) + .then((res) => { + setLoading(false); + console.log(res.data.data); + setAllFranchisee(res.data.data); + }) + .catch((err) => { + setLoading(false); + // getBack() }); - dispatch({ type: "calculatePrice" }); - toast.success("Item Removed"); - - }; - //increase qty - const increaseQuantity = (id) => { - - dispatch({ - type: "addToCart", - payload: { product: id }, - }); - dispatch({ type: "calculatePrice" }); - // localStorage.setItem("cartItems", JSON.stringify(AllStates.cart)); - } + getProductDetails(); + getFranchiseeDetails(); + }, []); + const handleChange = (e) => { + if (e.target.type === "text") { + setData((prev) => ({ ...prev, [e.target.id]: e.target.value })); + } else { + setOrderStatus(e.target.value); + } + }; + const handleQuantityChange = (e) => { + setData((prev) => ({ + ...prev, + quantity: e.target.value, + total_Price: productDetails?.base_Price * e.target.value, + })); + }; - const decreaseQuantity = (id) => { + // ------------------------Frenchisee handle------------------------------// - dispatch({ - type: "decrement", - payload: { product: id }, - }); + const handleGetSingleFrenchisee = async () => { + console.log(getFranchiseeID.current.value); + + axios + .get(`/api/franchisee/arrayspopulate/${getFranchiseeID.current.value}`, { + headers: { + "Access-Control-Allow-Origin": "*", + Authorization: `Bearer ${token}`, + }, + }) + .then((res) => { + setLoading(false); + console.log(res.data.data); + let options = { + Franchisee: res?.data?.data?._id, + name: res?.data?.data?.name, + + contact_Number: res?.data?.data?.contact_Number, + contact_Person_Name: res?.data?.data?.contact_Person_Name, + address: + res?.data?.data?.address_line_1 + + " " + + res?.data?.data?.address_line_2, + city: res?.data?.data?.city?.city_name, + price_Lable: res?.data?.data?.price_Lable, + state: res?.data?.data?.city?.state?.state_name, + banner: res?.data?.data?.banner?.url, + Franchisee_Url: res?.data?.data?.url, + }; + + dispatch({ type: "addShippingInfo", payload: options }); + + // localStorage.setItem("shippingInfo", JSON.stringify(AllStates.shipingInfo)); + + toast.success("Franchisee Added"); + }) + .catch((err) => { + setLoading(false); + }); + }; + const FranchiseeRemove = (id) => { + dispatch({ + type: "deleteFromshippingInfo", + payload: { Franchisee: id }, + }); + toast.success("Franchisee Removed"); + }; + // ------------------------Frenchisee handle End------------------------------// + // ------------------------product handle------------------------------// + + const handleGetSingleProduct = async (e) => { + axios + .get(`/api/product/getOne/${getValue.current.value}`, { + headers: { + "Access-Control-Allow-Origin": "*", + Authorization: `Bearer ${token}`, + }, + }) + .then((res) => { + setLoading(false); + const productAllkey = Object.keys(res?.data?.product); + const productAllValue = Object.values(res?.data?.product); + const findIndex1 = productAllkey.indexOf(shipingInfo?.price_Lable); + const findIndex2 = productAllkey.indexOf( + `${shipingInfo?.price_Lable}_With_Tax` + ); + + let options = { + name: res?.data?.product?.name, + price: productAllValue[findIndex1], + product: res?.data?.product?._id, + quantity: 1, + + image: res?.data?.product?.image?.url, + + taxId: res?.data?.product?.taxId, + price_With_Tax: productAllValue[findIndex2], + }; + dispatch({ type: "addToCart", payload: options }); dispatch({ type: "calculatePrice" }); - }; - // ------------------------product handle End------------------------------// + toast.success("Product Added"); + }) + .catch((err) => { + setLoading(false); + }); + }; + const handleRemove = (id) => { + dispatch({ + type: "deleteFromCart", + payload: { product: id }, + }); + dispatch({ type: "calculatePrice" }); + toast.success("Item Removed"); + }; + //increase qty + const increaseQuantity = (id) => { + dispatch({ + type: "addToCart", + payload: { product: id }, + }); + dispatch({ type: "calculatePrice" }); + // localStorage.setItem("cartItems", JSON.stringify(AllStates.cart)); + }; - function handleSubmit() { - if ( - shipingInfo === null) { - swal({ - title: 'Warning', - text: 'Please select Franchisee ', - icon: 'error', - button: 'Close', - dangerMode: true, - }) - return - } + const decreaseQuantity = (id) => { + dispatch({ + type: "decrement", + payload: { product: id }, + }); - else if (cartItems.length < 1) { - swal({ - title: 'Warning', - text: 'Please select atleast one product', - icon: 'error', - button: 'Close', - dangerMode: true, - }) - return - } + dispatch({ type: "calculatePrice" }); + }; + // ------------------------product handle End------------------------------// - - else if ( - tax === '' || - shippingCharge === '' || - total === '' - - ) { - swal({ - title: 'Warning', - text: 'Fill all mandatory fields', - icon: 'error', - button: 'Close', - dangerMode: true, - }) - return - } - - - - setLoading(true) - - - - - setLoading(true) - axios - .post( - `/api/order/create`, - { - orderItems: cartItems, - shippingInfo: shipingInfo, - shipping_charge: shippingCharge, - tax_amount: tax, - total_amount: total - - - }, - - { - headers: { - 'Access-Control-Allow-Origin': '*', - Authorization: `Bearer ${token}`, - }, - }, - ) - .then((res) => { - // console.log(res) - swal({ - title: 'Created', - text: res.data.message ? res.data.message : 'Order created!', - icon: 'success', - button: 'ok', - }) - setLoading(false) - navigate('/orders/new') - }) - .catch((error) => { - setLoading(false) - swal({ - title: 'Warning', - text: error.response.data.message ? error.response.data.message : 'Something went wrong!', - icon: 'error', - button: 'Retry', - dangerMode: true, - }) - }) + function handleSubmit() { + if (shipingInfo === null) { + swal({ + title: "Warning", + text: "Please select Franchisee ", + icon: "error", + button: "Close", + dangerMode: true, + }); + return; + } else if (cartItems.length < 1) { + swal({ + title: "Warning", + text: "Please select atleast one product", + icon: "error", + button: "Close", + dangerMode: true, + }); + return; + } else if (tax === "" || shippingCharge === "" || total === "") { + swal({ + title: "Warning", + text: "Fill all mandatory fields", + icon: "error", + button: "Close", + dangerMode: true, + }); + return; } + setLoading(true); - function getBack() { - navigate(`/orders/${status}`, { replace: true }) - } + setLoading(true); + axios + .post( + `/api/order/create`, + { + orderItems: cartItems, + shippingInfo: shipingInfo, + shipping_charge: shippingCharge, + tax_amount: tax, + total_amount: total, + }, - return ( - <> - {' '} -
    -
    -
    -
    -
    -
    { + // console.log(res) + swal({ + title: "Created", + text: res.data.message ? res.data.message : "Order created!", + icon: "success", + button: "ok", + }); + setLoading(false); + navigate("/orders/new"); + }) + .catch((error) => { + setLoading(false); + swal({ + title: "Warning", + text: error.response.data.message + ? error.response.data.message + : "Something went wrong!", + icon: "error", + button: "Retry", + dangerMode: true, + }); + }); + } + + function getBack() { + navigate(`/orders/${status}`, { replace: true }); + } + + return ( + <> + {" "} +
    +
    +
    +
    +
    +
    -
    - Add Order -
    -
    - - - - -
    - -
    - -
    -
    - - -
    -
    -
    -
    -
    - -
    - - -
    - - -
    - - - { - shipingInfo !== null && -
    -
    -
    - {shipingInfo?.name} -
    -
    -
    {shipingInfo?.name}
    - - Address. : {shipingInfo?.address} - -

    - Contact No. : {shipingInfo?.contact_Number} -

    -

    - Contact Person Name : {shipingInfo?.contact_Person_Name} -

    -

    - Price Lable : {shipingInfo?.price_Lable} -

    - - - - - - - - -
    -
    -
    - -
    - } - -
    - -
    {' '} -
    - -
    -
    -
    - - -
    -
    - - {shipingInfo !== null &&
    -
    -
    - -
    - - - -
    - -
    - -
    - - - { - cartItems && cartItems.map((productDetails, i) => -
    -
    -
    - {productDetails?.name} -
    -
    -
    {productDetails?.name}
    -
    -
    - - -
    - - {productDetails?.quantity} - - -
    - -

    - Price With Tax: ₹{productDetails?.price_With_Tax} -

    - -
    -
    -

    - Price: ₹{productDetails?.price} -

    - - - - -
    -
    -
    -
    -
    - -
    - ) - } - {subTotal &&
    - Total Order Value: ₹{subTotal} -
    } -
    -
    -
    - - } - - - - - - - -
    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Order Placed On : - {productData?.status_timeline?.new - ? new Date(productData?.status_timeline?.new).toLocaleString('en-IN', { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - }) - : new Date(productData?.placed_on).toLocaleString('en-IN', { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - })} -
    Processing Started : - {productData?.status_timeline?.processing - ? new Date(productData?.status_timeline?.processing).toLocaleString( - 'en-IN', - { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - }, - ) - : '-'} -
    Dispatched On : - {productData?.status_timeline?.dispatched - ? new Date(productData?.status_timeline?.dispatched).toLocaleString( - 'en-IN', - { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - }, - ) - : '-'} -
    Delivered On : - {productData?.status_timeline?.delivered - ? new Date(productData?.status_timeline?.delivered).toLocaleString( - 'en-IN', - { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - }, - ) - : '-'} -
    Cancelled On : - {productData?.status_timeline?.cancelled - ? new Date(productData?.status_timeline?.cancelled).toLocaleString( - 'en-IN', - { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - }, - ) - : '-'} -
    Returned On : - {productData?.status_timeline?.returned - ? new Date(productData?.status_timeline?.returned).toLocaleString( - 'en-IN', - { - month: 'short', - day: 'numeric', - year: 'numeric', - hour: '2-digit', - minute: 'numeric', - hour12: true, - }, - ) - : '-'} -
    -
    -
    - - - - - - -
    -
    -
    + > +
    + Add Order +
    +
    + + + + +
    +
    -
    - {/* */} + +
    +
    +
    +
    +
    + +
    + + +
    +
    + {shipingInfo !== null && ( +
    +
    +
    + {shipingInfo?.name} +
    +
    +
    {shipingInfo?.name}
    + + Address. : {shipingInfo?.address} + +

    + Contact No. : {shipingInfo?.contact_Number} +

    +

    + Contact Person Name :{" "} + {shipingInfo?.contact_Person_Name} +

    +

    + Price Lable : {shipingInfo?.price_Lable} +

    + + +
    +
    +
    +
    + )} +
    + +
    {" "} +
    + +
    +
    +
    +
    +
    + {shipingInfo !== null && ( +
    +
    +
    + +
    + + +
    +
    + +
    + + + {cartItems && + cartItems.map((productDetails, i) => ( +
    +
    +
    + {productDetails?.name} +
    +
    +
    + {productDetails?.name} +
    +
    +
    +
    + + + {productDetails?.quantity} + + +
    + +

    + Price With Tax: ₹ + {productDetails?.price_With_Tax} +

    + +
    +
    +

    + Price: ₹ + {productDetails?.price} +

    +
    +
    +
    +
    +
    +
    + ))} + {subTotal && ( +
    + Total Order Value: ₹{subTotal} +
    + )} +
    +
    +
    + )} + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Order Placed On : + {productData?.status_timeline?.new + ? new Date( + productData?.status_timeline?.new + ).toLocaleString("en-IN", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + }) + : new Date(productData?.placed_on).toLocaleString( + "en-IN", + { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + } + )} +
    Processing Started : + {productData?.status_timeline?.processing + ? new Date( + productData?.status_timeline?.processing + ).toLocaleString("en-IN", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + }) + : "-"} +
    Dispatched On : + {productData?.status_timeline?.dispatched + ? new Date( + productData?.status_timeline?.dispatched + ).toLocaleString("en-IN", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + }) + : "-"} +
    Delivered On : + {productData?.status_timeline?.delivered + ? new Date( + productData?.status_timeline?.delivered + ).toLocaleString("en-IN", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + }) + : "-"} +
    Cancelled On : + {productData?.status_timeline?.cancelled + ? new Date( + productData?.status_timeline?.cancelled + ).toLocaleString("en-IN", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + }) + : "-"} +
    Returned On : + {productData?.status_timeline?.returned + ? new Date( + productData?.status_timeline?.returned + ).toLocaleString("en-IN", { + month: "short", + day: "numeric", + year: "numeric", + hour: "2-digit", + minute: "numeric", + hour12: true, + }) + : "-"} +
    +
    +
    +
    - - ) +
    +
    +
    +
    + {/* */} +
    + + ); } -export default AddOrder +export default AddOrder; diff --git a/src/views/orders/EditOrder.js b/src/views/orders/EditOrder.js index 1b5d147..9622c32 100644 --- a/src/views/orders/EditOrder.js +++ b/src/views/orders/EditOrder.js @@ -93,7 +93,7 @@ function EditOrder() { function getProductDetails() { setLoading(true); axios - .get(`/api/product/getAll/`, { + .get(`/api/product/getAll/admin`, { headers: { "Access-Control-Allow-Origin": "*", Authorization: `Bearer ${token}`, diff --git a/src/views/pages/login/Login.js b/src/views/pages/login/Login.js index 46f1cbe..d0e09ca 100644 --- a/src/views/pages/login/Login.js +++ b/src/views/pages/login/Login.js @@ -100,8 +100,10 @@ const Login = () => { setLoading({ loading: true }); try { const res = await axios.post("/api/v1/user/login/", auth); + console.log(res); if (res.data.success == true) { localStorage.setItem("authToken", res.data.token); + let response = await axios.get(`/api/v1/user/details`, { headers: { Authorization: `Bearer ${res.data.token}`, @@ -109,7 +111,7 @@ const Login = () => { }); // console.log(response.data) const data = response.data; - if (data.user.role === "admin") { + if (data.user.role === "admin" || data.user.role === "Employee") { history("/dashboard"); setLoading(false); window.location.reload();