All files / src/pages accept-invitation.tsx

93.51% Statements 101/108
84.14% Branches 69/82
87.5% Functions 7/8
100% Lines 98/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399                                                                    69x 69x 69x 69x 69x   69x 69x 69x 69x 69x 69x 69x         69x 28x 1x 1x 1x     27x   27x   27x   9x 9x 9x 9x 9x     3x 3x 2x     7x 7x 7x       1x     6x 4x 1x 3x 1x 2x 1x   1x     2x     9x 9x     9x 9x       18x 18x 18x 11x 11x 11x     6x 6x 6x 4x 1x     3x 1x     2x 1x   1x     2x     17x       18x 18x     69x 7x 7x 7x   7x 7x 3x 3x 3x   3x   3x     4x 4x 3x 1x     2x 1x   1x     1x     7x         69x 28x                                 41x 1x                                         40x 9x   9x                                                                                                               31x 3x                       1x                   28x 6x                                     22x                                                                                                                                                        
import { useState, useEffect } from "react";
import { useSearch, Link, useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { CheckCircle, XCircle, Loader2, Mail, AlertCircle, UserPlus, LogIn } from "lucide-react";
import { useAuth } from "../lib/auth-context";
import { invitationApi, ApiError, GENERIC_ERROR_MESSAGE } from "../lib/api";
import { queryKeys } from "../lib/query-keys";
import { Button } from "../components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
} from "../components/ui/card";
 
type InvitationDetails = {
	id: number;
	email: string;
	role: string;
	pro: { id: string; businessName: string } | null;
	invitedBy: { id: string; name: string } | null;
	expiresAt: string;
};
 
type InvitationPreview = {
	email: string;
	role: string;
	proName: string;
	expiresAt: string;
	accountExists: boolean;
};
 
export function AcceptInvitationPage() {
	const { isAuthenticated, isLoading: authLoading, user, refreshSession } = useAuth();
	const queryClient = useQueryClient();
	const navigate = useNavigate();
	const search = useSearch({ strict: false }) as { token?: string };
	const token = search.token;
 
	const [invitation, setInvitation] = useState<InvitationDetails | null>(null);
	const [preview, setPreview] = useState<InvitationPreview | null>(null);
	const [isLoading, setIsLoading] = useState(true);
	const [isAccepting, setIsAccepting] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const [success, setSuccess] = useState(false);
	const [acceptedPro, setAcceptedPro] = useState<{
		id: string;
		businessName: string;
	} | null>(null);
 
	useEffect(() => {
		if (!token) {
			setError("Invalid invitation link. No token provided.");
			setIsLoading(false);
			return;
		}
 
		Iif (authLoading) return;
 
		let cancelled = false;
 
		if (!isAuthenticated) {
			// Fetch preview (no auth required) to show smart register/login
			const fetchPreview = async () => {
				const controller = new AbortController();
				const timeout = setTimeout(() => controller.abort(), 10_000);
				try {
					const response = await invitationApi.previewInvitation(token, {
						signal: controller.signal,
					});
					Iif (cancelled) return;
					if (response.data) {
						setPreview(response.data);
					}
				} catch (err) {
					Iif (cancelled) return;
					console.error("Failed to fetch invitation preview:", err);
					if (
						err instanceof DOMException &&
						err.name === "AbortError"
					) {
						setError(
							"Request timed out. Please try again.",
						);
					} else if (err instanceof ApiError) {
						if (err.code === "NOT_FOUND") {
							setError("This invitation link is invalid or has already been used.");
						} else if (err.code === "EXPIRED") {
							setError("This invitation has expired. Please ask for a new invitation.");
						} else if (err.code === "ALREADY_ACCEPTED") {
							setError("This invitation has already been accepted.");
						} else {
							setError(err.message);
						}
					} else {
						setError(GENERIC_ERROR_MESSAGE);
					}
				} finally {
					clearTimeout(timeout);
					Eif (!cancelled) setIsLoading(false);
				}
			};
			fetchPreview();
			return;
		}
 
		// Fetch full invitation details (requires auth)
		const fetchInvitation = async () => {
			try {
				const response = await invitationApi.getInvitation(token);
				Iif (cancelled) return;
				Eif (response.data) {
					setInvitation(response.data);
				}
			} catch (err) {
				Iif (cancelled) return;
				console.error("Failed to fetch invitation:", err);
				if (err instanceof ApiError) {
					if (err.code === "NOT_FOUND") {
						setError(
							"This invitation link is invalid or has already been used.",
						);
					} else if (err.code === "EXPIRED") {
						setError(
							"This invitation has expired. Please ask for a new invitation.",
						);
					} else if (err.code === "ALREADY_ACCEPTED") {
						setError("This invitation has already been accepted.");
					} else {
						setError(err.message);
					}
				} else {
					setError(GENERIC_ERROR_MESSAGE);
				}
			} finally {
				Eif (!cancelled) setIsLoading(false);
			}
		};
 
		fetchInvitation();
		return () => { cancelled = true; };
	}, [token, isAuthenticated, authLoading]);
 
	const handleAccept = async () => {
		Iif (!token) return;
		setIsAccepting(true);
		setError(null);
 
		try {
			const response = await invitationApi.acceptInvitation(token);
			Eif (response.data) {
				setSuccess(true);
				setAcceptedPro(response.data.pro);
				// Refresh auth state so hasProAccess is updated with the new role
				await refreshSession();
				// Invalidate ProContext's cached pro.me query so sidebar gets the new proRole
				await queryClient.invalidateQueries({ queryKey: queryKeys.pro.me() });
			}
		} catch (err) {
			console.error("Failed to accept invitation:", err);
			if (err instanceof ApiError) {
				if (err.code === "EMAIL_MISMATCH") {
					setError(
						`This invitation was sent to a different email address. You're logged in as ${user?.email}. Please log out and sign in with the correct account.`,
					);
				} else if (err.code === "ALREADY_MEMBER") {
					setError("You're already a member of this team.");
				} else {
					setError(err.message);
				}
			} else {
				setError(GENERIC_ERROR_MESSAGE);
			}
		} finally {
			setIsAccepting(false);
		}
	};
 
	// Loading state
	if (isLoading || authLoading) {
		return (
			<div className="min-h-screen flex items-center justify-center bg-background-subtle px-4">
				<Card className="w-full max-w-md">
					<CardContent className="py-12">
						<div className="flex flex-col items-center">
							<Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
							<p className="mt-4 text-foreground-muted">
								Loading invitation...
							</p>
						</div>
					</CardContent>
				</Card>
			</div>
		);
	}
 
	// No token
	if (!token) {
		return (
			<div className="min-h-screen flex items-center justify-center bg-background-subtle px-4">
				<Card className="w-full max-w-md">
					<CardHeader className="text-center">
						<XCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
						<CardTitle>Invalid Invitation</CardTitle>
						<CardDescription>
							This invitation link is invalid. No token was provided.
						</CardDescription>
					</CardHeader>
					<CardContent>
						<Link to="/login">
							<Button className="w-full">Go to Login</Button>
						</Link>
					</CardContent>
				</Card>
			</div>
		);
	}
 
	// Not authenticated - smart register/login based on preview
	if (!isAuthenticated) {
		const redirectUrl = `/accept-invitation?token=${token}`;
 
		return (
			<div className="min-h-screen flex items-center justify-center bg-background-subtle px-4">
				<Card className="w-full max-w-md">
					<CardHeader className="text-center">
						<Mail className="h-12 w-12 text-indigo-600 mx-auto mb-4" />
						<CardTitle>Team Invitation</CardTitle>
						<CardDescription>
							{preview ? (
								<>
									You've been invited to join <strong>{preview.proName}</strong> as{" "}
									<strong className="capitalize">{preview.role}</strong>.
								</>
							) : (
								"You've been invited to join a team on Interioring."
							)}
						</CardDescription>
					</CardHeader>
					<CardContent className="space-y-3">
						{preview?.accountExists ? (
							<>
								<p className="text-sm text-foreground-muted text-center mb-2">
									Sign in to your existing account to accept this invitation.
								</p>
								<Link
									to="/login"
									search={{ redirect: redirectUrl }}
								>
									<Button className="w-full">
										<LogIn className="h-4 w-4 mr-2" />
										Sign In
									</Button>
								</Link>
							</>
						) : (
							<>
								<p className="text-sm text-foreground-muted text-center mb-2">
									Create an account to join the team.
								</p>
								<Link
									to="/register"
									search={{ email: preview?.email, redirect: redirectUrl }}
								>
									<Button className="w-full">
										<UserPlus className="h-4 w-4 mr-2" />
										Create Account
									</Button>
								</Link>
							</>
						)}
					</CardContent>
				</Card>
			</div>
		);
	}
 
	// Success state
	if (success) {
		return (
			<div className="min-h-screen flex items-center justify-center bg-background-subtle px-4">
				<Card className="w-full max-w-md">
					<CardHeader className="text-center">
						<CheckCircle className="h-12 w-12 text-green-500 mx-auto mb-4" />
						<CardTitle>Welcome to the Team!</CardTitle>
						<CardDescription>
							You've successfully joined{" "}
							<strong>{acceptedPro?.businessName || "the team"}</strong>.
						</CardDescription>
					</CardHeader>
					<CardContent>
						<Button className="w-full" onClick={() => navigate({ to: "/" })}>
							Go to Dashboard
						</Button>
					</CardContent>
				</Card>
			</div>
		);
	}
 
	// Error state
	if (error && !invitation) {
		return (
			<div className="min-h-screen flex items-center justify-center bg-background-subtle px-4">
				<Card className="w-full max-w-md">
					<CardHeader className="text-center">
						<XCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
						<CardTitle>Invitation Error</CardTitle>
						<CardDescription>{error}</CardDescription>
					</CardHeader>
					<CardContent>
						<Link to="/">
							<Button className="w-full">Go to Dashboard</Button>
						</Link>
					</CardContent>
				</Card>
			</div>
		);
	}
 
	// Show invitation details and accept button
	return (
		<div className="min-h-screen flex items-center justify-center bg-background-subtle px-4">
			<Card className="w-full max-w-md">
				<CardHeader className="text-center">
					<Mail className="h-12 w-12 text-indigo-600 mx-auto mb-4" />
					<CardTitle>Team Invitation</CardTitle>
					<CardDescription>
						You've been invited to join a team on Interioring.
					</CardDescription>
				</CardHeader>
				<CardContent className="space-y-6">
					{invitation && (
						<div className="bg-background-subtle rounded-lg p-4 space-y-3">
							<div>
								<p className="text-sm text-foreground-muted">Team</p>
								<p className="font-medium">
									{invitation.pro?.businessName || "Unknown"}
								</p>
							</div>
							<div>
								<p className="text-sm text-foreground-muted">Invited by</p>
								<p className="font-medium">
									{invitation.invitedBy?.name || "Unknown"}
								</p>
							</div>
							<div>
								<p className="text-sm text-foreground-muted">Your Role</p>
								<p className="font-medium capitalize">{invitation.role}</p>
							</div>
							<div>
								<p className="text-sm text-foreground-muted">Invitation for</p>
								<p className="font-medium">{invitation.email}</p>
							</div>
						</div>
					)}
 
					{error && (
						<div className="flex items-start gap-2 p-3 bg-notification-error-bg text-notification-error-text rounded-lg text-sm">
							<AlertCircle className="h-5 w-5 flex-shrink-0 mt-0.5" />
							<p>{error}</p>
						</div>
					)}
 
					{invitation?.email.toLowerCase() !== user?.email?.toLowerCase() && (
						<div className="flex items-start gap-2 p-3 bg-yellow-50 text-yellow-700 rounded-lg text-sm">
							<AlertCircle className="h-5 w-5 flex-shrink-0 mt-0.5" />
							<p>
								This invitation was sent to <strong>{invitation?.email}</strong>
								, but you're logged in as <strong>{user?.email}</strong>. You
								may need to log out and sign in with the correct account.
							</p>
						</div>
					)}
 
					<div className="space-y-3">
						<Button
							className="w-full"
							onClick={handleAccept}
							isLoading={isAccepting}
							disabled={
								invitation?.email.toLowerCase() !== user?.email?.toLowerCase()
							}
						>
							Accept Invitation
						</Button>
						<Link to="/">
							<Button variant="outline" className="w-full">
								Decline
							</Button>
						</Link>
					</div>
				</CardContent>
			</Card>
		</div>
	);
}