161 lines
5.3 KiB
JavaScript
161 lines
5.3 KiB
JavaScript
import { useEffect, useRef, useState } from 'react';
|
||
import { useDispatch } from 'react-redux';
|
||
import {
|
||
ChangeAppExpDateData,
|
||
changeHeightforExpDate,
|
||
getAppSubscriptionDate,
|
||
} from './Features/BookingScreen/BookingData/BookingData.js';
|
||
import { sendSms } from './Features/Payment/PaymentDetails/PaymentDetails.js';
|
||
import {
|
||
getPurchasedAppDetails,
|
||
postInvoice,
|
||
} from './Features/BookingScreen/Pricing/Pricing.js';
|
||
import { getSession } from './Services/Others.js';
|
||
import { useNavigate } from 'react-router-dom';
|
||
|
||
const useSubscriptionManager = (sessionData, logout) => {
|
||
const dispatch = useDispatch();
|
||
const navigate = useNavigate();
|
||
const prevRemainingDays = useRef(null);
|
||
const [remainingDays, setRemainingDays] = useState(null);
|
||
const [extendModel, setExtendModel] = useState(false);
|
||
const handleCancel = () => {
|
||
logout();
|
||
setExtendModel(false);
|
||
};
|
||
const handlePay = () => {
|
||
setExtendModel(false);
|
||
let AppName = getSession('AppName');
|
||
navigate(`${subDirectory}PricingPage`, { state: { AppName: AppName } });
|
||
};
|
||
function formatDate(date) {
|
||
const year = date.getFullYear();
|
||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||
const day = String(date.getDate()).padStart(2, '0');
|
||
const hours = String(date.getHours()).padStart(2, '0');
|
||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||
const seconds = String(date.getSeconds()).padStart(2, '0');
|
||
const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
|
||
|
||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
|
||
}
|
||
|
||
function addDays(dateString, days) {
|
||
// Make it ISO-safe for iOS / WebView
|
||
const isoDate = dateString.replace(' ', 'T');
|
||
const currentDate = new Date(isoDate);
|
||
|
||
currentDate.setDate(currentDate.getDate() + Number(days));
|
||
|
||
return formatDate(currentDate);
|
||
}
|
||
|
||
// ---------------- MAIN FUNCTION ----------------
|
||
const freeExtend = async () => {
|
||
try {
|
||
const UserId = getSession('UserId');
|
||
const AppId = getSession('AppId');
|
||
// Current date
|
||
const now = new Date();
|
||
const currentDate = formatDate(now);
|
||
|
||
// 1️⃣ Get purchased app details
|
||
const response1 = await dispatch(
|
||
getPurchasedAppDetails({ AppId, UserId })
|
||
).unwrap();
|
||
|
||
const PurchasedDetails = response1?.data?.data;
|
||
|
||
if (!PurchasedDetails || !PurchasedDetails.length) {
|
||
console.error('No purchased details found');
|
||
return;
|
||
}
|
||
|
||
// 2️⃣ Prepare post data
|
||
const postData = {
|
||
UserId: UserId,
|
||
AppId: AppId,
|
||
PricingId: PurchasedDetails[0]?.PricingId,
|
||
PurDate: currentDate,
|
||
NoofDays: 30,
|
||
PaymentMode: 27,
|
||
PaymentStatus: 'S',
|
||
LicenseStatus: PurchasedDetails[0]?.LicenseStatus,
|
||
Price: PurchasedDetails[0]?.Price ?? 0,
|
||
TaxId: PurchasedDetails[0]?.TaxId ?? 0,
|
||
NetPrice: PurchasedDetails[0]?.ExistingPlanNetPrice ?? 0,
|
||
ValidityStart: currentDate,
|
||
ValidityEnd: addDays(currentDate, PurchasedDetails[0]?.NoOfDays),
|
||
CreatedBy: UserId,
|
||
TaxAmount: PurchasedDetails[0]?.TaxAmount ?? 0,
|
||
MobileNo: getSession('MobileNo'),
|
||
MailId: 'ts@gmmail.com',
|
||
Type: 'FreeExtend',
|
||
};
|
||
|
||
// 3️⃣ Post invoice
|
||
const response = await dispatch(postInvoice(postData)).unwrap();
|
||
|
||
// 4️⃣ Send SMS if required
|
||
if (response?.data?.statusCode === 1 && response?.data?.SMSbody) {
|
||
await dispatch(sendSms({ body: response.data.SMSbody }));
|
||
setExtendModel(false);
|
||
}
|
||
} catch (error) {
|
||
console.error('freeExtend error:', error);
|
||
}
|
||
};
|
||
useEffect(() => {
|
||
if (!sessionData) return;
|
||
|
||
const fetchExpDate = async () => {
|
||
const { CompId, AppId, BranchId, UserType } = sessionData;
|
||
|
||
const res = await dispatch(
|
||
getAppSubscriptionDate({ CompId, BranchId, AppId })
|
||
).unwrap();
|
||
|
||
const expData = res?.data?.data?.[0];
|
||
if (!expData) return logout();
|
||
|
||
if (prevRemainingDays.current !== expData.RemainingDays) {
|
||
prevRemainingDays.current = expData.RemainingDays;
|
||
|
||
setRemainingDays(expData.RemainingDays);
|
||
dispatch(ChangeAppExpDateData(expData));
|
||
dispatch(changeHeightforExpDate(expData.RemainingDays));
|
||
|
||
if (
|
||
expData.RemainingDays < 1 &&
|
||
expData.RemainingHours < 1 &&
|
||
expData.RemainingMinutes < 1 &&
|
||
expData.RemainingSeconds < 1 &&
|
||
UserType !== 'Super Admin'
|
||
) {
|
||
if (
|
||
(UserType !== 'Super Admin' || UserType !== 'Super Admin User') &&
|
||
expData?.PlanType?.toLowerCase() == 'extend expired'
|
||
) {
|
||
console.log('Subscription expired, logging out...');
|
||
alert('Subscription expired');
|
||
logout();
|
||
} else if (
|
||
(UserType !== 'Super Admin' || UserType !== 'Super Admin User') &&
|
||
expData?.PlanType?.toLowerCase() == 'plan expired'
|
||
) {
|
||
setExtendModel(true);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
fetchExpDate();
|
||
const interval = setInterval(fetchExpDate, 60 * 60 * 1000);
|
||
return () => clearInterval(interval);
|
||
}, [sessionData]);
|
||
|
||
return { remainingDays, handleCancel, handlePay, freeExtend, extendModel,setExtendModel };
|
||
};
|
||
|
||
export default useSubscriptionManager;
|