All files / src/components/projects ProjectDetailContainer.tsx

96.22% Statements 102/106
84% Branches 42/50
100% Functions 11/11
100% Lines 99/99

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                                                        141x 141x 141x     141x     141x 141x 141x 141x 141x 141x     141x 54x 17x   37x       141x     141x 59x 58x     57x 57x   57x 57x 53x 51x     51x 35x     35x 35x   35x 33x 33x       2x 2x         35x       35x       3x 3x 3x   56x 56x         141x 54x       141x 54x       141x 5x 5x 5x 5x 3x   3x   2x 2x 2x   5x       141x 2x 2x 2x 2x 1x 1x     2x   1x 1x   2x       141x 2x 2x 2x 2x 1x 1x     2x   1x 1x   2x       141x 8x 8x     141x 5x 5x 5x 5x   3x   2x 2x   5x           141x     141x     141x 1x               140x 53x               87x 5x             82x                                               1x          
// Smart container component that handles state and API logic for project details
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { notify } from "../../lib/notify";
import { usePro } from "../../lib/pro-context";
import { queryKeys } from "../../lib/query-keys";
import {
	getErrorMessage,
	type Project,
	type Pro,
} from "../../lib/api";
import {
	createProApiAdapter,
	createAdminApiAdapter,
	enhanceAdminAdapterWithRooms,
} from "./api-adapters";
import { ProjectDetailContent } from "./ProjectDetailContent";
import { ConfirmDialog } from "../ui/confirm-dialog";
import type { ProjectDetailContainerProps, ProjectApiAdapter } from "./types";
 
export function ProjectDetailContainer({
	projectId,
	context,
	onDelete,
	proId: overrideProId,
	initialTab,
}: ProjectDetailContainerProps) {
	// Get pro ID from context for pro view
	const { proId: contextProId, isLoading: proLoading } = usePro();
	const proId = overrideProId || contextProId;
	const queryClient = useQueryClient();
 
	// Project state
	const [project, setProject] = useState<
		(Project & { photos: unknown[] }) | null
	>(null);
	const [pro, setPro] = useState<Pro | null>(null);
	const [isLoading, setIsLoading] = useState(true);
	const [isSaving, setIsSaving] = useState(false);
	const [loadError, setLoadError] = useState<string | null>(null);
	const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
	const hasLoadedOnce = useRef(false);
 
	// Create API adapter based on context
	const baseAdapter = useMemo((): ProjectApiAdapter => {
		if (context === "pro" && proId) {
			return createProApiAdapter(proId);
		}
		return createAdminApiAdapter();
	}, [context, proId]);
 
	// Enhanced adapter with room support (set after project loads with proId)
	const [apiAdapter, setApiAdapter] = useState<ProjectApiAdapter>(baseAdapter);
 
	// Load project data
	const loadProject = useCallback(async () => {
		if (!projectId) return;
		if (context === "pro" && !proId) return;
 
		// Only show loading spinner on initial load, not on refresh
		if (!hasLoadedOnce.current) setIsLoading(true);
		setLoadError(null);
 
		try {
			const response = await baseAdapter.getProject(projectId);
			if (response.data) {
				setProject(response.data);
 
				// For admin context, load pro info and enhance adapter with room support
				if (context === "admin" && response.data.proId) {
					const projectProId = String(response.data.proId);
 
					// Load pro info
					Eif (baseAdapter.getPro) {
						try {
							const proResponse =
								await baseAdapter.getPro(projectProId);
							Eif (proResponse.data) {
								setPro(proResponse.data);
							}
						} catch (err) {
							// Pro info is optional, don't fail the whole page
							console.error("Failed to load pro info");
							notify.error(getErrorMessage(err));
						}
					}
 
					// Enhance adapter with room operations
					const enhancedAdapter = enhanceAdminAdapterWithRooms(
						baseAdapter,
						projectProId,
					);
					setApiAdapter(enhancedAdapter);
				}
			}
		} catch (err) {
			console.error("Failed to load project:", err);
			setLoadError(getErrorMessage(err));
			notify.error(getErrorMessage(err));
		} finally {
			setIsLoading(false);
			hasLoadedOnce.current = true;
		}
	}, [projectId, context, proId, baseAdapter]);
 
	// Load project on mount and when dependencies change
	useEffect(() => {
		loadProject();
	}, [loadProject]);
 
	// Update adapter when base adapter changes
	useEffect(() => {
		setApiAdapter(baseAdapter);
	}, [baseAdapter]);
 
	// Handlers
	const handleSave = async (updates: Partial<Project>) => {
		Iif (!project) return;
		setIsSaving(true);
		try {
			await apiAdapter.updateProject(projectId, updates);
			notify.success("Project updated successfully");
			
			await loadProject();
		} catch (err) {
			console.error("Failed to save project:", err);
			notify.error(getErrorMessage(err));
			throw err;
		} finally {
			setIsSaving(false);
		}
	};
 
	const handlePublish = async () => {
		Iif (!project) return;
		setIsSaving(true);
		try {
			await apiAdapter.publishProject(projectId);
			notify.success("Project published successfully");
			queryClient.invalidateQueries({
				queryKey: queryKeys.projects.list(proId ?? ""),
			});
			await loadProject();
		} catch (err) {
			console.error("Failed to publish project:", err);
			notify.error(getErrorMessage(err));
		} finally {
			setIsSaving(false);
		}
	};
 
	const handleArchive = async () => {
		Iif (!project) return;
		setIsSaving(true);
		try {
			await apiAdapter.archiveProject(projectId);
			notify.success("Project archived successfully");
			queryClient.invalidateQueries({
				queryKey: queryKeys.projects.list(proId ?? ""),
			});
			await loadProject();
		} catch (err) {
			console.error("Failed to archive project:", err);
			notify.error(getErrorMessage(err));
		} finally {
			setIsSaving(false);
		}
	};
 
	const handleDelete = async () => {
		Iif (!project) return;
		setDeleteConfirmOpen(true);
	};
 
	const handleDeleteConfirm = async () => {
		setDeleteConfirmOpen(false);
		setIsSaving(true);
		try {
			await apiAdapter.deleteProject(projectId);
			// Call the onDelete callback to navigate away
			onDelete?.();
		} catch (err) {
			console.error("Failed to delete project:", err);
			notify.error(getErrorMessage(err));
		} finally {
			setIsSaving(false);
		}
	};
 
 
	// Determine back link based on context
	const backLink = context === "pro" ? "/projects" : "/admin/projects";
 
	// Determine if rooms are supported
	const supportsRooms = Boolean(apiAdapter.getRooms);
 
	// Show loading while pro context is loading for pro view
	if (context === "pro" && proLoading) {
		return (
			<div className="flex items-center justify-center h-64">
				<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
			</div>
		);
	}
 
	// Show loading while project is loading
	if (isLoading) {
		return (
			<div className="flex items-center justify-center h-64">
				<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
			</div>
		);
	}
 
	// Show error or not found
	if (!project) {
		return (
			<div className="text-center py-12">
				<p className="text-error mb-4">{loadError || "Project not found"}</p>
			</div>
		);
	}
 
	return (
		<>
			<ProjectDetailContent
				project={project}
				pro={pro}
				context={context}
				isLoading={false}
				isSaving={isSaving}
				onSave={handleSave}
				onPublish={handlePublish}
				onArchive={handleArchive}
				onDelete={context === "admin" ? handleDelete : undefined}
				supportsRooms={supportsRooms}
				apiAdapter={apiAdapter}
				backLink={backLink}
				initialTab={initialTab}
			/>
			<ConfirmDialog
				open={deleteConfirmOpen}
				title="Delete project"
				description="Are you sure you want to delete this project? This action cannot be undone."
				confirmLabel="Delete"
				variant="destructive"
				onConfirm={handleDeleteConfirm}
				onCancel={() => setDeleteConfirmOpen(false)}
			/>
		</>
	);
}