diff --git a/src/pages/nearle/clients/createCustomer.js b/src/pages/nearle/clients/createCustomer.js index a7ba0eb..c908616 100644 --- a/src/pages/nearle/clients/createCustomer.js +++ b/src/pages/nearle/clients/createCustomer.js @@ -1,67 +1,73 @@ -import { useEffect, useState } from 'react'; +import { React, useEffect, useState } from 'react'; // material-ui import { useTheme } from '@mui/material/styles'; -import { Box, Button, FormLabel, Grid, InputLabel, MenuItem, Select, Stack, TextField, Typography } from '@mui/material'; - -// third-party -// import { PatternFormat } from 'react-number-format'; +import { + Box, + Button, + FormLabel, + Grid, + InputLabel, + MenuItem, + Select, + Stack, + TextField, + Typography, + IconButton, + Autocomplete, + InputAdornment +} from '@mui/material'; +import MyLocationIcon from '@mui/icons-material/MyLocation'; // project import import Avatar from 'components/@extended/Avatar'; import MainCard from 'components/MainCard'; -import { - // facebookColor, linkedInColor, twitterColor - ThemeMode -} from 'config'; + import axios from 'axios'; -// assets -import { - // FacebookFilled, LinkedinFilled, TwitterSquareFilled, - CameraOutlined -} from '@ant-design/icons'; + import { usePlacesWidget } from 'react-google-autocomplete'; import Loader from 'components/Loader'; import Geocode from 'react-geocode'; import { enqueueSnackbar } from 'notistack'; import { useNavigate } from 'react-router'; -// import { setLocationType } from 'react-geocode'; - -// const avatarImage = require.context('assets/images/users', true); - -// styles & constant -// const ITEM_HEIGHT = 48; -// const ITEM_PADDING_TOP = 8; -// const MenuProps = { -// PaperProps: { -// style: { -// maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP -// } -// } -// }; +import CloseIcon from '@mui/icons-material/Close'; const CreateCustomer = () => { + const appId = localStorage.getItem('applocationid'); const theme = useTheme(); const [selectedImage, setSelectedImage] = useState(undefined); const [avatar, setAvatar] = useState(); - // avatarImage(`./default.png`) const [businessname, setBusinessname] = useState(''); const [businessno, setBusinessno] = useState(''); - // const [role, setRole] = useState(''); const [mobilenumber, setMobilenumber] = useState(''); const [emailaddress, setEmailaddress] = useState(''); const [city, setCity] = useState(''); const [zipcode, setZipcode] = useState(''); const [address, setAddress] = useState(''); - const [state, setState] = useState(''); const [suburb, setSuburb] = useState(''); const [latlong, setLatlong] = useState({}); - const [profiledetails, setProfiledetails] = useState({}); - const [primarycontact, setPrimarycontact] = useState(''); const [firstname, setFirstname] = useState(''); const [doorno, setDoorno] = useState(''); const [landmark, setLandmark] = useState(''); const [tenantinfo, setTenantinfo] = useState({}); + const [inputValue2, setInputValue2] = useState(''); + const [appLocaLat, setAppLocaLat] = useState(); + const [appLocaLng, setAppLocaLng] = useState(); + const [appLocaRadius, setAppLocaRadius] = useState(); + const [locaName, setLocoName] = useState('Select Location'); + const [locations, setLocations] = useState('Select Location'); + const [tenantlist, setTenantlist] = useState([]); + const userid = localStorage.getItem('userid'); + const [isAppLocation, setIsAppLocation] = useState(false); + const [tenantLocations, setTenantlocations] = useState([]); + const [isClient, setisclient] = useState(false); + const [tid, setTid] = useState(0); + const [isBusiness, setIsBusiness] = useState(false); + const [tenanatLocoId, setTenanatLocoId] = useState(localStorage.getItem('locationid')); + const [tenantlocation, setTenantlocation] = useState(''); + const [isLocation, setIsLocation] = useState(false); + const [pickCust, setPickCust] = useState({}); + const [startPoint, setStartPoint] = useState({ latitude: 0, longitude: 0 }); const navigate = useNavigate(); @@ -71,34 +77,185 @@ const CreateCustomer = () => { const [loading, setLoading] = useState(false); useEffect(() => { - // fetchprofiledetails(localStorage.getItem('appuserid')); - // fetchprofiledetails(181); if (localStorage.getItem('tenantid')) { fetchtenantinfo(localStorage.getItem('tenantid')); } }, []); useEffect(() => { - try { - Geocode.fromAddress(address).then( - (response) => { - if (response.status == 'OK') { - const { lat, lng } = response.results[0].geometry.location; - setLatlong({ - lat, - lng - }); - console.log(response); - } - }, - (error) => { - console.log(error); - } - ); - } catch (err) { - console.log(err); + // Initialize Google Maps Autocomplete + if (inputValue2) { + const autocompleteInput = document.getElementById('addressAuto1'); + const autocomplete = new window.google.maps.places.Autocomplete(autocompleteInput, { + // types: ['(cities)'], // You can adjust the types parameter based on your requirements + strictBounds: true, + bounds: new window.google.maps.Circle({ + // center: new window.google.maps.LatLng(11.0050707, 76.9509083), + // radius: 100000 + center: new window.google.maps.LatLng(appLocaLat, appLocaLng), + + radius: appLocaRadius * 1000 + }).getBounds() + }); + let arr = []; + // Event listener for autocomplete place changed + autocomplete.addListener('place_changed', () => { + const place = autocomplete.getPlace(); + setInputValue2(`${place.name}, ${place.formatted_address}`); + console.log('new place', place); // Do something with the selected place + console.log(' pick (new place) lat lng', { lat: place.geometry.location.lat(), lng: place.geometry.location.lng() }); // Do something with the selected place + // to trigger getDistance + setStartPoint({ latitude: place.geometry.location.lat(), longitude: place.geometry.location.lng() }); + setAddress(`${place.name} ${place.formatted_address}`); + setPickCust({ ...pickCust, address: `${place.name} ${place.formatted_address}` }); + const address = { + address: `${place.name} ${place.formatted_address}`, + street_number: '', + route: '', + locality: '', + sublocality_level_1: '', + administrative_area_level_3: '', + administrative_area_level_1: '', + country: '', + postal_code: '' + }; + place.address_components.forEach((component) => { + component.types.forEach((type) => { + switch (type) { + case 'street_number': + address.street_number = component.long_name; + break; + case 'route': + address.route = component.long_name; + break; + case 'locality': + address.locality = component.long_name; + break; + case 'sublocality_level_1': + address.sublocality_level_1 = component.long_name; + break; + case 'administrative_area_level_3': + address.administrative_area_level_3 = component.long_name; + break; + case 'administrative_area_level_1': + address.administrative_area_level_1 = component.long_name; + break; + case 'country': + address.country = component.long_name; + break; + case 'postal_code': + address.postal_code = component.long_name; + break; + // Add more cases as needed for other types + } + }); + }); + + // Use address object as per your requirements + setPickCust({ + ...pickCust, + address: address.address, + doorno: `${address.street_number} ${address.route}`, + suburb: address.administrative_area_level_3, + city: address.locality, + state: address.administrative_area_level_1, + postcode: address.postal_code, + latitude: place.geometry.location.lat(), + longitude: place.geometry.location.lng() + }); + console.log('Pick Address:', address); + }); } - }, [address]); + }, [inputValue2]); + // ==================================================== || getapplocations || ==================================================== + const getapplocations = async () => { + setLoading(true); + await axios + .get(`${process.env.REACT_APP_URL}/utils/getapplocations/?applocationid=${appId}`) + .then((res) => { + console.log('getapplocations', res); + const { opentime, closetime, latitude, longitude, radius } = res.data.details[0]; + if (res.data.status) { + setAppLocaLat(latitude); + setAppLocaLng(longitude); + setAppLocaRadius(radius); + console.log('radius', radius); + } + setLoading(false); + }) + .catch((err) => { + console.log(err); + setLoading(false); + }); + }; + useEffect(() => { + getapplocations(); + }, [appId]); + + // ==============================|| fetchAppLocations ||============================== // + const fetchAppLocations = async () => { + try { + const locationRes = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${userid}`); + // const updatedLocations = [ + // ...locationRes.data.details, + // { partnername: 'All', applocationid: -1 } + // ]; + // console.log('fetchAppLocations', updatedLocations); + console.log('fetchAppLocations', locationRes.data.details); + setLocations(locationRes.data.details); + } catch (err) { + console.log('locationRes', err); + } + }; + useEffect(() => { + fetchAppLocations(); + }, []); + + // ===================================================== || fetchtenantinfolist || ===================================================== + + const fetchtenantinfolist = async (id) => { + setLoading(true); + await axios + .get(`${process.env.REACT_APP_URL}/tenants/gettenants/?applocationid=${id}&status=active`) + + .then((res) => { + console.log(res); + if (res.data.status) { + let arr = []; + res.data.details.map((val) => { + arr.push({ + ...val, + label: `${val.tenantname}` + }); + }); + setTenantlist(arr); + } + setLoading(false); + }) + .catch((err) => { + console.log(err); + setLoading(false); + }); + }; + // ============================================= || gettenantlocations (branches) || ============================================= + const gettenantlocations = async (id) => { + try { + const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${id}`); + console.log('gettenantlocations', res.data.details); + if (res.data.details.length == 1) { + setIsLocation(true); + setTenantlocations(res.data.details); + setTenanatLocoId(res.data.details[0].locationid); + setTenantlocation(res.data.details[0].locationaddress); //client address + setIsBusiness(true); + } else { + setTenantlocations(res.data.details); + setIsBusiness(false); // became true after select from tenanatLocations + } + } catch (err) { + console.log('gettenantlocations', err); + } + }; const opentoast = (message) => { enqueueSnackbar(message, { @@ -106,46 +263,6 @@ const CreateCustomer = () => { anchorOrigin: { vertical: 'top', horizontal: 'right' }, autoHideDuration: 2000 }); - // console.log(alertmessage) - }; - - const fetchprofiledetails = async (userid) => { - if (userid) { - setLoading(true); - try { - await axios - .get(`${process.env.REACT_APP_URL2}/tenants/getclient?id=${userid}`) - .then((res) => { - console.log(res); - if (res.data.message === 'Successful') { - let res1 = res.data.details; - setProfiledetails(res1); - setBusinessname(res1.tenantname); - setBusinessno(res1.registrationno); - setMobilenumber(res1.contactno); - setPrimarycontact(res1.primarycontact); - setEmailaddress(res1.primaryemail); - setAddress(res1.address); - setCity(res1.city); - setZipcode(res1.postcode); - setState(res1.state); - setSuburb(res1.suburb); - setLatlong({ - lat: res1.latitude, - lng: res1.longitude - }); - } - setLoading(false); - }) - .catch((err) => { - console.log(err); - setLoading(false); - }); - } catch (err) { - console.log(err); - setLoading(false); - } - } }; const fetchtenantinfo = async (tid) => { @@ -171,157 +288,74 @@ const CreateCustomer = () => { } }, [selectedImage]); - const { ref: materialRef } = usePlacesWidget({ - apiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY, - onPlaceSelected: (place) => { - console.log(place); - - setAddress(place.formatted_address); - let city1, zipcode1, state1, suburb1; - for (let i = 0; i < place.address_components.length; i++) { - for (let j = 0; j < place.address_components[i].types.length; j++) { - switch (place.address_components[i].types[j]) { - case 'locality': - city1 = place.address_components[i].long_name; - break; - case 'administrative_area_level_1': - state1 = place.address_components[i].long_name; - break; - case 'postal_code': - zipcode1 = place.address_components[i].long_name; - break; - case 'sublocality': - suburb1 = place.address_components[i].long_name; - break; - } - } - } - setCity(city1 || ''); - setState(state1 || ''); - setZipcode(zipcode1 || ''); - setSuburb(suburb1 || ''); - - // setAddress(place.formatted_address) - }, - // inputAutocompleteValue: "country", - options: { - // componentRestrictions: 'us', - // types: ["establishment"] - types: ['address' || 'geocode'] - } - }); - const createprofile = async () => { - console.log('res', businessname, businessno, mobilenumber, emailaddress, address, city, zipcode); + let obj = { + applocationid: +appId, + tenantid: +localStorage.getItem('tenantid'), + customerid: 0, + configid: 1, + firstname: firstname, + dialcode: '+91', + contactno: mobilenumber, + email: emailaddress, + doorno: doorno, + address: pickCust.address, + suburb: pickCust.suburb, + city: pickCust.city, + state: pickCust.state, + postcode: pickCust.postcode, + landmark: landmark, + latitude: startPoint.latitude.toString(), + longitude: startPoint.longitude.toString(), + profileimage: '', + devicetype: '', + deviceid: '', + customertoken: '', + primaryaddress: 1 + }; + console.log(obj); - // if (!businessname) { - // opentoast('Fill Business name') - // } else if (!businessno) { - // opentoast('Fill Registration No') - // } - // else - if (!firstname) { - opentoast('Fill Full name'); - } else if (!mobilenumber) { - opentoast('Fill Mobile Number'); - } - // else if (!emailaddress) { - // opentoast('Fill emailaddress') - // } - else if (!address) { - opentoast('Fill Address'); - } else if (!city) { - opentoast('Fill City'); - } else if (!zipcode) { - opentoast('Fill post code'); - } else if (!suburb) { - opentoast('Fill suburb'); - } - // else if (!emailaddress) { - // opentoast('Fill emailaddress') - // } - else if (!latlong.lat || !latlong.lng) { - opentoast('Choose valid address'); - } else { - let obj = { - customerid: 0, - configid: 1, - firstname: firstname, - applocationid: tenantinfo.applolcationid, - profileimage: '', - dialcode: '+91', - contactno: mobilenumber, - devicetype: '', - deviceid: '', - customertoken: '', - address: address, - suburb: suburb, - city: city, - state: state, - postcode: zipcode, - landmark: landmark, - doorno: doorno, - latitude: latlong.lat.toString(), - longitude: latlong.lng.toString(), - tenantid: parseInt(localStorage.getItem('tenantid')), - email: emailaddress, - primaryaddress: 1 - }; - - console.log(obj); - - setLoading(true); - try { - await axios - .post(`${process.env.REACT_APP_URL}/customers/create`, obj) - .then((res) => { - console.log(res); - if (res.data.status) { - enqueueSnackbar(' Created Successfully ', { - variant: 'success', - anchorOrigin: { vertical: 'top', horizontal: 'right' }, - autoHideDuration: 2000 - }); - navigate('/customers'); - // setTimeout(()=>{ - // fetchprofiledetails(localStorage.getItem('appuserid')); - - // },2000) - } else if (res.data.message == 'Customer Already available') { - enqueueSnackbar('Customer Already available', { - variant: 'error', - anchorOrigin: { vertical: 'top', horizontal: 'right' }, - autoHideDuration: 2000 - }); - } - setLoading(false); - }) - .catch((err) => { - console.log(err); - - setLoading(false); - enqueueSnackbar(err.message, { + setLoading(true); + try { + await axios + .post(`${process.env.REACT_APP_URL}/customers/create`, obj) + .then((res) => { + console.log(res); + if (res.data.status) { + enqueueSnackbar(' Created Successfully ', { + variant: 'success', + anchorOrigin: { vertical: 'top', horizontal: 'right' }, + autoHideDuration: 2000 + }); + navigate('/customers'); + } else if (res.data.message == 'Customer Already available') { + enqueueSnackbar('Customer Already available', { variant: 'error', anchorOrigin: { vertical: 'top', horizontal: 'right' }, autoHideDuration: 2000 }); + } + setLoading(false); + }) + .catch((err) => { + console.log(err); + + setLoading(false); + enqueueSnackbar(err.message, { + variant: 'error', + anchorOrigin: { vertical: 'top', horizontal: 'right' }, + autoHideDuration: 2000 }); - } catch (err) { - console.log(err); - setLoading(false); - } + }); + } catch (err) { + console.log(err); + setLoading(false); } }; - // const [experience, setExperience] = useState('0'); - - // const handleChange = (event) => { - // setExperience(event.target.value); - // }; return ( <> {loading && } - Create Customer @@ -329,318 +363,221 @@ const CreateCustomer = () => { - {/* - - - - - - - - - - - Upload - - - - - setSelectedImage(e.target.files?.[0])} - /> - - - - - - - - - - - - - - - - - - Role - setRole(e.target.value)} - value={role} - autoComplete='off' - - /> - - - - - - */} - - - - {/* - - Business Name - setBusinessname(e.target.value)} - value={businessname} - autoComplete='off' - /> - - - - - Registration No - setBusinessno(e.target.value)} - value={businessno} - autoComplete='off' - - /> - - */} - - - Name - setFirstname(e.target.value)} - value={firstname} - autoComplete="off" - /> - - - {/* - */} - - - Phone Number - - - { }} - onChange={(e) => { - if (e.target.value.toString().length <= 10) { - setMobilenumber(e.target.value); - } - }} - value={mobilenumber} - autoComplete="off" - // disabled - sx={{ cursor: 'not-allowed' }} - /> - - - - - - Email Address - setEmailaddress(e.target.value)} - value={emailaddress} - autoComplete="off" - /> - - - - - - Address - setAddress(e.target.value)} - inputRef={materialRef} - /> - - - - - - Location - setSuburb(e.target.value)} - value={suburb} - autoComplete="off" - /> - - - - - City - setCity(e.target.value)} - value={city} - autoComplete="off" - /> - - - - - - State - setState(e.target.value)} - value={state} - autoComplete="off" - /> - - - - - Post Code - setZipcode(e.target.value)} - value={zipcode} - autoComplete="off" - /> - - - - - - Door No - setDoorno(e.target.value)} - value={doorno} - autoComplete="off" - /> - - - - - Landmark - setLandmark(e.target.value)} - value={landmark} - autoComplete="off" - /> - - + + + {/* ===================================================== || Name|| ===================================================== */} + + + Name + setFirstname(e.target.value)} + value={firstname} + autoComplete="off" + /> + - + {/* ===================================================== || Phone Number || ===================================================== */} + + + Phone Number + + + { + if (e.target.value.toString().length <= 10) { + setMobilenumber(e.target.value); + } + }} + value={mobilenumber} + autoComplete="off" + // disabled + sx={{ cursor: 'not-allowed' }} + /> + + + + {/* ===================================================== || Email|| ===================================================== */} + + + + Email Address + setEmailaddress(e.target.value)} + value={emailaddress} + autoComplete="off" + /> + + + {/* ===================================================== || door no || ===================================================== */} + + + + Door No + setDoorno(e.target.value)} + value={doorno} + autoComplete="off" + /> + + + + {/* ===================================================== || Address || ===================================================== */} + + + + Address + setInputValue2(e.target.value)} + InputProps={{ + endAdornment: ( + { + setInputValue2(''); + setPickCust({ + ...pickCust, + doorno: '', + suburb: '', + city: '', + postcode: '', + landmark: '' + }); + setStartPoint({ latitude: 0, longitude: 0 }); + }} + size="small" + > + + + ) + }} + /> + + + + + + Location + setPickCust({ ...pickCust, suburb: e.target.value })} + value={pickCust.suburb} + autoComplete="off" + /> + + + + + City + setPickCust({ ...pickCust, city: e.target.value })} + value={pickCust.city} + autoComplete="off" + /> + + + + + + State + setPickCust({ ...pickCust, state: e.target.value })} + value={pickCust.state} + autoComplete="off" + /> + + + + + Post Code + setPickCust({ ...pickCust, postcode: e.target.value })} + value={pickCust.postcode} + autoComplete="off" + /> + + + + + + Landmark + setLandmark(e.target.value)} + value={landmark} + autoComplete="off" + /> + + + - {/* new1 */} - {/* `${option.firstname} (${option.contactno})`} - sx={{ mt: 2, mb: 1 }} - renderInput={(params) => ( - { - setSearchCustList(e.target.value); - }} - InputProps={{ - ...params.InputProps, - inputProps: { - ...params.inputProps, - maxLength: 10 - } - }} - /> - )} - onChange={(e, val, reason) => { - if (val) { - console.log('pickcustNew', val); - setStartPoint({ latitude: val.latitude, longitude: val.longitude }); - setPickCust(val); - setAddId1(1); - setSearchCustList(''); - } - if (reason == 'clear') { - setSearchCustList(''); - } - }} - noOptionsText={ - /^[0-9]{10}$/.test(searchCustList) ? ( - - { - setPickCust({ ...pickCust, contactno: searchCustList }); - handleOkClick1(); - setSearchCustList(''); - }} - /> - - ) : null - } - /> */}