1 Commits

Author SHA1 Message Date
0e46d692f9 fix of api url and new version packages 2025-06-06 16:31:39 +02:00
21 changed files with 484 additions and 1138 deletions

View File

@@ -1,16 +1,12 @@
import axios from "axios"; import axios from "axios";
import { useAuthStore } from "@/store/authStore";
const API_URL = "https://hopp.zikor.pl/api/v1"; const API_URL = "https://testowe.zikor.pl/api/v1";
export async function listCategories() { export async function listCategories() {
const { token } = useAuthStore.getState(); try {
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const response = await axios.get(`${API_URL}/vars/categories`);
return response.data;
try { } catch (err) {
const response = await axios.get(`${API_URL}/vars/categories`, { headers }); console.error("Nie udało się pobrać listy kategorii.", err.response.status);
return response.data; }
} catch (err) {
console.error("Nie udało się pobrać listy kategorii.", err.response.status);
}
} }

View File

@@ -1,16 +0,0 @@
import axios from "axios";
const API_URL = "https://hopp.zikor.pl/api/v1";
export async function getUserById(userId) {
try {
const response = await axios.get(`${API_URL}/clients/get/${userId}`);
return response.data;
} catch (err) {
console.error(
`Nie udało się pobrać danych użytkownika o ID ${userId}.`,
err.response.status
);
throw err;
}
}

View File

@@ -1,129 +1,129 @@
import axios from "axios"; import axios from "axios";
import FormData from "form-data"; import FormData from 'form-data'
import { useAuthStore } from "@/store/authStore"; import {useAuthStore} from "@/store/authStore";
// const API_URL = "https://testowe.zikor.pl/api/v1"; const API_URL = "https://testowe.zikor.pl/api/v1";
const API_URL = "https://hopp.zikor.pl/api/v1"; // const API_URL = "http://10.0.2.2:8080/api/v1";
export async function listNotices() { export async function listNotices() {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
const response = await fetch(`${API_URL}/notices/get/all`, { console.log(token);
headers: headers,
}); const response = await fetch(`${API_URL}/notices/get/all`, {
const data = await response.json(); headers: headers
if (!response.ok) { });
throw new Error(response.toString()); console.log(response);
} const data = await response.json();
return data; if (!response.ok) {
throw new Error(response.toString());
}
return data;
} }
export async function getNoticeById(noticeId) { export async function getNoticeById(noticeId) {
const response = await fetch(`${API_URL}/notices/get/${noticeId}`); const response = await fetch(`${API_URL}/notices/get/${noticeId}`);
const data = await response.json(); const data = await response.json();
if (!response.ok) { if (!response.ok) {
throw new Error("Error"); throw new Error("Error");
} }
return data; return data;
} }
export async function createNotice(notice) { export async function createNotice(notice) {
try { try {
const response = await axios.post(`${API_URL}/notices/add`, notice, { const response = await axios.post(`${API_URL}/notices/add`, notice, {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}); });
if (response.data.noticeId !== null) { if (response.data.noticeId !== null) {
for (const imageUri of notice.image) { for (const imageUri of notice.image) {
await uploadImage(response.data.noticeId, imageUri); await uploadImage(response.data.noticeId, imageUri);
} }
}
return response.data;
} catch (error) {
console.log("Error", error.response.data, error.response.status);
return null;
} }
return response.data;
} catch (error) {
console.log("Error", error.response.data, error.response.status);
return null;
}
} }
export async function getImageByNoticeId(noticeId) { export async function getImageByNoticeId(noticeId) {
let imageUrl; let imageUrl;
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`); const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
const imageName = listResponse.data[0]; const imageName = listResponse.data[0];
imageUrl = `${API_URL}/images/get/${imageName}`; imageUrl = `${API_URL}/images/get/${imageName}`;
return imageUrl; console.log(`Pobrano zdjęcie o nazwie: ${imageName}`);
} catch (err) {
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`); return imageUrl;
imageUrl = "https://http.cat/404.jpg"; } catch (err) {
return imageUrl; console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
} imageUrl = "https://http.cat/404.jpg";
return imageUrl;
}
} }
export async function getAllImagesByNoticeId(noticeId) { export async function getAllImagesByNoticeId(noticeId) {
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`); const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
if (listResponse.data && listResponse.data.length > 0) { if (listResponse.data && listResponse.data.length > 0) {
return listResponse.data.map( const imageUrls = listResponse.data.map(imageName =>
(imageName) => `${API_URL}/images/get/${imageName}` `${API_URL}/images/get/${imageName}`
); );
}
return ["https://http.cat/404.jpg"]; // console.log(`Pobrano ${imageUrls.length} zdjęć dla ogłoszenia o id: ${noticeId}`);
} catch (err) { return imageUrls;
if (err.response.status === 404) { }
// console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
return ["https://http.cat/404.jpg"]; // console.log(`Brak zdjęć dla ogłoszenia o id: ${noticeId}`);
return ["https://http.cat/404.jpg"];
} catch (err) {
// console.log(`Błąd podczas pobierania listy zdjęć dla ogłoszenia o id: ${noticeId}`, err);
return ["https://http.cat/404.jpg"];
} }
console.warn(
`Nie udało się pobrać listy zdjęć dla ogłoszenia o id: ${noticeId}`,
err
);
return ["https://http.cat/404.jpg"];
}
} }
export const uploadImage = async (noticeId, imageUri) => { export const uploadImage = async (noticeId, imageUri) => {
const formData = new FormData(); console.log(imageUri);
const filename = imageUri.split("/").pop(); const formData = new FormData();
const match = /\.(\w+)$/.exec(filename); const filename = imageUri.split('/').pop();
const type = match ? `image/${match[1]}` : "image/jpeg";
formData.append("file", { const match = /\.(\w+)$/.exec(filename);
uri: imageUri, const type = match ? `image/${match[1]}` : 'image/jpeg';
name: filename,
type: type,
});
try { formData.append('file', {
const response = await axios.post( uri: imageUri,
`${API_URL}/images/upload/${noticeId}`, name: filename,
formData, type: type,
{ });
headers: {
"Content-Type": "multipart/form-data", try {
}, const response = await axios.post(
} `${API_URL}/images/upload/${noticeId}`,
); formData,
console.info("Upload successful:", response.data); {
return response.data; headers: {
} catch (error) { 'Content-Type': 'multipart/form-data',
console.log("imageURI:", imageUri); },
console.error( }
"Error uploading image:", );
error.response.data, console.info('Upload successful:', response.data);
error.response.status return response.data;
); } catch (error) {
throw error; console.log("imageURI:", imageUri);
} console.error('Error uploading image:', error.response.data, error.response.status);
}; throw error;
}
}

View File

@@ -1,38 +1,29 @@
import axios from "axios"; import axios from "axios";
import { useAuthStore } from "@/store/authStore";
// import FormData from 'form-data' // import FormData from 'form-data'
const API_URL = "https://hopp.zikor.pl/api/v1/wishlist"; const API_URL = "https://testowe.zikor.pl/api/v1/wishlist";
export async function toggleNoticeStatus(noticeId) { export async function toggleNoticeStatus(noticeId) {
const { token } = useAuthStore.getState(); try {
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const response = await axios.post(`${API_URL}/toggle/${noticeId}`, null, {
headers: {
try { "Content-Type": "application/json",
const response = await axios.post( },
`${API_URL}/toggle/${noticeId}`, });
{}, return response.data;
{ } catch (error) {
headers, console.error("Error toggling wishlist item:", error);
} throw error;
); }
return response.data;
} catch (error) {
console.error("Error toggling wishlist item:", error);
throw error;
}
} }
export async function getWishlist() { export async function getWishlist() {
const { token } = useAuthStore.getState(); try {
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const response = await axios.get(`${API_URL}/`);
console.log("Wishlist response:", response.data);
try { return response.data;
const response = await axios.get(`${API_URL}/`, { headers }); } catch (error) {
console.log("Wishlist response:", response.data); console.error("Error fetching wishlist:", error);
return response.data; throw error;
} catch (error) { }
console.error("Error fetching wishlist:", error);
throw error;
}
} }

View File

@@ -2,7 +2,7 @@
"expo": { "expo": {
"name": "ArtisanConnect", "name": "ArtisanConnect",
"slug": "ArtisanConnect", "slug": "ArtisanConnect",
"scheme": "com.hamx.artisanconnect", "scheme": "Artisanconnect",
"version": "1.0.0", "version": "1.0.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/icon.png", "icon": "./assets/icon.png",
@@ -14,19 +14,13 @@
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"ios": { "ios": {
"supportsTablet": true, "supportsTablet": true
"bundleIdentifier": "com.hamx.artisanconnect"
}, },
"android": { "android": {
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png", "foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, }
"permissions": [
"android.permission.RECORD_AUDIO",
"android.permission.CAMERA"
],
"package": "com.hamx.artisanconnect"
}, },
"web": { "web": {
"favicon": "./assets/favicon.png" "favicon": "./assets/favicon.png"
@@ -46,12 +40,6 @@
} }
], ],
"expo-web-browser" "expo-web-browser"
], ]
"extra": {
"router": {},
"eas": {
"projectId": "7a0d8bc8-938f-4d2a-babb-945faee13429"
}
}
} }
} }

View File

@@ -1,5 +1,5 @@
import React, {useEffect, useState} from 'react'; import React, {useState} from 'react';
import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform} from 'react-native'; import {StyleSheet, ActivityIndicator, SafeAreaView, View} from 'react-native';
import {useAuthStore} from '@/store/authStore'; import {useAuthStore} from '@/store/authStore';
import {useRouter, Link} from 'expo-router'; import {useRouter, Link} from 'expo-router';
@@ -15,37 +15,12 @@ import {ArrowRightIcon} from "@/components/ui/icon"
import {Divider} from '@/components/ui/divider'; import {Divider} from '@/components/ui/divider';
import {Ionicons} from "@expo/vector-icons"; import {Ionicons} from "@expo/vector-icons";
import * as WebBrowser from 'expo-web-browser';
import * as Google from "expo-auth-session/providers/google";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {makeRedirectUri} from "expo-auth-session";
import Constants from 'expo-constants';
WebBrowser.maybeCompleteAuthSession();
// client_id ios 936418008320-ohefdfcebd41f6oa2o8phh1mgj9s49sl.apps.googleusercontent.com
// android 936418008320-d8dfjph5e4r28fcm1rbdfbh5phmbg03d.apps.googleusercontent.com
export default function Login() { export default function Login() {
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const {signIn, isLoading, signInWithGoogle} = useAuthStore(); const {signIn, isLoading} = useAuthStore();
const router = useRouter(); const router = useRouter();
const [request, response, promptAsync] = Google.useAuthRequest({
androidClientId: "936418008320-d8dfjph5e4r28fcm1rbdfbh5phmbg03d.apps.googleusercontent.com",
iosClientId: "936418008320-ohefdfcebd41f6oa2o8phh1mgj9s49sl.apps.googleusercontent.com",
webClientId: "936418008320-btdngtlfnjac1p67guje72m9el5q59a7.apps.googleusercontent.com",
redirectUri:
Platform.OS === 'android'
? makeRedirectUri({
scheme: Constants.expoConfig.android.package,
path: '/',
})
: undefined,
})
const handleInternalLogin = async () => { const handleInternalLogin = async () => {
if (!email || !password) { if (!email || !password) {
alert('Proszę wprowadzić email i hasło.'); alert('Proszę wprowadzić email i hasło.');
@@ -61,47 +36,6 @@ export default function Login() {
} }
} }
useEffect(() => {
handleGoogleLogin();
}, [response]);
const handleGoogleLogin = async () => {
// const user = await AsyncStorage.getItem("@user");
let user = null;
if (!user) {
if(response.type === "success") {
user = await getUserInfo(response.authentication.accessToken)
await signInWithGoogle(response.authentication.accessToken);
alert(`Zalogowano jako ${user.email}`);
}
} else {
console.info("Pobrano użytkownika z AsyncStorage:", JSON.parse(user));
alert(`Zalogowano jako ${user.email}`);
}
};
const getUserInfo = async (token) => {
if(!token) {
return
}
try {
const response = await fetch("https://www.googleapis.com/userinfo/v2/me",
{
headers: {
Authorization: `Bearer ${token}`
},
}
);
const user = await response.json();
await AsyncStorage.setItem("@user", JSON.stringify(user));
return user;
} catch (error) {
console.error("Błąd podczas pobierania informacji o użytkowniku:", error);
throw error;
}
}
if (isLoading) { if (isLoading) {
return ( return (
<View style={styles.container}> <View style={styles.container}>
@@ -148,7 +82,7 @@ export default function Login() {
</Text> </Text>
<Divider flex={1}/> <Divider flex={1}/>
</HStack> </HStack>
<Button size="sm" onPress={() => promptAsync()}> <Button size="sm">
<Ionicons name="logo-google" color="#fff"/> <Ionicons name="logo-google" color="#fff"/>
</Button> </Button>
</Box> </Box>

View File

@@ -1,70 +1,64 @@
import { Tabs, Redirect } from "expo-router"; import {Tabs} from "expo-router";
import { Ionicons } from "@expo/vector-icons"; import {Ionicons} from "@expo/vector-icons";
import { useAuthStore } from "@/store/authStore";
export default function TabLayout() { export default function TabLayout() {
const token = useAuthStore((state) => state.token); return (
<Tabs
if (!token) { screenOptions={{
return <Redirect href="/login" />; tabBarActiveTintColor: "rgb(var(--color-primary-500))",
} }}
return ( >
<Tabs <Tabs.Screen
screenOptions={{ name="index"
tabBarActiveTintColor: "rgb(var(--color-primary-500))", options={{
}} title: "Home",
> tabBarLabel: "Home",
<Tabs.Screen tabBarIcon: ({color, size}) => (
name="index" <Ionicons name="home-outline" size={size} color={color}/>
options={{ ),
title: "Home", }}
tabBarLabel: "Home", />
tabBarIcon: ({ color, size }) => ( <Tabs.Screen
<Ionicons name="home-outline" size={size} color={color} /> name="notices"
), options={{
}} title: "Ogłoszenia",
/> tabBarLabel: "Ogłoszenia",
<Tabs.Screen tabBarIcon: ({color, size}) => (
name="notices" <Ionicons name="list-outline" size={size} color={color}/>
options={{ ),
title: "Ogłoszenia", }}
tabBarLabel: "Ogłoszenia", />
tabBarIcon: ({ color, size }) => ( <Tabs.Screen
<Ionicons name="list-outline" size={size} color={color} /> name="notice/create"
), options={{
}} title: "Dodaj",
/> tabBarLabel: "Dodaj",
<Tabs.Screen tabBarIcon: ({color, size}) => (
name="notice/create" <Ionicons name="add-circle-outline" size={size} color={color}/>
options={{ ),
title: "Dodaj", }}
tabBarLabel: "Dodaj", />
tabBarIcon: ({ color, size }) => ( <Tabs.Screen
<Ionicons name="add-circle-outline" size={size} color={color} /> name="wishlist"
), options={{
}} title: "Ulubione",
/> tabBarLabel: "Ulubione",
<Tabs.Screen tabBarIcon: ({color, size}) => (
name="wishlist" <Ionicons name="heart-outline" size={size} color={color}/>
options={{ ),
title: "Ulubione", }}
tabBarLabel: "Ulubione", />
tabBarIcon: ({ color, size }) => ( <Tabs.Screen
<Ionicons name="heart-outline" size={size} color={color} /> name="dashboard"
), options={{
}} headerShown: false,
/> title: "Konto",
<Tabs.Screen tabBarLabel: "Konto",
name="dashboard" tabBarIcon: ({color, size}) => (
options={{ <Ionicons name="person-outline" size={size} color={color}/>
headerShown: false, ),
title: "Konto", }}
tabBarLabel: "Konto", />
tabBarIcon: ({ color, size }) => ( </Tabs>
<Ionicons name="person-outline" size={size} color={color} /> );
),
}}
/>
</Tabs>
);
} }

View File

@@ -1,15 +1,6 @@
import { DrawerItem } from "@react-navigation/drawer";
import { Drawer } from "expo-router/drawer"; import { Drawer } from "expo-router/drawer";
import { useAuthStore } from "@/store/authStore";
import {
DrawerContentScrollView,
DrawerItemList,
} from "@react-navigation/drawer";
export default function AccountDrawerLayout() { export default function AccountDrawerLayout() {
const signOut = useAuthStore((state) => state.signOut);
return ( return (
<Drawer <Drawer
screenOptions={{ screenOptions={{
@@ -18,19 +9,10 @@ export default function AccountDrawerLayout() {
drawerActiveBackgroundColor: "#f0f0f0", drawerActiveBackgroundColor: "#f0f0f0",
drawerItemStyle: { drawerItemStyle: {
borderRadius: 8, borderRadius: 8,
// backgroundColor: "transparent",
}, },
headerTintColor: "#1c1c1e", headerTintColor: "#1c1c1e",
}} }}
drawerContent={(props) => (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem
label="Wyloguj"
onPress={signOut}
labelStyle={{ color: "red" }}
/>
</DrawerContentScrollView>
)}
> >
<Drawer.Screen name="account" options={{ title: "Konto" }} /> <Drawer.Screen name="account" options={{ title: "Konto" }} />
<Drawer.Screen <Drawer.Screen

View File

@@ -1,105 +1,4 @@
import { Link } from "expo-router";
import { Pressable } from "react-native";
import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text"; import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack"; export default function User() {
import { Image } from "@/components/ui/image"; return <Text>Użytkownik</Text>;
import { ActivityIndicator } from "react-native";
import { useEffect, useState } from "react";
import { getUserById } from "@/api/client";
import { HStack } from "@gluestack-ui/themed";
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
useEffect(() => {
const fetchUser = async () => {
setIsLoading(true);
try {
const userData = await getUserById(currentUserId);
setUser(userData);
} catch (err) {
console.error("Błąd podczas pobierania danych użytkownika:", err);
} finally {
setIsLoading(false);
}
};
fetchUser();
}, []);
if (isLoading) {
return <ActivityIndicator />;
}
if (!user) {
return <Text>Nie udało się pobrać danych użytkownika.</Text>;
}
return (
<VStack className="bg-gray-50 flex-1">
<Box className="bg-white pb-6 shadow-sm">
<Box className="items-center pt-6 mb-4">
<Image
source={{
uri:
user.profileImage ||
"https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain",
}}
className="h-24 w-24 rounded-full border-4 border-white shadow-md"
alt="Zdjęcie profilowe"
/>
</Box>
<Text className="text-2xl font-bold text-center mb-1">
{user.firstName} {user.lastName}
</Text>
</Box>
<Box className="bg-white mt-4 p-5 border-t border-b border-gray-200">
<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>
</HStack>
<Pressable
className="border border-[#002f34] rounded-md py-2 px-4 self-start"
onPress={() => console.log("Edytuj dane użytkownika")}
>
<Text className="text-[#002f34] font-medium">Edytuj profil</Text>
</Pressable>
</Box>
<Box className="bg-white mt-4 p-5">
<Text className="font-bold text-lg mb-3">Moje konto</Text>
<Link href="/dashboard/userNotices" asChild>
<Pressable className="py-3 flex-row items-center border-b border-gray-100">
<Text className="text-lg flex-1">Moje ogłoszenia</Text>
<Text></Text>
</Pressable>
</Link>
{/*Tak dodałem, można zmienić na coś innego*/}
<Link href="/dashboard/userPaymentHistory" asChild>
<Pressable className="py-3 flex-row items-center border-b border-gray-100">
<Text className="text-lg flex-1">Historia płatności</Text>
<Text></Text>
</Pressable>
</Link>
{/* <Pressable className="py-3 flex-row items-center">
<Text className="text-lg flex-1">Ustawienia powiadomień</Text>
<Text>▶</Text>
</Pressable> */}
</Box>
{/* <Pressable className="mt-8 mx-5 p-4 bg-white rounded-md items-center shadow-sm">
<Text className="text-red-500 font-medium">Wyloguj się</Text>
</Pressable> */}
</VStack>
);
} }

View File

@@ -1,75 +1,4 @@
import { useNoticesStore } from "@/store/noticesStore"; import { Text } from "@/components/ui/text";
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";
export default function UserNotices() { export default function UserNotices() {
const { notices, fetchNotices } = useNoticesStore(); return <Text>Użytkownik</Text>;
const [isLoading, setIsLoading] = useState(true);
const currentUserId = 1; // Tymczasowo, do czasu zaimplementowania logowania bo nie moge pobrac usera
useEffect(() => {
const loadNotices = async () => {
setIsLoading(true);
try {
await fetchNotices();
} catch (err) {
console.error("Błąd podczas pobierania ogłoszeń:", err);
} finally {
setIsLoading(false);
}
};
loadNotices();
}, []);
const userNotices = notices.filter(notice => notice.clientId === currentUserId);
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>
)}
keyExtractor={(item) => item.noticeId.toString()}
/>
) : (
<Text>Nie masz żadnych ogłoszeń.</Text>
)}
</VStack>
);
} }

View File

@@ -1,20 +1,17 @@
import { ScrollView, View } from "react-native"; import { ScrollView, View } from "react-native";
import { useNoticesStore } from "@/store/noticesStore"; import { useNoticesStore } from '@/store/noticesStore';
import { CategorySection } from "@/components/CategorySection"; import { CategorySection } from "@/components/CategorySection";
import { NoticeSection } from "@/components/NoticeSection"; import { NoticeSection } from "@/components/NoticeSection";
import { UserSection } from "@/components/UserSection"; import { UserSection } from "@/components/UserSection";
import { SearchSection } from "@/components/SearchSection"; import { SearchSection } from "@/components/SearchSection";
import { FlatList } from "react-native"; import { FlatList } from 'react-native';
import { useAuthStore } from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { SafeAreaView } from "react-native";
export default function Home() { export default function Home() {
const token = useAuthStore((state) => state.token); const token = useAuthStore((state) => state.token);
const router = useRouter(); const router = useRouter();
const [isReady, setIsReady] = useState(false); const [isReady, setIsReady] = useState(false);
const fetchNotices = useNoticesStore((state) => state.fetchNotices);
useEffect(() => { useEffect(() => {
setIsReady(true); setIsReady(true);
@@ -26,41 +23,23 @@ export default function Home() {
} }
}, [isReady, token, router]); }, [isReady, token, router]);
useEffect(() => {
if (token) {
fetchNotices();
}
}, [token, fetchNotices]);
const notices = useNoticesStore((state) => state.notices); const notices = useNoticesStore((state) => state.notices);
// console.log("Notices:", notices); const latestNotices = [...notices]
const latestNotices = [...notices]
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate)) .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))
.slice(0, 6); .slice(0, 6);
const recomendedNotices = [...notices] const recomendedNotices = [...notices]
.sort(() => Math.random() - 0.5) .sort(() => Math.random() - 0.5)
.slice(0, 6); .slice(0, 6);
return ( return (
<SafeAreaView className="flex-1 m-2"> <View>
{/* <View> */} <SearchSection/>
<SearchSection /> <ScrollView showsVerticalScrollIndicator={false} className='m-2'>
<ScrollView showsVerticalScrollIndicator={false}>
<CategorySection title="Polecane kategorie" notices={notices} /> <CategorySection title="Polecane kategorie" notices={notices} />
<NoticeSection <NoticeSection title="Najnowsze ogłoszenia" notices={latestNotices} ctaLink="/notices?sort=latest"/>
title="Najnowsze ogłoszenia"
notices={latestNotices}
ctaLink="/notices?sort=latest"
/>
<UserSection title="Popularni sprzedawcy" notices={notices} /> <UserSection title="Popularni sprzedawcy" notices={notices} />
<NoticeSection <NoticeSection title="Proponowane ogłoszenia" notices={recomendedNotices} ctaLink="/notices"/>
title="Proponowane ogłoszenia" </ScrollView>
notices={recomendedNotices} </View>
ctaLink="/notices"
/>
</ScrollView>
{/* </View> */}
</SafeAreaView>
); );
} }

View File

@@ -7,14 +7,12 @@ import { Text } from "@/components/ui/text";
import { useEffect } from "react"; import { useEffect } from "react";
export default function Wishlist() { export default function Wishlist() {
const wishlistNotices = useWishlist((state) => state.wishlistNotices); const wishlistNotices = useWishlist((state) => state.wishlistNotices);
const fetchWishlist = useWishlist((state) => state.fetchWishlist); const fetchWishlist = useWishlist((state) => state.fetchWishlist);
useEffect(() => { useEffect(() => {
fetchWishlist(); fetchWishlist();
}, []); }, []);
// console.log("Wishlist notices:", wishlistNotices);
if (wishlistNotices.length === 0) { if (wishlistNotices.length === 0) {
return ( return (
<Box className="flex-row flex-1 justify-center"> <Box className="flex-row flex-1 justify-center">

View File

@@ -2,13 +2,21 @@ import { Stack, Redirect } from "expo-router";
import "@/global.css"; import "@/global.css";
import { GluestackUIProvider } from "@/components/ui/gluestack-ui-provider"; import { GluestackUIProvider } from "@/components/ui/gluestack-ui-provider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useNoticesStore } from "@/store/noticesStore";
const queryClient = new QueryClient(); const queryClient = new QueryClient();
export default function RootLayout() { export default function RootLayout() {
const fetchNotices = useNoticesStore((state) => state.fetchNotices);
useEffect(() => {
fetchNotices();
}, []);
return ( return (
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<GluestackUIProvider> <GluestackUIProvider>
<Stack <Stack
screenOptions={{ screenOptions={{
headerTintColor: "#1c1c1e", headerTintColor: "#1c1c1e",

View File

@@ -1,337 +1,133 @@
import { Link, Stack, useLocalSearchParams } from "expo-router"; import {Stack, useLocalSearchParams} from "expo-router";
import { Box } from "@/components/ui/box"; import {Box} from "@/components/ui/box";
import { Card } from "@/components/ui/card"; import {Card} from "@/components/ui/card";
import { Heading } from "@/components/ui/heading"; 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 { Ionicons } from "@expo/vector-icons"; import {Ionicons} from "@expo/vector-icons";
import { import {ActivityIndicator} from "react-native";
ActivityIndicator, import {useEffect, useState} from "react";
Dimensions, import {useNoticesStore} from "@/store/noticesStore";
FlatList, import {useWishlist} from "@/store/wishlistStore";
View, import {Pressable} from "react-native";
TextInput,
} 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");
export default function NoticeDetails() { export default function NoticeDetails() {
const { id } = useLocalSearchParams(); const {id} = useLocalSearchParams();
const [images, setImages] = useState([]); const [image, setImage] = useState(null);
const [isImageLoading, setIsImageLoading] = useState(true); const [isImageLoading, setIsImageLoading] = useState(true);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [notice, setNotice] = useState(null); const [notice, setNotice] = useState(null);
const [user, setUser] = useState(null);
const [isUserLoading, setIsUserLoading] = useState(true);
const flatListRef = useRef(null);
const [currentIndex, setCurrentIndex] = useState(0);
const [isMessageFormVisible, setIsMessageFormVisible] = useState(false); const {getNoticeById, getAllImagesByNoticeId} = useNoticesStore();
const [message, setMessage] = useState(""); const addNoticeToWishlist = useWishlist((state) => state.addNoticeToWishlist);
const [Email, setEmail] = useState(""); const removeNoticeFromWishlist = useWishlist((state) => state.removeNoticeFromWishlist);
const handleSendMessage = () => { const isInWishlist = useWishlist((state) =>
console.log("Wiadomość do:", user?.email); notice ? state.wishlistNotices.some((item) => item.noticeId === notice.noticeId) : false
console.log("Email nadawcy:", Email); );
console.log("Treść:", message);
setIsMessageFormVisible(false); useEffect(() => {
setMessage(""); const fetchNotice = async () => {
setEmail(""); setIsLoading(true);
}; try {
const noticeData = getNoticeById(Number(id));
if (noticeData) {
setNotice(noticeData);
setError(null);
} else {
setError(new Error(`Notice with ID ${id} not found.`));
}
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
const formatDate = (dateString) => { fetchNotice();
const date = new Date(dateString); }, [id]);
return date.toLocaleDateString("pl-PL", {
year: "numeric",
month: "2-digit",
day: "2-digit",
});
};
const { getNoticeById, getAllImagesByNoticeId } = useNoticesStore(); useEffect(() => {
const toggleNoticeInWishlist = useWishlist( const fetchImage = async () => {
(state) => state.toggleNoticeInWishlist setIsImageLoading(true);
); if (notice) {
try {
const images = await getAllImagesByNoticeId(notice.noticeId);
setImage(images && images.length > 0 ? images[0] : "https://http.cat/404.jpg");
} catch (err) {
console.error("Error while loading images:", err);
setImage("https://http.cat/404.jpg");
} finally {
setIsImageLoading(false);
}
}
};
const isInWishlist = useWishlist((state) => if (notice) {
id ? state.wishlistNotices.some((item) => item.noticeId == id) : false fetchImage();
); }
const onViewableItemsChanged = useRef(({ viewableItems }) => { }, [notice]);
if (viewableItems.length > 0) {
setCurrentIndex(viewableItems[0].index); if (isLoading) {
return <ActivityIndicator/>;
} }
}).current;
const viewabilityConfig = useRef({ if (error) {
itemVisiblePercentThreshold: 70, return <Text>Błąd, spróbuj ponownie póżniej: {error.message}</Text>;
}).current;
useEffect(() => {
const fetchNotice = async () => {
setIsLoading(true);
try {
const noticeData = getNoticeById(Number(id));
if (noticeData) {
setNotice(noticeData);
setError(null);
} else {
setError(new Error(`Notice with ID ${id} not found.`));
}
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
fetchNotice();
}, [id]);
useEffect(() => {
const fetchImage = async () => {
setIsImageLoading(true);
if (notice) {
try {
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
setImages(
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");
} finally {
setIsImageLoading(false);
}
}
};
if (notice) {
fetchImage();
} }
}, [notice]);
useEffect(() => { if (!notice) {
const fetchUser = async () => { return <Text>Nie znaleziono ogłoszenia</Text>;
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(); return (
}, [notice]); <Card className="p-0 rounded-lg m-3 flex-1">
<Stack.Screen
if (isLoading) { options={{
return <ActivityIndicator />; title: notice.title,
} }}
/>
if (error) { {isImageLoading ? (
return <Text>Błąd, spróbuj ponownie póżniej: {error.message}</Text>; <Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
} <ActivityIndicator size="large" color="#3b82f6" />
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()}
/>
{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>
)}
<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);
}}
>
<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"
/>
</Box> </Box>
<Box className="flex-1">
<Text className="text-xl font-bold text-gray-950">
{user.firstName} {user.lastName}
</Text>
<Text className="text-sm text-typography-700">
Email: {user.email}
</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> <Image
source={{
uri: image,
}}
className="h-auto w-full rounded-md aspect-[1/1]"
alt="image"
resizeMode="cover"
/>
)} )}
</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> <VStack className="p-2">
<Text className="bg-gray-100 p-3 rounded text-gray-500"> <Text className="text-sm font-normal mb-2 text-typography-700">
{user?.email || "Brak adresu e-mail"} {notice.title}
</Text> </Text>
<Text className="text-sm font-medium mb-1">Twój e-mail:</Text> <Box className="flex-row items-center">
<TextInput <Heading size="md" className="flex-1">
className="border border-gray-300 p-2 rounded" {notice.price}
placeholder="Wpisz swój adres e-mail" </Heading>
value={Email} <Pressable
onChangeText={setEmail} onPress={() => {
/> if (isInWishlist) {
removeNoticeFromWishlist(notice.noticeId);
<TextInput } else {
className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left" addNoticeToWishlist(notice);
multiline }
numberOfLines={4} }}
placeholder="Napisz swoją wiadomość..." >
value={message} <Ionicons
onChangeText={setMessage} name={isInWishlist ? "heart" : "heart-outline"}
/> size={24}
color={"primary-heading-500"}
<View className="flex-row justify-end space-x-2"> />
<Pressable </Pressable>
onPress={() => setIsMessageFormVisible(false)} </Box>
className="bg-gray-300 py-2 px-4 rounded-md" </VStack>
> </Card>
<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>
);
} }

View File

@@ -1,69 +0,0 @@
import { useLocalSearchParams } from "expo-router";
import { useState, useEffect } from "react";
import { FlatList, ActivityIndicator, Text } from "react-native";
import { Box } from "@/components/ui/box";
import { Image } from "@/components/ui/image";
import { VStack } from "@/components/ui/vstack";
import { Heading } from "@/components/ui/heading";
import { getUserById } from "@/api/client";
import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard";
export default function UserProfile() {
const { userId } = useLocalSearchParams();
const [user, setUser] = useState(null);
const [isUserLoading, setIsUserLoading] = useState(true);
const { notices } = useNoticesStore();
useEffect(() => {
const fetchUser = async () => {
setIsUserLoading(true);
try {
const userData = await getUserById(Number(userId));
setUser(userData);
} catch (err) {
console.error("Błąd podczas pobierania danych użytkownika:", err);
setUser(null);
} finally {
setIsUserLoading(false);
}
};
fetchUser();
}, [userId]);
if (isUserLoading) {
return <ActivityIndicator />;
}
if (!user) {
return <Text>Nie znaleziono użytkownika</Text>;
}
const userNotices = notices.filter(notice => notice.clientId === Number(userId));
return (
<VStack className="p-4">
<Box className="flex-row items-center mb-4">
<Image
source={{ uri: user.profileImage || "https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain" }}
className="h-16 w-16 rounded-full mr-4"
alt="Zdjęcie profilowe"
/>
<Heading size="lg">
{user.firstName} {user.lastName}
</Heading>
</Box>
{userNotices.length > 0 ? (
<FlatList
data={userNotices}
numColumns={2}
columnWrapperStyle={{ marginBottom: 10, justifyContent: "space-between" }}
renderItem={({ item }) => <NoticeCard notice={item} />}
keyExtractor={(item) => item.noticeId.toString()}
/>
) : (
<Text>Ten użytkownik nie ma żadnych ogłoszeń.</Text>
)}
</VStack>
);
}

View File

@@ -1,38 +1,31 @@
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"; import { Pressable } from '@/components/ui/pressable';
import { Pressable } from "@/components/ui/pressable"; import axios from 'axios';
import { listCategories } from "@/api/categories";
export function CategorySection({notices, title}) {
// const notices = useNoticesStore((state) => state.notices);
export function CategorySection({ notices, title }) {
const [categoryMap, setCategoryMap] = useState({}); const [categoryMap, setCategoryMap] = useState({});
useEffect(() => { useEffect(() => {
const fetchCategories = async () => { axios.get('https://testowe.zikor.pl/api/v1/vars/categories')
let data = await listCategories(); .then(res => setCategoryMap(res.data))
if (Array.isArray(data)) { .catch(() => setCategoryMap({}));
setCategoryMap(data); }, []);
}
};
fetchCategories(); const categories = Array.from(
}); new Set(notices.map((notice) => notice.category))
).filter(Boolean);
const categories = Array.from(
new Set(notices.map((notice) => notice.category))
).filter(Boolean);
const getCount = (category) => const getCount = (category) =>
notices.filter((notice) => notice.category === category).length; notices.filter((notice) => notice.category === category).length;
if (!categoryMap || Object.keys(categoryMap).length === 0) { return (
return null;
}
return (
<View className="mb-6"> <View className="mb-6">
<Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading> <Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading>
<FlatList <FlatList
@@ -45,15 +38,16 @@ export function CategorySection({ notices, title }) {
const categoryObj = categoryMap.find((cat) => cat.value === item); const categoryObj = categoryMap.find((cat) => cat.value === item);
return ( return (
<Link href={`/notices?category=${item}`} asChild> <Link href={`/notices?category=${item}`} asChild>
<Pressable className="bg-gray-200 p-4 rounded-lg mr-2"> <Pressable className="bg-gray-200 p-4 rounded-lg mr-2">
<Text> <Text>
{categoryObj ? categoryObj.label : item} ({getCount(item)}) {categoryObj ? categoryObj.label : item} ({getCount(item)})
</Text> </Text>
</Pressable> </Pressable>
</Link> </Link>
); );
}} }}
/> />
</View> </View>
); );
} }

View File

@@ -2,7 +2,6 @@ import { Input, InputField, InputIcon, InputSlot } from "@/components/ui/input"
import { SearchIcon } from "@/components/ui/icon" import { SearchIcon } from "@/components/ui/icon"
import { Box } from "@/components/ui/box" import { Box } from "@/components/ui/box"
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { View } from "react-native";
export function SearchSection({ searchQuery, setSearchQuery }) { export function SearchSection({ searchQuery, setSearchQuery }) {
const router = useRouter(); const router = useRouter();
@@ -15,17 +14,18 @@ export function SearchSection({ searchQuery, setSearchQuery }) {
}); });
}; };
return ( return (
<Box className="mb-2 bg-white p-2 rounded-md"> <Box className="m-2 bg-white">
<Input className="p-2"> <Input>
<InputSlot> <InputSlot>
<InputIcon as={SearchIcon} /> <InputIcon as={SearchIcon} />
</InputSlot> </InputSlot>
<InputField placeholder="Wyszukaj..." <InputField placeholder="Wyszukaj.."
value={searchQuery} value={searchQuery}
onChangeText={setSearchQuery} onChangeText={setSearchQuery}
onSubmitEditing={handleSubmit} onSubmitEditing={handleSubmit}
returnKeyType="search" /> returnKeyType="search" />
</Input> </Input>
</Box> </Box>
) )
} }

View File

@@ -1,27 +1,22 @@
import { View } from "react-native"; import { View} from 'react-native';
import { useEffect, useState } from "react"; import { useEffect, useState } from 'react'
import { Heading } from "@/components/ui/heading"; import { Heading } from '@/components/ui/heading';
import { FlatList } from "react-native"; import { FlatList } from 'react-native';
import axios from "axios"; import axios from 'axios';
import UserBlock from "@/components/UserBlock"; import UserBlock from '@/components/UserBlock';
import { useAuthStore } from "@/store/authStore";
export function UserSection({ notices, title }) { export function UserSection({notices, title}) {
const token = useAuthStore((state) => state.token);
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const [users, setUsers] = useState([]);
const [users, setUsers] = useState([]);
useEffect(() => { useEffect(() => {
if (token) { axios.get('https://testowe.zikor.pl/api/v1/clients/get/all')
axios .then(res => setUsers(res.data))
.get("https://hopp.zikor.pl/api/v1/clients/get/all", { headers }) .catch(() => setUsers([]));
.then((res) => setUsers(res.data)) }, []);
.catch(() => setUsers([]));
}
}, [token]);
const usersWithNoticeCount = users.map((user) => { const usersWithNoticeCount = users.map(user => {
const count = notices.filter((n) => n.clientId === user.id).length; const count = notices.filter(n => n.clientId === user.id).length;
return { ...user, noticeCount: count }; return { ...user, noticeCount: count };
}); });
@@ -29,7 +24,7 @@ export function UserSection({ notices, title }) {
.sort((a, b) => b.noticeCount - a.noticeCount) .sort((a, b) => b.noticeCount - a.noticeCount)
.slice(0, 5); .slice(0, 5);
return ( return (
<View className="mb-6"> <View className="mb-6">
<Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading> <Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading>
<FlatList <FlatList
@@ -38,9 +33,12 @@ export function UserSection({ notices, title }) {
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
contentContainerStyle={{ paddingHorizontal: 8, gap: 12 }} contentContainerStyle={{ paddingHorizontal: 8, gap: 12 }}
renderItem={({ item }) => { renderItem={({ item }) => {
return <UserBlock user={item} />; return (
<UserBlock user={item} />
);
}} }}
/> />
</View> </View>
); );
} }

View File

@@ -1,21 +0,0 @@
{
"cli": {
"version": ">= 16.8.0",
"appVersionSource": "remote"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {
"autoIncrement": true
}
},
"submit": {
"production": {}
}
}

View File

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

View File

@@ -1,141 +1,108 @@
import { create } from "zustand"; import {create} from "zustand";
import { createJSONStorage, persist } from "zustand/middleware"; import {createJSONStorage, persist} from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import axios from "axios"; import axios from "axios";
const API_URL = "https://hopp.zikor.pl/api/v1"; const API_URL = "https://testowe.zikor.pl/api/v1";
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set, get) => { (set) => ({
// Dodaj interceptor tylko raz user: null,
if (!axios.interceptors.response.handlers.length) { token: null,
axios.interceptors.response.use( isLoading: false,
(response) => response, error: null,
(error) => {
if (
(error.response && error.response.status === 401) ||
error.response.status === 403
) {
set({ user: null, token: null, isLoading: false });
delete axios.defaults.headers.common["Authorization"];
}
return Promise.reject(error);
}
);
}
return { signIn: async (email, password) => {
user_id: null, set({isLoading: true, error: null});
token: null, try {
isLoading: false, const response = await axios.post(`${API_URL}/auth/login`, {
error: null, email,
password
});
signIn: async (email, password) => { const user = response.data.user;
set({ isLoading: true, error: null }); const token = response.data.token;
try { set({user, token, isLoading: false});
const response = await axios.post(`${API_URL}/auth/login`, { } catch (error) {
email, set({error: error.response?.data?.message || error.message, isLoading: false});
password, throw error;
}); }
},
const user_id = response.data.user_id; signUp: async (userData) => {
const token = response.data.token; set({isLoading: true, error: null});
set({ user_id: user_id, token: token, isLoading: false }); try {
console.log(userData);
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; const response = await axios.post(`${API_URL}/auth/register`, userData, {
} catch (error) { headers: {'Content-Type': 'application/json'}
set({ });
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signUp: async (userData) => { console.log(response.data);
set({ isLoading: true, error: null });
try {
const response = await axios.post(
`${API_URL}/auth/register`,
userData,
{
headers: { "Content-Type": "application/json" },
}
);
const user_id = response.data.user_id; const user = response.data.user;
const token = response.data.token; const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false }); set({user, token, isLoading: false});
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; return user;
} catch (error) { } catch (error) {
set({ set({error: error.response?.data?.message || error.message, isLoading: false});
error: error.response?.data?.message || error.message, throw error;
isLoading: false, }
}); },
throw error;
}
},
signInWithGoogle: async (googleToken) => { signInWithGoogle: async (googleToken) => {
set({ isLoading: true, error: null }); set({isLoading: true, error: null});
try { try {
const response = await axios.post( const response = await axios.post(`${API_URL}/auth/google`, {token: googleToken});
`${API_URL}/auth/google`,
{ googleToken: googleToken },
{
headers: { "Content-Type": "application/json" },
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; const {user, token} = response.data;
} catch (error) { set({user, token, isLoading: false});
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signOut: async () => { axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
try {
await axios.post(`${API_URL}/auth/logout`);
} catch (error) {
console.error("Logout error:", error);
} finally {
delete axios.defaults.headers.common["Authorization"];
set({ user_id: null, token: null });
}
},
// checkAuth: async () => { return user;
// const { token } = useAuthStore.getState(); } catch (error) {
// if (!token) return null; set({error: error.response?.data?.message || error.message, isLoading: false});
throw error;
}
},
// set({ isLoading: true }); signOut: async () => {
// try { try {
// axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; // Можно отправить запрос на бэкенд для инвалидации токена
await axios.post(`${API_URL}/auth/logout`);
} catch (error) {
console.error("Logout error:", error);
} finally {
delete axios.defaults.headers.common["Authorization"];
set({user: null, token: null});
}
},
// const response = await axios.get(`${API_URL}/auth/me`); checkAuth: async () => {
const {token} = useAuthStore.getState();
if (!token) return null;
// set({ user_id: response.data, isLoading: false }); set({isLoading: true});
// return response.data; try {
// } catch (error) { axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
// delete axios.defaults.headers.common["Authorization"];
// set({ user_id: null, token: null, isLoading: false }); const response = await axios.get(`${API_URL}/auth/me`);
// return null;
// } set({user: response.data, isLoading: false});
// }, return response.data;
}; } catch (error) {
}, delete axios.defaults.headers.common["Authorization"];
{ set({user: null, token: null, isLoading: false});
name: "auth-storage", return null;
storage: createJSONStorage(() => AsyncStorage), }
} },
) }),
{
name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage),
}
)
); );