fix merge

This commit is contained in:
Patryk
2025-06-09 21:49:07 +02:00
parent a51345fd93
commit a04ef906cd
6 changed files with 246 additions and 351 deletions

View File

@@ -13,6 +13,6 @@ export async function listCategories() {
}); });
return response.data; return response.data;
} catch (err) { } catch (err) {
console.error("Nie udało się pobrać listy kategorii.", err.response.status); // console.error("Nie udało się pobrać listy kategorii.", err.response.status);
} }
} }

View File

@@ -7,10 +7,9 @@ export async function getUserById(userId) {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.get( const response = await axios.get(`${API_URL}/clients/get/${userId}`, {
`${API_URL}/clients/get/${userId}`, headers: headers,
headers });
);
return response.data; return response.data;
} catch (err) { } catch (err) {
console.error( console.error(

View File

@@ -15,15 +15,15 @@ export default function Home() {
const [isReady, setIsReady] = useState(false); const [isReady, setIsReady] = useState(false);
const fetchNotices = useNoticesStore((state) => state.fetchNotices); const fetchNotices = useNoticesStore((state) => state.fetchNotices);
useEffect(() => { // useEffect(() => {
setIsReady(true); // setIsReady(true);
}, []); // }, []);
useEffect(() => { // useEffect(() => {
if (isReady && !token) { // if (isReady && !token) {
router.replace("/login"); // router.replace("/login");
} // }
}, [isReady, token, router]); // }, [isReady, token, router]);
useEffect(() => { useEffect(() => {
if (token) { if (token) {

View File

@@ -5,7 +5,6 @@ import { Heading } from "@/components/ui/heading";
import { Image } from "@/components/ui/image"; import { Image } from "@/components/ui/image";
import { Text } from "@/components/ui/text"; import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack"; import { VStack } from "@/components/ui/vstack";
import { Avatar, AvatarImage, AvatarFallbackText } from "@gluestack-ui/themed";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { import {
ActivityIndicator, ActivityIndicator,
@@ -13,16 +12,14 @@ import {
FlatList, FlatList,
View, View,
TextInput, TextInput,
SafeAreaView, Alert,
} from "react-native"; } from "react-native";
import { useEffect, useState, useRef } from "react"; import { useEffect, useState, useRef } from "react";
import { useNoticesStore } from "@/store/noticesStore"; import { useNoticesStore } from "@/store/noticesStore";
import { useWishlist } from "@/store/wishlistStore"; import { useWishlist } from "@/store/wishlistStore";
import { Pressable, ScrollView } from "react-native"; import { Pressable, ScrollView } from "react-native";
import { getUserById } from "@/api/client"; import { getUserById } from "@/api/client";
import * as ScreenOrientation from "expo-screen-orientation";
import { useAuthStore } from "@/store/authStore"; const { width } = Dimensions.get("window");
import { sendEmail } from "@/api/email";
export default function NoticeDetails() { export default function NoticeDetails() {
const { id } = useLocalSearchParams(); const { id } = useLocalSearchParams();
@@ -33,74 +30,20 @@ export default function NoticeDetails() {
const [notice, setNotice] = useState(null); const [notice, setNotice] = useState(null);
const [user, setUser] = useState(null); const [user, setUser] = useState(null);
const [isUserLoading, setIsUserLoading] = useState(true); const [isUserLoading, setIsUserLoading] = useState(true);
const [isLandscape, setIsLandscape] = useState(false);
const flatListRef = useRef(null); const flatListRef = useRef(null);
const [currentIndex, setCurrentIndex] = useState(0); const [currentIndex, setCurrentIndex] = useState(0);
const [isMessageFormVisible, setIsMessageFormVisible] = useState(false); const [isMessageFormVisible, setIsMessageFormVisible] = useState(false);
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [isSending, setIsSending] = useState(false); const [Email, setEmail] = useState("");
const handleSendMessage = () => {
console.log("Wiadomość do:", user?.email);
console.log("Email nadawcy:", Email);
console.log("Treść:", message);
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.");
Alert.alert("Błąd", "Zaloguj się, aby wysłać wiadomość.");
setIsSending(false);
return;
}
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.");
Alert.alert("Błąd", "Nie znaleziono adresu email zalogowanego użytkownika.");
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("Błąd", "Nie udało się pobrać danych użytkownika. Spróbuj ponownie później.");
setIsSending(false);
return;
}
const emailData = {
to: user?.email || "",
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.");
Alert.alert("Błąd", "Wszystkie pola są wymagane!");
setIsSending(false);
return;
}
const result = await sendEmail(emailData);
if (result.success) {
console.log("Wiadomość wysłana pomyślnie!", result.result);
setIsMessageFormVisible(false); setIsMessageFormVisible(false);
setMessage(""); setMessage("");
Alert.alert("Sukces", "Wiadomość została wysłana!"); setEmail("");
} else {
console.error("Błąd podczas wysyłania wiadomości:", result.error);
Alert.alert("Błąd", `Nie udało się wysłać wiadomości: ${result.error}`);
}
setIsSending(false);
console.log("Zakończono proces wysyłania wiadomości.");
}; };
const formatDate = (dateString) => { const formatDate = (dateString) => {
@@ -118,63 +61,18 @@ export default function NoticeDetails() {
); );
const isInWishlist = useWishlist((state) => const isInWishlist = useWishlist((state) =>
id ? state.wishlistNotices.some((item) => item.noticeId == id) : false id ? state.wishlistNotices.some((item) => item.noticeId === id) : false
); );
const onViewableItemsChanged = useRef(({ viewableItems }) => { const onViewableItemsChanged = useRef(({ viewableItems }) => {
if (viewableItems.length > 0) { if (viewableItems.length > 0) {
setCurrentIndex(viewableItems[0].index); setCurrentIndex(viewableItems[0].index);
} }
}).current;
const viewabilityConfig = useRef({ const viewabilityConfig = useRef({
itemVisiblePercentThreshold: 70, itemVisiblePercentThreshold: 70,
}).current; }).current;
useEffect(() => {
const unlockOrientation = async () => {
try {
await ScreenOrientation.unlockAsync();
} catch (err) {
console.error("Error unlocking orientation:", err);
}
};
const getInitialOrientation = async () => {
try {
const orientation = await ScreenOrientation.getOrientationAsync();
setIsLandscape(
orientation === ScreenOrientation.Orientation.LANDSCAPE_LEFT ||
orientation === ScreenOrientation.Orientation.LANDSCAPE_RIGHT
);
} catch (err) {
console.error("Error getting initial orientation:", err);
}
};
unlockOrientation();
getInitialOrientation();
const subscription = ScreenOrientation.addOrientationChangeListener(
({ orientationInfo }) => {
const isLandscapeMode =
orientationInfo.orientation ===
ScreenOrientation.Orientation.LANDSCAPE_LEFT ||
orientationInfo.orientation ===
ScreenOrientation.Orientation.LANDSCAPE_RIGHT;
setIsLandscape(isLandscapeMode);
}
);
return () => {
ScreenOrientation.removeOrientationChangeListener(subscription);
ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.PORTRAIT_UP
).catch((err) =>
console.error("Error locking orientation on unmount:", err)
);
};
}, []);
useEffect(() => { useEffect(() => {
const fetchNotice = async () => { const fetchNotice = async () => {
setIsLoading(true); setIsLoading(true);
@@ -202,15 +100,14 @@ export default function NoticeDetails() {
if (notice) { if (notice) {
try { try {
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId); const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
console.log("Fetched images:", fetchedImages);
setImages( setImages(
fetchedImages && fetchedImages.length > 0 fetchedImages && fetchedImages.length > 0
? fetchedImages ? fetchedImages
: ["https://http.cat/404.jpg"] : { uri: "https://http.cat/404.jpg" }
); );
} catch (err) { } catch (err) {
console.error("Error while loading images:", err); console.error("Error while loading images:", err);
setImages(["https://http.cat/404.jpg"]); setImage({ uri: "https://http.cat/404.jpg" });
} finally { } finally {
setIsImageLoading(false); setIsImageLoading(false);
} }
@@ -220,10 +117,22 @@ export default function NoticeDetails() {
if (notice) { if (notice) {
fetchImage(); fetchImage();
} }
}, [notice]);
if (!notice) { useEffect(() => {
return <Text>Nie znaleziono ogłoszenia</Text>; const fetchUser = async () => {
if (notice && notice.clientId) {
setIsUserLoading(true);
try {
const userData = await getUserById(notice.clientId);
setUser(userData);
} catch (err) {
console.error("Nie udało się pobrać danych użytkownika:", err);
} finally {
setIsUserLoading(false);
} }
}
};
fetchUser(); fetchUser();
}, [notice]); }, [notice]);
@@ -233,91 +142,80 @@ export default function NoticeDetails() {
} }
if (error) { if (error) {
return <Text>Błąd, spróbuj ponownie źniej: {error.message}</Text>; return <Text>Błąd, spróbuj ponownie żniej: {error.message}</Text>;
} }
if (!notice) { if (!notice) {
return <Text>Nie znaleziono ogłoszenia</Text>; return <Text>Nie znaleziono ogłoszenia</Text>;
} }
const renderImageSection = () => {
if (isImageLoading) {
return ( return (
<Box <Card className="p-0 rounded-lg m-3 flex-1">
className={`h-auto w-full rounded-md ${ <Stack.Screen
isLandscape ? "h-screen" : "aspect-[1/1]" options={{
} bg-gray-100 items-center justify-center`} title: notice.title,
> }}
/>
{isImageLoading ? (
<Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
<ActivityIndicator size="large" color="#3b82f6" /> <ActivityIndicator size="large" color="#3b82f6" />
</Box> </Box>
); ) : (
} <Box className="sticky top-0 z-10 bg-white">
return (
<Box className={isLandscape ? "h-screen" : "sticky top-0 z-10 bg-white"}>
<FlatList <FlatList
ref={flatListRef} ref={flatListRef}
data={images} data={images}
horizontal horizontal
snapToAlignment="center" snapToInterval={width}
snapToAlignment="start"
decelerationRate="fast" decelerationRate="fast"
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
pagingEnabled pagingEnabled
onViewableItemsChanged={onViewableItemsChanged} onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig} viewabilityConfig={viewabilityConfig}
renderItem={({ item, index }) => ( renderItem={({ item, index }) => (
<View style={{ width: Dimensions.get("window").width }}> <View style={{ width: width }} className="p-1">
<Image <Image
source={{ uri: item }} source={item}
className={`h-auto w-full rounded-md ${ className="h-auto w-auto rounded-md aspect-[1/1]"
isLandscape ? "h-full" : "aspect-square"
}`}
alt={`Zdjęcie ${index + 1}`} alt={`Zdjęcie ${index + 1}`}
resizeMode={isLandscape ? "cover" : "contain"} resizeMode="cover"
onError={(e) => console.error("Image load error:", e.nativeEvent.error)}
/> />
</View> </View>
)} )}
keyExtractor={(item, index) => index.toString()} keyExtractor={(item, index) => index.toString()}
/> />
{images.length > 1 && ( {images.length > 1 && (
<Box className="flex-row justify-center mt-2"> <Box className="flex-row justify-center mt-2">
{images.map((_, index) => ( {images.map((_, index) => (
<Box <Box
key={index} key={index}
className={`w-2 h-2 rounded-full mx-1 ${ className={`w-2 h-2 rounded-full mx-1 ${
index === currentIndex ? "bg-primary-500" : "bg-gray-500"} index === currentIndex ? "bg-primary-500" : "bg-gray-300"
}`} }`}
/> />
))} ))}
</Box> </Box>
)} )}
</Box> </Box>
); )}
};
return (
<SafeAreaView style={{ flex: 1 }}>
<Card className="flex-1 p-4 m-3 rounded-lg shadow-sm">
<Stack.Screen
options={{
title: notice.title,
}}
/>
<ScrollView showsVerticalScrollIndicator={false}> <ScrollView showsVerticalScrollIndicator={false}>
{renderImageSection()} <VStack className="p-2">
<VStack className="p-4"> <Text className="text-sm font-normal mb-2 text-typography-700">
<Text className="text-sm font-normal mb-2 text-gray-600">
{formatDate(notice.publishDate)} {formatDate(notice.publishDate)}
</Text> </Text>
<Text className="text-2xl font-bold mb-2 text-center bg-gray-100 rounded-md p-4"> <Text className="text-2xl text-gray-950 font-bold mb-2 text-center bg-gray-50 rounded-md p-2">
{notice.title} {notice.title}
</Text> </Text>
<Box className="flex-row items-center bg-gray-100 rounded-md p-2">
<Heading size="md" className="flex-1 text-lg"> <Box className="flex-row items-center bg-gray-50 rounded-md p-2">
<Text className="text-sm text-gray-500">Cena: </Text> <Heading size="md" className="flex-1 text-xl text-gray-950">
<Text className="text-sm text-typography-500">Cena: </Text>
{notice.price} {notice.price}
</Heading> </Heading>
<Pressable <Pressable
onPress={() => { onPress={() => {
toggleNoticeInWishlist(id); toggleNoticeInWishlist(id);
@@ -326,59 +224,58 @@ export default function NoticeDetails() {
<Ionicons <Ionicons
name={isInWishlist ? "heart" : "heart-outline"} name={isInWishlist ? "heart" : "heart-outline"}
size={24} size={24}
color="#3b82f6" color={"primary-heading-500"}
/> />
</Pressable> </Pressable>
</Box> </Box>
<Box className="mt-4 bg-gray-100 p-3 rounded-lg"> <Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-sm text-gray-500"> <Text className="text-sm text-typography-500">
Kategoria:{" "} Kategoria:{" "}
<Text className="font-bold text-gray-900">{notice.category}</Text> <Text className="font-bold text-gray-950">{notice.category}</Text>
</Text> </Text>
</Box> </Box>
<Box className="mt-4 bg-gray-100 p-3 rounded-lg"> <Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-xl font-bold text-gray-900">Opis ogłoszenia</Text> <Text className="text-2xl text-gray-950">Opis ogloszenia</Text>
<Text className="text-sm text-gray-700">{notice.description}</Text> <Text className="text-sm text-typography-700">
{notice.description}
</Text>
</Box> </Box>
<Box className="mt-4 bg-gray-100 p-3 rounded-lg">
<Text className="text-sm text-gray-500">Użytkownik:</Text> <Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-sm text-typography-500">Uzytkownik:</Text>
{isUserLoading ? ( {isUserLoading ? (
<ActivityIndicator /> <ActivityIndicator />
) : user ? ( ) : user ? (
<> <>
<Box className="mr-4"> <Box className="mr-4">
<Avatar size="md"> <Image
<AvatarImage
source={{ source={{
uri: uri:
user.image || user.profileImage ||
"https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain", "https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain",
}} }} // Domyślny obraz, jeśli brak zdjęcia profilowego
className="h-12 w-12 rounded-full"
alt="Zdjęcie profilowe" alt="Zdjęcie profilowe"
/> />
<AvatarFallbackText>
{user.firstName?.[0]}
{user.lastName?.[0]}
</AvatarFallbackText>
</Avatar>
</Box> </Box>
<Box className="flex-1"> <Box className="flex-1">
<Text className="text-lg font-bold text-gray-900"> <Text className="text-xl font-bold text-gray-950">
{user.firstName} {user.lastName} {user.firstName} {user.lastName}
</Text> </Text>
<Text className="text-sm text-gray-700"> <Text className="text-sm text-typography-700">
Email: {user.email} Email: {user.email}
</Text> </Text>
<Pressable <Pressable
onPress={() => setIsMessageFormVisible(true)} onPress={() => setIsMessageFormVisible(true)}
className="mt-3 bg-blue-500 py-2 px-4 rounded-md" className="mt-3 bg-primary-500 py-2 px-4 rounded-md"
> >
<Text className="text-white text-center font-bold"> <Text className="text-white text-center font-bold">
Wyślij wiadomość Wyślij wiadomość
</Text> </Text>
</Pressable> </Pressable>
<Link href={`/user/${notice.clientId}`}> <Link href={`/user/${notice.clientId}`}>
<Text className="text-lg font-bold text-center text-blue-600 mt-3"> <Text className="text-xl p-3 font-bold text-center text-typography-700 mt-3">
Zobacz więcej ogłoszeń od {user.firstName} Zobacz więcej ogłoszeń od {user.firstName}
</Text> </Text>
</Link> </Link>
@@ -396,15 +293,19 @@ export default function NoticeDetails() {
<Text className="text-lg font-bold mb-4"> <Text className="text-lg font-bold mb-4">
Wyślij wiadomość do {user?.firstName} Wyślij wiadomość do {user?.firstName}
</Text> </Text>
<Text className="text-sm font-medium mb-1">Do:</Text> <Text className="text-sm font-medium mb-1">Do:</Text>
<Text className="bg-gray-100 p-3 rounded text-gray-500"> <Text className="bg-gray-100 p-3 rounded text-gray-500">
{user?.email || "Brak adresu e-mail"} {user?.email || "Brak adresu e-mail"}
</Text> </Text>
<Text className="text-sm font-medium mb-1">Temat:</Text> <Text className="text-sm font-medium mb-1">Twój e-mail:</Text>
<Text className="bg-gray-100 p-3 rounded text-gray-500"> <TextInput
Zapytanie o ogłoszenie '{notice.title || "Brak nazwy ogłoszenia"}' className="border border-gray-300 p-2 rounded"
</Text> placeholder="Wpisz swój adres e-mail"
<Text className="text-sm font-medium mb-1">Treść:</Text> value={Email}
onChangeText={setEmail}
/>
<TextInput <TextInput
className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left" className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left"
multiline multiline
@@ -413,6 +314,7 @@ export default function NoticeDetails() {
value={message} value={message}
onChangeText={setMessage} onChangeText={setMessage}
/> />
<View className="flex-row justify-end space-x-2"> <View className="flex-row justify-end space-x-2">
<Pressable <Pressable
onPress={() => setIsMessageFormVisible(false)} onPress={() => setIsMessageFormVisible(false)}
@@ -420,22 +322,17 @@ export default function NoticeDetails() {
> >
<Text className="text-gray-800">Anuluj</Text> <Text className="text-gray-800">Anuluj</Text>
</Pressable> </Pressable>
<Pressable <Pressable
onPress={handleSendMessage} onPress={handleSendMessage}
className="bg-blue-500 py-2 px-4 rounded-md" className="bg-primary-500 py-2 px-4 rounded-md"
disabled={isSending}
> >
{isSending ? (
<ActivityIndicator color="#fff" />
) : (
<Text className="text-white">Wyślij</Text> <Text className="text-white">Wyślij</Text>
)}
</Pressable> </Pressable>
</View> </View>
</View> </View>
</View> </View>
)} )}
</Card> </Card>
</SafeAreaView>
); );
} }

View File

@@ -1,6 +1,5 @@
import { View, FlatList } from "react-native"; import { View, FlatList } from "react-native";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useAuthStore } from "@/store/authStore";
import { Heading } from "@/components/ui/heading"; import { Heading } from "@/components/ui/heading";
import { Text } from "@/components/ui/text"; import { Text } from "@/components/ui/text";
import { Link } from "expo-router"; import { Link } from "expo-router";
@@ -17,7 +16,6 @@ export function CategorySection({ notices, title }) {
setCategoryMap(data); setCategoryMap(data);
} }
}; };
fetchCategories(); fetchCategories();
}, []); }, []);

View File

@@ -11,22 +11,23 @@ let interceptorInitialized = false;
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set, get) => { (set, get) => {
// if (!interceptorInitialized.current) { if (!interceptorInitialized.current) {
// axios.interceptors.response.use( axios.interceptors.response.use(
// (response) => response, (response) => response,
// (error) => { (error) => {
// if ( if (
// (error.response && error.response.status === 401) || (error.response && error.response.status === 401) ||
// error.response.status === 403 error.response.status === 403
// ) { ) {
// set({ user_id: null, token: null, isLoading: false }); set({ user_id: null, token: null, isLoading: false });
// delete axios.defaults.headers.common["Authorization"]; delete axios.defaults.headers.common["Authorization"];
// } router.replace("/login");
// return Promise.reject(error); }
// } return Promise.reject(error);
// ); }
// interceptorInitialized = true; );
// } interceptorInitialized = true;
}
return { return {
user_id: null, user_id: null,
token: null, token: null,