11 Commits

Author SHA1 Message Date
7ec883100f headers user is hidden, [userId] is changed to "Ogłsozenia uzytkownika" 2025-06-09 21:12:10 +02:00
c25495ba3f AppIco added 2025-06-09 20:51:09 +02:00
be51f1e9cc Mail sender is working 2025-06-09 20:39:00 +02:00
14bd178f84 Mail sender is working 2025-06-09 20:38:13 +02:00
7fc1312ddc Avatar + SafeAreaView 2025-06-09 19:27:05 +02:00
1d3cbeef3a Added ScreenRotation to notice and updated userNotices 2025-06-08 17:22:02 +02:00
Patryk
dbf07cea0a improve account style 2025-06-08 11:23:09 +02:00
Patryk
e2e5543e0d fix notice status 2025-06-08 10:30:14 +02:00
Patryk
ca59c94783 del duplicate url 2025-06-08 09:52:13 +02:00
Patryk
e849a39603 Merge remote-tracking branch 'origin/integrateWithAuth' 2025-06-08 09:39:56 +02:00
0e46d692f9 fix of api url and new version packages 2025-06-06 16:31:39 +02:00
14 changed files with 1535 additions and 721 deletions

View File

@@ -0,0 +1,30 @@
import { useAuthStore } from "@/store/authStore";
const API_URL = "https://hopp.zikor.pl/api/v1";
export const sendEmail = async (emailData) => {
const token = useAuthStore.getState().token;
try {
const response = await fetch(`${API_URL}/email/send`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token && { Authorization: `Bearer ${token}` }),
},
body: JSON.stringify(emailData),
});
if (!response.ok) {
const errorMessage = `HTTP error! Status: ${response.status}`;
console.error("Error przy wysyłaniu maila", errorMessage);
return { success: false, error: errorMessage };
}
const result = await response.text();
return { success: true, result };
} catch (error) {
console.error("Error przy wysyłaniu maila:", error.message);
return { success: false, error: error.message };
}
};

View File

@@ -0,0 +1,12 @@
import axios from "axios";
import FormData from "form-data";
const API_URL = "https://hopp.zikor.pl/api/v1";
export async function listOrders() {
const response = await fetch(`${API_URL}/orders/get/all`);
const data = await response.json();
if (!response.ok) {
throw new Error(response.toString());
}
return data;
}

View File

@@ -5,7 +5,7 @@
"scheme": "com.hamx.artisanconnect",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"icon": "./assets/AppIco.png",
"userInterfaceStyle": "light",
"newArchEnabled": true,
"splash": {

View File

@@ -8,12 +8,12 @@ import { ActivityIndicator } from "react-native";
import { useEffect, useState } from "react";
import { getUserById } from "@/api/client";
import { HStack } from "@gluestack-ui/themed";
import { useAuthStore } from "@/store/authStore";
export default function Account() {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const currentUserId = 2; // Tymczasowo, do czasu zaimplementowania logowania bo nie moge pobrac usera
const currentUserId = useAuthStore((state) => state.user_id);
useEffect(() => {
const fetchUser = async () => {
setIsLoading(true);
@@ -37,9 +37,10 @@ export default function Account() {
return <Text>Nie udało się pobrać danych użytkownika.</Text>;
}
console.log(user);
return (
<VStack className="bg-gray-50 flex-1">
<Box className="bg-white pb-6 shadow-sm">
<VStack className=" flex-1 m-2">
<Box className="bg-white p-5 rounded-lg ">
<Box className="items-center pt-6 mb-4">
<Image
source={{
@@ -57,12 +58,12 @@ export default function Account() {
</Text>
</Box>
<Box className="bg-white mt-4 p-5 border-t border-b border-gray-200">
<Box className="bg-white mt-4 p-5 rounded-lg">
<Text className="font-bold text-lg mb-3">Moje dane</Text>
<HStack className="mb-3">
<Text className="text-gray-600 w-24">E-mail</Text>
<Text className="flex-1">{user.email || "brak danych"}</Text>
<Text className="text-gray-600 w-24">E-mail: </Text>
<Text className=" text-gray-600 ">{user.email}</Text>
</HStack>
<Pressable
@@ -73,7 +74,7 @@ export default function Account() {
</Pressable>
</Box>
<Box className="bg-white mt-4 p-5">
<Box className="bg-white mt-4 p-5 rounded-lg">
<Text className="font-bold text-lg mb-3">Moje konto</Text>
<Link href="/dashboard/userNotices" asChild>

View File

@@ -1,16 +1,17 @@
import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard";
import {Button} from "react-native";
import {Box} from "@/components/ui/box";
import {Text} from "@/components/ui/text";
import {VStack} from "@/components/ui/vstack";
import {ActivityIndicator, FlatList } from "react-native";
import {useEffect, useState} from "react";
import { Button } from "react-native";
import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { ActivityIndicator, FlatList } from "react-native";
import { useEffect, useState } from "react";
import {useAuthStore} from "@/store/authStore";
export default function UserNotices() {
const { notices, fetchNotices } = useNoticesStore();
const currentUserId = useAuthStore((state) => state.user_id);
const [isLoading, setIsLoading] = useState(true);
const currentUserId = 1; // Tymczasowo, do czasu zaimplementowania logowania bo nie moge pobrac usera
useEffect(() => {
const loadNotices = async () => {
@@ -24,52 +25,65 @@ export default function UserNotices() {
}
};
loadNotices();
}, []);
}, [fetchNotices]);
const userNotices = notices.filter(notice => notice.clientId === currentUserId);
const userNotices = notices
.filter((notice) => notice.clientId === currentUserId)
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));
if (isLoading) {
return <ActivityIndicator />;
}
return (
<VStack className="p-4">
<Text className="text-2xl font-bold mb-4">Moje ogłoszenia</Text>
{userNotices.length > 0 ? (
<FlatList
data={userNotices}
numColumns={2}
columnWrapperStyle={{ marginBottom: 10, justifyContent: "space-between" }}
renderItem={({ item }) => (
<Box className="flex-1">
<NoticeCard notice={item} />
<Box className="flex-row justify-between mt-2">
<Button
title="Promuj"
onPress={() => {
// TODO: Implementacja promocji ogłoszenia
console.log(`Promuj ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
>
</Button>
<Button
title="Podbij"
onPress={() => {
// TODO: Implementacja podbicia ogłoszenia
console.log(`Podbij ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
>
</Button>
</Box>
</Box>
<VStack className="p-2">
{/* <Text className="text-2xl font-bold mb-4">Moje ogłoszenia</Text> */}
{userNotices.length > 0 ? (
<FlatList
data={userNotices}
// numColumns={1}
// columnWrapperStyle={{
// marginBottom: 10,
// justifyContent: "space-between",
// }}
renderItem={({ item }) => (
<Box className="flex-1 mb-4 pb-2 bg-white rounded-lg">
<NoticeCard notice={item} />
<Box className="flex-row justify-between mt-2">
{item.status === "ACTIVE" ? (
<Button
title="Usuń"
onPress={() => {
console.log(`Promuj ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
></Button>
) : (
<Button
title="Aktywj"
onPress={() => {
console.log(`Promuj ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
></Button>
)}
keyExtractor={(item) => item.noticeId.toString()}
/>
) : (
<Text>Nie masz żadnych ogłoszeń.</Text>
)}
</VStack>
<Button
title="Podbij"
onPress={() => {
// TODO: Implementacja podbicia ogłoszenia
console.log(`Podbij ogłoszenie ${item.noticeId}`);
}}
className="bg-primary-500 py-2 px-4 rounded-md"
></Button>
</Box>
</Box>
)}
keyExtractor={(item) => item.noticeId.toString()}
/>
) : (
<Text>Nie masz żadnych ogłoszeń.</Text>
)}
</VStack>
);
}
}

View File

@@ -34,11 +34,14 @@ export default function Home() {
const notices = useNoticesStore((state) => state.notices);
// console.log("Notices:", notices);
// console.log("Notices length:", notices.length);
const latestNotices = [...notices]
const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
// console.log("Activer Notices:", activeNotices.length);
const latestNotices = [...activeNotices]
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))
.slice(0, 6);
const recomendedNotices = [...notices]
const recomendedNotices = [...activeNotices]
.sort(() => Math.random() - 0.5)
.slice(0, 6);
@@ -47,13 +50,13 @@ export default function Home() {
{/* <View> */}
<SearchSection />
<ScrollView showsVerticalScrollIndicator={false}>
<CategorySection title="Polecane kategorie" notices={notices} />
<CategorySection title="Polecane kategorie" notices={activeNotices} />
<NoticeSection
title="Najnowsze ogłoszenia"
notices={latestNotices}
ctaLink="/notices?sort=latest"
/>
<UserSection title="Popularni sprzedawcy" notices={notices} />
<UserSection title="Popularni sprzedawcy" notices={activeNotices} />
<NoticeSection
title="Proponowane ogłoszenia"
notices={recomendedNotices}

View File

@@ -1,4 +1,10 @@
import { FlatList, Text, ActivityIndicator, RefreshControl, Dimensions } from "react-native";
import {
FlatList,
Text,
ActivityIndicator,
RefreshControl,
Dimensions,
} from "react-native";
import { useState, useEffect } from "react";
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { useNoticesStore } from "@/store/noticesStore";
@@ -11,345 +17,372 @@ import { listCategories } from "@/api/categories";
import { FormControl, FormControlLabel } from "@/components/ui/form-control";
import { Input, InputField } from "@/components/ui/input";
import { HStack } from "@/components/ui/hstack";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { KeyboardAvoidingView, Platform } from "react-native";
import {
Actionsheet,
ActionsheetContent,
ActionsheetItem,
ActionsheetItemText,
ActionsheetDragIndicator,
ActionsheetDragIndicatorWrapper,
ActionsheetBackdrop,
Actionsheet,
ActionsheetContent,
ActionsheetItem,
ActionsheetItemText,
ActionsheetDragIndicator,
ActionsheetDragIndicatorWrapper,
ActionsheetBackdrop,
} from "@/components/ui/actionsheet";
import {
Select,
SelectTrigger,
SelectInput,
SelectIcon,
SelectPortal,
SelectBackdrop,
SelectContent,
SelectDragIndicator,
SelectDragIndicatorWrapper,
SelectItem,
Select,
SelectTrigger,
SelectInput,
SelectIcon,
SelectPortal,
SelectBackdrop,
SelectContent,
SelectDragIndicator,
SelectDragIndicatorWrapper,
SelectItem,
} from "@/components/ui/select";
import { ScrollView } from "react-native-gesture-handler";
export default function Notices() {
// Hooks
const { notices, fetchNotices } = useNoticesStore();
const [refreshing, setRefreshing] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [showActionsheet, setShowActionsheet] = useState(false);
const [showSortSheet, setShowSortSheet] = useState(false);
const [categories, setCategories] = useState([]);
const [filteredNotices, setFilteredNotices] = useState([]);
const params = useLocalSearchParams();
const router = useRouter();
// Hooks
const { notices, fetchNotices } = useNoticesStore();
const [refreshing, setRefreshing] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [showActionsheet, setShowActionsheet] = useState(false);
const [showSortSheet, setShowSortSheet] = useState(false);
const [categories, setCategories] = useState([]);
const [filteredNotices, setFilteredNotices] = useState([]);
const params = useLocalSearchParams();
const router = useRouter();
useEffect(() => {
const fetchSelectItems = async () => {
try {
const data = await listCategories();
if (Array.isArray(data)) {
setCategories(data);
} else {
console.error('listCategories did not return an array:', data);
setError(new Error('Invalid categories data'));
}
} catch (error) {
console.error('Error fetching select items:', error);
setError(error);
}
};
fetchSelectItems();
}, []);
useEffect(() => {
loadData();
}, []);
useEffect(() => {
let result = notices;
if (params.category) {
result = result.filter(notice => notice.category === params.category);
useEffect(() => {
const fetchSelectItems = async () => {
try {
const data = await listCategories();
if (Array.isArray(data)) {
setCategories(data);
} else {
console.error("listCategories did not return an array:", data);
setError(new Error("Invalid categories data"));
}
} catch (error) {
console.error("Error fetching select items:", error);
setError(error);
}
};
fetchSelectItems();
}, []);
if (params.sort) {
if( params.sort == "latest"){
result = [...result].sort(
(a, b) => new Date(b.publishDate) - new Date(a.publishDate)
);
}else if (params.sort == "oldest") {
result = [...result].sort(
(a, b) => new Date(a.publishDate) - new Date(b.publishDate)
);
}else if (params.sort == "cheapest") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceA - priceB;
});
}else if (params.sort == "expensive") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceB - priceA;
});
}
useEffect(() => {
loadData();
}, []);
}
useEffect(() => {
let result = notices.filter((notice) => notice.status === "ACTIVE");
if (params.priceFrom) {
result = result.filter(notice => {
const price = parseFloat(notice.price);
const priceFrom = parseFloat(params.priceFrom);
return !isNaN(price) && price >= priceFrom;
});
}
if (params.category) {
result = result.filter((notice) => notice.category === params.category);
}
if (params.priceTo) {
result = result.filter(notice => {
const price = parseFloat(notice.price);
const priceTo = parseFloat(params.priceTo);
return !isNaN(price) && price <= priceTo;
});
}
if (params.sort) {
if (params.sort == "latest") {
result = [...result].sort(
(a, b) => new Date(b.publishDate) - new Date(a.publishDate)
);
} else if (params.sort == "oldest") {
result = [...result].sort(
(a, b) => new Date(a.publishDate) - new Date(b.publishDate)
);
} else if (params.sort == "cheapest") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceA - priceB;
});
} else if (params.sort == "expensive") {
result = [...result].sort((a, b) => {
const priceA = parseFloat(a.price);
const priceB = parseFloat(b.price);
return isNaN(priceA) || isNaN(priceB) ? 0 : priceB - priceA;
});
}
}
if (params.priceFrom) {
result = result.filter((notice) => {
const price = parseFloat(notice.price);
const priceFrom = parseFloat(params.priceFrom);
return !isNaN(price) && price >= priceFrom;
});
}
if (params.search) {
const searchTerm = params.search.toLowerCase();
result = result.filter(notice => {
return notice.title.toLowerCase().includes(searchTerm);
});
}
if (params.priceTo) {
result = result.filter((notice) => {
const price = parseFloat(notice.price);
const priceTo = parseFloat(params.priceTo);
return !isNaN(price) && price <= priceTo;
});
}
setFilteredNotices(result);
}, [notices,
if (params.search) {
const searchTerm = params.search.toLowerCase();
result = result.filter((notice) => {
return notice.title.toLowerCase().includes(searchTerm);
});
}
setFilteredNotices(result);
}, [
notices,
params.category,
params.sort,
params.priceFrom,
params.priceTo,
params.search]);
params.search,
]);
let filterActive =
!!params.category ||
!!params.sort ||
!!params.priceFrom ||
!!params.priceTo ||
!!params.search;
let filterActive = !!params.category || !!params.sort || !!params.priceFrom || !!params.priceTo || !!params.search;
const loadData = async () => {
setIsLoading(true);
try {
await fetchNotices();
setError(null);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
const handleCategorySelect = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, category: value }
});
};
const handlePriceFrom = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceFrom: value }
});
const loadData = async () => {
setIsLoading(true);
try {
await fetchNotices();
setError(null);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
const handlePriceTo = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceTo: value }
});
const handleCategorySelect = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, category: value },
});
};
const handlePriceFrom = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceFrom: value },
});
};
const handlePriceTo = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, priceTo: value },
});
};
const handleClose = () => setShowActionsheet(false);
const handleSort = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, sort: value },
});
setShowSortSheet(false);
};
const onRefresh = async () => {
setRefreshing(true);
try {
await fetchNotices();
} catch (err) {
setError(err);
} finally {
setRefreshing(false);
}
};
const handleClose = () => setShowActionsheet(false);
if (isLoading && !refreshing) {
return <ActivityIndicator />;
}
const handleSort = (value) => {
router.replace({
pathname: "/notices",
params: { ...params, sort: value }
});
setShowSortSheet(false);
}
if (error) {
return <Text>Nie udało się pobrać listy. {error.message}</Text>;
}
const onRefresh = async () => {
setRefreshing(true);
try {
await fetchNotices();
} catch (err) {
setError(err);
} finally {
setRefreshing(false);
}
};
const SCREEN_HEIGHT = Dimensions.get("window").height;
if (isLoading && !refreshing) {
return <ActivityIndicator />;
}
const selectedCategory =
(params.category &&
categories?.find((cat) => cat.value === params.category)) ||
null;
if (error) {
return <Text>Nie udało się pobrać listy. {error.message}</Text>;
}
const SCREEN_HEIGHT = Dimensions.get('window').height;
const selectedCategory = params.category && categories?.find(
(cat) => cat.value === params.category
) || null;
return (
<>
<Box style={{ flexDirection: "row", padding: 8, paddingTop: 16, paddingBottom: 16, backgroundColor: "white", alignItems: "center", justifyContent: "space-between" }}>
<Box style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<Button variant="outline" onPress={() => setShowActionsheet(true)}>
<ButtonText>Filtruj</ButtonText>
<Ionicons name="filter-outline" size={20} color="black" />
</Button>
<Button variant="outline" onPress={() => setShowSortSheet(true)}>
<Ionicons name="chevron-expand-outline" size={20} color="black" />
</Button>
</Box>
{filterActive && (
<Button variant="link" onPress={() => router.replace("/notices")}>
<ButtonText>Wyczyść</ButtonText>
</Button>
)}
</Box>
<Actionsheet isOpen={showActionsheet} onClose={handleClose}>
<ActionsheetBackdrop />
<ActionsheetContent style={{ maxHeight: SCREEN_HEIGHT * 0.6, width: '100%' }} >
<KeyboardAwareScrollView
contentContainerStyle={{ flexGrow: 1, width: '100%' }}
enableOnAndroid={true}
extraScrollHeight={40}
return (
<>
<Box
style={{
flexDirection: "row",
padding: 8,
paddingTop: 16,
paddingBottom: 16,
backgroundColor: "white",
alignItems: "center",
justifyContent: "space-between",
}}
>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<Box className="mb-4" style={{ width: "100%" }}>
<HStack space="md" style={{ width: "100%" }}>
<FormControl
style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Od:"
value={params.priceFrom || ''}
onChangeText={handlePriceFrom}
/>
</Input>
</FormControl>
<FormControl
style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Do:"
value={params.priceTo || ''}
onChangeText={handlePriceTo}
/>
</Input>
</FormControl>
</HStack>
</Box>
<Box className="mb-4" style={{ flex: 1 }}>
<Select
style={{ flex: 1 }}
selectedValue={params.category || ''}
onValueChange={handleCategorySelect}
>
<SelectTrigger variant="outline" size="md">
<SelectInput
style={{ flex: 1 }}
placeholder="Wybierz kategorię"
value={selectedCategory ? selectedCategory.label : ""}
/>
<SelectIcon style={{ marginRight: 12 }} as={ChevronDownIcon} />
</SelectTrigger>
<SelectPortal>
<SelectBackdrop />
<SelectContent
style={{ maxHeight: SCREEN_HEIGHT * 0.6}}
>
<SelectDragIndicatorWrapper>
<SelectDragIndicator />
</SelectDragIndicatorWrapper>
<FlatList
style={{ width: '100%' }}
data={categories}
keyExtractor={(item) => item.value?.toString() || item.id?.toString() || Math.random().toString()}
renderItem={({ item }) => (
<SelectItem
label={item.label}
value={item.value}
/>
)}
/>
</SelectContent>
</SelectPortal>
</Select>
</Box>
</KeyboardAwareScrollView>
</ActionsheetContent>
</Actionsheet>
<Actionsheet isOpen={showSortSheet} onClose={() => setShowSortSheet(false)}>
<ActionsheetBackdrop />
<ActionsheetContent>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<ActionsheetItem
className={ !params.sort ? 'bg-gray-200' : ''}
onPress={() => handleSort()}>
<ActionsheetItemText>Trafność</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'latest' ? 'bg-gray-200' : ''}
onPress={() => handleSort('latest')}>
<ActionsheetItemText>Najnowsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'oldest' ? 'bg-gray-200' : ''}
onPress={() => handleSort('oldest')}>
<ActionsheetItemText>Najstarsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'cheapest' ? 'bg-gray-200' : ''}
onPress={() => handleSort('cheapest')}>
<ActionsheetItemText>Najtańsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={ params.sort == 'expensive' ? 'bg-gray-200' : ''}
onPress={() => handleSort('expensive')}>
<ActionsheetItemText>Najdroższe</ActionsheetItemText>
</ActionsheetItem>
</ActionsheetContent>
</Actionsheet>
<FlatList
data={filteredNotices}
numColumns={2}
columnWrapperStyle={{ gap: 8, marginHorizontal: 8 }}
contentContainerStyle={{ paddingBottom: 16 }}
renderItem={({ item }) => <NoticeCard notice={item} />}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={["#3b82f6"]}
tintColor="#3b82f6"
<Box style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
<Button variant="outline" onPress={() => setShowActionsheet(true)}>
<ButtonText>Filtruj</ButtonText>
<Ionicons name="filter-outline" size={20} color="black" />
</Button>
<Button variant="outline" onPress={() => setShowSortSheet(true)}>
<Ionicons name="chevron-expand-outline" size={20} color="black" />
</Button>
</Box>
{filterActive && (
<Button variant="link" onPress={() => router.replace("/notices")}>
<ButtonText>Wyczyść</ButtonText>
</Button>
)}
</Box>
<Actionsheet isOpen={showActionsheet} onClose={handleClose}>
<ActionsheetBackdrop />
<ActionsheetContent
style={{ maxHeight: SCREEN_HEIGHT * 0.6, width: "100%" }}
>
<KeyboardAwareScrollView
contentContainerStyle={{ flexGrow: 1, width: "100%" }}
enableOnAndroid={true}
extraScrollHeight={40}
>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<Box className="mb-4" style={{ width: "100%" }}>
<HStack space="md" style={{ width: "100%" }}>
<FormControl style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Od:"
value={params.priceFrom || ""}
onChangeText={handlePriceFrom}
/>
}
/>
</>
);
}
</Input>
</FormControl>
<FormControl style={{ flex: 1 }}>
<Input>
<InputField
keyboardType="numeric"
placeholder="Do:"
value={params.priceTo || ""}
onChangeText={handlePriceTo}
/>
</Input>
</FormControl>
</HStack>
</Box>
<Box className="mb-4" style={{ flex: 1 }}>
<Select
style={{ flex: 1 }}
selectedValue={params.category || ""}
onValueChange={handleCategorySelect}
>
<SelectTrigger variant="outline" size="md">
<SelectInput
style={{ flex: 1 }}
placeholder="Wybierz kategorię"
value={selectedCategory ? selectedCategory.label : ""}
/>
<SelectIcon
style={{ marginRight: 12 }}
as={ChevronDownIcon}
/>
</SelectTrigger>
<SelectPortal>
<SelectBackdrop />
<SelectContent style={{ maxHeight: SCREEN_HEIGHT * 0.6 }}>
<SelectDragIndicatorWrapper>
<SelectDragIndicator />
</SelectDragIndicatorWrapper>
<FlatList
style={{ width: "100%" }}
data={categories}
keyExtractor={(item) =>
item.value?.toString() ||
item.id?.toString() ||
Math.random().toString()
}
renderItem={({ item }) => (
<SelectItem label={item.label} value={item.value} />
)}
/>
</SelectContent>
</SelectPortal>
</Select>
</Box>
</KeyboardAwareScrollView>
</ActionsheetContent>
</Actionsheet>
<Actionsheet
isOpen={showSortSheet}
onClose={() => setShowSortSheet(false)}
>
<ActionsheetBackdrop />
<ActionsheetContent>
<ActionsheetDragIndicatorWrapper>
<ActionsheetDragIndicator />
</ActionsheetDragIndicatorWrapper>
<ActionsheetItem
className={!params.sort ? "bg-gray-200" : ""}
onPress={() => handleSort()}
>
<ActionsheetItemText>Trafność</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "latest" ? "bg-gray-200" : ""}
onPress={() => handleSort("latest")}
>
<ActionsheetItemText>Najnowsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "oldest" ? "bg-gray-200" : ""}
onPress={() => handleSort("oldest")}
>
<ActionsheetItemText>Najstarsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "cheapest" ? "bg-gray-200" : ""}
onPress={() => handleSort("cheapest")}
>
<ActionsheetItemText>Najtańsze</ActionsheetItemText>
</ActionsheetItem>
<ActionsheetItem
className={params.sort == "expensive" ? "bg-gray-200" : ""}
onPress={() => handleSort("expensive")}
>
<ActionsheetItemText>Najdroższe</ActionsheetItemText>
</ActionsheetItem>
</ActionsheetContent>
</Actionsheet>
<FlatList
data={filteredNotices}
numColumns={2}
// numColumns={2}
// columnContainerClassName="m-2"
columnWrapperClassName="m-2"
columnWrapperStyle={{ gap: 8, marginHorizontal: 8 }}
contentContainerStyle={{ paddingBottom: 16 }}
renderItem={({ item }) => <NoticeCard notice={item} />}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={["#3b82f6"]}
tintColor="#3b82f6"
/>
}
/>
</>
);
}

View File

@@ -17,6 +17,7 @@ return (
}}
>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="user" options={{ headerShown: false }} />
<Stack.Screen
name="(auth)/login"
options={{ headerShown: false }}/>

View File

@@ -5,6 +5,7 @@ import { Heading } from "@/components/ui/heading";
import { Image } from "@/components/ui/image";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { Avatar, AvatarImage, AvatarFallbackText } from "@gluestack-ui/themed";
import { Ionicons } from "@expo/vector-icons";
import {
ActivityIndicator,
@@ -12,14 +13,16 @@ import {
FlatList,
View,
TextInput,
SafeAreaView, Alert,
} from "react-native";
import { useEffect, useState, useRef } from "react";
import { useNoticesStore } from "@/store/noticesStore";
import { useWishlist } from "@/store/wishlistStore";
import { Pressable, ScrollView } from "react-native";
import { getUserById } from "@/api/client";
const { width } = Dimensions.get("window");
import * as ScreenOrientation from "expo-screen-orientation";
import { useAuthStore } from "@/store/authStore";
import { sendEmail } from "@/api/email";
export default function NoticeDetails() {
const { id } = useLocalSearchParams();
@@ -30,20 +33,74 @@ export default function NoticeDetails() {
const [notice, setNotice] = useState(null);
const [user, setUser] = useState(null);
const [isUserLoading, setIsUserLoading] = useState(true);
const [isLandscape, setIsLandscape] = useState(false);
const flatListRef = useRef(null);
const [currentIndex, setCurrentIndex] = useState(0);
const [isMessageFormVisible, setIsMessageFormVisible] = useState(false);
const [message, setMessage] = useState("");
const [Email, setEmail] = useState("");
const handleSendMessage = () => {
console.log("Wiadomość do:", user?.email);
console.log("Email nadawcy:", Email);
console.log("Treść:", message);
const [isSending, setIsSending] = useState(false);
setIsMessageFormVisible(false);
setMessage("");
setEmail("");
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);
setMessage("");
Alert.alert("Sukces", "Wiadomość została wysłana!");
} 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) => {
@@ -57,12 +114,13 @@ export default function NoticeDetails() {
const { getNoticeById, getAllImagesByNoticeId } = useNoticesStore();
const toggleNoticeInWishlist = useWishlist(
(state) => state.toggleNoticeInWishlist
(state) => state.toggleNoticeInWishlist
);
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 }) => {
if (viewableItems.length > 0) {
setCurrentIndex(viewableItems[0].index);
@@ -73,6 +131,51 @@ export default function NoticeDetails() {
itemVisiblePercentThreshold: 70,
}).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(() => {
const fetchNotice = async () => {
setIsLoading(true);
@@ -100,14 +203,15 @@ export default function NoticeDetails() {
if (notice) {
try {
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
console.log("Fetched images:", fetchedImages);
setImages(
fetchedImages && fetchedImages.length > 0
? fetchedImages
: ["https://http.cat/404.jpg"]
fetchedImages && fetchedImages.length > 0
? fetchedImages
: ["https://http.cat/404.jpg"]
);
} catch (err) {
console.error("Error while loading images:", err);
setImage("https://http.cat/404.jpg");
setImages(["https://http.cat/404.jpg"]);
} finally {
setIsImageLoading(false);
}
@@ -142,196 +246,209 @@ export default function NoticeDetails() {
}
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) {
return <Text>Nie znaleziono ogłoszenia</Text>;
}
return (
<Card className="p-0 rounded-lg m-3 flex-1">
<Stack.Screen
options={{
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" />
</Box>
) : (
<Box className="sticky top-0 z-10 bg-white">
<FlatList
ref={flatListRef}
data={images}
horizontal
snapToAlignment="center"
decelerationRate="fast"
showsHorizontalScrollIndicator={false}
pagingEnabled
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig}
renderItem={({ item, index }) => (
<View style={{ width: width }}>
<Image
source={{ uri: item }}
className="h-auto w-full rounded-md aspect-square"
alt={`Zdjęcie ${index + 1}`}
resizeMode="contain"
/>
</View>
)}
keyExtractor={(item, index) => index.toString()}
/>
const renderImageSection = () => {
if (isImageLoading) {
return (
<Box
className={`h-auto w-full rounded-md ${
isLandscape ? "h-screen" : "aspect-[1/1]"
} bg-gray-100 items-center justify-center`}
>
<ActivityIndicator size="large" color="#3b82f6" />
</Box>
);
}
return (
<Box className={isLandscape ? "h-screen" : "sticky top-0 z-10 bg-white"}>
<FlatList
ref={flatListRef}
data={images}
horizontal
snapToAlignment="center"
decelerationRate="fast"
showsHorizontalScrollIndicator={false}
pagingEnabled
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig}
renderItem={({ item, index }) => (
<View style={{ width: Dimensions.get("window").width }}>
<Image
source={{ uri: item }}
className={`h-auto w-full rounded-md ${
isLandscape ? "h-full" : "aspect-square"
}`}
alt={`Zdjęcie ${index + 1}`}
resizeMode={isLandscape ? "cover" : "contain"}
onError={(e) => console.error("Image load error:", e.nativeEvent.error)}
/>
</View>
)}
keyExtractor={(item, index) => index.toString()}
/>
{images.length > 1 && (
<Box className="flex-row justify-center mt-2">
{images.map((_, index) => (
<Box
key={index}
className={`w-2 h-2 rounded-full mx-1 ${
index === currentIndex ? "bg-primary-500" : "bg-gray-300"
}`}
/>
))}
</Box>
<Box className="flex-row justify-center mt-2">
{images.map((_, index) => (
<Box
key={index}
className={`w-2 h-2 rounded-full mx-1 ${
index === currentIndex ? "bg-primary-500" : "bg-gray-500"}
}`}
/>
))}
</Box>
)}
</Box>
)}
);
};
<ScrollView showsVerticalScrollIndicator={false}>
<VStack className="p-2">
<Text className="text-sm font-normal mb-2 text-typography-700">
{formatDate(notice.publishDate)}
</Text>
<Text className="text-2xl text-gray-950 font-bold mb-2 text-center bg-gray-50 rounded-md p-2">
{notice.title}
</Text>
<Box className="flex-row items-center bg-gray-50 rounded-md p-2">
<Heading size="md" className="flex-1 text-xl text-gray-950">
<Text className="text-sm text-typography-500">Cena: </Text>
{notice.price}
</Heading>
<Pressable
onPress={() => {
toggleNoticeInWishlist(id);
return (
<SafeAreaView style={{ flex: 1 }}>
<Card className="flex-1 p-4 m-3 rounded-lg shadow-sm">
<Stack.Screen
options={{
title: notice.title,
}}
>
<Ionicons
name={isInWishlist ? "heart" : "heart-outline"}
size={24}
color={"primary-heading-500"}
/>
</Pressable>
</Box>
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-sm text-typography-500">
Kategoria:{" "}
<Text className="font-bold text-gray-950">{notice.category}</Text>
</Text>
</Box>
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-2xl text-gray-950">Opis ogloszenia</Text>
<Text className="text-sm text-typography-700">
{notice.description}
</Text>
</Box>
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-sm text-typography-500">Uzytkownik:</Text>
{isUserLoading ? (
<ActivityIndicator />
) : user ? (
<>
<Box className="mr-4">
<Image
source={{
uri:
user.profileImage ||
"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"
/>
<ScrollView showsVerticalScrollIndicator={false}>
{renderImageSection()}
<VStack className="p-4">
<Text className="text-sm font-normal mb-2 text-gray-600">
{formatDate(notice.publishDate)}
</Text>
<Text className="text-2xl font-bold mb-2 text-center bg-gray-100 rounded-md p-4">
{notice.title}
</Text>
<Box className="flex-row items-center bg-gray-100 rounded-md p-2">
<Heading size="md" className="flex-1 text-lg">
<Text className="text-sm text-gray-500">Cena: </Text>
{notice.price}
</Heading>
<Pressable
onPress={() => {
toggleNoticeInWishlist(id);
}}
>
<Ionicons
name={isInWishlist ? "heart" : "heart-outline"}
size={24}
color="#3b82f6"
/>
</Box>
<Box className="flex-1">
<Text className="text-xl font-bold text-gray-950">
{user.firstName} {user.lastName}
</Pressable>
</Box>
<Box className="mt-4 bg-gray-100 p-3 rounded-lg">
<Text className="text-sm text-gray-500">
Kategoria:{" "}
<Text className="font-bold text-gray-900">{notice.category}</Text>
</Text>
</Box>
<Box className="mt-4 bg-gray-100 p-3 rounded-lg">
<Text className="text-xl font-bold text-gray-900">Opis ogłoszenia</Text>
<Text className="text-sm text-gray-700">{notice.description}</Text>
</Box>
<Box className="mt-4 bg-gray-100 p-3 rounded-lg">
<Text className="text-sm text-gray-500">Użytkownik:</Text>
{isUserLoading ? (
<ActivityIndicator />
) : user ? (
<>
<Box className="mr-4">
<Avatar size="md">
<AvatarImage
source={{
uri:
user.image ||
"https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain",
}}
alt="Zdjęcie profilowe"
/>
<AvatarFallbackText>
{user.firstName?.[0]}
{user.lastName?.[0]}
</AvatarFallbackText>
</Avatar>
</Box>
<Box className="flex-1">
<Text className="text-lg font-bold text-gray-900">
{user.firstName} {user.lastName}
</Text>
<Text className="text-sm text-gray-700">
Email: {user.email}
</Text>
<Pressable
onPress={() => setIsMessageFormVisible(true)}
className="mt-3 bg-blue-500 py-2 px-4 rounded-md"
>
<Text className="text-white text-center font-bold">
Wyślij wiadomość
</Text>
</Pressable>
<Link href={`/user/${notice.clientId}`}>
<Text className="text-lg font-bold text-center text-blue-600 mt-3">
Zobacz więcej ogłoszeń od {user.firstName}
</Text>
</Link>
</Box>
</>
) : (
<Text>Błąd podczas ładowania danych użytkownika</Text>
)}
</Box>
</VStack>
</ScrollView>
{isMessageFormVisible && (
<View className="absolute inset-0 bg-black bg-opacity-50 justify-center items-center z-20">
<View className="bg-white p-4 rounded-lg w-4/5">
<Text className="text-lg font-bold mb-4">
Wyślij wiadomość do {user?.firstName}
</Text>
<Text className="text-sm text-typography-700">
Email: {user.email}
<Text className="text-sm font-medium mb-1">Do:</Text>
<Text className="bg-gray-100 p-3 rounded text-gray-500">
{user?.email || "Brak adresu e-mail"}
</Text>
<Pressable
onPress={() => setIsMessageFormVisible(true)}
className="mt-3 bg-primary-500 py-2 px-4 rounded-md"
>
<Text className="text-white text-center font-bold">
Wyślij wiadomość
</Text>
</Pressable>
<Link href={`/user/${notice.clientId}`}>
<Text className="text-xl p-3 font-bold text-center text-typography-700 mt-3">
Zobacz więcej ogłoszeń od {user.firstName}
</Text>
</Link>
</Box>
</>
) : (
<Text>Błąd podczas ładowania danych użytkownika</Text>
)}
</Box>
</VStack>
</ScrollView>
{isMessageFormVisible && (
<View className="absolute inset-0 bg-black bg-opacity-50 justify-center items-center z-20">
<View className="bg-white p-4 rounded-lg w-4/5">
<Text className="text-lg font-bold mb-4">
Wyślij wiadomość do {user?.firstName}
</Text>
<Text className="text-sm font-medium mb-1">Do:</Text>
<Text className="bg-gray-100 p-3 rounded text-gray-500">
{user?.email || "Brak adresu e-mail"}
</Text>
<Text className="text-sm font-medium mb-1">Twój e-mail:</Text>
<TextInput
className="border border-gray-300 p-2 rounded"
placeholder="Wpisz swój adres e-mail"
value={Email}
onChangeText={setEmail}
/>
<TextInput
className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left"
multiline
numberOfLines={4}
placeholder="Napisz swoją wiadomość..."
value={message}
onChangeText={setMessage}
/>
<View className="flex-row justify-end space-x-2">
<Pressable
onPress={() => setIsMessageFormVisible(false)}
className="bg-gray-300 py-2 px-4 rounded-md"
>
<Text className="text-gray-800">Anuluj</Text>
</Pressable>
<Pressable
onPress={handleSendMessage}
className="bg-primary-500 py-2 px-4 rounded-md"
>
<Text className="text-white">Wyślij</Text>
</Pressable>
</View>
</View>
</View>
)}
</Card>
<Text className="text-sm font-medium mb-1">Temat:</Text>
<Text className="bg-gray-100 p-3 rounded text-gray-500">
Zapytanie o ogłoszenie '{notice.title || "Brak nazwy ogłoszenia"}'
</Text>
<Text className="text-sm font-medium mb-1">Treść:</Text>
<TextInput
className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left"
multiline
numberOfLines={4}
placeholder="Napisz swoją wiadomość..."
value={message}
onChangeText={setMessage}
/>
<View className="flex-row justify-end space-x-2">
<Pressable
onPress={() => setIsMessageFormVisible(false)}
className="bg-gray-300 py-2 px-4 rounded-md"
>
<Text className="text-gray-800">Anuluj</Text>
</Pressable>
<Pressable
onPress={handleSendMessage}
className="bg-blue-500 py-2 px-4 rounded-md"
disabled={isSending}
>
{isSending ? (
<ActivityIndicator color="#fff" />
) : (
<Text className="text-white">Wyślij</Text>
)}
</Pressable>
</View>
</View>
</View>
)}
</Card>
</SafeAreaView>
);
}
}

View File

@@ -0,0 +1,11 @@
import { Stack } from 'expo-router';
export default function UserLayout() {
return (
<Stack
screenOptions={{
headerTitle: 'Ogłoszenia użytkownika',
}}
/>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 304 KiB

View File

@@ -1,111 +1,117 @@
import {Box} from "@/components/ui/box";
import {Card} from "@/components/ui/card";
import {Heading} from "@/components/ui/heading";
import {Image} from "@/components/ui/image";
import {Text} from "@/components/ui/text";
import {VStack} from "@/components/ui/vstack";
import {Link} from "expo-router";
import {Pressable, ActivityIndicator, View} from "react-native";
import {useWishlist} from "@/store/wishlistStore";
import {useNoticesStore} from "@/store/noticesStore";
import {Ionicons} from "@expo/vector-icons";
import {useEffect, useState} from "react";
import { Box } from "@/components/ui/box";
import { Card } from "@/components/ui/card";
import { Heading } from "@/components/ui/heading";
import { Image } from "@/components/ui/image";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { Link } from "expo-router";
import { Pressable, ActivityIndicator, View } from "react-native";
import { useWishlist } from "@/store/wishlistStore";
import { useNoticesStore } from "@/store/noticesStore";
import { Ionicons } from "@expo/vector-icons";
import { useEffect, useState } from "react";
export function NoticeCard({notice}) {
const noticeId = notice?.noticeId;
export function NoticeCard({ notice }) {
const noticeId = notice?.noticeId;
const toggleNoticeInWishlist = useWishlist((state) => state.toggleNoticeInWishlist);
const isInWishlist = useWishlist((state) =>
noticeId ? state.wishlistNotices.some((item) => item.noticeId === noticeId) : false
);
const toggleNoticeInWishlist = useWishlist(
(state) => state.toggleNoticeInWishlist
);
const isInWishlist = useWishlist((state) =>
noticeId
? state.wishlistNotices.some((item) => item.noticeId === noticeId)
: false
);
const [image, setImage] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [image, setImage] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const {getAllImagesByNoticeId} = useNoticesStore();
const { getAllImagesByNoticeId } = useNoticesStore();
useEffect(() => {
let isMounted = true;
useEffect(() => {
let isMounted = true;
const fetchImage = async () => {
if (!noticeId) {
if (isMounted) {
setImage("https://http.cat/404.jpg");
setIsLoading(false);
}
return;
}
const fetchImage = async () => {
if (!noticeId) {
if (isMounted) {
setImage("https://http.cat/404.jpg");
setIsLoading(false);
}
return;
}
setIsLoading(true);
try {
const images = await getAllImagesByNoticeId(noticeId);
if (isMounted) {
setImage(images && images.length > 0 ? images[0] : "https://http.cat/404.jpg");
}
} catch (error) {
console.error(`Error while loading image: ${error}`);
if (isMounted) {
setImage("https://http.cat/404.jpg");
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
setIsLoading(true);
try {
const images = await getAllImagesByNoticeId(noticeId);
if (isMounted) {
setImage(
images && images.length > 0 ? images[0] : "https://http.cat/404.jpg"
);
}
} catch (error) {
console.error(`Error while loading image: ${error}`);
if (isMounted) {
setImage("https://http.cat/404.jpg");
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
fetchImage();
fetchImage();
return () => {
isMounted = false;
};
}, [noticeId]);
return () => {
isMounted = false;
};
}, [noticeId]);
if (!notice) {
return <View style={{flex: 1}} />;
}
if (!notice) {
return <View style={{ flex: 1 }} />;
}
return (
<Link href={`/notice/${noticeId}`} asChild>
<Pressable className="flex-1">
<Card className="p-0 rounded-lg max-w-[460px] flex-1">
{isLoading ? (
<Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
<ActivityIndicator size="large" color="#3b82f6" />
</Box>
) : (
<Image
source={{
uri: image,
}}
className="h-auto w-full rounded-md aspect-[1/1]"
alt="image"
resizeMode="cover"
/>
)}
<VStack className="p-2">
<Text className="text-sm font-normal mb-2 text-typography-700">
{notice.title}
</Text>
<Box className="flex-row items-center">
<Heading size="md" className="flex-1">
{notice.price}
</Heading>
<Pressable
onPress={() => {
toggleNoticeInWishlist(noticeId);
}}
>
<Ionicons
name={isInWishlist ? "heart" : "heart-outline"}
size={24}
color={"primary-heading-500"}
/>
</Pressable>
</Box>
</VStack>
</Card>
</Pressable>
</Link>
);
}
return (
<Link href={`/notice/${noticeId}`} asChild>
<Pressable className="flex-1">
<Card className="p-0 rounded-lg max-w-[460px] flex-1">
{isLoading ? (
<Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
<ActivityIndicator size="large" color="#3b82f6" />
</Box>
) : (
<Image
source={{
uri: image,
}}
className="h-auto w-full rounded-md aspect-[1/1]"
alt="image"
resizeMode="cover"
/>
)}
<VStack className="p-2">
<Text className="text-sm font-normal mb-2 text-typography-700">
{notice.title}
</Text>
<Box className="flex-row items-center">
<Heading size="md" className="flex-1">
{notice.price}
</Heading>
<Pressable
onPress={() => {
toggleNoticeInWishlist(noticeId);
}}
>
<Ionicons
name={isInWishlist ? "heart" : "heart-outline"}
size={24}
color={"primary-heading-500"}
/>
</Pressable>
</Box>
</VStack>
</Card>
</Pressable>
</Link>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -36,10 +36,10 @@
"@tanstack/react-query": "^5.74.4",
"axios": "^1.9.0",
"babel-plugin-module-resolver": "^5.0.2",
"expo": "^53.0.0",
"expo-auth-session": "~6.1.5",
"expo-camera": "~16.1.6",
"expo-constants": "~17.1.6",
"expo": "^53.0.10",
"expo-auth-session": "~6.2.0",
"expo-camera": "~16.1.7",
"expo-constants": "~17.1.5",
"expo-image-picker": "~16.1.4",
"expo-linking": "~7.1.4",
"expo-router": "~5.0.5",
@@ -51,7 +51,7 @@
"nativewind": "^4.1.23",
"react": "19.0.0",
"react-dom": "19.0.0",
"react-native": "0.79.2",
"react-native": "0.79.3",
"react-native-css-interop": "^0.1.22",
"react-native-gesture-handler": "~2.24.0",
"react-native-keyboard-aware-scroll-view": "^0.9.5",
@@ -62,7 +62,8 @@
"react-native-web": "~0.20.0",
"tailwindcss": "^3.4.17",
"zustand": "^5.0.3",
"expo-crypto": "~14.1.4"
"expo-crypto": "~14.1.4",
"expo-screen-orientation": "~8.1.7"
},
"devDependencies": {
"@babel/core": "^7.20.0",