import React, { useEffect, useState } from "react"; import Button from "@material-ui/core/Button"; import { Link, useNavigate } from "react-router-dom"; import swal from "sweetalert"; import axios from "axios"; import { isAutheticated } from "src/auth"; import CloudUploadIcon from "@mui/icons-material/CloudUpload"; import DeleteSharpIcon from "@mui/icons-material/DeleteSharp"; import { Box, FormControl, IconButton, MenuItem, Select, TextField, } from "@mui/material"; // import { WebsiteURL } from '../WebsiteURL' const AddProduct = () => { const token = isAutheticated(); const navigate = useNavigate(); const [loading, setLoading] = useState(false); const [allTax, setAllTax] = useState([]); const [categories, setCategoies] = useState([]); const [imagesPreview, setImagesPreview] = useState([]); // const [allimage, setAllImage] = useState([]); const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [productImages, setProductImages] = useState([]); const [price, setPrice] = useState(0); const [category, setCategoryName] = useState(""); const [error, setError] = useState(""); const [selectedTax, setselectedTax] = useState(); const [totalAmt, setTotalAmt] = useState(0); const [gst_amount, setGst_amount] = useState(0); const handleFileChange = (e) => { const files = e.target.files; // Check the total number of selected files if (productImages.length + files.length > 4) { setError("You can only upload up to 4 images."); return; } // Check file types and append to selectedFiles const allowedTypes = ["image/jpeg", "image/png", "image/jpg"]; const selected = []; for (let i = 0; i < files.length; i++) { if (productImages.length + selected.length >= 4) { break; // Don't allow more than 4 images } if (allowedTypes.includes(files[i].type)) { selected.push(files[i]); } } if (selected.length === 0) { setError("Please upload only PNG, JPEG, or JPG files."); } else { setError(""); setProductImages([...productImages, ...selected]); } }; const handelDelete = (image) => { const filtered = productImages.filter((item) => item !== image); setProductImages(filtered); }; // get All categories const getCategories = async () => { try { const response = await axios.get("/api/category/getCategories", { headers: { Authorization: `Bearer ${token}`, }, }); if (response.status === 200) { setCategoies(response?.data?.categories); } } catch (error) { swal({ title: error, text: " please login to access the resource ", icon: "error", button: "Retry", dangerMode: true, }); } }; // Get all tax const getAllTax = async () => { const res = await axios.get(`/api/tax/view_tax`, { headers: { "Access-Control-Allow-Origin": "*", Authorization: `Bearer ${token}`, }, }); if (res.data) { setAllTax(res.data); } }; useEffect(() => { getAllTax(); getCategories(); }, [token]); const TaxRatechange = async (e) => { let m = JSON.parse(e.target.value); if (m?.tax) { let totalprice = Number(price) + Number((price * m?.tax) / 100); setGst_amount(Number((price * m?.tax) / 100)?.toFixed(2)); setTotalAmt(totalprice?.toFixed(2)); setselectedTax(m?._id); } }; const handleSubmit = () => { if ( name === "" || description === "" || productImages.length == 0 || category === "" || selectedTax === "" || gst_amount === "" || price === "" ) { swal({ title: "Warning", text: "Fill all mandatory fields", icon: "error", button: "Close", dangerMode: true, }); return; } setLoading(true); const formData = new FormData(); formData.append("name", name); formData.append("description", description); formData.append("price", price); formData.append("category", category); formData.append("total_amount", totalAmt); formData.append("gst_amount", gst_amount); formData.append("gst", selectedTax); productImages.forEach((Singleimage) => { // console.log(Singleimage) formData.append("image", Singleimage); }); axios .post(`/api/product/create/`, formData, { headers: { Authorization: `Bearer ${token}`, "Content-Type": "multipart/formdata", "Access-Control-Allow-Origin": "*", }, }) .then((res) => { swal({ title: "Added", text: "Product added successfully!", icon: "success", button: "ok", }); setLoading(false); navigate("/products", { replace: true }); }) .catch((err) => { setLoading(false); const message = err.response?.data?.message ? err.response?.data?.message : "Something went wrong!"; swal({ title: "Warning", text: message, icon: "error", button: "Retry", dangerMode: true, }); }); }; const handlePriceChange = (e) => { const newPrice = e.target.value; setPrice(newPrice); const selectedTaxObj = allTax.find((t) => t._id === selectedTax); if (selectedTaxObj && !isNaN(newPrice)) { const gstAmount = (newPrice * selectedTaxObj.tax) / 100; const totalAmount = Number(newPrice) + gstAmount; setGst_amount(gstAmount.toFixed(2)); setTotalAmt(totalAmount.toFixed(2)); } }; // console.log(data); // console.log(productImages); return (
Add Product

setName(e.target.value)} /> {name ? ( <> {35 - name.length} characters left ) : ( <> )}{" "}