import React, { useEffect } from "react";
import { useTenantDetails } from "../../hooks/useTenant";
import { useDispatch } from "react-redux";
import { setCurrentTenant } from "../../slices/globalVariablesSlice";
import { useNavigate } from "react-router-dom";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { SUBSCRIPTION_PLAN_FREQUENCIES } from "../../utils/constants";
const SubScriptionHistory = ({ tenantId }) => {
const { data, isLoading, isError, error } = useTenantDetails(tenantId);
const dispatch = useDispatch();
const navigate = useNavigate();
useEffect(() => {
if (data) {
dispatch(setCurrentTenant({ operationMode: 1, data }));
} else {
dispatch(setCurrentTenant({ operationMode: 0, data: null }));
}
}, [data, dispatch]);
const handleUpgradePlan = () => {
navigate("/tenants/new-tenant");
};
if (isLoading) return
Loading...
;
if (isError) return {error}
;
const plan = data?.currentPlan;
const features = data?.currentPlanFeatures;
const subscriptionHistory = data?.subscriptionHistery;
if (!plan) {
return (
Add your new subscription
);
}
// Format dates
const end = plan?.endDate ? new Date(plan.endDate) : null;
const today = new Date();
const daysLeft = end
? Math.max(0, Math.ceil((end - today) / (1000 * 60 * 60 * 24)))
: 0;
// Render logic for subscription history table
const renderSubscriptionHistory = () => {
if (!subscriptionHistory || subscriptionHistory.length === 0) {
return (
No subscription history found
);
}
const sortedHistory = subscriptionHistory
.slice()
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
return (
<>
{/* Table for larger screens */}
| Date |
Type |
Amount |
Plan Name |
Action |
{sortedHistory.map((item) => (
| {formatUTCToLocalTime(item?.createdAt)} |
{SUBSCRIPTION_PLAN_FREQUENCIES[item.frequency] || "N/A"} |
{item.currency?.symbol || "₹"} {item.price}
|
{item.planName} |
|
))}
{/* Card-based view for smaller screens */}
>
);
};
return (
{/* Left Card: Active Subscription */}
{plan.planName || "N/A"}
{plan.description && (
{plan.description}
)}
{plan.currency?.symbol || "₹"} {plan.price}
{SUBSCRIPTION_PLAN_FREQUENCIES[plan.frequency] || ""}
Activated Since:{" "}
{plan.startDate ? formatUTCToLocalTime(plan.startDate) : "N/A"} (
{daysLeft} days left)
Ends on:{" "}
{plan.endDate ? formatUTCToLocalTime(plan.endDate) : "N/A"}
{/* Features list */}
Features
{features?.modules &&
Object.entries(features.modules).map(([key, mod]) => {
if (!mod?.name) return null;
return (
{mod.name}
);
})}
{/* Right Card: Subscription History */}
{renderSubscriptionHistory()}
);
};
export default SubScriptionHistory;