This commit is contained in:
IGNY8 VPS (Salman)
2025-12-08 08:52:44 +00:00
parent 3f2879d269
commit 8231c499c2
8 changed files with 215 additions and 90 deletions

View File

@@ -3,7 +3,6 @@ import { Navigate, useLocation } from "react-router-dom";
import { useAuthStore } from "../../store/authStore";
import { useErrorHandler } from "../../hooks/useErrorHandler";
import { trackLoading } from "../common/LoadingStateMonitor";
import { fetchAPI } from "../../services/api";
interface ProtectedRouteProps {
children: ReactNode;
@@ -19,12 +18,6 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
const { addError } = useErrorHandler('ProtectedRoute');
const [showError, setShowError] = useState(false);
const [errorMessage, setErrorMessage] = useState<string>('');
const [paymentCheck, setPaymentCheck] = useState<{
loading: boolean;
hasDefault: boolean;
hasAny: boolean;
}>({ loading: true, hasDefault: false, hasAny: false });
const PLAN_ALLOWED_PATHS = [
'/account/plans',
'/account/billing',
@@ -33,6 +26,7 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
'/account/team',
'/account/usage',
'/billing',
'/payment',
];
const isPlanAllowedPath = PLAN_ALLOWED_PATHS.some((prefix) =>
@@ -44,40 +38,6 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
trackLoading('auth-loading', loading);
}, [loading]);
// Fetch payment methods to confirm default method availability
useEffect(() => {
if (!isAuthenticated) {
setPaymentCheck({ loading: false, hasDefault: false, hasAny: false });
return;
}
let cancelled = false;
const loadPaymentMethods = async () => {
setPaymentCheck((prev) => ({ ...prev, loading: true }));
try {
const data = await fetchAPI('/v1/billing/payment-methods/');
const methods = data?.results || [];
const hasAny = methods.length > 0;
// Treat id 14 as the intended default, or any method marked default
const hasDefault = methods.some((m: any) => m.is_default) || methods.some((m: any) => String(m.id) === '14');
if (!cancelled) {
setPaymentCheck({ loading: false, hasDefault, hasAny });
}
} catch (err) {
if (!cancelled) {
setPaymentCheck({ loading: false, hasDefault: false, hasAny: false });
console.warn('ProtectedRoute: failed to fetch payment methods', err);
}
}
};
loadPaymentMethods();
return () => {
cancelled = true;
};
}, [isAuthenticated]);
// Validate account + plan whenever auth/user changes
useEffect(() => {
if (!isAuthenticated) {
@@ -161,21 +121,16 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
// If authenticated but missing an active plan, keep user inside billing/onboarding
const accountStatus = user?.account?.status;
const accountInactive = accountStatus && ['suspended', 'cancelled'].includes(accountStatus);
const missingPlan = user?.account && !user.account.plan;
const missingPayment = !paymentCheck.loading && (!paymentCheck.hasDefault || !paymentCheck.hasAny);
const pendingPayment = accountStatus === 'pending_payment';
const isPrivileged = user?.role === 'developer' || user?.is_superuser;
if ((missingPlan || accountInactive || missingPayment) && !isPlanAllowedPath) {
if (paymentCheck.loading) {
return (
<div className="flex items-center justify-center min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="text-center max-w-md px-4">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-brand-500 mb-4"></div>
<p className="text-lg font-medium text-gray-800 dark:text-white mb-2">Checking billing status...</p>
</div>
</div>
);
if (!isPrivileged) {
if (pendingPayment && !isPlanAllowedPath) {
return <Navigate to="/account/billing" state={{ from: location }} replace />;
}
if (accountInactive && !isPlanAllowedPath) {
return <Navigate to="/account/plans" state={{ from: location }} replace />;
}
return <Navigate to="/account/plans" state={{ from: location }} replace />;
}
return <>{children}</>;

View File

@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from "../../icons";
import Label from "../form/Label";
@@ -6,7 +6,7 @@ import Input from "../form/input/InputField";
import Checkbox from "../form/input/Checkbox";
import { useAuthStore } from "../../store/authStore";
export default function SignUpForm() {
export default function SignUpForm({ planDetails: planDetailsProp, planLoading: planLoadingProp }: { planDetails?: any; planLoading?: boolean }) {
const [showPassword, setShowPassword] = useState(false);
const [isChecked, setIsChecked] = useState(false);
const [formData, setFormData] = useState({
@@ -18,17 +18,52 @@ export default function SignUpForm() {
accountName: "",
});
const [error, setError] = useState("");
const [planDetails, setPlanDetails] = useState<any | null>(planDetailsProp || null);
const [planLoading, setPlanLoading] = useState(planLoadingProp || false);
const [planError, setPlanError] = useState("");
const navigate = useNavigate();
const { register, loading } = useAuthStore();
const planSlug = useMemo(() => new URLSearchParams(window.location.search).get("plan") || "", []);
const paidPlans = ["starter", "growth", "scale"];
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const planSlug = params.get("plan");
const paidPlans = ["starter", "growth", "scale"];
if (planSlug && paidPlans.includes(planSlug)) {
navigate(`/payment?plan=${planSlug}`, { replace: true });
setError("");
}
}, [navigate]);
}, [planSlug]);
useEffect(() => {
if (planDetailsProp) {
setPlanDetails(planDetailsProp);
setPlanLoading(!!planLoadingProp);
setPlanError("");
return;
}
const fetchPlan = async () => {
if (!planSlug) return;
setPlanLoading(true);
setPlanError("");
try {
const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || "https://api.igny8.com/api";
const res = await fetch(`${API_BASE_URL}/v1/auth/plans/?slug=${planSlug}`);
const data = await res.json();
const plan = data?.results?.[0];
if (!plan) {
setPlanError("Plan not found or inactive.");
} else {
const features = Array.isArray(plan.features)
? plan.features.map((f: string) => f.charAt(0).toUpperCase() + f.slice(1))
: [];
setPlanDetails({ ...plan, features });
}
} catch (e: any) {
setPlanError("Unable to load plan details right now.");
} finally {
setPlanLoading(false);
}
};
fetchPlan();
}, [planSlug, planDetailsProp, planLoadingProp]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
@@ -53,18 +88,22 @@ export default function SignUpForm() {
// Generate username from email if not provided
const username = formData.username || formData.email.split("@")[0];
// No plan_id needed - backend auto-assigns free trial
await register({
const user = await register({
email: formData.email,
password: formData.password,
username: username,
first_name: formData.firstName,
last_name: formData.lastName,
account_name: formData.accountName,
plan_slug: planSlug || undefined,
});
// Redirect to dashboard/sites instead of payment page
navigate("/sites", { replace: true });
const status = user?.account?.status;
if (status === "pending_payment") {
navigate("/account/billing", { replace: true });
} else {
navigate("/sites", { replace: true });
}
} catch (err: any) {
setError(err.message || "Registration failed. Please try again.");
}
@@ -88,7 +127,9 @@ export default function SignUpForm() {
Start Your Free Trial
</h1>
<p className="text-sm text-gray-500 dark:text-gray-400">
No credit card required. 100 AI credits to get started.
{planSlug && paidPlans.includes(planSlug)
? `You're signing up for the ${planSlug} plan. You'll be taken to billing to complete payment.`
: "No credit card required. 100 AI credits to get started."}
</p>
</div>
<div>