Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion web_app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,25 @@
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.13.5",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@types/swagger-ui-react": "^4.18.3",
"@vitejs/plugin-react": "^4.3.3",
"@vitest/ui": "^4.0.14",
"autoprefixer": "^10.4.20",
"eslint": "^9.13.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.11.0",
"jsdom": "^27.2.0",
"postcss": "^8.5.1",
"tailwindcss": "^3.4.17",
"typescript": "~5.6.2",
"typescript-eslint": "^8.11.0",
"vite": "^5.4.10"
"vite": "^7.2.4",
"vitest": "^4.0.14"
}
}
62 changes: 52 additions & 10 deletions web_app/src/Librarian/LibrarianAddBook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ const LibrarianAddBook: React.FC = () => {
if (!authorOptions.includes(author)) {
try {
const token = localStorage.getItem('access_token');
if (!token) {
return;
}
if (!token) return;

const response = await fetch(`${API_BASE_URL}/api/authors`, {
method: 'POST',
Expand All @@ -113,16 +111,26 @@ const LibrarianAddBook: React.FC = () => {
});

if (!response.ok) {
if (response.status === 409) {
throw new Error("Ten autor już istnieje.");
}

const errorText = await response.text();
throw new Error(`Błąd ${response.status}: ${errorText}`);
const finalMessage = errorText || response.statusText;
throw new Error(`Błąd ${response.status}: ${finalMessage}`);
}

await fetchAuthors('');
await fetchPublishers('');
toast.success(`Dodano nowego autora: ${author}`);

} catch (err) {
console.error("Error adding author:", err);
setError('Wystąpił błąd podczas dodawania autora.');
const msg = (err as Error).message || "Błąd dodawania autora";
setError(msg);
toast.error(msg);

setAuthors(prev => prev.filter(a => a !== author));
}
}
}
Expand Down Expand Up @@ -166,14 +174,26 @@ const LibrarianAddBook: React.FC = () => {
body: JSON.stringify({ name: publisherName }),
});

if (!response.ok) throw new Error(await response.text());
if (!response.ok) {
if (response.status === 409) {
throw new Error("To wydawnictwo już istnieje.");
}

const errorText = await response.text();
const finalMessage = errorText || response.statusText;
throw new Error(`Błąd ${response.status}: ${finalMessage}`);
}

await fetchPublishers('');
toast.success(`Dodano nowe wydawnictwo: ${publisherName}`);
} catch (err) {
console.error("Error adding publisher:", err);
const msg = (err as Error).message || "Błąd dodawania wydawnictwa";

toast.error(msg);
setPublisher('');
}
}
//setPublisherInput('');
setShowPublisherDropdown(false);
};

Expand All @@ -187,7 +207,7 @@ const LibrarianAddBook: React.FC = () => {
};

const handleAddBook = async () => {
if (!title.trim() || !categoryName.trim() || authors.length === 0 || !publisher.trim() || !isbn.trim() || !language.trim() || releaseYear === null) {
if (!title.trim() || !categoryName.trim() || authors.length === 0 || !publisher.trim() || !isbn.trim() || !language.trim() || releaseYear === '') {
setError('Wszystkie pola są wymagane.');
return;
}
Expand Down Expand Up @@ -228,12 +248,34 @@ const LibrarianAddBook: React.FC = () => {

if (!response.ok) {
const errorText = await response.text();
throw new Error(`Błąd ${response.status}: ${errorText}`);

if (response.status === 409) {
throw new Error("Książka o podanym numerze ISBN już istnieje.");
}

if (response.status === 400) {
throw new Error(errorText || "Nieprawidłowe dane formularza.");
}

if (response.status === 401) {
throw new Error("Sesja wygasła. Proszę zalogować się ponownie.");
}

if (response.status === 413) {
throw new Error("Wybrane zdjęcie jest zbyt duże.");
}

// Code 500 and other unknown
const finalMessage = errorText || response.statusText || 'Unknown Server Error';
throw new Error(`Błąd ${response.status}: ${finalMessage}`);
}

toast.success("Książka została dodana!");
navigate('/librarian-dashboard');
} catch (error) {
setError((error as Error).message || 'Wystąpił błąd podczas dodawania książki.');
const msg = (error as Error).message || 'Wystąpił błąd.';
setError(msg);
toast.error(msg);
} finally {
setLoading(false);
}
Expand Down
74 changes: 59 additions & 15 deletions web_app/src/Librarian/LibrarianHomePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,19 @@ const LibrarianHomePage: React.FC = () => {
name: string;
}

// UPDATED: Matches your new JSON structure
interface LibraryAddress {
street: string;
city: string;
postalCode: string;
}

interface Library {
id: number;
name: string;
phoneNumber: string;
email: string;
address: LibraryAddress;
}

// Books
Expand Down Expand Up @@ -77,14 +87,25 @@ const LibrarianHomePage: React.FC = () => {
const [isLoading, setIsLoading] = useState(false);
const isFetchingRef = useRef(false);

// NEW: Ref for the scrollable list container
const listRef = useRef<HTMLUListElement>(null);

useEffect(() => {
fetchAssignedLibrary();
fetchDropdownData();
}, []);

// Logic to reset list when library toggle changes
useEffect(() => {
if (assignedLibrary !== null) {
fetchBooks(isUserLibraryChecked);
setBookSearchResults([]); // Clear existing results
setPage(0);
setHasMore(true);
// We use a timeout to allow state to settle before fetching
const timeoutId = setTimeout(() => {
fetchBooks(isUserLibraryChecked, 0);
}, 0);
return () => clearTimeout(timeoutId);
}
}, [isUserLibraryChecked, assignedLibrary]);

Expand Down Expand Up @@ -122,17 +143,29 @@ const LibrarianHomePage: React.FC = () => {
}
}, [deleteBooksMessage]);

// Lazy Loading
// UPDATED: Lazy Loading attached to the list element instead of window
useEffect(() => {
const handleScroll = () => {
const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 1000;
if (nearBottom && !isLoading && hasMore) {
fetchBooks(isUserLibraryChecked, page);
if (listRef.current) {
const { scrollTop, scrollHeight, clientHeight } = listRef.current;
// Check if scrolled near bottom
if (scrollTop + clientHeight >= scrollHeight - 50) {
if (!isLoading && hasMore) {
fetchBooks(isUserLibraryChecked, page);
}
}
}
};

window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
const listElement = listRef.current;
if (listElement) {
listElement.addEventListener('scroll', handleScroll);
}
return () => {
if (listElement) {
listElement.removeEventListener('scroll', handleScroll);
}
};
}, [isLoading, hasMore, page, isUserLibraryChecked]);

useWebSocketNotification('librarian/orders/pending', () => {
Expand Down Expand Up @@ -232,16 +265,20 @@ const LibrarianHomePage: React.FC = () => {

const fetchBooks = async (filterByLibrary: boolean, pageToFetch: number = 0) => {
const token = localStorage.getItem('access_token');
if (!token || isFetchingRef.current || isLoading || !hasMore) return;
// Prevent fetching if we are already loading or if there is no more data (unless it's page 0)
if (!token || isFetchingRef.current || (isLoading && pageToFetch !== 0) || (!hasMore && pageToFetch !== 0)) return;

isFetchingRef.current = true;
setIsLoading(true);

const queryParams = new URLSearchParams();

if (filterByLibrary && assignedLibrary?.id) {
queryParams.append("libraryId", assignedLibrary.id.toString());
// --- API UPDATE START ---
// Changed from 'libraryId' to 'library' (string name) based on new requirements
if (filterByLibrary && assignedLibrary?.name) {
queryParams.append("library", assignedLibrary.name);
}
// --- API UPDATE END ---

if (bookSearchInput) queryParams.append("title", bookSearchInput);
if (categoryInput) queryParams.append("category", categoryInput);
Expand All @@ -253,7 +290,7 @@ const LibrarianHomePage: React.FC = () => {
if (releaseYearTo) queryParams.append("releaseYearTo", releaseYearTo.toString());

queryParams.append("page", pageToFetch.toString());
queryParams.append("size", "2");
queryParams.append("size", "10"); // Adjusted size for better scrolling experience

try {
const response = await fetch(`${API_BASE_URL}/api/books/search?${queryParams.toString()}`, {
Expand All @@ -269,9 +306,11 @@ const LibrarianHomePage: React.FC = () => {
const data = await response.json();
const newBooks = data.content;

setBookSearchResults(prev => [...prev, ...newBooks]);
setBookSearchResults(prev => pageToFetch === 0 ? newBooks : [...prev, ...newBooks]);
setPage(pageToFetch + 1);
setHasMore(!data.last);

// Updated check based on new JSON response which has totalPages
setHasMore(data.currentPage < data.totalPages - 1);

} catch (error) {
console.error("Error: ", error);
Expand All @@ -286,8 +325,10 @@ const LibrarianHomePage: React.FC = () => {
setBookSearchResults([]);
setPage(0);
setHasMore(true);
fetchBooks(isUserLibraryChecked, 0);
} else {
fetchBooks(isUserLibraryChecked, 0);
}
fetchBooks(isUserLibraryChecked, 0);
};

const handleRedirectToAddBook = () => {
Expand Down Expand Up @@ -636,7 +677,10 @@ const LibrarianHomePage: React.FC = () => {
</div>

{searchResults.length > 0 ? (
<ul className="mt-12 bg-white p-3 rounded max-h-[40vw] overflow-y-auto">
<ul
ref={listRef}
className="mt-12 bg-white p-3 rounded max-h-[40vw] overflow-y-auto"
>
{searchResults.map((book, index) => (
<li
key={index}
Expand Down
10 changes: 10 additions & 0 deletions web_app/src/LibraryAdmin/LibraryAdminAddLibrary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const LibraryAdminAddLibrary: React.FC = () => {
emailAddress: '',
});

const [errorMessage, setErrorMessage] = useState<string>('');

const handleLogout = () => {
localStorage.removeItem('access_token');
localStorage.removeItem('role');
Expand All @@ -38,6 +40,7 @@ const LibraryAdminAddLibrary: React.FC = () => {

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setErrorMessage('');

const requestBody = {
street: formData.addressLine,
Expand All @@ -64,9 +67,11 @@ const LibraryAdminAddLibrary: React.FC = () => {
navigate('/processing-info');
} else {
console.error('Error submitting request', response.statusText);
setErrorMessage('Wystąpił błąd podczas wysyłania formularza.');
}
} catch (error) {
console.error('Error:', error);
setErrorMessage('Nie udało się połączyć z serwerem. Sprawdź swoje połączenie internetowe.');
}
};

Expand Down Expand Up @@ -129,6 +134,11 @@ const LibraryAdminAddLibrary: React.FC = () => {
Złóż podanie
</button>
</div>
{errorMessage && (
<p className="mt-6 text-left text-red-600 font-semibold">
{errorMessage}
</p>
)}
</form>
</section>
</main>
Expand Down
Loading