import React, { useState, useRef, useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Messages } from '../../Components/Notifications/Messages'; import { useNavigate } from 'react-router-dom'; import { Form } from 'antd'; import { clearSession, encryptedValuesUrlFun, getSession, sessionStore, } from '../../Services/Others'; import FormHeader from '../PageComponents/FormHeader.jsx'; import { DropDowns } from '../../Components/Forms/DropDown.jsx'; import '../../Styles/UpiDetails/upidetails.scss'; import { changeSelectedBranchId, changeWarehouse, checkSession, getCompBranchData, getLoginuser, PostLoginSuser, PUTLoginuser, } from '../../Features/BrachLogin/BranchLogin.js'; import { gettableData } from '../../Features/PreferenceMaster/PreferenceMaster.js'; import { changeOrderCardDetails, getPreferenceData, } from '../../Features/BookingScreen/BookingData/BookingData.js'; import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js'; import { getTemplate } from '../../Features/ThemeChange/ThemeChange.js'; import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx'; import { RadioGrpButton } from '../../Components/Forms/RadioGroup.jsx'; import { UserDataBasedOnBranchId } from '../../Features/Reports/Reports.js'; import { GLobalSadminUserPin, GLobalSadminUserData, } from '../../Features/BrachLogin/BranchLogin'; import { BsShopWindow } from 'react-icons/bs'; const subDirectory = import.meta.env.BASE_URL; const BranchLogin = () => { const formRef = useRef(null); const dispatch = useDispatch(); const navigate = useNavigate(); const [messageType, setMessageType] = useState(null); const [messageData, setMessageData] = useState(null); const [modal, setModal] = useState(false); const [SelectType, setSelectType] = useState('O'); const [SelectTypeName, setSelectTypeName] = useState('OTP'); const [pinInput, setpinInput] = useState(false); const [otp, setOtp] = useState(); const [FirstTimeOtp, setFirstTimeOtp] = useState(false); const [FirstTimePin, setFirstTimePin] = useState(false); const [seconds, setSeconds] = useState(0); const [disabled, setDisabled] = useState(false); const clicked = useRef(false); const timerDuration = 30; const [seletedBranchData, setseletedBranchData] = useState(); const [CompBranchData, setCompBranchData] = useState(); const [UserType, setUserType] = useState( getSession('UserType') ? getSession('UserType') : 'Super Admin' ); const CompId = getSession('CompId'); const AppId = getSession('AppId'); const UserId = getSession('UserId'); const sessionId = getSession('SessionId'); const inputRefs = useRef([]); const [pin, setPin] = useState(['', '', '', '']); const [aftergetPin, setAftergetPin] = useState(false); const [selectedUserData, setSelectedUserData] = useState(null); const [userDropDown, setuserDropDown] = useState([]); const SAdminuserPin = useSelector(GLobalSadminUserPin); const SAdminUserData = useSelector(GLobalSadminUserData); useEffect(() => { inputRefs?.current[0]?.focus(); // Focus first input on mount }, []); const items = [ { name: 'Home', link: `${subDirectory}app-page/home`, }, ]; useEffect(() => { fetchBranchData(); // Call the async function immediately dispatch(changeBreadCrumb({ items: items })); if (UserType != 'Super Admin User') { setAftergetPin(true); } }, []); useEffect(() => { if (aftergetPin == true && UserType == 'Super Admin User') { fetchData(seletedBranchData); } }, [aftergetPin]); useEffect(() => { let interval = null; if (disabled && seconds > 0) { interval = setInterval(() => { setSeconds((prev) => prev - 1); }, 1000); } else if (seconds === 0) { setDisabled(false); clicked.current = false; // Enable button after timer ends // Enable button after timer ends } return () => { if (interval) clearInterval(interval); }; }, [seconds, disabled]); const fetchData = async (e, type) => { await sessionStore('BranchId', e); let data = { CompId: CompId, BranchId: e, AppId: AppId, UserId: UserId, }; let res = await dispatch(getPreferenceData(data)).unwrap(); await dispatch( getTemplate({ CompId: CompId, BranchId: e, AppId: AppId }) ).unwrap(); const filterSettingIdName = 'Dashboard'; const filteredDatas = res?.data?.data?.[0]?.SettingDtlDetails?.filter( (item) => item.SettingIdName === filterSettingIdName ); if (res?.data?.statusCode == 1 && type !== 'W') { filteredDatas?.[0]?.SettingValue == 'Y' ? navigate(`${subDirectory}app-page/home`) : navigate(`${subDirectory}sales`); } else { navigate(`${subDirectory}app-page/home`); } }; const fetchBranchData = async () => { if (UserType === 'Super Admin' || UserType === 'Super Admin User') { const response = await dispatch( getCompBranchData({ CompId: CompId, AppId: AppId }) ).unwrap(); if (response?.data?.statusCode === 1) { setCompBranchData(response?.data?.data); } else { setMessageType('error'); setMessageData(response?.data?.response); } } else if (UserType === 'Admin' || UserType === 'Admin User') { const response = await dispatch( getCompBranchData({ AppId: AppId, UserId: UserId, CompId: CompId }) ).unwrap(); if (response?.data?.statusCode === 1) { setCompBranchData(response?.data?.data); } else { setMessageType('error'); setMessageData(response?.data?.response); } } }; useEffect(() => { if (CompBranchData?.length == 1) { if (UserType != 'Super Admin User') { fetchData(CompBranchData[0]?.BrId); } else { const checkData = SAdminUserData?.filter( (item) => item?.AppId == AppId && item?.CompId == CompId && item?.BranchId == CompBranchData[0]?.BrId ); if ( UserType == 'Super Admin User' && (checkData?.length == 0 || checkData?.[0]?.Status !== 'Y') ) { userDropData(CompBranchData[0]?.BrId); setModal(true); } else { setAftergetPin(true); } } } }, [CompBranchData]); const onChangeBranch = async (e) => { let data = CompBranchData?.find((a) => a?.BrId == e); if (data?.LocationType == 'W') { sessionStore("Warehouse", true) await dispatch(changeWarehouse(true)); } else { sessionStore("Warehouse", false) await dispatch(changeWarehouse(false)); } setseletedBranchData(e); dispatch(changeSelectedBranchId(e)); await sessionStore('BranchId', e); dispatch(changeOrderCardDetails([])); if (UserType != 'Super Admin User') { await fetchData(e, data?.LocationType); } else { const checkData = SAdminUserData?.filter( (item) => item?.AppId == AppId && item?.CompId == CompId && item?.BranchId == e ); if ( UserType == 'Super Admin User' && (checkData?.length == 0 || checkData?.[0]?.Status !== 'Y') ) { userDropData(e); setModal(true); } else { setAftergetPin(true); } } }; const handleSubmit = async (enteredPin) => { if (otp == Number(enteredPin)) { let data = { CompId: CompId, BranchId: seletedBranchData, AppId: AppId, UserId: UserId, SignInType: SelectTypeName, SecurityCode: Number(enteredPin), UpdatedBy: UserId, SessionId: sessionId, EmpId: selectedUserData, }; let response = await dispatch(PUTLoginuser(data)).unwrap(); if (response?.data?.statusCode == 1) { await dispatch(checkSession({ UserId, sessionId })).unwrap(); setModal(false); setAftergetPin(true); inputRefs?.current?.forEach((ref) => { if (ref) { ref.value = ''; } }); setPin(['', '', '', '']); } } else { alert(`Invalid ${SelectType == 'O' ? 'OTP' : 'Pin'}`); } }; const handleChange = (index, event) => { const value = event.target.value; if (/^\d$/.test(value)) { const newPin = [...pin]; newPin[index] = value; setPin(newPin); if (index < inputRefs?.current?.length - 1) { inputRefs?.current[index + 1]?.focus(); // Move to next input } if (newPin.every((num) => num !== '')) { handleSubmit(newPin.join('')); // Call function when all 4 digits are entered } // Call function when all 4 digits are entered } else { event.target.value = ''; const newPin = [...pin]; newPin[index] = value; setPin(newPin); // Clear input if more than one digit is entered } }; const sentpinfn = async () => { let data = { CompId: CompId, BranchId: seletedBranchData, AppId: AppId, UserId: UserId, SignInType: SelectTypeName, CreatedBy: UserId, EmpId: selectedUserData, }; let response = await dispatch(PostLoginSuser(data)).unwrap(); if (response?.data?.statusCode == 1) { setOtp(response?.data?.OTP || response?.data?.PIN); setpinInput(true); // Show PIN/OTP input fields setSeconds(timerDuration); // Start the countdown timer setDisabled(true); // Disable the button temporarily console.log('OTP Sent!'); if (SelectTypeName === 'OTP') { setFirstTimeOtp(true); // Set OTP as sent } else { setFirstTimePin(true); // Set PIN as sent } } }; const handleClick = () => { if (selectedUserData) { if (clicked.current) return; clicked.current = true; if (seconds === 0) { sentpinfn(); // Resend PIN/OTP after 30 seconds } inputRefs?.current?.forEach((ref) => { if (ref) { ref.value = ''; // Reset the value of each input } }); setPin(['', '', '', '']); } else { alert('Please select user'); } }; const ChangeMethod = (e) => { setSelectType(e); setSelectTypeName(e === 'O' ? 'OTP' : 'PIN'); }; const userDropData = async (e) => { const gettinguserDropDown = await dispatch( UserDataBasedOnBranchId(e) ).unwrap(); if (gettinguserDropDown?.data?.statusCode === 1) { let finaluserDropDown = gettinguserDropDown?.data?.data?.filter( (value) => value.ActiveStatus === 'A' ); setuserDropDown(finaluserDropDown); } }; const UserDropDownChange = async (e) => { setSelectedUserData(e); }; const handlePageChange = async () => { console.log('i am called', CompBranchData); if (CompBranchData?.length === 1) { const commonUrl = import.meta.env.ENV_COMMON_BASE_URL; const MobileNo = encryptedValuesUrlFun(getSession('MobileNo')); const userName = encryptedValuesUrlFun(getSession('userName')); const UserId = encryptedValuesUrlFun(getSession('UserId')); const UserType = encryptedValuesUrlFun(getSession('UserType')); const CompId = encryptedValuesUrlFun(getSession('CompId')); const CompName = encryptedValuesUrlFun(getSession('CompName')); const SessionId = encryptedValuesUrlFun(getSession('SessionId')); if (sessionStorage.getItem('BranchId') !== null) { clearSession('BranchId'); } if (sessionStorage.getItem('AppId') !== null) { clearSession('AppId'); } const param = { MN: MobileNo, UN: userName, UD: UserId, UT: UserType, CD: CompId, CN: CompName, SD: SessionId, }; const queryParams = new URLSearchParams(param).toString(); window.location.replace( `${commonUrl}/home/landing-page/home?${queryParams}` ); } else { setseletedBranchData(); if (sessionStorage.getItem('BranchId') !== null) { clearSession('BranchId'); } navigate(`${subDirectory}app-page/branch-login`); } if (sessionStorage.getItem('hasRefreshed') !== null) { sessionStorage.removeItem('hasRefreshed'); } setModal(false); }; return ( <>