All files / src/components/projects ProjectFormModal.tsx

98.55% Statements 68/69
80.88% Branches 55/68
100% Functions 5/5
100% Lines 67/67

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                                                                                                                                    111x 111x   111x     111x 111x 111x 111x 111x 111x 111x 111x 111x 111x     111x     111x                     111x     111x 38x 38x   38x         37x   38x     38x   1x 1x       38x       111x 38x 10x 10x 10x     10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x     10x 9x       28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x       111x 13x 13x 13x   13x                                                     13x     111x   111x   109x                                                                                                                                                                                                            
import { useState, useEffect, type FormEvent } from "react";
import { notify } from "../../lib/notify";
import { X } from "lucide-react";
import { Button } from "../ui/button";
import { useDialogAccessibility } from "../../hooks";
import {
	taxonomyApi,
	getErrorMessage,
	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 ProjectFormData {
	title: string;
	description?: string | 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;
}
 
interface ProjectFormModalProps {
	isOpen: boolean;
	isEditing: boolean;
	initialData: Project | null;
	isSaving: boolean;
	onClose: () => void;
	onSubmit: (data: ProjectFormData) => void;
}
 
export function ProjectFormModal({
	isOpen,
	isEditing,
	initialData,
	isSaving,
	onClose,
	onSubmit,
}: ProjectFormModalProps) {
	// Form state - Basic fields
	const [title, setTitle] = useState("");
	const [description, setDescription] = useState("");
	// Form state - New portfolio fields
	const [scope, setScope] = useState<("design" | "material" | "execution")[]>(
		[],
	);
	const [workedAreaIds, setWorkedAreaIds] = useState<string[]>([]);
	const [propertyType, setPropertyType] = useState("");
	const [propertySize, setPropertySize] = useState("");
	const [projectAreaSqft, setProjectAreaSqft] = useState("");
	const [budgetRange, setBudgetRange] = useState("");
	const [duration, setDuration] = useState("");
	const [materialTagIds, setMaterialTagIds] = useState<string[]>([]);
	const [clientTestimonial, setClientTestimonial] = useState("");
	const [yearCompleted, setYearCompleted] = useState("");
	const [useRooms, setUseRooms] = useState(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);
				notify.error(getErrorMessage(err));
			}
		};
 
		loadTaxonomyData();
	}, []);
 
	// Initialize form when editing
	useEffect(() => {
		if (isEditing && initialData) {
			setTitle(initialData.title);
			setDescription(initialData.description || "");
			setScope(
				(initialData.scope || []) as ("design" | "material" | "execution")[],
			);
			setWorkedAreaIds(initialData.workedAreaIds || []);
			setLocalityId(initialData.localityId || "");
			setPropertyType(initialData.propertyType || "");
			setPropertySize(initialData.propertySize || "");
			setProjectAreaSqft(initialData.projectAreaSqft?.toString() || "");
			setBudgetRange(initialData.budgetRange || "");
			setDuration(initialData.duration || "");
			setMaterialTagIds(initialData.materialTagIds || []);
			setClientTestimonial(initialData.clientTestimonial || "");
			setYearCompleted(initialData.yearCompleted?.toString() || "");
			setUseRooms(initialData.useRooms || false);
 
			// Initialize location cascade
			if (initialData.localityId) {
				initializeFromLocality(initialData.localityId);
			}
		} else {
			// Reset form for create mode
			setTitle("");
			setDescription("");
			setScope([]);
			setWorkedAreaIds([]);
			setLocalityId("");
			setPropertyType("");
			setPropertySize("");
			setProjectAreaSqft("");
			setBudgetRange("");
			setDuration("");
			setMaterialTagIds([]);
			setClientTestimonial("");
			setYearCompleted("");
			setUseRooms(false);
		}
	}, [isEditing, initialData, initializeFromLocality, setLocalityId]);
 
	const handleSubmit = (e: FormEvent) => {
		e.preventDefault();
		Iif (!isValidPropertySize(propertySize)) return;
		const normalizedPropertySize = normalizePropertySize(propertySize);
 
		const data: ProjectFormData = {
			title,
			description: description || null,
			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,
		};
 
		onSubmit(data);
	};
 
	const { dialogRef, handleFocusTrap } = useDialogAccessibility(onClose);
 
	if (!isOpen) return null;
 
	return (
		<div className="fixed inset-0 z-50 flex items-center justify-center p-4" tabIndex={-1}>
			<button
				type="button"
				aria-label="Close modal"
				className="fixed inset-0 bg-black/50 cursor-default"
				onClick={onClose}
				tabIndex={-1}
			/>
			<div
				ref={dialogRef}
				role="dialog"
				aria-modal="true"
				aria-labelledby="project-form-dialog-title"
				onKeyDown={handleFocusTrap}
				className="relative bg-background-elevated rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto"
			>
				<div className="sticky top-0 bg-background-elevated border-b px-6 py-4 flex items-center justify-between z-10">
					<h2 id="project-form-dialog-title" className="text-lg font-semibold">
						{isEditing ? "Edit Project" : "New Project"}
					</h2>
					<button
						type="button"
						onClick={onClose}
						aria-label="Close"
						className="text-foreground-subtle hover:text-foreground-muted"
					>
						<X className="h-5 w-5" />
					</button>
				</div>
 
				<form onSubmit={handleSubmit} className="p-6 space-y-6">
					<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 gap-3 pt-4 border-t sticky bottom-0 bg-background-elevated">
						<Button
							type="button"
							variant="outline"
							onClick={onClose}
							className="flex-1"
						>
							Cancel
						</Button>
						<Button type="submit" isLoading={isSaving} className="flex-1">
							{isEditing ? "Save Changes" : "Create Project"}
						</Button>
					</div>
				</form>
			</div>
		</div>
	);
}