6 Commits
27 changed files with 1661 additions and 154 deletions
+10
View File
@@ -0,0 +1,10 @@
node_modules
npm-debug.log
dist
.git
.gitignore
.idea
.vscode
Dockerfile
README.md
+2
View File
@@ -0,0 +1,2 @@
VITE_API_URL=/api/v1
+2
View File
@@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
.env
+16
View File
@@ -0,0 +1,16 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginxinc/nginx-unprivileged:1.27-alpine AS runtime
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 8000
CMD ["nginx", "-g", "daemon off;"]
+16 -9
View File
@@ -1,16 +1,23 @@
# React + Vite
# Listhub Frontend Repository
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
To start developing
Currently, two official plugins are available:
```bash
npm install
```
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
and then
## React Compiler
```bash
npm run start
```
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
## API configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
The frontend reads the base backend URL from `VITE_API_URL` in `src/config/api.js`.
- Default: `/api/v1` (works with the Vite dev proxy)
- To override it, create a local `.env` file and set `VITE_API_URL` to your backend URL
See `.env.example` for a ready-to-copy example.
+20
View File
@@ -0,0 +1,20 @@
server {
listen 8000;
server_name _;
root /usr/share/nginx/html;
index index.html;
server_tokens off;
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(?:css|js|mjs|json|ico|png|jpg|jpeg|gif|svg|webp|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
}
+20 -9
View File
@@ -1,8 +1,13 @@
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import { useAuthStore } from './store/authStore';
import { BrowserRouter as Router, Navigate, Route, Routes } from "react-router-dom";
import AppLayout from "./components/AppLayout";
import Login from "./pages/Login";
import CreateNotice from "./pages/CreateNotice";
import EditNotice from "./pages/EditNotice";
import MyNotices from "./pages/MyNotices";
import NoticeDetails from "./pages/NoticeDetails";
import NoticesPage from "./pages/NoticesPage";
import { useAuthStore } from "./store/authStore";
import Registration from "@/pages/Registration.jsx";
const ProtectedRoute = ({ children }) => {
const token = useAuthStore((state) => state.token);
@@ -17,15 +22,21 @@ function App() {
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/registration" element={<Registration />} />
<Route
path="/"
element={
<ProtectedRoute>
<Home />
<AppLayout />
</ProtectedRoute>
}
/>
{/* Fallback */}
>
<Route path="/" element={<Navigate to="/notices" replace />} />
<Route path="/notices" element={<NoticesPage />} />
<Route path="/notices/create" element={<CreateNotice />} />
<Route path="/notices/:id" element={<NoticeDetails />} />
<Route path="/notices/:id/edit" element={<EditNotice />} />
<Route path="/dashboard/my-notices" element={<MyNotices />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Router>
+10
View File
@@ -0,0 +1,10 @@
import axios from "axios";
import { API_URL } from "../config/api";
const api = axios.create({
baseURL: API_URL,
});
export { api };
export default api;
+7 -9
View File
@@ -1,10 +1,8 @@
import axios from "axios";
export const API_URL = "/api/v1";
import api from "./api";
export async function login(userData) {
try {
const response = await axios.post(`${API_URL}/auth/login`, userData, {
const response = await api.post(`/auth/login`, userData, {
headers: {"Content-Type": "application/json"},
});
return response.data;
@@ -16,7 +14,7 @@ export async function login(userData) {
export async function register(userData) {
try {
const response = await axios.post(`${API_URL}/auth/register`, userData, {
const response = await api.post(`/auth/register`, userData, {
headers: {"Content-Type": "application/json"},
});
return response.data;
@@ -28,8 +26,8 @@ export async function register(userData) {
export async function googleLogin(googleToken) {
try {
const response = await axios.post(
`${API_URL}/auth/google`,
const response = await api.post(
`/auth/google`,
{ googleToken: googleToken },
{
headers: { "Content-Type": "application/json" },
@@ -45,8 +43,8 @@ export async function googleLogin(googleToken) {
export async function logout(token) {
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const response = await axios.post(
`${API_URL}/auth/logout`,
const response = await api.post(
`/auth/logout`,
{},
{
headers: headers,
+10
View File
@@ -0,0 +1,10 @@
import { useAuthStore } from "../store/authStore";
import api from "./api";
export async function listCategories() {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const response = await api.get(`/vars/categories`, { headers });
return Array.isArray(response.data) ? response.data : [];
}
+113 -88
View File
@@ -1,43 +1,62 @@
import axios from "axios";
import { useAuthStore } from "../store/authStore";
import api from "./api";
const API_URL = "/api/v1";
const getAuthHeaders = () => {
const { token } = useAuthStore.getState();
return token ? { Authorization: `Bearer ${token}` } : {};
};
const buildImageUrl = (imageName) => `/images/get/${imageName}`;
const fetchImageAsBlobUrl = async (imageUrl) => {
const headers = getAuthHeaders();
const response = await api.get(imageUrl, {
headers,
responseType: "blob",
});
return URL.createObjectURL(response.data);
};
export async function listNotices() {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = getAuthHeaders();
const response = await fetch(`${API_URL}/notices/get/all`, {
const response = await api.get(`/notices/get/all`, {
headers: headers,
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Failed to fetch notices");
}
return data;
return response.data;
}
export async function getNoticeById(noticeId) {
const response = await fetch(`${API_URL}/notices/get/${noticeId}`);
const data = await response.json();
if (!response.ok) {
throw new Error("Error fetching notice");
}
return data;
const headers = getAuthHeaders();
const response = await api.get(`/notices/get/${noticeId}`, {
headers,
});
return response.data;
}
export async function createNotice(notice) {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = getAuthHeaders();
const payload = {
title: notice.title,
description: notice.description,
price: notice.price,
category: notice.category,
status: notice.status,
attributes: notice.attributes,
};
try {
const response = await axios.post(`${API_URL}/notices/add`, notice, {
const response = await api.post(`/notices/add`, payload, {
headers: headers,
});
if (response.data.noticeId !== null && notice.image) {
for (let i = 0; i < notice.image.length; i++) {
await uploadImage(response.data.noticeId, notice.image[i], i === 0);
const image = notice.image[i];
if (image instanceof File) {
await uploadImage(response.data.noticeId, image, i === 0);
}
}
}
@@ -49,47 +68,55 @@ export async function createNotice(notice) {
}
export async function getImageByNoticeId(noticeId) {
const headers = getAuthHeaders();
try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
const listResponse = await api.get(`/images/list/${noticeId}`, {
headers,
});
const imageName = listResponse.data[0];
return `${API_URL}/images/get/${imageName}`;
} catch (err) {
return "https://http.cat/404.jpg";
if (!imageName) {
return null;
}
return await fetchImageAsBlobUrl(buildImageUrl(imageName));
} catch {
return null;
}
}
export async function getAllImagesByNoticeId(noticeId) {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = getAuthHeaders();
try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {
const listResponse = await api.get(`/images/list/${noticeId}`, {
headers: headers,
});
if (listResponse.data && listResponse.data.length > 0) {
return listResponse.data.map((imageName) => ({
uri: `${API_URL}/images/get/${imageName}`,
headers: headers,
}));
const imageUrls = await Promise.all(
listResponse.data.map(async (imageName) => {
try {
return await fetchImageAsBlobUrl(buildImageUrl(imageName));
} catch {
return null;
}
})
);
return imageUrls.filter((url) => typeof url === "string" && url.trim());
}
return [{ uri: "https://http.cat/404.jpg" }];
} catch (err) {
return [{ uri: "https://http.cat/404.jpg" }];
return [];
} catch {
return [];
}
}
export const uploadImage = async (noticeId, file, isFirst) => {
const { token } = useAuthStore.getState();
const headers = {
...(token ? { Authorization: `Bearer ${token}` } : {}),
"Content-Type": "multipart/form-data",
};
const headers = getAuthHeaders();
const formData = new FormData();
formData.append("file", file);
try {
const response = await axios.post(
`${API_URL}/images/upload/${noticeId}?isMainImage=${isFirst}`,
const response = await api.post(
`/images/upload/${noticeId}?isMainImage=${isFirst}`,
formData,
{ headers: headers }
);
@@ -101,64 +128,62 @@ export const uploadImage = async (noticeId, file, isFirst) => {
};
export const deleteNotice = async (noticeId) => {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const response = await axios.delete(
`${API_URL}/notices/delete/${noticeId}`,
{ headers: headers }
);
return response.data;
} catch (error) {
throw error;
}
const headers = getAuthHeaders();
const response = await api.delete(
`/notices/delete/${noticeId}`,
{ headers: headers }
);
return response.data;
};
export const editNotice = async (noticeId, notice) => {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = getAuthHeaders();
const response = await api.put(
`/notices/edit/${noticeId}`,
{
title: notice.title,
description: notice.description,
price: notice.price,
category: notice.category,
status: notice.status,
attributes: notice.attributes,
},
{ headers: headers }
);
try {
const response = await axios.put(
`${API_URL}/notices/edit/${noticeId}`,
{
title: notice.title,
description: notice.description,
price: notice.price,
category: notice.category,
status: notice.status,
attributes: notice.attributes,
},
{ headers: headers }
);
if (response.data && notice.image && notice.image.length > 0) {
for (let i = 0; i < notice.image.length; i++) {
const image = notice.image[i];
if (image instanceof File) {
await uploadImage(noticeId, image, i === 0);
}
if (response.data && notice.image && notice.image.length > 0) {
for (let i = 0; i < notice.image.length; i++) {
const image = notice.image[i];
if (image instanceof File) {
await uploadImage(noticeId, image, i === 0);
}
}
return response.data;
} catch (error) {
throw error;
}
return response.data;
};
export const deleteImage = async (filename) => {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = getAuthHeaders();
const response = await api.delete(
`/images/delete/${filename}`,
{ headers: headers }
);
return response.data;
};
export async function listImageNamesByNoticeId(noticeId) {
const headers = getAuthHeaders();
try {
const response = await axios.delete(
`${API_URL}/images/delete/${filename}`,
{ headers: headers }
);
return response.data;
const response = await api.get(`/images/list/${noticeId}`, {
headers,
});
return Array.isArray(response.data) ? response.data : [];
} catch (error) {
if (error.response?.status === 404) {
return [];
}
throw error;
}
};
}
+4 -6
View File
@@ -1,15 +1,13 @@
import axios from "axios";
import { useAuthStore } from "../store/authStore";
const API_URL = "/api/v1/wishlist";
import api from "./api";
export async function toggleNoticeStatus(noticeId) {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const response = await axios.post(
`${API_URL}/toggle/${noticeId}`,
const response = await api.post(
`/wishlist/toggle/${noticeId}`,
{},
{ headers: headers }
);
@@ -25,7 +23,7 @@ export async function getWishlist() {
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const response = await axios.get(`${API_URL}/`, { headers: headers });
const response = await api.get(`/wishlist/`, { headers: headers });
return response.data;
} catch (error) {
console.error("Error fetching wishlist:", error);
+50
View File
@@ -0,0 +1,50 @@
import { LogOut, PlusCircle } from "lucide-react";
import { NavLink, Outlet } from "react-router-dom";
import { useAuthStore } from "../store/authStore";
const navClass = ({ isActive }) =>
`px-3 py-2 text-sm font-medium rounded-md transition-colors ${
isActive ? "bg-primary/10 text-primary" : "text-gray-600 hover:text-gray-900"
}`;
export default function AppLayout() {
const { signOut } = useAuthStore();
return (
<div className="min-h-screen bg-gray-50">
<header className="sticky top-0 z-20 border-b border-gray-200 bg-white">
<div className="mx-auto flex h-16 w-full max-w-6xl items-center justify-between px-4">
<NavLink to="/notices" className="text-lg font-bold text-primary">
ArtisanConnect
</NavLink>
<nav className="flex items-center gap-2">
<NavLink className={navClass} to="/notices">
Ogloszenia
</NavLink>
<NavLink className={navClass} to="/dashboard/my-notices">
Moje
</NavLink>
<NavLink
className="inline-flex items-center gap-2 rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white hover:bg-primary/90"
to="/notices/create"
>
<PlusCircle size={16} />
Dodaj
</NavLink>
<button
className="inline-flex items-center gap-2 rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-700 hover:bg-gray-100"
onClick={signOut}
type="button"
>
<LogOut size={16} />
Wyloguj
</button>
</nav>
</div>
</header>
<main className="mx-auto w-full max-w-6xl px-4 py-6">
<Outlet />
</main>
</div>
);
}
+170
View File
@@ -0,0 +1,170 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { listCategories } from "../api/categories";
import { getImageByNoticeId } from "../api/notices";
let categoryLabelCache = null;
let categoryLabelPromise = null;
const getCategoryLabelMap = async () => {
if (categoryLabelCache) {
return categoryLabelCache;
}
if (categoryLabelPromise) {
return categoryLabelPromise;
}
categoryLabelPromise = listCategories()
.then((items) => {
const map = new Map(
(items || []).map((item) => [String(item.value), item.label])
);
categoryLabelCache = map;
return map;
})
.catch(() => new Map())
.finally(() => {
categoryLabelPromise = null;
});
return categoryLabelPromise;
};
export default function NoticeCard({ notice, actions }) {
const [imageUrl, setImageUrl] = useState(null);
const [isImageLoading, setIsImageLoading] = useState(true);
const [categoryLabel, setCategoryLabel] = useState(notice?.category || "");
useEffect(() => {
let isMounted = true;
const loadImage = async () => {
if (!notice?.noticeId) {
if (isMounted) {
setImageUrl(null);
setIsImageLoading(false);
}
return;
}
if (isMounted) {
setIsImageLoading(true);
}
try {
const image = await getImageByNoticeId(notice.noticeId);
if (isMounted) {
const normalizedImage =
typeof image === "string" && image.trim() ? image : null;
setImageUrl(normalizedImage);
setIsImageLoading(false);
} else if (typeof image === "string" && image.startsWith("blob:")) {
URL.revokeObjectURL(image);
}
} catch {
if (isMounted) {
setImageUrl(null);
setIsImageLoading(false);
}
}
};
loadImage();
return () => {
isMounted = false;
};
}, [notice?.noticeId]);
useEffect(() => {
return () => {
if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) {
URL.revokeObjectURL(imageUrl);
}
};
}, [imageUrl]);
useEffect(() => {
let isMounted = true;
const resolveCategoryLabel = async () => {
if (!notice?.category) {
setCategoryLabel("");
return;
}
const map = await getCategoryLabelMap();
if (isMounted) {
setCategoryLabel(map.get(String(notice.category)) || notice.category);
}
};
resolveCategoryLabel();
return () => {
isMounted = false;
};
}, [notice?.category]);
if (!notice) {
return null;
}
return (
<article className="overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm">
<Link to={`/notices/${notice.noticeId}`}>
{isImageLoading || !imageUrl ? (
isImageLoading ? (
<div className="flex aspect-square w-full items-center justify-center bg-gray-100">
<span
aria-label="Loading image"
className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-primary"
role="status"
/>
</div>
) : (
<div className="flex aspect-square w-full items-center justify-center bg-gray-100">
<span className="rounded-md bg-gray-200 px-3 py-1 text-sm font-medium text-gray-600">
No Image
</span>
</div>
)
) : (
<img
alt={notice.title}
className="aspect-square w-full bg-gray-100 object-cover"
onError={() => setImageUrl(null)}
src={imageUrl}
/>
)}
</Link>
<div className="space-y-3 p-4">
<div className="flex items-start justify-between gap-3">
<Link
className="font-semibold text-gray-900 hover:text-primary"
to={`/notices/${notice.noticeId}`}
>
{notice.title}
</Link>
<span className="whitespace-nowrap text-lg font-bold text-primary">
{notice.price} zl
</span>
</div>
<p className="text-sm text-gray-600">{categoryLabel}</p>
{/* {notice.status && (
<span
className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${
notice.status === "ACTIVE"
? "bg-green-100 text-green-700"
: "bg-yellow-100 text-yellow-700"
}`}
>
{notice.status}
</span>
)} */}
{actions ? <div className="flex gap-2 pt-1">{actions}</div> : null}
</div>
</article>
);
}
+213
View File
@@ -0,0 +1,213 @@
import { useEffect, useMemo, useState } from "react";
import { attributes } from "../data/attributesData";
const defaultErrors = {
title: false,
description: false,
price: false,
category: false,
};
export default function NoticeForm({
initialValues,
categories,
submitLabel,
isSubmitting,
status = "ACTIVE",
onSubmit,
}) {
const [title, setTitle] = useState(initialValues?.title ?? "");
const [description, setDescription] = useState(initialValues?.description ?? "");
const [price, setPrice] = useState(initialValues?.price?.toString() ?? "");
const [category, setCategory] = useState(initialValues?.category ?? "");
const [images, setImages] = useState(initialValues?.images ?? []);
const [selectedAttributes, setSelectedAttributes] = useState(
initialValues?.selectedAttributes ?? {}
);
const [errors, setErrors] = useState(defaultErrors);
const previewUrls = useMemo(
() =>
images.map((img) => (img instanceof File ? URL.createObjectURL(img) : img)),
[images]
);
useEffect(() => {
return () => {
previewUrls.forEach((url) => {
if (url.startsWith("blob:")) {
URL.revokeObjectURL(url);
}
});
};
}, [previewUrls]);
const handleFilesChange = (event) => {
const fileList = Array.from(event.target.files ?? []);
setImages(fileList);
};
const handleSubmit = async (event) => {
event.preventDefault();
const nextErrors = {
title: !title.trim(),
description: !description.trim(),
price: !price.toString().trim(),
category: !category.trim(),
};
setErrors(nextErrors);
if (Object.values(nextErrors).some(Boolean)) {
return;
}
const formattedAttributes = Object.entries(selectedAttributes)
.filter(([, value]) => value)
.map(([name, value]) => ({ name, value }));
await onSubmit({
title: title.trim(),
description: description.trim(),
price: price.toString().trim(),
category,
status,
image: images,
attributes: formattedAttributes,
});
};
return (
<form className="space-y-5 rounded-lg border border-gray-200 bg-white p-5" onSubmit={handleSubmit}>
<div>
<label className="mb-1 block text-sm font-medium text-gray-700" htmlFor="notice-images">
Zdjecia
</label>
<input
accept="image/*"
className="block w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
id="notice-images"
multiple
onChange={handleFilesChange}
type="file"
/>
<p className="mt-1 text-xs text-gray-500">
Pierwsze zdjecie bedzie zdjeciem glownym.
</p>
{previewUrls.length > 0 ? (
<div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4">
{previewUrls.map((url, index) => (
<img
alt={`Podglad ${index + 1}`}
className="aspect-square w-full rounded-md border border-gray-200 object-cover"
key={`${url}-${index}`}
src={url}
/>
))}
</div>
) : null}
</div>
<div>
<label className="mb-1 block text-sm font-medium text-gray-700" htmlFor="notice-title">
Tytul*
</label>
<input
className={`w-full rounded-md border px-3 py-2 text-sm ${
errors.title ? "border-red-500" : "border-gray-300"
}`}
id="notice-title"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-gray-700" htmlFor="notice-description">
Opis*
</label>
<textarea
className={`min-h-28 w-full rounded-md border px-3 py-2 text-sm ${
errors.description ? "border-red-500" : "border-gray-300"
}`}
id="notice-description"
onChange={(event) => setDescription(event.target.value)}
value={description}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div>
<label className="mb-1 block text-sm font-medium text-gray-700" htmlFor="notice-price">
Cena*
</label>
<input
className={`w-full rounded-md border px-3 py-2 text-sm ${
errors.price ? "border-red-500" : "border-gray-300"
}`}
id="notice-price"
onChange={(event) => setPrice(event.target.value)}
type="number"
value={price}
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-gray-700" htmlFor="notice-category">
Kategoria*
</label>
<select
className={`w-full rounded-md border px-3 py-2 text-sm ${
errors.category ? "border-red-500" : "border-gray-300"
}`}
id="notice-category"
onChange={(event) => setCategory(event.target.value)}
value={category}
>
<option value="">Wybierz kategorie</option>
{categories.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
{Object.entries(attributes).map(([label, options]) => (
<div key={label}>
<label className="mb-1 block text-sm font-medium text-gray-700" htmlFor={`attr-${label}`}>
{label}
</label>
<select
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm"
id={`attr-${label}`}
onChange={(event) =>
setSelectedAttributes((prev) => ({
...prev,
[label]: event.target.value,
}))
}
value={selectedAttributes[label] ?? ""}
>
<option value="">Wybierz</option>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</div>
))}
</div>
<button
className="inline-flex rounded-md bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-60"
disabled={isSubmitting}
type="submit"
>
{isSubmitting ? "Zapisywanie..." : submitLabel}
</button>
</form>
);
}
+8
View File
@@ -0,0 +1,8 @@
const DEFAULT_API_URL = "http://localhost:8080/api/v1";
const trimTrailingSlash = (value) => value.replace(/\/+$/, "");
export const API_URL = trimTrailingSlash(
import.meta.env.VITE_API_URL || DEFAULT_API_URL
);
+28
View File
@@ -0,0 +1,28 @@
export const attributes = {
Kolor: [
"Zielony",
"Czerwony",
"Niebieski",
"Zolty",
"Bialy",
"Czarny",
"Rozowy",
"Szary",
"Fioletowy",
"Pomaranczowy",
"Inny",
],
Material: [
"Bawelna",
"Welna",
"Syntetyk",
"Skora",
"Len",
"Jedwab",
"Poliester",
"Akryl",
"Wiskoza",
"Nylon",
"Inny",
],
};
+55
View File
@@ -0,0 +1,55 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { listCategories } from "../api/categories";
import NoticeForm from "../components/NoticeForm";
import { useNoticesStore } from "../store/noticesStore";
export default function CreateNotice() {
const navigate = useNavigate();
const { addNotice, fetchNotices } = useNoticesStore();
const [categories, setCategories] = useState([]);
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
let isMounted = true;
const loadCategories = async () => {
const data = await listCategories();
if (isMounted) {
setCategories(data);
}
};
loadCategories();
return () => {
isMounted = false;
};
}, []);
const handleSubmit = async (payload) => {
setIsSubmitting(true);
try {
const result = await addNotice(payload);
if (result) {
await fetchNotices();
navigate("/dashboard/my-notices");
}
} finally {
setIsSubmitting(false);
}
};
return (
<section className="space-y-4">
<h1 className="text-2xl font-bold text-gray-900">Dodaj ogloszenie</h1>
<NoticeForm
categories={categories}
isSubmitting={isSubmitting}
onSubmit={handleSubmit}
status="ACTIVE"
submitLabel="Dodaj"
/>
</section>
);
}
+149
View File
@@ -0,0 +1,149 @@
import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { listCategories } from "../api/categories";
import { getNoticeById } from "../api/notices";
import NoticeForm from "../components/NoticeForm";
import { useAuthStore } from "../store/authStore";
import { useNoticesStore } from "../store/noticesStore";
const mapAttributes = (notice) => {
const attrs = {};
if (!Array.isArray(notice?.attributes)) {
return attrs;
}
notice.attributes.forEach((attr) => {
if (attr?.name) {
attrs[attr.name] = attr.value;
}
});
return attrs;
};
export default function EditNotice() {
const { id } = useParams();
const navigate = useNavigate();
const { user_id } = useAuthStore();
const { fetchNotices, getAllImagesByNoticeId, editNotice } = useNoticesStore();
const [categories, setCategories] = useState([]);
const [currentNotice, setCurrentNotice] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect(() => {
let isMounted = true;
const loadData = async () => {
setIsLoading(true);
try {
const categoriesPromise = listCategories();
const cachedNotices = useNoticesStore.getState().notices;
if (!cachedNotices.length) {
await fetchNotices();
}
let notice = useNoticesStore
.getState()
.notices.find((item) => String(item.noticeId) === String(id));
if (!notice) {
notice = await getNoticeById(id);
}
const [categoriesData, imageUrls] = await Promise.all([
categoriesPromise,
getAllImagesByNoticeId(id),
]);
if (isMounted) {
setCategories(categoriesData);
setCurrentNotice({
...notice,
images: imageUrls,
});
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
loadData();
return () => {
isMounted = false;
};
}, [fetchNotices, getAllImagesByNoticeId, id]);
const isOwner = useMemo(() => {
if (!currentNotice) {
return false;
}
return String(currentNotice.clientId) === String(user_id);
}, [currentNotice, user_id]);
const initialValues = useMemo(() => {
if (!currentNotice) {
return null;
}
return {
title: currentNotice.title,
description: currentNotice.description,
price: currentNotice.price,
category: currentNotice.category,
images: currentNotice.images ?? [],
selectedAttributes: mapAttributes(currentNotice),
};
}, [currentNotice]);
const handleSubmit = async (payload) => {
setIsSubmitting(true);
try {
await editNotice(id, payload);
await fetchNotices();
navigate("/dashboard/my-notices");
} finally {
setIsSubmitting(false);
}
};
if (isLoading) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
Ladowanie danych...
</div>
);
}
if (!currentNotice) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
Nie znaleziono ogloszenia.
</div>
);
}
if (!isOwner) {
return (
<div className="space-y-3 rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
<p>Nie masz uprawnien do edycji tego ogloszenia.</p>
<Link className="font-semibold text-primary hover:underline" to="/dashboard/my-notices">
Wroc do moich ogloszen
</Link>
</div>
);
}
return (
<section className="space-y-4">
<h1 className="text-2xl font-bold text-gray-900">Edytuj ogloszenie</h1>
<NoticeForm
categories={categories}
initialValues={initialValues}
isSubmitting={isSubmitting}
key={id}
onSubmit={handleSubmit}
submitLabel="Zapisz zmiany"
/>
</section>
);
}
+2 -2
View File
@@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import { useEffect } from 'react';
import { useNoticesStore } from '../store/noticesStore';
import { useAuthStore } from '../store/authStore';
import { LogOut, Search, PlusCircle, Heart, User } from 'lucide-react';
@@ -9,7 +9,7 @@ export default function Home() {
useEffect(() => {
fetchNotices();
}, []);
}, [fetchNotices]);
const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
+1 -14
View File
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { Eye, EyeOff, ArrowRight } from 'lucide-react';
@@ -112,19 +112,6 @@ export default function Login() {
<span className="px-2 bg-white text-gray-400 font-medium">lub</span>
</div>
</div>
<button
onClick={() => alert("Google Login placeholder")}
className="w-full flex items-center justify-center gap-2 border border-gray-300 py-3 rounded-lg hover:bg-gray-50 transition-colors"
>
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/>
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
</svg>
Zaloguj się przez Google
</button>
</div>
</div>
);
+105
View File
@@ -0,0 +1,105 @@
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import NoticeCard from "../components/NoticeCard";
import { useAuthStore } from "../store/authStore";
import { useNoticesStore } from "../store/noticesStore";
export default function MyNotices() {
const { user_id } = useAuthStore();
const { notices, deleteNotice, fetchNotices } = useNoticesStore();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let isMounted = true;
const loadNotices = async () => {
setIsLoading(true);
try {
await fetchNotices();
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
loadNotices();
return () => {
isMounted = false;
};
}, [fetchNotices]);
const userNotices = useMemo(
() =>
notices
.filter((notice) => String(notice.clientId) === String(user_id))
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate)),
[notices, user_id]
);
const handleDelete = async (noticeId) => {
const confirmed = window.confirm("Usunac ogloszenie?");
if (!confirmed) {
return;
}
await deleteNotice(noticeId);
await fetchNotices();
};
return (
<section className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h1 className="text-2xl font-bold text-gray-900">Moje ogloszenia</h1>
<Link
className="inline-flex rounded-md bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary/90"
to="/notices/create"
>
Dodaj nowe
</Link>
</div>
{isLoading ? (
<div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
Ladowanie...
</div>
) : null}
{!isLoading && userNotices.length === 0 ? (
<div className="rounded-lg border border-dashed border-gray-300 bg-white p-8 text-center text-sm text-gray-600">
Nie masz jeszcze ogloszen.
</div>
) : null}
{!isLoading && userNotices.length > 0 ? (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{userNotices.map((notice) => (
<NoticeCard
actions={
<>
{/* {notice.status === "INACTIVE" ? (*/
<Link
className="rounded-md border border-primary px-3 py-2 text-sm font-semibold text-primary hover:bg-primary/10"
to={`/notices/${notice.noticeId}/edit`}
>
Edytuj
</Link>
/*) : null} */}
<button
className="rounded-md border border-red-300 px-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-50"
onClick={() => handleDelete(notice.noticeId)}
type="button"
>
Usun
</button>
</>
}
key={notice.noticeId}
notice={notice}
/>
))}
</div>
) : null}
</section>
);
}
+199
View File
@@ -0,0 +1,199 @@
import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { getAllImagesByNoticeId, getNoticeById } from "../api/notices";
import { useAuthStore } from "../store/authStore";
import { useNoticesStore } from "../store/noticesStore";
export default function NoticeDetails() {
const { id } = useParams();
const navigate = useNavigate();
const { user_id } = useAuthStore();
const { notices, deleteNotice, fetchNotices } = useNoticesStore();
const [notice, setNotice] = useState(null);
const [images, setImages] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [isImagesLoading, setIsImagesLoading] = useState(true);
useEffect(() => {
let isMounted = true;
const loadNotice = async () => {
setIsLoading(true);
try {
let found = notices.find((item) => String(item.noticeId) === String(id));
if (!found) {
found = await getNoticeById(id);
}
if (isMounted) {
setNotice(found);
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
const loadImages = async () => {
setIsImagesLoading(true);
try {
const imageUrls = await getAllImagesByNoticeId(id);
if (isMounted) {
setImages(imageUrls);
} else {
imageUrls.forEach((imageUrl) => {
if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) {
URL.revokeObjectURL(imageUrl);
}
});
}
} finally {
if (isMounted) {
setIsImagesLoading(false);
}
}
};
loadNotice();
loadImages();
return () => {
isMounted = false;
};
}, [id, notices]);
useEffect(() => {
return () => {
images.forEach((imageUrl) => {
if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) {
URL.revokeObjectURL(imageUrl);
}
});
};
}, [images]);
const isOwner = useMemo(() => {
if (!notice) {
return false;
}
return String(notice.clientId) === String(user_id);
}, [notice, user_id]);
const handleDelete = async () => {
const confirmed = window.confirm("Usunac ogloszenie?");
if (!confirmed) {
return;
}
await deleteNotice(Number(id));
await fetchNotices();
navigate("/dashboard/my-notices");
};
if (isLoading) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
Ladowanie ogloszenia...
</div>
);
}
if (!notice) {
return (
<div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
Nie znaleziono ogloszenia.
</div>
);
}
return (
<section className="space-y-5">
<div className="flex items-start justify-between gap-3">
<div>
<h1 className="text-2xl font-bold text-gray-900">{notice.title}</h1>
<p className="text-sm text-gray-500">{notice.category}</p>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
{isImagesLoading ? (
<div className="flex aspect-4/3 w-full items-center justify-center rounded-lg border border-gray-200 bg-gray-100 sm:col-span-2">
<span
aria-label="Loading images"
className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-primary"
role="status"
/>
</div>
) : images.length > 0 ? (
images.map((image, index) => (
<img
alt={`${notice.title} ${index + 1}`}
className="aspect-4/3 w-full rounded-lg border border-gray-200 bg-gray-100 object-cover"
key={`${image}-${index}`}
src={image}
/>
))
) : (
<div className="flex aspect-4/3 w-full items-center justify-center rounded-lg border border-gray-200 bg-gray-100 sm:col-span-2">
<span className="rounded-md bg-gray-200 px-3 py-1 text-sm font-medium text-gray-600">
No Image
</span>
</div>
)}
<div className="rounded-lg border border-gray-200 bg-white p-4">
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">Opis</h2>
<p className="whitespace-pre-wrap text-gray-700">{notice.description}</p>
<span className="text-2xl font-bold text-primary">{notice.price} zl</span>
</div>
</div>
{Array.isArray(notice.attributes) && notice.attributes.length > 0 ? (
<div className="rounded-lg border border-gray-200 bg-white p-4">
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">
Atrybuty
</h2>
<div className="flex flex-wrap gap-2">
{notice.attributes.map((attr) => (
<span
className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700"
key={`${attr.name}-${attr.value}`}
>
{attr.name}: {attr.value}
</span>
))}
</div>
</div>
) : null}
<div className="flex flex-wrap gap-2">
<Link
className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100"
to="/notices"
>
Wroc do listy
</Link>
{isOwner ? (
<>
{notice.status === "INACTIVE" ? (
<Link
className="rounded-md border border-primary px-4 py-2 text-sm font-semibold text-primary hover:bg-primary/10"
to={`/notices/${notice.noticeId}/edit`}
>
Edytuj
</Link>
) : null}
<button
className="rounded-md border border-red-300 px-4 py-2 text-sm font-semibold text-red-600 hover:bg-red-50"
onClick={handleDelete}
type="button"
>
Usun
</button>
</>
) : null}
</div>
</section>
);
}
+215
View File
@@ -0,0 +1,215 @@
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import NoticeCard from "../components/NoticeCard";
import { listCategories } from "../api/categories";
import { attributes } from "../data/attributesData";
import { useNoticesStore } from "../store/noticesStore";
const sortNotices = (items, sort) => {
if (sort === "latest") {
return [...items].sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));
}
if (sort === "oldest") {
return [...items].sort((a, b) => new Date(a.publishDate) - new Date(b.publishDate));
}
if (sort === "cheapest") {
return [...items].sort((a, b) => Number(a.price) - Number(b.price));
}
if (sort === "expensive") {
return [...items].sort((a, b) => Number(b.price) - Number(a.price));
}
return items;
};
export default function NoticesPage() {
const { notices, fetchNotices } = useNoticesStore();
const [isLoading, setIsLoading] = useState(true);
const [categories, setCategories] = useState([]);
const [search, setSearch] = useState("");
const [category, setCategory] = useState("");
const [sort, setSort] = useState("");
const [priceFrom, setPriceFrom] = useState("");
const [priceTo, setPriceTo] = useState("");
const [selectedAttributes, setSelectedAttributes] = useState({});
useEffect(() => {
let isMounted = true;
const loadData = async () => {
setIsLoading(true);
try {
const [categoriesData] = await Promise.all([listCategories(), fetchNotices()]);
if (isMounted) {
setCategories(categoriesData);
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
loadData();
return () => {
isMounted = false;
};
}, [fetchNotices]);
const filteredNotices = useMemo(() => {
let result = notices.filter((notice) => notice.status === "ACTIVE");
if (category) {
result = result.filter((notice) => notice.category === category);
}
if (search.trim()) {
const searchTerm = search.trim().toLowerCase();
result = result.filter((notice) => notice.title.toLowerCase().includes(searchTerm));
}
if (priceFrom) {
result = result.filter((notice) => Number(notice.price) >= Number(priceFrom));
}
if (priceTo) {
result = result.filter((notice) => Number(notice.price) <= Number(priceTo));
}
Object.entries(selectedAttributes).forEach(([attributeName, attributeValue]) => {
if (!attributeValue) {
return;
}
result = result.filter((notice) =>
notice.attributes?.some(
(attr) => attr.name === attributeName && attr.value === attributeValue
)
);
});
return sortNotices(result, sort);
}, [category, notices, priceFrom, priceTo, search, selectedAttributes, sort]);
const clearFilters = () => {
setSearch("");
setCategory("");
setSort("");
setPriceFrom("");
setPriceTo("");
setSelectedAttributes({});
};
return (
<section className="space-y-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-2xl font-bold text-gray-900">Ogloszenia</h1>
<Link
className="inline-flex rounded-md bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary/90"
to="/notices/create"
>
Dodaj ogloszenie
</Link>
</div>
<div className="space-y-3 rounded-lg border border-gray-200 bg-white p-4">
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
<input
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
onChange={(event) => setSearch(event.target.value)}
placeholder="Szukaj po tytule"
value={search}
/>
<select
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
onChange={(event) => setCategory(event.target.value)}
value={category}
>
<option value="">Wszystkie kategorie</option>
{categories.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
<select
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
onChange={(event) => setSort(event.target.value)}
value={sort}
>
<option value="">Sortowanie</option>
<option value="latest">Najnowsze</option>
<option value="oldest">Najstarsze</option>
<option value="cheapest">Najtansze</option>
<option value="expensive">Najdrozsze</option>
</select>
<button
className="rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100"
onClick={clearFilters}
type="button"
>
Wyczyść filtry
</button>
</div>
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
<input
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
min="0"
onChange={(event) => setPriceFrom(event.target.value)}
placeholder="Cena od"
type="number"
value={priceFrom}
/>
<input
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
min="0"
onChange={(event) => setPriceTo(event.target.value)}
placeholder="Cena do"
type="number"
value={priceTo}
/>
{Object.entries(attributes).map(([label, options]) => (
<select
className="rounded-md border border-gray-300 px-3 py-2 text-sm"
key={label}
onChange={(event) =>
setSelectedAttributes((prev) => ({
...prev,
[label]: event.target.value,
}))
}
value={selectedAttributes[label] ?? ""}
>
<option value="">{label}</option>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
))}
</div>
</div>
{isLoading ? (
<div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
Ladowanie ogloszen...
</div>
) : null}
{!isLoading && filteredNotices.length === 0 ? (
<div className="rounded-lg border border-dashed border-gray-300 bg-white p-8 text-center text-sm text-gray-600">
Brak ogloszen dla wybranych filtrow.
</div>
) : null}
{!isLoading && filteredNotices.length > 0 ? (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{filteredNotices.map((notice) => (
<NoticeCard key={notice.noticeId} notice={notice} />
))}
</div>
) : null}
</section>
);
}
+183
View File
@@ -0,0 +1,183 @@
import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { Eye, EyeOff, ArrowRight } from 'lucide-react';
export default function Registration() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [emailError, setEmailError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [formError, setFormError] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const { signUp, isLoading } = useAuthStore();
const navigate = useNavigate();
const validateEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const handleRegistration = async (e) => {
e.preventDefault();
setFormError('');
if (!email || !password || !confirmPassword) {
setFormError('Proszę uzupełnić wszystkie pola.');
return;
}
if (!validateEmail(email)) {
setEmailError('Nieprawidłowy format adresu email');
return;
}
if (password !== confirmPassword) {
setPasswordError('Hasła nie są takie same');
return;
}
try {
await signUp({ email, password });
navigate('/');
} catch (e) {
setFormError(e.response?.data?.message || e.message || 'Błąd rejestracji');
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
</div>
);
}
return (
<div className="flex items-center justify-center min-h-screen bg-gray-50 px-4">
<div className="w-full max-w-md p-8 bg-white border border-gray-200 rounded-2xl shadow-sm">
<div className="mb-6">
<h1 className="text-3xl font-bold text-gray-900 mb-2">Rejestracja</h1>
<div className="flex items-center text-sm">
<span className="text-gray-500 mr-1">Masz już konto?</span>
<Link to="/login" className="text-primary hover:underline font-medium flex items-center">
Zaloguj się
<ArrowRight size={16} className="ml-1" />
</Link>
</div>
</div>
<form onSubmit={handleRegistration} className="space-y-4">
{formError && <p className="text-red-500 text-sm">{formError}</p>}
<div>
{emailError && <p className="text-red-500 text-xs mb-1">{emailError}</p>}
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
setFormError('');
if (e.target.value && !validateEmail(e.target.value)) {
setEmailError('Nieprawidłowy format adresu email');
} else {
setEmailError('');
}
}}
className={`w-full px-4 py-3 rounded-lg border ${emailError ? 'border-red-500' : 'border-gray-300'} focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all`}
required
/>
</div>
<div className="relative">
<input
type={showPassword ? "text" : "password"}
placeholder="Hasło"
value={password}
onChange={(e) => {
const nextPassword = e.target.value;
setPassword(nextPassword);
setFormError('');
if (confirmPassword && nextPassword !== confirmPassword) {
setPasswordError('Hasła nie są takie same');
} else {
setPasswordError('');
}
}}
className={`w-full px-4 py-3 rounded-lg border ${passwordError ? 'border-red-500' : 'border-gray-300'} focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all`}
required
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
{showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
</button>
</div>
<div className="relative">
{passwordError && <p className="text-red-500 text-xs mb-1">{passwordError}</p>}
<input
type={showConfirmPassword ? "text" : "password"}
placeholder="Potwierdź hasło"
value={confirmPassword}
onChange={(e) => {
const nextConfirmPassword = e.target.value;
setConfirmPassword(nextConfirmPassword);
setFormError('');
if (password && password !== nextConfirmPassword) {
setPasswordError('Hasła nie są takie same');
} else {
setPasswordError('');
}
}}
className={`w-full px-4 py-3 rounded-lg border ${passwordError ? 'border-red-500' : 'border-gray-300'} focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all`}
required
/>
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
{showConfirmPassword ? <EyeOff size={20} /> : <Eye size={20} />}
</button>
</div>
<button
type="submit"
disabled={Boolean(emailError || passwordError)}
className="w-full bg-primary text-white font-bold py-3 rounded-lg hover:bg-primary/90 transition-colors shadow-md shadow-primary/20"
>
Zarejestruj się
</button>
</form>
<div className="relative my-8">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-200"></div>
</div>
<div className="relative flex justify-center text-sm">
<span className="px-2 bg-white text-gray-400 font-medium">lub</span>
</div>
</div>
<button
onClick={() => alert("Google Login placeholder")}
className="w-full flex items-center justify-center gap-2 border border-gray-300 py-3 rounded-lg hover:bg-gray-50 transition-colors"
>
<svg className="w-5 h-5" viewBox="0 0 24 24">
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/>
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
</svg>
Zarejestruj się przez Google
</button>
</div>
</div>
);
}
+32 -16
View File
@@ -1,26 +1,42 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import axios from "axios";
import * as api from "../api/auth";
import apiClient from "../api/api";
let authInterceptorId = null;
const shouldRedirectToLogin = (error) => {
const status = Number(error?.response?.status);
return status === 401 || status === 403;
};
const registerAuthInterceptor = (set) => {
if (authInterceptorId !== null) {
return;
}
authInterceptorId = apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (!shouldRedirectToLogin(error)) {
return Promise.reject(error);
}
set({ user_id: null, token: null, isLoading: false });
delete apiClient.defaults.headers.common["Authorization"];
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
return Promise.reject(error);
}
);
};
export const useAuthStore = create(
persist(
(set, get) => {
// Axios interceptor for handling 401/403
axios.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && (error.response.status === 401 || error.response.status === 403)) {
set({ user_id: null, token: null, isLoading: false });
delete axios.defaults.headers.common["Authorization"];
// Redirect to login using window.location for global interceptor
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
}
return Promise.reject(error);
}
);
registerAuthInterceptor(set);
return {
user_id: null,
+21 -1
View File
@@ -4,6 +4,7 @@ import * as api from "../api/notices";
export const useNoticesStore = create((set, get) => ({
notices: [],
error: null,
fetchNotices: async () => {
set({ error: null });
try {
@@ -31,10 +32,21 @@ export const useNoticesStore = create((set, get) => ({
editNotice: async (noticeId, notice) => {
try {
const hasNewImages = Array.isArray(notice.image)
? notice.image.some((img) => img instanceof File)
: false;
if (hasNewImages) {
const currentImageNames = await api.listImageNamesByNoticeId(noticeId);
for (const filename of currentImageNames) {
await api.deleteImage(filename);
}
}
const updatedNotice = await api.editNotice(noticeId, notice);
set((state) => ({
notices: state.notices.map((n) =>
n.noticeId == noticeId ? updatedNotice : n
n.noticeId === noticeId ? updatedNotice : n
),
}));
return updatedNotice;
@@ -51,6 +63,14 @@ export const useNoticesStore = create((set, get) => ({
);
},
getAllImagesByNoticeId: async (noticeId) => {
try {
return await api.getAllImagesByNoticeId(noticeId);
} catch {
return [];
}
},
deleteNotice: async (noticeId) => {
try {
await api.deleteNotice(noticeId);