All files / src/components/projects ProjectEditForm.tsx

98.33% Statements 59/60
97.08% Branches 100/103
100% Functions 9/9
100% Lines 59/59

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                                                                                                                            146x     146x 146x 146x     146x     146x     146x     146x 146x 146x     146x 146x 146x     146x     146x     146x     146x     146x                     146x     146x 29x 29x   29x         28x   29x     29x   1x       29x       146x 116x 115x         146x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 56x       146x 6x 6x 6x   6x                                                         6x     146x       29x                                                                   1x                                 1x                                                                                                                                                      
// Project edit form for admin editing capability
import { useState, useEffect, type FormEvent } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { Button } from "../ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import {
	taxonomyApi,
	type Project,
	type ServiceCategory,
	type MaterialTag,
} from "../../lib/api";
import {
	isValidPropertySize,
	normalizePropertySize,
} from "@interioring/utils/validation/property-size";
import { useLocationCascade } from "../../hooks/useLocationCascade";
import {
	BasicInfoSection,
	CategorySection,
	LocationPropertySection,
	BudgetTimelineSection,
	TagsSection,
	AdditionalInfoSection,
} from "./form-sections";
 
export interface ProjectEditFormData {
	title: string;
	description?: string | null;
	status?: "draft" | "published" | "archived" | null;
	scope?: ("design" | "material" | "execution")[] | null;
	workedAreaIds?: string[] | null;
	localityId?: string | null;
	propertyType?:
		| "apartment"
		| "villa"
		| "independent_house"
		| "commercial"
		| null;
	propertySize?: string | null;
	projectAreaSqft?: number | null;
	budgetRange?: "under_1l" | "1_3l" | "3_5l" | "5_10l" | "above_10l" | null;
	duration?: string | null;
	materialTagIds?: string[] | null;
	clientTestimonial?: string | null;
	yearCompleted?: number | null;
	useRooms?: boolean;
	isFeatured?: boolean;
}
 
interface ProjectEditFormProps {
	project: Project;
	isSaving: boolean;
	onSubmit: (data: ProjectEditFormData) => Promise<void>;
	context?: "pro" | "admin";
}
 
export function ProjectEditForm({
	project,
	isSaving,
	onSubmit,
	context = "admin",
}: ProjectEditFormProps) {
	const [isExpanded, setIsExpanded] = useState(false);
 
	// Form state - Basic fields
	const [title, setTitle] = useState(project.title || "");
	const [description, setDescription] = useState(project.description || "");
	const [status, setStatus] = useState<"draft" | "published" | "archived">(
		project.status || "draft",
	);
	const [isFeatured, setIsFeatured] = useState(project.isFeatured || false);
 
	// Form state - New portfolio fields
	const [scope, setScope] = useState<("design" | "material" | "execution")[]>(
		(project.scope || []) as ("design" | "material" | "execution")[],
	);
	const [workedAreaIds, setWorkedAreaIds] = useState<string[]>(
		project.workedAreaIds || [],
	);
	const [propertyType, setPropertyType] = useState(project.propertyType || "");
	const [propertySize, setPropertySize] = useState(project.propertySize || "");
	const [projectAreaSqft, setProjectAreaSqft] = useState(
		project.projectAreaSqft?.toString() || "",
	);
	const [budgetRange, setBudgetRange] = useState(project.budgetRange || "");
	const [duration, setDuration] = useState(project.duration || "");
	const [materialTagIds, setMaterialTagIds] = useState<string[]>(
		project.materialTagIds || [],
	);
	const [clientTestimonial, setClientTestimonial] = useState(
		project.clientTestimonial || "",
	);
	const [yearCompleted, setYearCompleted] = useState(
		project.yearCompleted?.toString() || "",
	);
	const [useRooms, setUseRooms] = useState(project.useRooms || false);
 
	// Taxonomy data
	const [serviceCategories, setServiceCategories] = useState<ServiceCategory[]>(
		[],
	);
	const [materialTags, setMaterialTags] = useState<MaterialTag[]>([]);
 
	// Location cascade
	const {
		cities,
		localities,
		selectedCityId,
		localityId,
		setLocalityId,
		handleCityChange,
		initializeFromLocality,
	} = useLocationCascade();
 
	// Load taxonomy data on component mount
	useEffect(() => {
		const loadTaxonomyData = async () => {
			try {
				const [serviceCategoriesRes, materialTagsRes] =
					await Promise.all([
						taxonomyApi.getServiceCategories(),
						taxonomyApi.getMaterialTags(),
					]);
 
				setServiceCategories(serviceCategoriesRes.data || []);
				// Flatten material tags from grouped object
				const allMaterialTags = Object.values(
					materialTagsRes.data || {},
				).flat();
				setMaterialTags(allMaterialTags);
			} catch (err) {
				console.error("Failed to load taxonomy data:", err);
			}
		};
 
		loadTaxonomyData();
	}, []);
 
	// Initialize location cascade when project locality changes
	useEffect(() => {
		if (project.localityId && cities.length > 0) {
			initializeFromLocality(project.localityId);
		}
	}, [project.localityId, cities.length, initializeFromLocality]);
 
	// Update form state when project changes
	useEffect(() => {
		setTitle(project.title || "");
		setDescription(project.description || "");
		setStatus(project.status || "draft");
		setIsFeatured(project.isFeatured || false);
		setScope((project.scope || []) as ("design" | "material" | "execution")[]);
		setWorkedAreaIds(project.workedAreaIds || []);
		setPropertyType(project.propertyType || "");
		setPropertySize(project.propertySize || "");
		setProjectAreaSqft(project.projectAreaSqft?.toString() || "");
		setBudgetRange(project.budgetRange || "");
		setDuration(project.duration || "");
		setMaterialTagIds(project.materialTagIds || []);
		setClientTestimonial(project.clientTestimonial || "");
		setYearCompleted(project.yearCompleted?.toString() || "");
		setUseRooms(project.useRooms || false);
		if (project.localityId) {
			setLocalityId(project.localityId);
		}
	}, [project, setLocalityId]);
 
	const handleSubmit = async (e: FormEvent) => {
		e.preventDefault();
		Iif (!isValidPropertySize(propertySize)) return;
		const normalizedPropertySize = normalizePropertySize(propertySize);
 
		const data: ProjectEditFormData = {
			title,
			description: description || null,
			status: status as "draft" | "published" | "archived",
			isFeatured,
			scope: scope.length > 0 ? scope : null,
			workedAreaIds: workedAreaIds.length > 0 ? workedAreaIds : null,
			localityId: localityId || null,
			propertyType: propertyType
				? (propertyType as
						| "apartment"
						| "villa"
						| "independent_house"
						| "commercial")
				: null,
			propertySize: normalizedPropertySize || null,
			projectAreaSqft: projectAreaSqft
				? Number.parseInt(projectAreaSqft, 10)
				: null,
			budgetRange: budgetRange
				? (budgetRange as "under_1l" | "1_3l" | "3_5l" | "5_10l" | "above_10l")
				: null,
			duration: duration || null,
			materialTagIds: materialTagIds.length > 0 ? materialTagIds : null,
			clientTestimonial: clientTestimonial || null,
			yearCompleted: yearCompleted ? Number.parseInt(yearCompleted, 10) : null,
			useRooms,
		};
 
		await onSubmit(data);
	};
 
	return (
		<Card>
			<CardHeader
				className="cursor-pointer"
				onClick={() => setIsExpanded(!isExpanded)}
			>
				<div className="flex items-center justify-between">
					<CardTitle>Edit Project Details</CardTitle>
					<Button variant="ghost" size="sm">
						{isExpanded ? (
							<ChevronUp className="h-5 w-5" />
						) : (
							<ChevronDown className="h-5 w-5" />
						)}
					</Button>
				</div>
			</CardHeader>
			{isExpanded && (
				<CardContent>
					<form onSubmit={handleSubmit} className="space-y-6">
						{/* Status Section - Admin only */}
						{context === "admin" && (
							<div className="space-y-4">
								<h3 className="text-md font-semibold text-foreground-default border-b pb-2">
									Project Status
								</h3>
								<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
									<div>
										<label
											htmlFor="project-status"
											className="block text-sm font-medium text-foreground-default mb-1"
										>
											Status
										</label>
										<select
											id="project-status"
											value={status}
											onChange={(e) =>
												setStatus(
													e.target.value as "draft" | "published" | "archived",
												)
											}
											className="flex h-10 w-full rounded-md border border-default bg-background-elevated px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500"
										>
											<option value="draft">Draft</option>
											<option value="published">Published</option>
											<option value="archived">Archived</option>
										</select>
									</div>
 
									<div className="flex items-center">
										<label className="flex items-center gap-2">
											<input
												type="checkbox"
												checked={isFeatured}
												onChange={(e) => setIsFeatured(e.target.checked)}
												className="rounded border-default text-info focus:ring-primary-500"
											/>
											<span className="text-sm font-medium text-foreground-default">
												Featured Project
											</span>
										</label>
									</div>
								</div>
							</div>
						)}
 
						<BasicInfoSection
							title={title}
							description={description}
							onTitleChange={setTitle}
							onDescriptionChange={setDescription}
						/>
 
						<CategorySection
							scope={scope}
							workedAreaIds={workedAreaIds}
							serviceCategories={serviceCategories}
							onScopeChange={setScope}
							onWorkedAreaIdsChange={setWorkedAreaIds}
						/>
 
						<LocationPropertySection
							cities={cities}
							localities={localities}
							selectedCityId={selectedCityId}
							localityId={localityId}
							propertyType={propertyType}
							propertySize={propertySize}
							projectAreaSqft={projectAreaSqft}
							onCityChange={handleCityChange}
							onLocalityChange={setLocalityId}
							onPropertyTypeChange={setPropertyType}
							onPropertySizeChange={setPropertySize}
							onProjectAreaSqftChange={setProjectAreaSqft}
						/>
 
						<BudgetTimelineSection
							budgetRange={budgetRange}
							duration={duration}
							yearCompleted={yearCompleted}
							onBudgetRangeChange={setBudgetRange}
							onDurationChange={setDuration}
							onYearCompletedChange={setYearCompleted}
						/>
 
						<TagsSection
							materialTags={materialTags}
							materialTagIds={materialTagIds}
							onMaterialTagIdsChange={setMaterialTagIds}
						/>
 
						<AdditionalInfoSection
							useRooms={useRooms}
							clientTestimonial={clientTestimonial}
							onUseRoomsChange={setUseRooms}
							onClientTestimonialChange={setClientTestimonial}
						/>
 
						<div className="flex justify-end pt-4 border-t">
							<Button type="submit" isLoading={isSaving}>
								Save Changes
							</Button>
						</div>
					</form>
				</CardContent>
			)}
		</Card>
	);
}