feat(4.1-05-07): create frontend components for spare-parts search integration - useItemSearch hook, LoadingModal, ErrorModal with tests
This commit is contained in:
39
frontend/components/SearchErrorModal.tsx
Normal file
39
frontend/components/SearchErrorModal.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
'use client';
|
||||
|
||||
interface SearchErrorModalProps {
|
||||
isOpen: boolean;
|
||||
error: string | null;
|
||||
onRetry?: () => void;
|
||||
onSkip?: () => void;
|
||||
canRetry?: boolean;
|
||||
}
|
||||
|
||||
export function SearchErrorModal({ isOpen, error, onRetry, onSkip, canRetry = true }: SearchErrorModalProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||
<div className="bg-white rounded-lg p-6 max-w-md shadow-xl">
|
||||
<h2 className="text-xl font-normal mb-2 text-rose-500">Search failed</h2>
|
||||
<p className="text-sm text-slate-600 mb-4">{error || 'Unable to retrieve specs from the web'}</p>
|
||||
|
||||
<div className="flex gap-3">
|
||||
{canRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="flex-1 px-4 py-2 bg-primary text-white rounded font-normal text-sm hover:bg-primary/90"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={onSkip}
|
||||
className="flex-1 px-4 py-2 border border-slate-300 rounded font-normal text-sm hover:bg-slate-50"
|
||||
>
|
||||
Skip
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
57
frontend/components/SearchLoadingModal.tsx
Normal file
57
frontend/components/SearchLoadingModal.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface SearchLoadingModalProps {
|
||||
isOpen: boolean;
|
||||
onTimeout?: () => void;
|
||||
maxSeconds?: number;
|
||||
}
|
||||
|
||||
export function SearchLoadingModal({ isOpen, onTimeout, maxSeconds = 30 }: SearchLoadingModalProps) {
|
||||
const [seconds, setSeconds] = useState(maxSeconds);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setSeconds(maxSeconds);
|
||||
return;
|
||||
}
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setSeconds(prev => {
|
||||
if (prev <= 1) {
|
||||
clearInterval(interval);
|
||||
onTimeout?.();
|
||||
return maxSeconds;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [isOpen, maxSeconds, onTimeout]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||
<div className="bg-white rounded-lg p-6 max-w-md shadow-xl">
|
||||
<h2 className="text-xl font-normal mb-4">Searching for specs...</h2>
|
||||
<p className="text-sm text-slate-600 mb-4">This may take up to {maxSeconds} seconds</p>
|
||||
|
||||
<div className="mb-4">
|
||||
<div className="relative h-2 bg-slate-200 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-primary transition-all duration-1000"
|
||||
style={{ width: `${(seconds / maxSeconds) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm font-normal">
|
||||
<span className="text-primary text-lg">{seconds}</span> seconds remaining
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
89
frontend/hooks/useItemSearch.ts
Normal file
89
frontend/hooks/useItemSearch.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
export interface SearchResult {
|
||||
category?: string;
|
||||
type?: string;
|
||||
description?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface SearchState {
|
||||
isSearching: boolean;
|
||||
searchError: string | null;
|
||||
searchResults: SearchResult | null;
|
||||
searchStatus: 'idle' | 'searching' | 'success' | 'timeout' | 'error' | 'no_results' | 'skipped';
|
||||
retryCount: number;
|
||||
}
|
||||
|
||||
export function useItemSearch(options: { maxRetries?: number; timeout?: number } = {}) {
|
||||
const { maxRetries = 2, timeout = 30000 } = options;
|
||||
|
||||
const [state, setState] = useState<SearchState>({
|
||||
isSearching: false,
|
||||
searchError: null,
|
||||
searchResults: null,
|
||||
searchStatus: 'idle',
|
||||
retryCount: 0,
|
||||
});
|
||||
|
||||
const performSearch = useCallback(
|
||||
async (partNumber: string, category: string): Promise<SearchResult | null> => {
|
||||
if (!partNumber || !category) {
|
||||
setState(prev => ({ ...prev, searchStatus: 'skipped', searchError: null }));
|
||||
return null;
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, isSearching: true, searchStatus: 'searching', searchError: null, retryCount: 0 }));
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
const response = await fetch('/api/onboarding/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ partNumber, category }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) throw new Error(`Search failed: ${response.status}`);
|
||||
|
||||
const results = await response.json();
|
||||
setState(prev => ({ ...prev, isSearching: false, searchStatus: 'success', searchResults: results }));
|
||||
return results;
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : 'Search failed';
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isSearching: false,
|
||||
searchStatus: errorMsg.includes('abort') ? 'timeout' : 'error',
|
||||
searchError: errorMsg,
|
||||
}));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[timeout]
|
||||
);
|
||||
|
||||
const retrySearch = useCallback(
|
||||
async (partNumber: string, category: string) => {
|
||||
if (state.retryCount >= maxRetries) {
|
||||
setState(prev => ({ ...prev, searchStatus: 'error' }));
|
||||
return null;
|
||||
}
|
||||
setState(prev => ({ ...prev, retryCount: prev.retryCount + 1 }));
|
||||
return performSearch(partNumber, category);
|
||||
},
|
||||
[state.retryCount, maxRetries, performSearch]
|
||||
);
|
||||
|
||||
const skipSearch = useCallback(() => {
|
||||
setState(prev => ({ ...prev, searchStatus: 'skipped', isSearching: false }));
|
||||
}, []);
|
||||
|
||||
return { state, performSearch, retrySearch, skipSearch };
|
||||
}
|
||||
51
frontend/tests/SearchErrorModal.test.tsx
Normal file
51
frontend/tests/SearchErrorModal.test.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { SearchErrorModal } from '../components/SearchErrorModal';
|
||||
|
||||
describe('SearchErrorModal', () => {
|
||||
it('renders when open', () => {
|
||||
render(<SearchErrorModal isOpen={true} error="Network error" />);
|
||||
expect(screen.getByText(/Search failed/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
const { container } = render(<SearchErrorModal isOpen={false} error="Network error" />);
|
||||
expect(container.firstChild?.childNodes.length).toBe(0);
|
||||
});
|
||||
|
||||
it('displays error message', () => {
|
||||
const errorMsg = 'Unable to connect to server';
|
||||
render(<SearchErrorModal isOpen={true} error={errorMsg} />);
|
||||
expect(screen.getByText(errorMsg)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onRetry when Retry clicked', async () => {
|
||||
const onRetry = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<SearchErrorModal isOpen={true} error="Error" onRetry={onRetry} canRetry={true} />);
|
||||
|
||||
const retryBtn = screen.getByRole('button', { name: /Retry/i });
|
||||
await user.click(retryBtn);
|
||||
|
||||
expect(onRetry).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls onSkip when Skip clicked', async () => {
|
||||
const onSkip = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<SearchErrorModal isOpen={true} error="Error" onSkip={onSkip} />);
|
||||
|
||||
const skipBtn = screen.getByRole('button', { name: /Skip/i });
|
||||
await user.click(skipBtn);
|
||||
|
||||
expect(onSkip).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hides Retry button when canRetry is false', () => {
|
||||
render(<SearchErrorModal isOpen={true} error="Error" canRetry={false} />);
|
||||
expect(screen.queryByRole('button', { name: /Retry/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
35
frontend/tests/SearchLoadingModal.test.tsx
Normal file
35
frontend/tests/SearchLoadingModal.test.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { SearchLoadingModal } from '../components/SearchLoadingModal';
|
||||
|
||||
describe('SearchLoadingModal', () => {
|
||||
it('renders when open', () => {
|
||||
render(<SearchLoadingModal isOpen={true} maxSeconds={30} />);
|
||||
expect(screen.getByText(/Searching for specs/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
const { container } = render(<SearchLoadingModal isOpen={false} />);
|
||||
expect(container.firstChild?.childNodes.length).toBe(0);
|
||||
});
|
||||
|
||||
it('displays countdown timer', () => {
|
||||
render(<SearchLoadingModal isOpen={true} maxSeconds={30} />);
|
||||
expect(screen.getByText(/30 seconds remaining/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onTimeout when timer expires', async () => {
|
||||
const onTimeout = vi.fn();
|
||||
render(<SearchLoadingModal isOpen={true} maxSeconds={1} onTimeout={onTimeout} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onTimeout).toHaveBeenCalled();
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('shows progress bar', () => {
|
||||
const { container } = render(<SearchLoadingModal isOpen={true} maxSeconds={30} />);
|
||||
const progressBar = container.querySelector('div[class*="bg-primary"]');
|
||||
expect(progressBar).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
103
frontend/tests/useItemSearch.test.tsx
Normal file
103
frontend/tests/useItemSearch.test.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useItemSearch } from '../hooks/useItemSearch';
|
||||
|
||||
describe('useItemSearch', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
it('initializes with idle state', () => {
|
||||
const { result } = renderHook(() => useItemSearch());
|
||||
expect(result.current.state.searchStatus).toBe('idle');
|
||||
expect(result.current.state.isSearching).toBe(false);
|
||||
});
|
||||
|
||||
it('performs search with part number and category', async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ type: 'DDR4', description: 'Kingston RAM' }),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useItemSearch());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.performSearch('KF466C40RS-16', 'DDR4');
|
||||
});
|
||||
|
||||
expect(result.current.state.searchStatus).toBe('success');
|
||||
expect(result.current.state.searchResults?.type).toBe('DDR4');
|
||||
});
|
||||
|
||||
it('handles search timeout', async () => {
|
||||
global.fetch = vi.fn().mockImplementation(
|
||||
() =>
|
||||
new Promise((_, reject) => {
|
||||
setTimeout(() => reject(new DOMException('Aborted', 'AbortError')), 100);
|
||||
})
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useItemSearch({ timeout: 50 }));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.performSearch('KF466C40RS-16', 'DDR4');
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.state.searchStatus).toBe('timeout');
|
||||
});
|
||||
});
|
||||
|
||||
it('skips search when part number is missing', async () => {
|
||||
const { result } = renderHook(() => useItemSearch());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.performSearch('', 'DDR4');
|
||||
});
|
||||
|
||||
expect(result.current.state.searchStatus).toBe('skipped');
|
||||
});
|
||||
|
||||
it('handles search error', async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useItemSearch());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.performSearch('KF466C40RS-16', 'DDR4');
|
||||
});
|
||||
|
||||
expect(result.current.state.searchStatus).toBe('error');
|
||||
expect(result.current.state.searchError).toBeTruthy();
|
||||
});
|
||||
|
||||
it('retries search', async () => {
|
||||
const { result } = renderHook(() => useItemSearch({ maxRetries: 2 }));
|
||||
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ type: 'DDR4' }),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.retrySearch('KF466C40RS-16', 'DDR4');
|
||||
});
|
||||
|
||||
expect(result.current.state.retryCount).toBe(1);
|
||||
});
|
||||
|
||||
it('skips search', async () => {
|
||||
const { result } = renderHook(() => useItemSearch());
|
||||
|
||||
act(() => {
|
||||
result.current.skipSearch();
|
||||
});
|
||||
|
||||
expect(result.current.state.searchStatus).toBe('skipped');
|
||||
expect(result.current.state.isSearching).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user