import React, { useState, useEffect, useCallback } from 'react';
import { Collapse, Radio } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import Emi from '../../../../Images/PayOptImgs/emi.png';
import CrediCard from '../../../../Images/PayOptImgs/creditcard.png';
import DebitCard from '../../../../Images/PayOptImgs/debitcard.png';
import CashCard from '../../../../Images/PayOptImgs/cashcard.png';
import NetBank from '../../../../Images/PayOptImgs/netbank.png';
import Wallet from '../../../../Images/PayOptImgs/wallet.png';
import Upi from '../../../../Images/PayOptImgs/upi.png';
import { IoPhonePortraitOutline } from 'react-icons/io5';
import { AiOutlineFileDone } from 'react-icons/ai';
import { CgMoreO } from 'react-icons/cg';
import '../../../../Styles/BookingScreen/Components/UtillComponents/PricingPage.scss';
import { CiSearch } from 'react-icons/ci';
import TextAreaInput from '../../../../Components/Forms/TextArea';
import Search from '../../../../Components/Forms/Search';
import { DefaultModal } from '../../../../Components/Modal/DefaultModal';
import { InputField } from '../../../../Components/Forms/InputField';
import {
CheckPaymentStatus,
getccavenuePaymentDetails,
getPricingType,
getPurchasedAppDetails,
getUserDetails,
postInvoice,
} from '../../../../Features/BookingScreen/Pricing/Pricing';
import Buttons from '../../../../Components/Forms/Buttons';
import {
getPreferenceData,
GlobalAppExpDateData,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import { Messages } from '../../../../Components/Notifications/Messages';
import CryptoJS from 'crypto-js';
import { GenerateLogout } from '../../../../Features/BrachLogin/BranchLogin';
import { getActivePaymentUpiDetails, sendSms } from '../../../../Features/Payment/PaymentDetails/PaymentDetails';
import {
clearSession,
encryptedValuesUrlFun,
getSession,
} from '../../../../Services/Others';
import PaymentGatewayEmbedded from './PaymentGatewayEmbedded';
const SECRET_KEY = import.meta.env.ENV_SECRET_KEY;
const commonSubDir = import.meta.env.ENV_COMMON_BASE_URL;
const CustomPaymentUrl = import.meta.env.ENV_CUSTOM_PAYMENT_URL;
const subDirectory = import.meta.env.ENV_BASE_URL;
const PricingPage = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const [PricingId, setPricingId] = useState(
getSession('PricingId') ? getSession('PricingId') : null
);
const [activeBusinessUpiDetails, setActiveBusinessUpiDetails] = useState([]);
const AppExpDate = useSelector(GlobalAppExpDateData);
const UserType = getSession('UserType');
const UserId =
UserType == 'Admin' ? getSession('UserId') : AppExpDate?.UserId;
const CompId = getSession('CompId');
const AppName = getSession('AppName');
const AppId = getSession('AppId');
const BranchId = getSession('BranchId');
const [MobileNo, setMobileNo] = useState(getSession('MobileNo'));
const [invoiceDetails, setinvoiceDetails] = useState([]);
const [UserDetails, setUserDetails] = useState([]);
const [BookingId, setBookingId] = useState(null);
const [messageType, setMessageType] = useState(null);
const [messageData, setMessageData] = useState(null);
const [timeLeft, setTimeLeft] = useState(null);
const [Buttondisabled, setButtondisabled] = useState(false);
const [CompanyName, setCompanyName] = useState(null);
const [zipcode, setzipcode] = useState(null);
const [address, setaddress] = useState(null);
const [City, setCity] = useState(null);
const [Dist, setDist] = useState(null);
const [State, setState] = useState(null);
const [email, setemail] = useState(null);
const [zipcondit, setZipcondit] = useState(true);
const [gstcondit, setgstcondit] = useState(true);
const [emailcondit, setemailcondit] = useState(true);
const [citycondit, setcitycondit] = useState(true);
const [statecondit, setstatecondit] = useState(true);
const [addresscondit, setaddresscondit] = useState(true);
const [gst, setgst] = useState(null);
const [PaymentDetails, setPaymentDetails] = useState();
const [selectedOption, setselectedOption] = useState();
const [value, setValue] = useState();
const [itemsdata, setItemsdata] = useState();
const [dataAccept, setDataAccept] = useState();
const [cardName, setCardName] = useState();
const [moreInfo, setmoreInfo] = useState(false);
const [currentDate, setCurrentDate] = useState('');
const [PurchasedDetails, setPurchasedDetails] = useState([]);
const [Companydetails, setCompanydetails] = useState([]);
const [delay, setDelay] = useState(null);
const [businessUpiModal, setBusinessUpiModal] = useState(false);
const [paymentSucess, setPaymentSuccess] = useState(false);
const [OrderId, setOrderId] = useState(null);
const [PaymentPageLink, setPaymentPageLink] = useState(null);
const Gstpattern =
/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9A-Za-z]{1}$/;
const numberPattern = /^[0-9]+$/;
const [PayableAmount, setPayableAmount] = useState(0);
useEffect(() => {
setPayableAmount(invoiceDetails[0]?.NetPrice);
}, [invoiceDetails]);
useEffect(() => {
if (!paymentSucess) return;
const timeoutId = setTimeout(() => {
setPaymentSuccess(false);
redirectAfterPay();
}, 3000);
return () => clearTimeout(timeoutId);
}, [paymentSucess]);
const redirectAfterPay = () => {
navigate(`${subDirectory}sales`);
}
useEffect(() => {
fetchData();
GetPaymentDetails();
fetchUpiDetails()
}, []);
async function fetchUpiDetails() {
try {
const response = await dispatch(getActivePaymentUpiDetails()).unwrap();
if (response?.data?.statusCode == 1) {
setActiveBusinessUpiDetails(response?.data?.data?.filter((e) => e?.DetailType == "BU"));
}
}
catch (error) {
console.log(error, "errorerrorerror")
}
}
useEffect(() => {
if (UserDetails?.[0]?.MailId) {
setemail(UserDetails?.[0]?.MailId);
}
}, [UserDetails]);
let GetPaymentDetails = async () => {
const response = await dispatch(getccavenuePaymentDetails()).unwrap();
if (response?.data?.statusCode == 1) {
setPaymentDetails(response?.data?.data);
let index = await response?.data?.data?.findIndex(
(item) => item.MethodName == 'NetBanking'
);
setselectedOption(index);
setItemsdata(response?.data?.data?.[index]?.Details);
}
};
let fetchData = async () => {
let response = await dispatch(
getPurchasedAppDetails({ AppId, UserId })
).unwrap();
let response1 = await dispatch(
getPreferenceData({ AppId, BranchId, CompId,UserId })
).unwrap();
setPurchasedDetails(response?.data?.data);
setCompanydetails(response1?.data?.data);
setPricingId(response?.data?.data?.[0]?.PricingId);
};
useEffect(() => {
const timer = setInterval(() => {
setDelay(delay - 1);
}, 1000);
if (BookingId != null) {
checkPayment();
}
if (delay === 0) {
UpdatePaymentStatus();
clearInterval(timer);
}
if (delay === null) {
clearInterval(timer);
}
return () => {
clearInterval(timer);
};
}, [delay]);
const handleCancel = () => {
setmoreInfo(false);
};
const encryptedValuesFun = (value) => {
const encryptedValue = CryptoJS.AES.encrypt(
JSON.stringify(value),
SECRET_KEY
).toString();
if (encryptedValue) {
return encryptedValue
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, ''); // Base64 URL-safe encoding
}
};
const UpdatePaymentStatus = async () => {
let putdata = {};
putdata['UpdatedBy'] = getSession('UserId');
putdata['PaymentStatus'] = 'F';
putdata['UniqueId'] = BookingId;
};
const checkPayment = async () => {
let response = await dispatch(CheckPaymentStatus(BookingId)).unwrap();
if (response?.data?.statusCode === 1) {
setprintdata(response?.data?.data);
setPaymentStatus(true);
setDelay(null);
setMessageType('success');
setMessageData('Payment Success!');
setTimeout(() => {
redirectAfterPay();
}, 15000);
}
};
useEffect(() => {
if (timeLeft === 0) {
setButtondisabled(false);
setTimeLeft(null);
}
// exit early when we reach 0
if (!timeLeft) return;
// save intervalId to clear the interval when the
// component re-renders
const intervalId = setInterval(() => {
setTimeLeft(timeLeft - 1);
}, 1000);
// clear interval on re-render to avoid memory leaks
return () => clearInterval(intervalId);
}, [timeLeft]);
useEffect(() => {
fetchFeature(PricingId);
}, [PricingId]);
useEffect(() => {
getUserDetail();
}, []);
const fetchFeature = async (PricingId) => {
const response = await dispatch(getPricingType(PricingId)).unwrap();
if (response?.data?.statusCode === 1) {
setinvoiceDetails(response?.data?.data);
}
};
const getUserDetail = async () => {
const response = await dispatch(getUserDetails(UserId)).unwrap();
if (response?.data?.statusCode === 1) {
setUserDetails(response?.data?.data ? response?.data?.data : []);
setMobileNo(
response?.data?.data?.[0]?.MobileNo > 0
? response?.data?.data?.[0]?.MobileNo
: getSession('MobileNo')
);
}
};
function addDays(dateString, days) {
const currentDate = new Date(dateString);
currentDate.setDate(currentDate.getDate() + days);
// Extract individual date components
const year = currentDate.getFullYear();
const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
const day = currentDate.getDate().toString().padStart(2, '0');
const hours = currentDate.getHours().toString().padStart(2, '0');
const minutes = currentDate.getMinutes().toString().padStart(2, '0');
const seconds = currentDate.getSeconds().toString().padStart(2, '0');
const milliseconds = currentDate
.getMilliseconds()
.toString()
.padStart(3, '0');
// Construct the formatted date string
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
return formattedDate;
}
const onSubmit = async () => {
let bankDetails = {
PayOpt: PaymentDetails?.[selectedOption]?.PayOpt,
CardType: PaymentDetails?.[selectedOption]?.CardType,
cardName:
PaymentDetails?.[selectedOption]?.CardType != 'UPI' ? cardName : 'UPI',
};
if (!email) {
setMessageType('error');
setMessageData('Please Enter Email');
} else {
if (
bankDetails?.PayOpt != undefined &&
bankDetails?.CardType != undefined &&
bankDetails?.cardName != undefined
) {
let postData = {};
postData['UserId'] = UserId;
postData['AppId'] = getSession('AppId');
postData['PricingId'] = PurchasedDetails?.[0]?.PricingId;
postData['PurDate'] = currentDate;
postData['NoofDays'] = PurchasedDetails?.[0]?.NoOfDays;
postData['PaymentMode'] = 27;
postData['PaymentStatus'] = 'P';
postData['LicenseStatus'] = PurchasedDetails?.[0]?.LicenseStatus;
postData['Price'] = PurchasedDetails?.[0]?.Price
? PurchasedDetails?.[0]?.Price
: 0;
postData['TaxId'] = PurchasedDetails?.[0]?.TaxId
? PurchasedDetails?.[0]?.TaxId
: 0;
postData['NetPrice'] = PurchasedDetails?.[0]?.ExistingPlanNetPrice
? PurchasedDetails?.[0]?.ExistingPlanNetPrice
: 0;
postData['ValidityStart'] = currentDate;
postData['ValidityEnd'] = addDays(
currentDate,
PurchasedDetails?.[0]?.NoOfDays
);
postData['CreatedBy'] = getSession('UserId');
postData['TaxAmount'] = PurchasedDetails?.[0]?.TaxAmount
? PurchasedDetails?.[0]?.TaxAmount
: 0;
postData['MobileNo'] = getSession('MobileNo');
postData['MailId'] = email;
postData['Gst'] = Gstpattern?.test(gst) ? gst : null;
postData['BillingName'] = Companydetails?.[0]?.CompName;
postData['Zip'] = numberPattern.test(zipcode) ? zipcode : null;
postData['City'] = City;
postData['State'] = State;
postData['Address'] = address;
postData['District'] = Dist;
let response = await dispatch(postInvoice(postData)).unwrap();
if (response?.data?.statusCode == 1) {
if (response?.data?.SMSbody) {
const postData = {
body: response?.data?.SMSbody,
};
await dispatch(sendSms(postData));
}
setBookingId(response?.data?.BookingId);
const form = document.createElement('form');
form.method = 'POST';
form.action = `${CustomPaymentUrl}/ccavRequestHandler`;
form.style.display = 'none'; // Hide the form
const data1 = {
merchant_id: '15191',
order_id: response?.data?.OrderId,
currency: 'INR',
amount: PayableAmount,
redirect_url:
'https://pozo.app/CustomPaymentGateway/CustomPaymentGateway/ccavResponseHandler',
cancel_url:
'https://pozo.app/CustomPaymentGateway/CustomPaymentGateway/ccavResponseHandler',
payment_option: PaymentDetails?.[selectedOption]?.PayOpt,
card_type: PaymentDetails?.[selectedOption]?.CardType,
card_name:
PaymentDetails?.[selectedOption]?.CardType != 'UPI'
? cardName
: 'UPI',
data_accept: dataAccept,
language: 'EN',
billing_name:
Companydetails?.[0]?.CompName != null
? Companydetails?.[0]?.CompName
: 'User',
billing_address: address != null ? address : 'xyz',
billing_city: City != null ? City : 'xyz',
billing_state: State != null ? State : 'xyz',
billing_zip: zipcode != null ? zipcode : '000000',
billing_country: 'India',
billing_tel: MobileNo,
billing_email: email,
delivery_name: 'R',
delivery_address: 'N',
delivery_city: Dist != null ? Dist : 'xyz',
delivery_zip: 'O',
delivery_country: 'India',
delivery_tel: Gstpattern?.test(gst) ? gst : null,
merchant_param1: getSession('SessionId'),
merchant_param2: response?.data?.BookingId,
merchant_param3: getSession('UserId'),
merchant_param4: invoiceDetails?.[0]?.PricingName,
merchant_param5: 'paymentHandler.html',
promo_code: '',
customer_identifier: '',
};
Object.keys(data1).forEach((key) => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = encryptedValuesFun(data1[key]);
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
}
} else {
setMessageType('error');
setMessageData('Please Select the Payment');
}
}
};
const onSubmitBusinessUpi = async () => {
let bankDetails = {
PayOpt: PaymentDetails?.[selectedOption]?.PayOpt,
CardType: PaymentDetails?.[selectedOption]?.CardType,
cardName:
PaymentDetails?.[selectedOption]?.CardType != 'UPI' ? cardName : 'UPI',
};
if (!email) {
setMessageType('error');
setMessageData('Please Enter Email');
}
else {
let postData = {};
postData['UserId'] = UserId;
postData['AppId'] = getSession('AppId');
postData['PricingId'] = PurchasedDetails?.[0]?.PricingId;
postData['PurDate'] = currentDate;
postData['NoofDays'] = PurchasedDetails?.[0]?.NoOfDays;
postData['PaymentMode'] = 27;
postData['PaymentStatus'] = 'P';
postData['LicenseStatus'] = PurchasedDetails?.[0]?.LicenseStatus;
postData['Price'] = PurchasedDetails?.[0]?.Price
? PurchasedDetails?.[0]?.Price
: 0;
postData['TaxId'] = PurchasedDetails?.[0]?.TaxId
? PurchasedDetails?.[0]?.TaxId
: 0;
postData['NetPrice'] = PurchasedDetails?.[0]?.ExistingPlanNetPrice
? PurchasedDetails?.[0]?.ExistingPlanNetPrice
: 0;
postData['ValidityStart'] = currentDate;
postData['ValidityEnd'] = addDays(
currentDate,
PurchasedDetails?.[0]?.NoOfDays
);
postData['CreatedBy'] = getSession('UserId');
postData['TaxAmount'] = PurchasedDetails?.[0]?.TaxAmount
? PurchasedDetails?.[0]?.TaxAmount
: 0;
postData['MobileNo'] = getSession('MobileNo');
postData['MailId'] = email;
postData['Gst'] = Gstpattern?.test(gst) ? gst : null;
postData['BillingName'] = Companydetails?.[0]?.CompName;
postData['Zip'] = numberPattern.test(zipcode) ? zipcode : null;
postData['City'] = City;
postData['State'] = State;
postData['Address'] = address;
postData['District'] = Dist;
postData["PaymentOptionType"] = "BU";
postData["MerchantId"] = activeBusinessUpiDetails?.[0]?.MerchantId;
postData["PaymentType"] = activeBusinessUpiDetails?.[0]?.MerchantNameId;
let response = await dispatch(postInvoice(postData)).unwrap();
if (response?.data?.statusCode == 1) {
if (response?.data?.SMSbody) {
const postData = {
body: response?.data?.SMSbody,
};
await dispatch(sendSms(postData));
}
setBusinessUpiModal(true)
setOrderId(response?.data?.OrderId)
setPaymentPageLink(response?.data?.PaymentPageLink)
}
}
};
const onComplete = useCallback(() => {
setMessageData(null);
setMessageType(null);
}, []);
const setCompanyNames = async (e) => {
setCompanyName(e?.target?.value);
};
const setCitys = async (e) => {
setCity(e?.target?.value);
setcitycondit(true);
};
const setStates = async (e) => {
setState(e?.target?.value);
setstatecondit(true);
};
const setgsts = async (e) => {
setgst(e);
};
function checkCondition1(input) {
if (input?.length === 15 && Gstpattern?.test(input)) {
setgstcondit(true);
setgsts(input);
} else if (input?.length === 0) {
setgstcondit(true);
} else {
setgstcondit(false);
}
setgsts(input);
}
function isValidEmail(email) {
const emailRegex =
/^[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,255}\.[a-zA-Z]{2,}$/;
return emailRegex.test(email);
}
const getViewMore = () => {
setmoreInfo(!moreInfo);
};
function handleInputChange(event) {
// setemail(event?.target?.value)
if (isValidEmail(event?.target?.value)) {
setemailcondit(true);
setEmailValue(event?.target?.value);
} else {
setemail(undefined);
setemailcondit(false);
}
}
const setaddresss = async (e) => {
setaddress(e?.target?.value);
setaddresscondit(true);
};
const setzipcodes = async (e) => {
setzipcode(e);
};
const setEmailValue = async (e) => {
setemail(e);
};
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') {
setCity(response[0]['PostOffice'][0]['Block']);
setDist(response[0]['PostOffice'][0]['District']);
setState(response[0]['PostOffice'][0]['State']);
setcitycondit(true);
setstatecondit(true);
}
};
async function checkCondition(input) {
if (input?.length === 6 && numberPattern.test(input)) {
setZipcondit(true);
setzipcodes(input);
await getPincodeValues(input);
} else if (input?.length === 0) {
setZipcondit(true);
} else {
setZipcondit(false);
setCity(null);
setState(null);
}
setzipcodes(input);
}
const onChange = (e) => {
setValue(e?.target?.value);
setDataAccept(
itemsdata?.[e.target.value]?.dataAcceptedAt == 'CCAvenue' ? 'Y' : 'N'
);
setCardName(itemsdata?.[e.target.value]?.cardName);
};
const onSearchChange = (e) => {
let Details = PaymentDetails?.[selectedOption]?.Details;
let searchTerm = e.target.value?.toLowerCase();
let updated = Details.filter((item) =>
item.cardName?.toLowerCase().startsWith(searchTerm)
);
setItemsdata(updated);
};
const items = [
{
key: '1',
label: `${
PaymentDetails?.[selectedOption]?.CardType == 'CRDC' ||
PaymentDetails?.[selectedOption]?.CardType == 'DBCRD'
? 'Choose Your Card'
: PaymentDetails?.[selectedOption]?.CardType == 'WLT'
? 'Choose Your Wallet'
: 'Choose Your Bank'
} `,
children: (
{PurchasedDetails?.[0]?.ExistingPlanNetPrice > 0 ? `₹ ${PurchasedDetails?.[0]?.ExistingPlanNetPrice}` : '₹ 0.00'}
to Pay
{UserDetails?.[0]?.MailId}
) : (Enter Valid Email
)}{' '} {MobileNo ? MobileNo : ''}
Enter Address
)}Enter Valid Gst
)}Enter Valid Zipcode
)}Enter City
)}Enter State
)}{PurchasedDetails?.[0]?.ExistingPlanNetPrice > 0 ? `₹ ${PurchasedDetails?.[0]?.ExistingPlanNetPrice}` : '₹ 0.00'}
to Pay
{UserDetails?.[0]?.MailId}
) : (Enter Valid Email
)}{' '} {MobileNo ? MobileNo : ''}
Enter Address
)}Enter Valid Gst
)}Enter Valid Zipcode
)}Enter City
)}Enter State
)}