import React, { useState, useEffect, useRef, useCallback } from 'react'; import { Form, Input, InputNumber, Button, TimePicker, Space, Checkbox, Collapse, Tooltip, Modal, Table, Tag, Switch, Select, message, } from 'antd'; import { PlusOutlined, MinusOutlined, DeleteOutlined, InfoCircleOutlined, ArrowRightOutlined, PlusCircleOutlined, } from '@ant-design/icons'; // Import your custom components (adjust paths as needed) import CropUpload from '../../Components/Forms/CropUpload.jsx'; import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx'; import { DropDowns } from '../../Components/Forms/DropDown.jsx'; import { getAllsubcatdata, getProdCatData, getProdSubCatData, getUomData, postProductData, prodCatDataSelector, prodSubCatDataSelector, putProductData, ServiceType, uomDataSelector, } from '../../Features/ProductPage/ProductPage.js'; import { useSelector } from 'react-redux'; import { useDispatch } from 'react-redux'; import { getSession } from '../../Services/Others.js'; import { ApplicationPreferences, getCommonAppPreference, } from '../../Features/BrachLogin/BranchLogin.js'; import { getAdmin, taxSelector } from '../../Features/Tax/Tax.js'; import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js'; import { useLocation, useNavigate } from 'react-router-dom'; import './SportsMaster.scss'; import { EmpDepartMentDropDown, EmpDesgDropDown, EmpTypeDropDown, getEmpBasedOnCmpIdBrId, GettingShiftData, postEmp, UserDataBasedOnBranchId, } from '../../Features/EmpMaster/EmpMaster.js'; import { DatePic } from '../../Components/Forms/DatePickerEmpMaster.jsx'; import moment from 'moment'; import { InputField } from '../../Components/Forms/InputField.jsx'; import Cancellation from '../CancelReschedule/Cancellation.jsx'; import EmployeeMasterForm from '../EmpMaster/EmpMasterForm.jsx'; const { Panel } = Collapse; const { TextArea } = Input; const subDirectory = import.meta.env.ENV_BASE_URL; const { RangePicker } = TimePicker; export function SafeRangeTimePicker(props) { const popupClass = 'no-hover-autoscroll-timepicker'; const userScrollTimeout = 150; // ms - time window to consider a scroll as user-initiated // Attach handlers whenever the panel opens; we use a ref to store cleanup const cleanupRef = useRef(() => {}); const onOpenChange = useCallback((open) => { // when closed cleanup immediately if (!open) { cleanupRef.current(); cleanupRef.current = () => {}; return; } // Wait for panel to render in DOM requestAnimationFrame(() => { const columns = document.querySelectorAll( `.${popupClass} .ant-picker-time-panel-column` ); const disposers = []; columns.forEach((column) => { let rememberedScroll = column.scrollTop; let lastUserScroll = 0; let disableHoverAuto = false; // Mark last user scroll on wheel / touchstart const onUserScrollAttempt = (e) => { lastUserScroll = Date.now(); }; // On mouse enter remember current scroll and enable 'guard' for auto-scrolling const onMouseEnter = () => { rememberedScroll = column.scrollTop; disableHoverAuto = true; }; // On mouse leave, disable the guard so normal behavior resumes const onMouseLeave = () => { disableHoverAuto = false; }; // On scroll: if guard is on and there hasn't been a recent user wheel/touch, // assume this scroll is the unwanted auto-scroll and revert to rememberedScroll. const onScroll = () => { const now = Date.now(); const recentUser = now - lastUserScroll <= userScrollTimeout; if (disableHoverAuto && !recentUser) { // cancel the auto scroll by snapping back // use requestAnimationFrame to avoid layout thrash requestAnimationFrame(() => { column.scrollTop = rememberedScroll; }); } else { // user scrolled — update remembered position rememberedScroll = column.scrollTop; } }; column.addEventListener('wheel', onUserScrollAttempt, { passive: true, }); column.addEventListener('touchstart', onUserScrollAttempt, { passive: true, }); column.addEventListener('mouseenter', onMouseEnter); column.addEventListener('mouseleave', onMouseLeave); column.addEventListener('scroll', onScroll); disposers.push(() => { column.removeEventListener('wheel', onUserScrollAttempt); column.removeEventListener('touchstart', onUserScrollAttempt); column.removeEventListener('mouseenter', onMouseEnter); column.removeEventListener('mouseleave', onMouseLeave); column.removeEventListener('scroll', onScroll); }); }); // Save cleanup cleanupRef.current = () => disposers.forEach((d) => d()); }); }, []); // cleanup on unmount useEffect(() => { return () => cleanupRef.current(); }, []); return ( ); } const SportSlotCreation = ({ formType }) => { const [form] = Form.useForm(); const navigate = useNavigate(); const dispatch = useDispatch(); const location = useLocation(); const state = location?.state; const editstate = state?.editstate; console.log(editstate, 'editstate'); const UomData = useSelector(uomDataSelector); const ApplicationPreferenceData = useSelector(ApplicationPreferences); const TaxData = useSelector(taxSelector); const UomTypePreference = ApplicationPreferenceData?.find( (preference) => preference?.PreferredCatName === 'Product Uom' )?.PreferenceCatDetails; const UomPreference = UomData?.filter((item) => UomTypePreference?.some?.( (e) => e?.PreferredSubCatName?.toLowerCase() == item?.ConfigName?.toLowerCase() && e?.PreferredStatus == 'Y' ) ); const ProdCatData = useSelector(prodCatDataSelector); const ProdSubCatData = useSelector(prodSubCatDataSelector); const [selectedType, setSelectedType] = useState(null); const [selectedTypeName, setselectedTypeName] = useState(null); const [selectedCategory, setSelectedCategory] = useState(null); const [selectedSubCategory, setSelectedSubCategory] = useState(null); const [selectedCoach, setSelectedCoach] = useState(null); const [selectedCoachName, setSelectedCoachName] = useState(null); console.log(selectedType, 'selectedType'); const [slotDuration, setSlotDuration] = useState(1); const [generatedSlots, setGeneratedSlots] = useState([]); const [startTime, setStartTime] = useState(null); const [endTime, setEndTime] = useState(null); const [defaultPrice, setDefaultPrice] = useState(null); const [SelectedTaxId, setSelectedTaxId] = useState(null); const [individualPricing, setIndividualPricing] = useState(false); const [OnlineBooking, setOnlineBooking] = useState(false); const [individualDefaultPrice, setIndividualDefaultPrice] = useState(null); console.log(defaultPrice, 'defaultPricedefaultPrice'); // const [fullSlotDefaultPrice, setFullSlotDefaultPrice] = useState(0); // const [openCategoryModal, setOpenCategoryModal] = useState(false); // const [openSubCategoryModal, setOpenSubCategoryModal] = useState(false); // const [openCoachModal, setOpenCoachModal] = useState(false); const [ServicesDatas, setServicesDatas] = useState([]); // const [EmpTypeDropDownData, setEmpTypeDropDownData] = useState([]); // const [seletedEmpTypeDrop, setseletedEmpTypeDrop] = useState(null); // const [EmpDesgDropDownData, setEmpDesgDropDownData] = useState([]); // const [seletedEmpDesigDrop, setseletedEmpDesigDrop] = useState(null); // const [EmpDeptDropDownData, setEmpDeptDropDownData] = useState([]); // const [seletedEmpDeptDrop, setseletedEmpDeptDrop] = useState(null); // const [ShiftDownData, setShiftDownData] = useState([]); // const [seletedShiftDrop, setseletedShiftDrop] = useState(null); // const [AppPreference, setAppPreference] = useState([]); // const [SelectedDate, setSelectedDate] = useState(null); // const [showPassword, setShowPassword] = useState(false); const [userDropDown, setuserDropDown] = useState([]); const [EmployeesDatas, setEmployeesDatas] = useState([]); const [selectedUserData, setSelectedUserData] = useState(null); // const [zipCodeData, setZipCodeData] = useState(false); // state for multiple images const [imageUrls, setImageUrls] = useState([]); // Image states const [imageUrl, setImageUrl] = useState(''); // const [imageopen, setimageOpen] = useState(false); // const [imagedata, setimagedata] = useState([]); // const [selectedImage, setSelectedImage] = useState(null); // const [onlineImage, setOnlineImage] = useState(null); const CompId = getSession('CompId'); const BranchId = getSession('BranchId'); const AppId = getSession('AppId'); const UserId = getSession('UserId'); // Day selection states const [selectedDays, setSelectedDays] = useState({ monday: false, tuesday: false, wednesday: false, thursday: false, friday: false, saturday: false, sunday: false, }); const [selectAllDays, setSelectAllDays] = useState(false); // const departmentTypePreference = AppPreference?.[0]?.PreferenceDetails?.find( // (preference) => preference?.PreferredCatName === 'Department' // ); // const activeDeptTypes = departmentTypePreference?.PreferenceCatDetails?.filter( // (payment) => payment.PreferredStatus !== 'Y') const items = [ { name: 'Home', link: `${subDirectory}app-page/home`, }, { name: 'Slot', link: `${subDirectory}setting/product-master/`, }, { name: editstate ? 'Edit' : 'New', link: null, }, ]; useEffect(() => { const allSelected = Object.values(selectedDays).every((day) => day); setSelectAllDays(allSelected); }, [selectedDays]); useEffect(() => { dispatch(changeBreadCrumb({ items: items })); dispatch(getUomData()); dispatch(getProdCatData({ AppId: AppId })); // dispatch(getProdTaxData({ AppId: AppId })); dispatch(getAdmin({ CompId: CompId, AppId: AppId })); ServiceTypeFn(); getEmployees(); if (formType == 'edit') { const daysOfWeek = editstate?.SlotDetails?.[0]?.DayOfWeek?.map((e) => e.trim()?.toLowerCase() ); dispatch(getProdSubCatData({ ConfigId: editstate?.ProdCat })); setselectedTypeName(editstate?.ProdTypeName); setSelectedType(editstate?.ProdType); setSelectedCategory(editstate?.ProdCat); setSelectedTaxId(editstate?.TaxId); setSelectedSubCategory(editstate?.ProdSubCat); setSelectedDays({ monday: daysOfWeek?.includes('monday'), tuesday: daysOfWeek?.includes('tuesday'), wednesday: daysOfWeek?.includes('wednesday'), thursday: daysOfWeek?.includes('thursday'), friday: daysOfWeek?.includes('friday'), saturday: daysOfWeek?.includes('saturday'), sunday: daysOfWeek?.includes('sunday'), }); setIndividualPricing( editstate?.SlotDetails?.some((e) => e?.SinglePrice != e?.MRP) ); setOnlineBooking( editstate?.SlotDetails?.some((e) => e?.OnlineApplicable == 'Y') ); setDefaultPrice(editstate?.SlotDetails?.[0]?.SellPrice); setIndividualDefaultPrice(editstate?.SlotDetails?.[0]?.SinglePrice); form.setFieldsValue({ defaultPrice: editstate?.SlotDetails?.[0]?.SellPrice, }); form.setFieldsValue({ individualDefaultPrice: editstate?.SlotDetails?.[0]?.SinglePrice, }); setStartTime(editstate?.SlotDetails?.[0]?.AvailableFrom); setEndTime( editstate?.SlotDetails?.[editstate?.SlotDetails?.length - 1] ?.AvailableTo ); setGeneratedSlots( editstate?.SlotDetails?.map((e) => { return { SlotName: e?.SlotName, AvailableFrom: e?.AvailableFrom, AvailableTo: e?.AvailableTo, OnlineApplicable: e?.OnlineApplicable == 'Y' ? true : false, individualPurchase: e?.SinglePrice != e?.MRP ? true : false, individualPrice: e?.SinglePrice, MRP: e?.MRP, SellPrice: e?.SellPrice, ExceptionFrom: '', ExceptionTo: '', IsHoliday: 'N', DayOfWeek: e?.DayOfWeek, active: true, Remarks: 'string', }; }) ); // se setSelectedCoach(Number(editstate?.TrainerId)); setSelectedCoachName(editstate?.ProdName); form.setFieldsValue({ coach: Number(editstate?.TrainerId) }); setOnlineBooking( editstate?.SlotDetails?.some((e) => e?.OnlineApplicable == 'Y') ); setIndividualPricing( editstate?.SlotDetails?.some((e) => e?.SinglePrice != e?.MRP) ); setSlotDuration(editstate?.SlotHours); setDefaultPrice(editstate?.SlotDetails?.[0]?.SellPrice); setImageUrl(editstate?.ProdLogo); form.setFieldsValue({ 'Sport-subCategory': editstate?.ProdSubCat }); form.setFieldsValue({ TaxId: editstate?.TaxId }); form.setFieldsValue({ 'Sport-category': editstate?.ProdCat }); form.setFieldsValue({ type: editstate?.ProdType }); form.setFieldsValue({ maxCapacity: editstate?.Size }); form.setFieldsValue({ groundName: editstate?.ProdName }); form.setFieldsValue({ defaultPrice: editstate?.SlotDetails?.[0]?.SellPrice, }); form.setFieldsValue({ description: editstate?.SportDec?.[0]?.description, }); form.setFieldsValue({ facilities: editstate?.SportDec?.[0]?.Facilities }); form.setFieldsValue({ terms: editstate?.SportDec?.[0]?.Terms }); form.setFieldsValue({ cancellationPolicy: editstate?.SportDec?.[0]?.CancellationPolicy, }); } }, []); // useEffect(() => { // getApplicationPreference() // BranchDropDownChange() // }, []) // const getApplicationPreference = async () => { // const response = await dispatch(getCommonAppPreference(AppId)).unwrap(); // if (response?.data?.statusCode === 1) { // setAppPreference(response?.data?.data) // } // } // const BranchDropDownChange = async (e = BranchId) => { // // formRef.current?.setFieldsValue({ BranchId: e }); // let gettinguserDropDown = []; // gettinguserDropDown = await dispatch( // UserDataBasedOnBranchId({ // BranchId: e, // Type: 'E', // }) // ).unwrap(); // if (gettinguserDropDown?.data?.statusCode === 1) { // let finaluserDropDown = gettinguserDropDown?.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettinguserDropDown?.data?.data?.length === 1) { // setSelectedUserData( // gettinguserDropDown?.data?.data?.length === 1 // ? gettinguserDropDown?.data?.data[0]?.UserId // : null // ); // form?.setFieldsValue({ // UserId: // gettinguserDropDown?.data?.data?.length === 1 // ? gettinguserDropDown?.data?.data[0]?.UserId // : null, // }); // await UserDropDownChangeMobile( // gettinguserDropDown?.data?.data[0]?.UserId, // finaluserDropDown // ); // } // setuserDropDown(finaluserDropDown); // } // }; // const UserDropDownChangeMobile = async (e, Mobile) => { // // MobileNo // let mob = Mobile.filter((item) => item?.UserId === e); // console.log(mob, 'ddddddddd'); // const data = mob?.length > 0 ? mob[0] : {}; // form?.setFieldsValue({ // UserId: e, // MobileNo: data.MobileNo, // Address1: data.Address1, // Address2: data.Address2, // Latitude: data.Latitude, // Longitude: data.Longitude, // Zip: data.Zip, // MailId: data.MailId, // State: data.State, // UserImage: data.UserImage, // }); // // await getPincodeValues(mob?.[0]?.Zip); // setSelectedUserData(e); // const gettingEmpTypeDropDown = await dispatch(EmpTypeDropDown()).unwrap(); // if (gettingEmpTypeDropDown?.data?.statusCode === 1) { // let finalEmpTypeDropDown = gettingEmpTypeDropDown?.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettingEmpTypeDropDown?.data?.data?.length === 1) { // setseletedEmpTypeDrop( // gettingEmpTypeDropDown?.data?.data?.length === 1 // ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // : null // ); // form.setFieldsValue({ // EmpType: // gettingEmpTypeDropDown?.data?.data?.length === 1 // ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // : null, // }); // await EmpTypeDropDownChange( // gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // ); // } // // // setEmpTypeDropDownData(finalEmpTypeDropDown); // } // }; // const onChange = async (date, dateString) => { // if (!dateString) { // setSelectedDate(); // } else { // // Convert and format the date properly // const Date1 = moment(dateString, 'DD-MM-YYYY').format('YYYY-MM-DDTHH:mm:ss'); // form?.setFieldsValue({ EmpDOJ: Date1 }); // await setSelectedDate(Date1); // } // }; const handleDayChange = (day) => { setSelectedDays((prev) => ({ ...prev, [day]: !prev[day], })); }; const handleSelectAllDays = (checked) => { setSelectAllDays(checked); if (checked) { setSelectedDays({ monday: true, tuesday: true, wednesday: true, thursday: true, friday: true, saturday: true, sunday: true, }); } else { setSelectedDays({ monday: false, tuesday: false, wednesday: false, thursday: false, friday: false, saturday: false, sunday: false, }); } }; const getEmployees = async () => { const gettingTableData = await dispatch( getEmpBasedOnCmpIdBrId({ cmpId: CompId, BranchId: BranchId }) ).unwrap(); if (gettingTableData?.data?.statusCode === 1) { setEmployeesDatas(gettingTableData?.data?.data); } }; const ServiceTypeFn = async () => { let Response = await dispatch(ServiceType()).unwrap(); if (Response?.data?.statusCode == 1) { setServicesDatas(Response?.data?.data); } else { setServicesDatas([]); } }; // const HandleEmpTypeDropDownData = async () => { // const gettingEmpTypeDropDown = await dispatch(EmpTypeDropDown()).unwrap(); // if (gettingEmpTypeDropDown?.data?.statusCode === 1) { // let finalEmpTypeDropDown = gettingEmpTypeDropDown?.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettingEmpTypeDropDown?.data?.data?.length === 1) { // setseletedEmpTypeDrop( // gettingEmpTypeDropDown?.data?.data?.length === 1 // ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // : null // ); // form.current?.setFieldsValue({ // EmpType: // gettingEmpTypeDropDown?.data?.data?.length === 1 // ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // : null, // }); // await EmpTypeDropDownChange( // gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // ); // } // // // setEmpTypeDropDownData(finalEmpTypeDropDown); // } // }; // const getPincodeValues = async (pinCode) => { // let response = ''; // await fetch(`https://api.postalpincode.in/pincode/${pinCode}`) // .then((res) => res.text()) // .then((text) => (response = JSON.parse(text))); // if (response[0]['Status'] === 'Success') { // setZipCodeData(true); // form?.setFieldsValue({ // City: response[0]['PostOffice'][0]['Block'], // Dist: response[0]['PostOffice'][0]['District'], // State: response[0]['PostOffice'][0]['State'], // }); // } else { // setZipCodeData(false); // } // }; // const UserDropDownChange = async (e) => { // let mob = userDropDown.filter((item) => item?.UserId === e); // await getPincodeValues(mob?.[0]?.Zip); // setSelectedUserData(e); // const gettingEmpTypeDropDown = await dispatch(EmpTypeDropDown()).unwrap(); // if (gettingEmpTypeDropDown?.data?.statusCode === 1) { // let finalEmpTypeDropDown = gettingEmpTypeDropDown?.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettingEmpTypeDropDown?.data?.data?.length === 1) { // setseletedEmpTypeDrop( // gettingEmpTypeDropDown?.data?.data?.length === 1 // ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // : null // ); // form?.setFieldsValue({ // EmpType: // gettingEmpTypeDropDown?.data?.data?.length === 1 // ? gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // : null, // }); // await EmpTypeDropDownChange( // gettingEmpTypeDropDown?.data?.data[0]?.ConfigId // ); // } // // // setEmpTypeDropDownData(finalEmpTypeDropDown); // } // }; // const EmpTypeDropDownChange = async (e) => { // form.setFieldsValue({ EmpType: e }); // setseletedEmpTypeDrop(e); // const gettingEmpDesgDropDown = await dispatch( // EmpDesgDropDown({ AppId: AppId }) // ).unwrap(); // if (gettingEmpDesgDropDown.data?.statusCode === 1) { // let finalEmpDesgDropDown = gettingEmpDesgDropDown.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettingEmpDesgDropDown?.data?.data?.length === 1) { // setseletedEmpDesigDrop( // gettingEmpDesgDropDown?.data?.data?.length === 1 // ? gettingEmpDesgDropDown?.data?.data[0]?.ConfigId // : null // ); // form.setFieldsValue({ // EmpDesig: // gettingEmpDesgDropDown?.data?.data?.length === 1 // ? gettingEmpDesgDropDown?.data?.data[0]?.ConfigId // : null, // }); // await EmpDesigDropDownChange( // gettingEmpDesgDropDown?.data?.data[0]?.ConfigId // ); // } // setEmpDesgDropDownData(finalEmpDesgDropDown); // } // }; // const EmpDesigDropDownChange = async (e) => { // form.setFieldsValue({ EmpDesig: e }); // setseletedEmpDesigDrop(e); // const gettingEmpDeptDropDown = await dispatch( // EmpDepartMentDropDown() // ).unwrap(); // if (gettingEmpDeptDropDown.data?.statusCode === 1) { // let finalEmpDeptDropDown = gettingEmpDeptDropDown.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettingEmpDeptDropDown?.data?.data?.length === 1) { // setseletedEmpDeptDrop( // gettingEmpDeptDropDown?.data?.data?.length === 1 // ? gettingEmpDeptDropDown?.data?.data[0]?.ConfigId // : null // ); // formsetFieldsValue({ // EmpDept: // gettingEmpDeptDropDown?.data?.data?.length === 1 // ? gettingEmpDeptDropDown?.data?.data[0]?.ConfigId // : null, // }); // await EmpDeptDropDownChange( // gettingEmpDeptDropDown?.data?.data[0]?.ConfigId // ); // } // setEmpDeptDropDownData(finalEmpDeptDropDown); // } // }; // const EmpDeptDropDownChange = async (e) => { // form.setFieldsValue({ EmpDept: e }); // setseletedEmpDeptDrop(e); // const gettingShiftDropDown = await dispatch( // GettingShiftData(CompId) // ).unwrap(); // if (gettingShiftDropDown.data?.statusCode === 1) { // let finalShiftDropDown = gettingShiftDropDown.data?.data?.filter( // (value) => value.ActiveStatus === 'A' // ); // if (gettingShiftDropDown?.data?.data?.length === 1) { // setseletedShiftDrop( // gettingShiftDropDown?.data?.data?.length === 1 // ? gettingShiftDropDown?.data?.data[0]?.ShiftId // : null // ); // form?.setFieldsValue({ // EmpShiftId: // gettingShiftDropDown?.data?.data?.length === 1 // ? gettingShiftDropDown?.data?.data[0]?.ShiftId // : null, // }); // await ShiftDropDownChange(gettingShiftDropDown?.data?.data[0]?.ShiftId); // } // setShiftDownData(finalShiftDropDown); // } // }; // const ShiftDropDownChange = async (e) => { // form?.setFieldsValue({ EmpShiftId: e }); // setseletedShiftDrop(e); // }; const handleTypeChange = (value) => { setSelectedType(value); setselectedTypeName( ServicesDatas?.find((e) => e?.ConfigId == value)?.ConfigName ); setSelectedCategory(null); setSelectedSubCategory(null); setSelectedCoach(null); form.setFieldsValue({ type: value }); }; const handleTaxDropDownChange = async (TaxId) => { form.setFieldsValue({ TaxId: TaxId }); await setSelectedTaxId(TaxId); }; // Handle category change const handleCategoryChange = (value) => { dispatch(getProdSubCatData({ ConfigId: value })); setSelectedCategory(value); setSelectedSubCategory(null); form.setFieldsValue({ 'Sport-category': value }); }; // Handle sub category change const handleSubCategoryChange = (value) => { form.setFieldsValue({ 'Sport-subCategory': value }); setSelectedSubCategory(value); }; // Handle coach change const handleCoachChange = (value) => { setSelectedCoach(value); setSelectedCoachName( EmployeesDatas?.find((e) => e?.UserId == value)?.EmpFirstName ); form.setFieldsValue({ coach: value }); }; // Duration controls const increaseDuration = () => { setSlotDuration((prev) => Math.min(prev + 1, 24)); }; const decreaseDuration = () => { setSlotDuration((prev) => Math.max(prev - 1, 1)); }; const handleDurationInput = (value) => { if (value >= 1 && value <= 24) { setSlotDuration(value); } }; // Get field name based on category // const getFieldName = () => { // if (!selectedCategory) return 'Facility Name'; // const category = sportCategories.find(cat => cat.ConfigId === selectedCategory); // if (!category) return 'Facility Name'; // switch (category.ConfigName.toLowerCase()) { // case 'tennis': // case 'badminton': // case 'basketball': // return 'Court Name'; // case 'swimming': // return 'Swimming Pool Name'; // case 'cricket': // case 'football': // case 'volleyball': // default: // return 'Ground Name'; // } // }; // Generate slots based on time range and duration const generateSlots = () => { if (!startTime || !endTime) { message.error('Please select start and end time'); return; } const start = moment(startTime, 'HH:mm'); const end = moment(endTime, 'HH:mm'); if (end <= start) { message.error('End time must be after start time'); return; } // Check if at least one day is selected const hasSelectedDays = Object.values(selectedDays).some((day) => day); if (!hasSelectedDays) { message.error('Please select at least one day for slot availability'); return; } // Validate prices if (!defaultPrice || defaultPrice < 1) { message.error('Price Per Slot must be at least ₹1'); return; } if ( individualPricing && (!individualDefaultPrice || individualDefaultPrice < 1) ) { message.error('Individual Price must be at least ₹1'); return; } const durationMinutes = slotDuration * 60; const slots = []; let currentTime = start; let slotNumber = 1; while (currentTime < end) { const slotEnd = moment(currentTime).add(durationMinutes, 'minutes'); if (slotEnd > end) break; // Set both individual and full slot prices const individualPrice = individualPricing ? individualDefaultPrice : defaultPrice; const fullSlotPrice = defaultPrice; slots.push({ id: `slot-${slotNumber}`, SlotName: `Slot ${slotNumber}`, // startTime: currentTime.format('HH:mm'), AvailableFrom: currentTime.format('HH:mm'), AvailableTo: slotEnd.format('HH:mm'), // endTime: slotEnd.format('HH:mm'), individualPrice: individualPrice, MRP: fullSlotPrice, SellPrice: fullSlotPrice, // fullSlotPrice: fullSlotPrice, editable: true, individualPurchase: individualPricing, OnlineApplicable: OnlineBooking, active: true, IsHoliday: null, DayOfWeek: Object.keys(selectedDays)?.filter( (day) => selectedDays[day] ), }); currentTime = slotEnd; slotNumber++; } if (slots.length === 0) { Modal.warning({ title: 'No Slots Generated', content: 'No slots can be generated with the current time range and duration.', }); return; } setGeneratedSlots(slots); }; // Slot management functions const updateSlotName = (index, newName) => { const updatedSlots = [...generatedSlots]; updatedSlots[index].SlotName = newName; setGeneratedSlots(updatedSlots); }; const updateIndividualPrice = (index, price) => { const updatedSlots = [...generatedSlots]; updatedSlots[index].individualPrice = price || 0; setGeneratedSlots(updatedSlots); }; // const updateFullSlotPrice = (index, price) => { // const updatedSlots = [...generatedSlots]; // updatedSlots[index].fullSlotPrice = price || 0; // setGeneratedSlots(updatedSlots); // }; const toggleIndividualPurchase = (index) => { const updatedSlots = [...generatedSlots]; updatedSlots[index].individualPurchase = !updatedSlots[index].individualPurchase; setGeneratedSlots(updatedSlots); }; const toggleOnlineApplicable = (index) => { const updatedSlots = [...generatedSlots]; updatedSlots[index].OnlineApplicable = !updatedSlots[index].OnlineApplicable; setGeneratedSlots(updatedSlots); }; const removeSlot = (index) => { Modal.confirm({ title: 'Confirm Delete', content: 'Are you sure you want to delete this slot?', okText: 'Yes', cancelText: 'No', onOk() { const updatedSlots = generatedSlots?.filter((_, i) => i !== index); setGeneratedSlots(updatedSlots); }, }); }; // const toggleSlotActive = (index) => { // const updatedSlots = [...generatedSlots]; // updatedSlots[index].active = !updatedSlots[index].active; // setGeneratedSlots(updatedSlots); // }; const updateImageUrl = (url, index = 0) => { // keep legacy single imageUrl for backward compatibility setImageUrl(url); setImageUrls((prev) => { const copy = Array.isArray(prev) ? [...prev] : []; copy[index] = { ...(copy[index] || {}), image: url, }; return copy; }); }; // Image handling functions // const updateImageUrls = (url, index = 0) => { // // support updating a specific index in the images array // setImageUrls(prev => { // const copy = Array.isArray(prev) ? [...prev] : []; // copy[index] = { // ...(copy[index] || {}), // image: url, // }; // return copy; // }); // // also update main image for legacy places // setImageUrl(url); // }; // const updateImageName = (name, index = 0) => { // setImageUrls(prev => { // const copy = Array.isArray(prev) ? [...prev] : []; // copy[index] = { // ...(copy[index] || {}), // name: name, // }; // return copy; // }); // }; // const addimages = () => { // setimageOpen(true); // }; // const handleimage = () => { // setimageOpen(false); // setSelectedImage(null); // }; // const submitimage = async () => { // if (selectedImage) { // setImageUrl(selectedImage.image); // setOnlineImage(selectedImage.image); // } // setimageOpen(false); // }; const getSelectedDaysText = () => { const daysMap = { monday: 'Mon', tuesday: 'Tue', wednesday: 'Wed', thursday: 'Thu', friday: 'Fri', saturday: 'Sat', sunday: 'Sun', }; const selected = Object.entries(selectedDays) ?.filter(([_, isSelected]) => isSelected) .map(([day]) => daysMap[day]); return selected.length > 0 ? selected.join(', ') : 'No days selected'; }; const slotColumns = [ { title: 'Sl.No', key: 'sno', align: 'center', width: '60px', render: (text, record, index) => index + 1, }, { title: 'Slot Name', dataIndex: 'SlotName', key: 'SlotName', align: 'center', render: (text, record, index) => ( updateSlotName(index, e.target.value)} className="sports-master__slot-input" placeholder="Enter slot name" /> ), }, { title: 'Time Slot', key: 'time', align: 'center', width: '120px', render: (record) => (
{record.AvailableFrom}
to
{record.AvailableTo}
), }, { title: 'Days', key: 'DayOfWeek', align: 'center', width: '150px', render: (record) => { const daysArray = Array.isArray(record?.DayOfWeek) ? record.DayOfWeek.map((day) => day.trim()) : []; console.log(daysArray, 'daysArray11111111'); return (
{daysArray?.map((day, index) => ( {day?.[0]?.toUpperCase()} ))}
); }, }, { title: 'Individual Price (₹)', dataIndex: 'individualPrice', key: 'individualPrice', align: 'center', width: '140px', render: (text, record, index) => record?.individualPurchase ? ( updateIndividualPrice(index, value)} min={0} max={99999} className="sports-master__input-number" formatter={(value) => `₹ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') } parser={(value) => value.replace(/₹\s?|(,*)/g, '')} size="small" /> ) : ( - ), }, // { // title: 'Full Slot Price (₹)', // dataIndex: 'fullSlotPrice', // key: 'fullSlotPrice', // align: 'center', // width: '140px', // render: (text, record, index) => ( // updateFullSlotPrice(index, value)} // min={0} // className="sports-master__input-number" // formatter={value => `₹ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} // parser={value => value.replace(/₹\s?|(,*)/g, '')} // size="small" // /> // ), // }, { title: 'Individual Purchase', dataIndex: 'individualPurchase', key: 'individualPurchase', align: 'center', width: '120px', render: (text, record, index) => ( toggleIndividualPurchase(index)} /> ), }, { title: 'Online Booking', dataIndex: 'OnlineApplicable', key: 'OnlineApplicable', align: 'center', width: '120px', render: (text, record, index) => ( toggleOnlineApplicable(index)} /> ), }, // { // title: 'Status', // key: 'status', // align: 'center', // width: '100px', // render: (record, _, index) => ( // toggleSlotActive(index)} // size="small" // checkedChildren="A" // unCheckedChildren="I" // /> // ), // }, { title: 'Action', key: 'action', align: 'center', width: '80px', render: (text, record, index) => ( */} {/* {imageUrl && (
{selectedType
)} */} )} {/* Day Selection */}
handleSelectAllDays(e.target.checked)} > Select All Days
handleDayChange('monday')} > Monday
handleDayChange('tuesday')} > Tuesday
handleDayChange('wednesday')} > Wednesday
handleDayChange('thursday')} > Thursday
handleDayChange('friday')} > Friday
handleDayChange('saturday')} > Saturday
handleDayChange('sunday')} > Sunday
{/*
Selected Days: {getSelectedDaysText()}
*/}
{ if (times && timeStrings) { setStartTime(timeStrings[0]); setEndTime(timeStrings[1]); } else { setStartTime(null); setEndTime(null); } }} popupClassName="no-scroll-timepicker" placeholder={['Start time', 'End time']} />
{/*
*/} {/*
*/}
`₹ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') } parser={(value) => value.replace(/₹\s?|(,*)/g, '')} onChange={setDefaultPrice} value={defaultPrice} />
setIndividualPricing(e.target.checked)} > Individual Pricing
setOnlineBooking(e.target.checked)} > Online Booking
{individualPricing && (
`₹ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') } parser={(value) => value.replace(/₹\s?|(,*)/g, '')} onChange={setIndividualDefaultPrice} value={individualDefaultPrice} />
)}
Configuration Summary
{selectedTypeName && ( <> Type:{' '} {selectedTypeName === 'Ground' ? 'Ground' : 'Coach'} | )} Days: {getSelectedDaysText()}
{/*
Pricing Mode: {individualPricing ? 'Individual ' : 'Standard Pricing'}
*/} {individualPricing && (
Default Individual Price: ₹ {individualDefaultPrice || ' 0'}
)}
{/* Generated Slots Section */} {generatedSlots.length > 0 && ( Generated Slots ({generatedSlots.length} slots) {individualPricing && ( Dual Pricing Mode )} 0 ? 'green' : 'red'}> {totals.activeSlots} Active {getSelectedDaysText()} } key="1" >
Total Slots
{totals.totalSlots}
Active Slots
{totals.activeSlots}
Individual Revenue
₹{totals.totalIndividualRevenue}
{/*
Full Slot Revenue
₹{totals.totalFullSlotRevenue}
*/}
Available on: {getSelectedDaysText()}
)} {/* Additional Information */} {/*