ADD: Notice CRUD
This commit is contained in:
+18
-9
@@ -1,8 +1,12 @@
|
|||||||
import React from 'react';
|
import { BrowserRouter as Router, Navigate, Route, Routes } from "react-router-dom";
|
||||||
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
import AppLayout from "./components/AppLayout";
|
||||||
import Home from './pages/Home';
|
import Login from "./pages/Login";
|
||||||
import Login from './pages/Login';
|
import CreateNotice from "./pages/CreateNotice";
|
||||||
import { useAuthStore } from './store/authStore';
|
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";
|
||||||
|
|
||||||
const ProtectedRoute = ({ children }) => {
|
const ProtectedRoute = ({ children }) => {
|
||||||
const token = useAuthStore((state) => state.token);
|
const token = useAuthStore((state) => state.token);
|
||||||
@@ -18,14 +22,19 @@ function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<Login />} />
|
<Route path="/login" element={<Login />} />
|
||||||
<Route
|
<Route
|
||||||
path="/"
|
|
||||||
element={
|
element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
<Home />
|
<AppLayout />
|
||||||
</ProtectedRoute>
|
</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 />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</Router>
|
</Router>
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { useAuthStore } from "../store/authStore";
|
||||||
|
|
||||||
|
const API_URL = "/api/v1";
|
||||||
|
|
||||||
|
export async function listCategories() {
|
||||||
|
const { token } = useAuthStore.getState();
|
||||||
|
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||||
|
|
||||||
|
const response = await axios.get(`${API_URL}/vars/categories`, { headers });
|
||||||
|
return Array.isArray(response.data) ? response.data : [];
|
||||||
|
}
|
||||||
+80
-44
@@ -2,10 +2,26 @@ import axios from "axios";
|
|||||||
import { useAuthStore } from "../store/authStore";
|
import { useAuthStore } from "../store/authStore";
|
||||||
|
|
||||||
const API_URL = "/api/v1";
|
const API_URL = "/api/v1";
|
||||||
|
const FALLBACK_IMAGE_URL = "https://http.cat/404.jpg";
|
||||||
|
|
||||||
|
const getAuthHeaders = () => {
|
||||||
|
const { token } = useAuthStore.getState();
|
||||||
|
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildImageUrl = (imageName) => `${API_URL}/images/get/${imageName}`;
|
||||||
|
|
||||||
|
const fetchImageAsBlobUrl = async (imageUrl) => {
|
||||||
|
const headers = getAuthHeaders();
|
||||||
|
const response = await axios.get(imageUrl, {
|
||||||
|
headers,
|
||||||
|
responseType: "blob",
|
||||||
|
});
|
||||||
|
return URL.createObjectURL(response.data);
|
||||||
|
};
|
||||||
|
|
||||||
export async function listNotices() {
|
export async function listNotices() {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
||||||
|
|
||||||
const response = await fetch(`${API_URL}/notices/get/all`, {
|
const response = await fetch(`${API_URL}/notices/get/all`, {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
@@ -19,7 +35,10 @@ export async function listNotices() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getNoticeById(noticeId) {
|
export async function getNoticeById(noticeId) {
|
||||||
const response = await fetch(`${API_URL}/notices/get/${noticeId}`);
|
const headers = getAuthHeaders();
|
||||||
|
const response = await fetch(`${API_URL}/notices/get/${noticeId}`, {
|
||||||
|
headers,
|
||||||
|
});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Error fetching notice");
|
throw new Error("Error fetching notice");
|
||||||
@@ -28,16 +47,28 @@ export async function getNoticeById(noticeId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function createNotice(notice) {
|
export async function createNotice(notice) {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
||||||
|
const payload = {
|
||||||
|
title: notice.title,
|
||||||
|
description: notice.description,
|
||||||
|
price: notice.price,
|
||||||
|
category: notice.category,
|
||||||
|
status: notice.status,
|
||||||
|
attributes: notice.attributes,
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axios.post(`${API_URL}/notices/add`, notice, {
|
const response = await axios.post(`${API_URL}/notices/add`, payload, {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.data.noticeId !== null && notice.image) {
|
if (response.data.noticeId !== null && notice.image) {
|
||||||
for (let i = 0; i < notice.image.length; i++) {
|
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,41 +80,48 @@ export async function createNotice(notice) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getImageByNoticeId(noticeId) {
|
export async function getImageByNoticeId(noticeId) {
|
||||||
|
const headers = getAuthHeaders();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
|
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {
|
||||||
|
headers,
|
||||||
|
});
|
||||||
const imageName = listResponse.data[0];
|
const imageName = listResponse.data[0];
|
||||||
return `${API_URL}/images/get/${imageName}`;
|
if (!imageName) {
|
||||||
} catch (err) {
|
return FALLBACK_IMAGE_URL;
|
||||||
return "https://http.cat/404.jpg";
|
}
|
||||||
|
return await fetchImageAsBlobUrl(buildImageUrl(imageName));
|
||||||
|
} catch {
|
||||||
|
return FALLBACK_IMAGE_URL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllImagesByNoticeId(noticeId) {
|
export async function getAllImagesByNoticeId(noticeId) {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
||||||
try {
|
try {
|
||||||
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {
|
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (listResponse.data && listResponse.data.length > 0) {
|
if (listResponse.data && listResponse.data.length > 0) {
|
||||||
return listResponse.data.map((imageName) => ({
|
return await Promise.all(
|
||||||
uri: `${API_URL}/images/get/${imageName}`,
|
listResponse.data.map(async (imageName) => {
|
||||||
headers: headers,
|
try {
|
||||||
}));
|
return await fetchImageAsBlobUrl(buildImageUrl(imageName));
|
||||||
|
} catch {
|
||||||
|
return FALLBACK_IMAGE_URL;
|
||||||
}
|
}
|
||||||
return [{ uri: "https://http.cat/404.jpg" }];
|
})
|
||||||
} catch (err) {
|
);
|
||||||
return [{ uri: "https://http.cat/404.jpg" }];
|
}
|
||||||
|
return [FALLBACK_IMAGE_URL];
|
||||||
|
} catch {
|
||||||
|
return [FALLBACK_IMAGE_URL];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const uploadImage = async (noticeId, file, isFirst) => {
|
export const uploadImage = async (noticeId, file, isFirst) => {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = {
|
|
||||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
||||||
"Content-Type": "multipart/form-data",
|
|
||||||
};
|
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append("file", file);
|
formData.append("file", file);
|
||||||
|
|
||||||
@@ -101,25 +139,16 @@ export const uploadImage = async (noticeId, file, isFirst) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const deleteNotice = async (noticeId) => {
|
export const deleteNotice = async (noticeId) => {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await axios.delete(
|
const response = await axios.delete(
|
||||||
`${API_URL}/notices/delete/${noticeId}`,
|
`${API_URL}/notices/delete/${noticeId}`,
|
||||||
{ headers: headers }
|
{ headers: headers }
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const editNotice = async (noticeId, notice) => {
|
export const editNotice = async (noticeId, notice) => {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await axios.put(
|
const response = await axios.put(
|
||||||
`${API_URL}/notices/edit/${noticeId}`,
|
`${API_URL}/notices/edit/${noticeId}`,
|
||||||
{
|
{
|
||||||
@@ -143,22 +172,29 @@ export const editNotice = async (noticeId, notice) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteImage = async (filename) => {
|
export const deleteImage = async (filename) => {
|
||||||
const { token } = useAuthStore.getState();
|
const headers = getAuthHeaders();
|
||||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await axios.delete(
|
const response = await axios.delete(
|
||||||
`${API_URL}/images/delete/${filename}`,
|
`${API_URL}/images/delete/${filename}`,
|
||||||
{ headers: headers }
|
{ headers: headers }
|
||||||
);
|
);
|
||||||
return response.data;
|
return response.data;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listImageNamesByNoticeId(noticeId) {
|
||||||
|
const headers = getAuthHeaders();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${API_URL}/images/list/${noticeId}`, {
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
return Array.isArray(response.data) ? response.data : [];
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (error.response?.status === 404) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
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("https://http.cat/404.jpg");
|
||||||
|
const [categoryLabel, setCategoryLabel] = useState(notice?.category || "");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isMounted = true;
|
||||||
|
|
||||||
|
const loadImage = async () => {
|
||||||
|
if (!notice?.noticeId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const image = await getImageByNoticeId(notice.noticeId);
|
||||||
|
if (isMounted) {
|
||||||
|
setImageUrl(image);
|
||||||
|
} else if (typeof image === "string" && image.startsWith("blob:")) {
|
||||||
|
URL.revokeObjectURL(image);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (isMounted) {
|
||||||
|
setImageUrl("https://http.cat/404.jpg");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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}`}>
|
||||||
|
<img
|
||||||
|
alt={notice.title}
|
||||||
|
className="aspect-square w-full bg-gray-100 object-cover"
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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",
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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.filter((url) => !url.includes("http.cat/404.jpg")),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} 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
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect } from 'react';
|
import { useEffect } from 'react';
|
||||||
import { useNoticesStore } from '../store/noticesStore';
|
import { useNoticesStore } from '../store/noticesStore';
|
||||||
import { useAuthStore } from '../store/authStore';
|
import { useAuthStore } from '../store/authStore';
|
||||||
import { LogOut, Search, PlusCircle, Heart, User } from 'lucide-react';
|
import { LogOut, Search, PlusCircle, Heart, User } from 'lucide-react';
|
||||||
@@ -9,7 +9,7 @@ export default function Home() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchNotices();
|
fetchNotices();
|
||||||
}, []);
|
}, [fetchNotices]);
|
||||||
|
|
||||||
const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
|
const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useNavigate, Link } from 'react-router-dom';
|
import { useNavigate, Link } from 'react-router-dom';
|
||||||
import { useAuthStore } from '../store/authStore';
|
import { useAuthStore } from '../store/authStore';
|
||||||
import { Eye, EyeOff, ArrowRight } from 'lucide-react';
|
import { Eye, EyeOff, ArrowRight } from 'lucide-react';
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
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);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isMounted = true;
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
let found = notices.find((item) => String(item.noticeId) === String(id));
|
||||||
|
if (!found) {
|
||||||
|
found = await getNoticeById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageUrls = await getAllImagesByNoticeId(id);
|
||||||
|
if (isMounted) {
|
||||||
|
setNotice(found);
|
||||||
|
setImages(imageUrls);
|
||||||
|
} else {
|
||||||
|
imageUrls.forEach((imageUrl) => {
|
||||||
|
if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) {
|
||||||
|
URL.revokeObjectURL(imageUrl);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (isMounted) {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadData();
|
||||||
|
|
||||||
|
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">
|
||||||
|
{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="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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import * as api from "../api/notices";
|
|||||||
export const useNoticesStore = create((set, get) => ({
|
export const useNoticesStore = create((set, get) => ({
|
||||||
notices: [],
|
notices: [],
|
||||||
error: null,
|
error: null,
|
||||||
|
|
||||||
fetchNotices: async () => {
|
fetchNotices: async () => {
|
||||||
set({ error: null });
|
set({ error: null });
|
||||||
try {
|
try {
|
||||||
@@ -31,6 +32,17 @@ export const useNoticesStore = create((set, get) => ({
|
|||||||
|
|
||||||
editNotice: async (noticeId, notice) => {
|
editNotice: async (noticeId, notice) => {
|
||||||
try {
|
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);
|
const updatedNotice = await api.editNotice(noticeId, notice);
|
||||||
set((state) => ({
|
set((state) => ({
|
||||||
notices: state.notices.map((n) =>
|
notices: state.notices.map((n) =>
|
||||||
@@ -51,6 +63,14 @@ export const useNoticesStore = create((set, get) => ({
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getAllImagesByNoticeId: async (noticeId) => {
|
||||||
|
try {
|
||||||
|
return await api.getAllImagesByNoticeId(noticeId);
|
||||||
|
} catch {
|
||||||
|
return ["https://http.cat/404.jpg"];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
deleteNotice: async (noticeId) => {
|
deleteNotice: async (noticeId) => {
|
||||||
try {
|
try {
|
||||||
await api.deleteNotice(noticeId);
|
await api.deleteNotice(noticeId);
|
||||||
|
|||||||
Reference in New Issue
Block a user