import React, { useState, useEffect } from "react"; import { TextField, Button, Card, Grid, Typography, FormHelperText, Autocomplete, CircularProgress, } from "@mui/material"; import { useNavigate } from "react-router-dom"; import toast from "react-hot-toast"; import axios from "axios"; import { isAutheticated } from "src/auth"; import { City, State } from "country-state-city"; const AddPrincipalDistributor = () => { const navigate = useNavigate(); const token = isAutheticated(); const [user, setUser] = useState({ name: "", email: "", phone: "", }); const [data, setData] = useState({ street: "", city: "", state: "", postalCode: "", country: "India", tradeName: "", gstNumber: "", panNumber: "", }); const [loading, setLoading] = useState(false); const [stateOptions, setStateOptions] = useState([]); const [cityOptions, setCityOptions] = useState([]); const [selectedState, setSelectedState] = useState(null); const [selectedCity, setSelectedCity] = useState(null); useEffect(() => { const fetchStates = async () => { const states = State.getStatesOfCountry("IN").map((state) => ({ label: state.name, value: state.isoCode, })); setStateOptions(states); }; fetchStates(); }, []); useEffect(() => { const fetchCities = async () => { if (selectedState) { const cities = City.getCitiesOfState("IN", selectedState.value).map( (city) => ({ label: city.name, value: city.name, }) ); setCityOptions(cities); } }; fetchCities(); }, [selectedState]); const handleInputChange = (e) => { setUser({ ...user, [e.target.name]: e.target.value }); }; const handleDataChange = (e) => { setData({ ...data, [e.target.name]: e.target.value }); }; const handleStateChange = (event, newValue) => { setSelectedState(newValue); }; const handleCityChange = (event, newValue) => { setSelectedCity(newValue); }; const generatePassword = (name, email) => { const combinedStr = (name + email).toLowerCase(); const specialChars = "@#*"; const alphaChars = combinedStr.match(/[a-zA-Z]/g); const filteredChars = combinedStr.match(/[^\W_]/g); let passwordChars = alphaChars.concat(filteredChars); 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); const password = passwordChars.join("").slice(0, 8); return password; }; const handleFormSubmit = async (e) => { e.preventDefault(); try { if ( !user.name || !user.email || !user.phone || !selectedState || !selectedCity || !data.street || !data.postalCode ) { throw new Error("Fill all fields!"); } setLoading(true); const generatedPassword = generatePassword(user.name, user.email); const userResponse = await axios.post("/api/v1/user/register", { ...user, password: generatedPassword, }); if (userResponse.status === 201) { const userId = userResponse.data.userId; const addressResponse = await axios.post( `/api/shipping/address/admin/new/${userId}`, { ...data, state: selectedState.label, // Send selected state label city: selectedCity.label, // Send selected city label }, { headers: { Authorization: `Bearer ${token}`, }, } ); setLoading(false); if (addressResponse.status === 201) { toast.success("Principal Distributor and Address Added Successfully"); navigate("/principal-distributor"); } } } catch (error) { setLoading(false); console.error("Error adding principal distributor and address:", error); toast.error(error.response?.data?.message || "Something went wrong!"); } }; const handleCancel = () => { navigate("/principal-distributor"); }; return (
Add Principal Distributor
Basic Information Business Details Address option.label} value={selectedState} onChange={handleStateChange} renderInput={(params) => ( )} /> option.label} value={selectedCity} onChange={handleCityChange} renderInput={(params) => ( )} />
); }; export default AddPrincipalDistributor;