add edit notice and clean code

This commit is contained in:
Patryk
2025-06-11 20:56:39 +02:00
parent b323f02654
commit 3c042d2cfb
7 changed files with 118 additions and 67 deletions

View File

@@ -40,12 +40,9 @@ export async function createNotice(notice) {
if (response.data.noticeId !== null) {
for (const image of notice.image) {
console.log("image", image);
if(notice.image.indexOf(image) === 0) {
console.log("Image is first:", image);
if (notice.image.indexOf(image) === 0) {
await uploadImage(response.data.noticeId, image, true);
}
console.log("image", image);
await uploadImage(response.data.noticeId, image, false);
}
}
@@ -67,7 +64,6 @@ export async function getImageByNoticeId(noticeId) {
return imageUrl;
} catch (err) {
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
imageUrl = "https://http.cat/404.jpg";
return imageUrl;
}
@@ -77,7 +73,9 @@ export async function getAllImagesByNoticeId(noticeId) {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {headers: headers});
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, {
headers: headers,
});
if (listResponse.data && listResponse.data.length > 0) {
return listResponse.data.map((imageName) => ({
@@ -104,7 +102,7 @@ export const uploadImage = async (noticeId, imageObj, isFirst) => {
const { token } = useAuthStore.getState();
const headers = {
...(token ? { Authorization: `Bearer ${token}` } : {}),
'Content-Type': 'multipart/form-data'
"Content-Type": "multipart/form-data",
};
const formData = new FormData();
@@ -130,8 +128,6 @@ export const uploadImage = async (noticeId, imageObj, isFirst) => {
console.info("Upload successful:", response.data);
return response.data;
} catch (error) {
console.log("imageURI:", imageObj);
console.error(
"Error uploading image:",
error.response.data,
@@ -160,3 +156,65 @@ export const deleteNotice = async (noticeId) => {
throw error;
}
};
export const editNotice = async (noticeId, notice) => {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
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];
const isFirst = i == 0;
if (typeof image === "string" && !image.startsWith("http")) {
await uploadImage(noticeId, image, isFirst);
}
}
}
return response.data;
} catch (error) {
console.error(
"Error editing notice:",
error.response?.data,
error.response?.status
);
throw error;
}
};
export const deleteImage = async (filename) => {
const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {};
try {
const response = await axios.delete(
`${API_URL}/images/delete/${filename}`,
{ headers: headers }
);
return response.data;
} catch (error) {
console.error(
"Error deleting image:",
error.response?.data,
error.response?.status
);
throw error;
}
};

View File

@@ -31,7 +31,7 @@ import { ChevronDownIcon } from "@/components/ui/icon";
import { useNoticesStore } from "@/store/noticesStore";
import { listCategories } from "@/api/categories";
import { useRouter } from "expo-router";
import { attributes } from "@/data/attributesData"; // Assuming you have a separate file for attributes data}
import { attributes } from "@/data/attributesData";
import { useLocalSearchParams } from "expo-router";
export default function EditNotice() {
@@ -43,7 +43,6 @@ export default function EditNotice() {
const [price, setPrice] = useState("");
const [category, setCategory] = useState("");
const [image, setImage] = useState([]);
const [images, setImages] = useState([]);
const [isImageLoading, setIsImageLoading] = useState(true);
const [selectItems, setSelectItems] = useState([]);
const [isLoading, setIsLoading] = useState(false);
@@ -84,7 +83,6 @@ export default function EditNotice() {
attributesObj[attr.name] = attr.value;
});
setSelectedAttributes(attributesObj);
// console.log("Attributes loaded:", attributesObj);
}
}
@@ -92,20 +90,13 @@ export default function EditNotice() {
setIsImageLoading(true);
try {
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
console.log("Fetched images:", fetchedImages);
if (fetchedImages && fetchedImages.length > 0) {
const imageUris = fetchedImages.map((img) => img.uri);
setImages(fetchedImages);
setImage(imageUris);
console.log("Image URIs set:", imageUris);
setImage(fetchedImages);
} else {
setImages([]);
setImage([]);
}
} catch (err) {
console.error("Error while loading images:", err);
setImages([]);
setImage([]);
} finally {
setIsImageLoading(false);
@@ -115,7 +106,7 @@ export default function EditNotice() {
if (notice) {
fetchImage();
}
}, [notices]);
}, [notices, id]);
const [error, setError] = useState({
title: false,
@@ -154,10 +145,9 @@ export default function EditNotice() {
value: value,
})
);
// console.log("Selected attributes:", formattedAttributes);
setIsLoading(true);
try {
const result = await editNotice({
const result = await editNotice(id, {
title: title,
description: description,
price: price,
@@ -168,14 +158,12 @@ export default function EditNotice() {
});
if (result) {
console.log("Notice created successfully with ID: ", result.noticeId);
await fetchNotices();
clearForm();
router.push("/(tabs)/dashboard/userNotices");
}
} catch (error) {
console.error("Error creating notice. Error message: ", error.message);
console.error("Error editing notice. Error message: ", error.message);
} finally {
setIsLoading(false);
}
@@ -210,27 +198,12 @@ export default function EditNotice() {
}
};
const clearForm = () => {
setTitle("");
setDescription("");
setPrice("");
setCategory("");
setImage([]);
setSelectedAttributes({});
setError({
title: false,
description: false,
price: false,
category: false,
});
};
if (isLoading) {
return (
<Box className="items-center justify-center flex-1">
<ActivityIndicator size="large" color="#787878" />
<Text size="md" bold="true" className="mt-5">
Dodajemy ogłoszenie...
Edytuj ogłoszenie...
</Text>
</Box>
);
@@ -258,14 +231,22 @@ export default function EditNotice() {
</Text>
{image && image.length > 0 && (
<VStack space="xs" className="flex-row flex-wrap">
{image.map((img, index) => (
{image.map((img, index) => {
const imageSource =
typeof img === "string" ? { uri: img } : img;
return (
<Image
key={index}
source={{ uri: img }}
source={imageSource}
style={styles.image}
className="m-1"
onError={(error) =>
console.log(`Image ${index} error:`, error)
}
/>
))}
);
})}
</VStack>
)}
</VStack>
@@ -381,7 +362,7 @@ export default function EditNotice() {
onPress={handleEditNotice}
disabled={isLoading}
>
<ButtonText className="text-typography-0">Dodaj</ButtonText>
<ButtonText className="text-typography-0">Edytuj</ButtonText>
</Button>
</VStack>
</FormControl>

View File

@@ -162,7 +162,6 @@ export default function UserNotices() {
<Button
className="ml-2"
onPress={() => {
console.log("Edytuj notice");
router.replace(
`dashboard/notice/edit/${item.noticeId}`
);

View File

@@ -94,7 +94,6 @@ export default function CreateNotice() {
});
if (!title || !description || !price || !category) {
console.log("Error in form");
return;
}
const formattedAttributes = Object.entries(selectedAttributes).map(
@@ -103,7 +102,6 @@ export default function CreateNotice() {
value: value,
})
);
// console.log("Selected attributes:", formattedAttributes);
setIsLoading(true);
try {
const result = await addNotice({

View File

@@ -134,7 +134,6 @@ export default function Notices() {
Object.keys(params).forEach((key) => {
if (key.startsWith("attribute_")) {
// console.log("Filtering by attribute:", key);
const attributeName = key.replace("attribute_", "");
const attributeValue = params[key];
@@ -207,7 +206,6 @@ export default function Notices() {
newParams[`attribute_${attributeName}`] = value;
}
// console.log("New Params:", newParams);
router.replace({
pathname: "/notices",
params: newParams,
@@ -250,8 +248,6 @@ export default function Notices() {
categories?.find((cat) => cat.value === params.category)) ||
null;
// console.log("Filtered Notices:", filteredNotices);
return (
<>
<Box

View File

@@ -54,10 +54,8 @@ export default function NoticeDetails() {
const handleSendMessage = async () => {
setIsSending(true);
console.log("Rozpoczynanie procesu wysyłania wiadomości...");
const { user_id, token } = useAuthStore.getState();
console.log("Dane z authStore:", { user_id, token });
if (!user_id || !token) {
console.error("Brak danych zalogowanego użytkownika.");
@@ -68,9 +66,7 @@ export default function NoticeDetails() {
let currentUserEmail = "";
try {
console.log(`Pobieranie danych użytkownika dla user_id : $ { user_id }`);
const currentUser = await getUserById(user_id);
console.log("Dane zalogowanego użytkownika:", currentUser);
currentUserEmail = currentUser?.email;
if (!currentUserEmail) {
console.error("Nie znaleziono adresu email zalogowanego użytkownika.");
@@ -81,8 +77,6 @@ export default function NoticeDetails() {
setIsSending(false);
return;
}
console.log(`Pobrano email zalogowanego użytkownika
: $ { currentUserEmail }`);
} catch (error) {
console.error("Błąd podczas pobierania danych użytkownika:", error);
Alert.alert(
@@ -98,7 +92,6 @@ export default function NoticeDetails() {
subject: `Zapytanie ${currentUserEmail} o ogłoszenie ${notice.title}`,
body: message,
};
console.log("Dane emaila do wysyłki:", emailData);
if (!emailData.to || !emailData.subject || !emailData.body) {
console.error("Walidacja nieudana: brakujące pola w emailData.");
@@ -109,7 +102,6 @@ export default function NoticeDetails() {
const result = await sendEmail(emailData);
if (result.success) {
console.log("Wiadomość wysłana pomyślnie!", result.result);
setIsMessageFormVisible(false);
setMessage("");
Alert.alert("Sukces", "Wiadomość została wysłana!");
@@ -122,7 +114,6 @@ export default function NoticeDetails() {
);
}
setIsSending(false);
console.log("Zakończono proces wysyłania wiadomości.");
};
const formatDate = (dateString) => {

View File

@@ -26,6 +26,34 @@ export const useNoticesStore = create((set, get) => ({
}
},
editNotice: async (noticeId, notice) => {
try {
if (notice.image.length > 0 && typeof notice.image[0] == "string") {
const currentImages = await api.getAllImagesByNoticeId(noticeId);
if (currentImages && currentImages.length > 0) {
for (const image of currentImages) {
const filename = image.uri
? image.uri.split("/").pop()
: image.split("/").pop();
await api.deleteImage(filename);
}
}
}
const updatedNotice = await api.editNotice(noticeId, notice);
set((state) => ({
notices: state.notices.map((n) =>
n.noticeId == noticeId ? updatedNotice : n
),
}));
return updatedNotice;
} catch (error) {
console.error("Error editing notice:", error);
set({ error });
throw error;
}
},
getNoticeById: (noticeId) => {
return get().notices.find(
(notice) => String(notice.noticeId) === String(noticeId)