All files / components/records CreateRecordDialog.tsx

66.19% Statements 47/71
56.52% Branches 26/46
75% Functions 12/16
67.16% Lines 45/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                                                                                          208x 208x 208x 208x 208x     208x 208x 208x 208x     208x 125x   13x                                       13x 23x                             112x 112x 112x       208x 38x                           208x 6x 6x     6x 6x   6x 1x 1x       5x 5x 8x 8x       5x               5x 5x 5x 4x   1x   5x       208x 512x     208x                         1x                                                                                                   512x 512x       38x                                            
/**
 * Create record dialog component
 * Dynamic form for creating records in a collection
 */
 
import { useState, useEffect } from 'react';
import { AppDialog } from '@/components/common/AppDialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from '@/components/ui/select';
import { RefreshCw } from 'lucide-react';
import DynamicFieldInput from './DynamicFieldInput';
import type { FieldDefinition } from '@/services/collections.service';
import type { RecordData } from '@/types/records.types';
import { initializeFormState, validateFormState } from '@/lib/form-helpers';
import { handleApiError } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import { getAccounts, type AccountListItem } from '@/services/accounts.service';
 
interface CreateRecordDialogProps {
	open: boolean;
	onOpenChange: (open: boolean) => void;
	onSubmit: (data: RecordData) => Promise<void>;
	schema: FieldDefinition[];
	collectionName: string;
	// For reference fields
	referenceRecords?: Record<string, RecordData[]>;
	onFetchReferenceRecords?: (collection: string) => Promise<void>;
}
 
export default function CreateRecordDialog({
	open,
	onOpenChange,
	onSubmit,
	schema,
	collectionName,
	referenceRecords = {},
	onFetchReferenceRecords,
}: CreateRecordDialogProps) {
	const { account } = useAuthStore();
	const [formState, setFormState] = useState(() => initializeFormState(schema));
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const [fetchingReferences, setFetchingReferences] = useState<Set<string>>(new Set());
 
	// Account selection state (for superadmins only)
	const [accounts, setAccounts] = useState<AccountListItem[]>([]);
	const [selectedAccountId, setSelectedAccountId] = useState<string>('');
	const [loadingAccounts, setLoadingAccounts] = useState(false);
	const isSuperadmin = account?.id === '00000000-0000-0000-0000-000000000000';
 
	// Fetch accounts and reference records when dialog opens
	useEffect(() => {
		if (open) {
			// Fetch accounts for superadmins
			Iif (isSuperadmin) {
				const fetchAccountsList = async () => {
					setLoadingAccounts(true);
					try {
						const response = await getAccounts({ page_size: 100 });
						setAccounts(response.items);
						// Pre-select first account if available
						if (response.items.length > 0 && !selectedAccountId) {
							setSelectedAccountId(response.items[0].id);
						}
					} catch (err) {
						console.error('Failed to fetch accounts:', err);
					} finally {
						setLoadingAccounts(false);
					}
				};
				fetchAccountsList();
			}
 
			// Fetch records for all reference fields
			schema.forEach(async (field) => {
				Iif (field.type === 'reference' && field.collection && onFetchReferenceRecords) {
					setFetchingReferences((prev) => new Set(prev).add(field.name));
					try {
						await onFetchReferenceRecords(field.collection);
					} finally {
						setFetchingReferences((prev) => {
							const next = new Set(prev);
							next.delete(field.name);
							return next;
						});
					}
				}
			});
		} else {
			// Reset form when dialog closes
			setFormState(initializeFormState(schema));
			setError(null);
			setSelectedAccountId('');
		}
	}, [open, schema, onFetchReferenceRecords, isSuperadmin, selectedAccountId]);
 
	const handleFieldChange = (fieldName: string, value: unknown) => {
		setFormState((prev) => ({
			...prev,
			fields: {
				...prev.fields,
				[fieldName]: {
					...prev.fields[fieldName],
					value,
					error: null, // Clear error on change
					touched: true,
				},
			},
		}));
	};
 
	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		setError(null);
 
		// Validate all fields
		const validatedState = validateFormState(formState, schema);
		setFormState(validatedState);
 
		if (!validatedState.isValid) {
			setError('Please fix the validation errors before submitting');
			return;
		}
 
		// Build record data from form state (skip computed fields — they are read-only)
		const recordData: Record<string, unknown> = {};
		for (const field of schema) {
			Iif (field.type === 'computed') continue;
			recordData[field.name] = formState.fields[field.name]?.value;
		}
 
		// Add account_id for superadmins
		Iif (isSuperadmin) {
			if (!selectedAccountId) {
				setError('Please select an account');
				return;
			}
			recordData.account_id = selectedAccountId;
		}
 
		setIsSubmitting(true);
		try {
			await onSubmit(recordData);
			onOpenChange(false);
		} catch (err) {
			setError(handleApiError(err));
		} finally {
			setIsSubmitting(false);
		}
	};
 
	const isReferenceLoading = schema.some(
		(field) => field.type === 'reference' && fetchingReferences.has(field.name),
	);
 
	return (
		<AppDialog
			open={open}
			onOpenChange={onOpenChange}
			title="Create Record"
			description={<>Add a new record to the <strong>{collectionName}</strong> collection.</>}
			className="max-w-2xl"
			footer={
				!isReferenceLoading ? (
					<>
						<Button
							type="button"
							variant="outline"
							onClick={() => onOpenChange(false)}
							disabled={isSubmitting}
						>
							Cancel
						</Button>
						<Button type="submit" form="create-record-form" disabled={isSubmitting}>
							{isSubmitting ? 'Creating...' : 'Create Record'}
						</Button>
					</>
				) : undefined
			}
		>
			{isReferenceLoading ? (
				<div className="flex items-center justify-center py-8">
					<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
					<span className="ml-2 text-muted-foreground">
						Loading reference data...
					</span>
				</div>
			) : (
				<form id="create-record-form" onSubmit={handleSubmit} className="space-y-6">
					{/* Account selector for superadmins */}
					{isSuperadmin && (
						<div className="space-y-2 pb-4 border-b">
							<Label htmlFor="account-select">Account *</Label>
							<Select
								value={selectedAccountId}
								onValueChange={setSelectedAccountId}
								disabled={loadingAccounts || isSubmitting}
							>
								<SelectTrigger id="account-select">
									<SelectValue placeholder="Select an account" />
								</SelectTrigger>
								<SelectContent>
									{accounts.map((account) => (
										<SelectItem key={account.id} value={account.id}>
											{account.name} ({account.account_code})
										</SelectItem>
									))}
								</SelectContent>
							</Select>
							{loadingAccounts && (
								<p className="text-sm text-muted-foreground">
									Loading accounts...
								</p>
							)}
						</div>
					)}
 
					<div className="max-h-[60vh] overflow-y-auto pr-4 space-y-4">
						{schema.filter(f => f.type !== 'computed').map((field) => (
							<DynamicFieldInput
								key={field.name}
								field={field}
								value={formState.fields[field.name]?.value}
								onChange={(value) => handleFieldChange(field.name, value)}
								error={formState.fields[field.name]?.error || undefined}
								disabled={isSubmitting}
								referenceRecords={
									field.type === 'reference' && field.collection
										? (referenceRecords[field.collection] || [])
										: undefined
								}
							/>
						))}
					</div>
 
					{error && (
						<div className="bg-destructive/10 border border-destructive/20 rounded-lg p-4">
							<p className="text-destructive text-sm">{error}</p>
						</div>
					)}
				</form>
			)}
		</AppDialog>
	);
}