8 Commits

Author SHA1 Message Date
Patryk
c39f9c383e fix account 2025-06-08 09:37:50 +02:00
Patryk
717dd32543 refactor: clean up API_URL definition and improve error handling in authStore 2025-06-08 09:21:04 +02:00
Patryk
0c92a4b4ee Merge remote-tracking branch 'origin/authentication' into integrateWithAuth 2025-06-08 09:20:08 +02:00
Patryk
612210a944 fix wishlist in notice screen 2025-06-07 23:15:22 +02:00
Patryk
c19333ad8b fix login check and urls 2025-06-07 23:08:21 +02:00
d4133f28bd autoryzacja działa zarówno na android jak i ios 2025-06-06 15:49:08 +02:00
b6f2225148 scheme fix 2025-06-04 22:25:31 +02:00
8dc51fafdf AUTORYZACJA DO GOOOOOGLA DZIALA 2025-06-04 22:09:03 +02:00
17 changed files with 861 additions and 701 deletions

View File

@@ -1,12 +1,11 @@
import axios from "axios"; import axios from "axios";
import {useAuthStore} from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
const API_URL = "https://testowe.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
export async function listCategories() { export async function listCategories() {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.get(`${API_URL}/vars/categories`, { headers }); const response = await axios.get(`${API_URL}/vars/categories`, { headers });

View File

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

View File

@@ -1,21 +1,18 @@
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 = "http://10.0.2.2:8080/api/v1"; const API_URL = "https://hopp.zikor.pl/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}` } : {};
console.log(token);
const response = await fetch(`${API_URL}/notices/get/all`, { const response = await fetch(`${API_URL}/notices/get/all`, {
headers: headers headers: headers,
}); });
console.log(response);
const data = await response.json(); const data = await response.json();
if (!response.ok) { if (!response.ok) {
throw new Error(response.toString()); throw new Error(response.toString());
@@ -62,8 +59,6 @@ export async function getImageByNoticeId(noticeId) {
const imageName = listResponse.data[0]; const imageName = listResponse.data[0];
imageUrl = `${API_URL}/images/get/${imageName}`; imageUrl = `${API_URL}/images/get/${imageName}`;
console.log(`Pobrano zdjęcie o nazwie: ${imageName}`);
return imageUrl; return imageUrl;
} catch (err) { } catch (err) {
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`); console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
@@ -77,33 +72,34 @@ export async function getAllImagesByNoticeId(noticeId) {
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) {
const imageUrls = listResponse.data.map(imageName => return listResponse.data.map(
`${API_URL}/images/get/${imageName}` (imageName) => `${API_URL}/images/get/${imageName}`
); );
// console.log(`Pobrano ${imageUrls.length} zdjęć dla ogłoszenia o id: ${noticeId}`);
return imageUrls;
} }
// console.log(`Brak zdjęć dla ogłoszenia o id: ${noticeId}`);
return ["https://http.cat/404.jpg"]; return ["https://http.cat/404.jpg"];
} catch (err) { } catch (err) {
// console.log(`Błąd podczas pobierania listy zdjęć dla ogłoszenia o id: ${noticeId}`, err); if (err.response.status === 404) {
// console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
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"]; return ["https://http.cat/404.jpg"];
} }
} }
export const uploadImage = async (noticeId, imageUri) => { export const uploadImage = async (noticeId, imageUri) => {
console.log(imageUri);
const formData = new FormData(); const formData = new FormData();
const filename = imageUri.split('/').pop(); const filename = imageUri.split("/").pop();
const match = /\.(\w+)$/.exec(filename); const match = /\.(\w+)$/.exec(filename);
const type = match ? `image/${match[1]}` : 'image/jpeg'; const type = match ? `image/${match[1]}` : "image/jpeg";
formData.append('file', { formData.append("file", {
uri: imageUri, uri: imageUri,
name: filename, name: filename,
type: type, type: type,
@@ -115,15 +111,19 @@ export const uploadImage = async (noticeId, imageUri) => {
formData, formData,
{ {
headers: { headers: {
'Content-Type': 'multipart/form-data', "Content-Type": "multipart/form-data",
}, },
} }
); );
console.info('Upload successful:', response.data); console.info("Upload successful:", response.data);
return response.data; return response.data;
} catch (error) { } catch (error) {
console.log("imageURI:", imageUri); console.log("imageURI:", imageUri);
console.error('Error uploading image:', error.response.data, error.response.status); console.error(
"Error uploading image:",
error.response.data,
error.response.status
);
throw error; throw error;
} }
} };

View File

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

View File

@@ -2,7 +2,7 @@
"expo": { "expo": {
"name": "ArtisanConnect", "name": "ArtisanConnect",
"slug": "ArtisanConnect", "slug": "ArtisanConnect",
"scheme": "Artisanconnect", "scheme": "com.hamx.artisanconnect",
"version": "1.0.0", "version": "1.0.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/icon.png", "icon": "./assets/icon.png",
@@ -14,13 +14,19 @@
"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"
@@ -40,6 +46,12 @@
} }
], ],
"expo-web-browser" "expo-web-browser"
] ],
"extra": {
"router": {},
"eas": {
"projectId": "7a0d8bc8-938f-4d2a-babb-945faee13429"
}
}
} }
} }

View File

@@ -1,5 +1,5 @@
import React, {useState} from 'react'; import React, {useEffect, useState} from 'react';
import {StyleSheet, ActivityIndicator, SafeAreaView, View} from 'react-native'; import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform} 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,12 +15,37 @@ 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} = useAuthStore(); const {signIn, isLoading, signInWithGoogle} = 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.');
@@ -36,6 +61,47 @@ 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}>
@@ -82,7 +148,7 @@ export default function Login() {
</Text> </Text>
<Divider flex={1}/> <Divider flex={1}/>
</HStack> </HStack>
<Button size="sm"> <Button size="sm" onPress={() => promptAsync()}>
<Ionicons name="logo-google" color="#fff"/> <Ionicons name="logo-google" color="#fff"/>
</Button> </Button>
</Box> </Box>

View File

@@ -1,7 +1,13 @@
import {Tabs} from "expo-router"; import { Tabs, Redirect } 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);
if (!token) {
return <Redirect href="/login" />;
}
return ( return (
<Tabs <Tabs
screenOptions={{ screenOptions={{
@@ -13,8 +19,8 @@ export default function TabLayout() {
options={{ options={{
title: "Home", title: "Home",
tabBarLabel: "Home", tabBarLabel: "Home",
tabBarIcon: ({color, size}) => ( tabBarIcon: ({ color, size }) => (
<Ionicons name="home-outline" size={size} color={color}/> <Ionicons name="home-outline" size={size} color={color} />
), ),
}} }}
/> />
@@ -23,8 +29,8 @@ export default function TabLayout() {
options={{ options={{
title: "Ogłoszenia", title: "Ogłoszenia",
tabBarLabel: "Ogłoszenia", tabBarLabel: "Ogłoszenia",
tabBarIcon: ({color, size}) => ( tabBarIcon: ({ color, size }) => (
<Ionicons name="list-outline" size={size} color={color}/> <Ionicons name="list-outline" size={size} color={color} />
), ),
}} }}
/> />
@@ -33,8 +39,8 @@ export default function TabLayout() {
options={{ options={{
title: "Dodaj", title: "Dodaj",
tabBarLabel: "Dodaj", tabBarLabel: "Dodaj",
tabBarIcon: ({color, size}) => ( tabBarIcon: ({ color, size }) => (
<Ionicons name="add-circle-outline" size={size} color={color}/> <Ionicons name="add-circle-outline" size={size} color={color} />
), ),
}} }}
/> />
@@ -43,8 +49,8 @@ export default function TabLayout() {
options={{ options={{
title: "Ulubione", title: "Ulubione",
tabBarLabel: "Ulubione", tabBarLabel: "Ulubione",
tabBarIcon: ({color, size}) => ( tabBarIcon: ({ color, size }) => (
<Ionicons name="heart-outline" size={size} color={color}/> <Ionicons name="heart-outline" size={size} color={color} />
), ),
}} }}
/> />
@@ -54,8 +60,8 @@ export default function TabLayout() {
headerShown: false, headerShown: false,
title: "Konto", title: "Konto",
tabBarLabel: "Konto", tabBarLabel: "Konto",
tabBarIcon: ({color, size}) => ( tabBarIcon: ({ color, size }) => (
<Ionicons name="person-outline" size={size} color={color}/> <Ionicons name="person-outline" size={size} color={color} />
), ),
}} }}
/> />

View File

@@ -1,6 +1,15 @@
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={{
@@ -9,10 +18,19 @@ 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

@@ -55,13 +55,6 @@ export default function Account() {
<Text className="text-2xl font-bold text-center mb-1"> <Text className="text-2xl font-bold text-center mb-1">
{user.firstName} {user.lastName} {user.firstName} {user.lastName}
</Text> </Text>
<Pressable
className="border border-[#002f34] rounded-md py-2 px-4 self-center"
onPress={() => console.log("Edytuj dane użytkownika")}
>
<Text className="text-[#002f34] font-medium">Edytuj profil</Text>
</Pressable>
</Box> </Box>
<Box className="bg-white mt-4 p-5 border-t border-b border-gray-200"> <Box className="bg-white mt-4 p-5 border-t border-b border-gray-200">
@@ -71,6 +64,13 @@ export default function Account() {
<Text className="text-gray-600 w-24">E-mail</Text> <Text className="text-gray-600 w-24">E-mail</Text>
<Text className="flex-1">{user.email || "brak danych"}</Text> <Text className="flex-1">{user.email || "brak danych"}</Text>
</HStack> </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>
<Box className="bg-white mt-4 p-5"> <Box className="bg-white mt-4 p-5">
@@ -91,15 +91,15 @@ export default function Account() {
</Pressable> </Pressable>
</Link> </Link>
<Pressable className="py-3 flex-row items-center"> {/* <Pressable className="py-3 flex-row items-center">
<Text className="text-lg flex-1">Ustawienia powiadomień</Text> <Text className="text-lg flex-1">Ustawienia powiadomień</Text>
<Text>▶</Text> <Text>▶</Text>
</Pressable> </Pressable> */}
</Box> </Box>
<Pressable className="mt-8 mx-5 p-4 bg-white rounded-md items-center shadow-sm"> {/* <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> <Text className="text-red-500 font-medium">Wyloguj się</Text>
</Pressable> </Pressable> */}
</VStack> </VStack>
); );
} }

View File

@@ -1,18 +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-safe-area-context";
import { SafeAreaView } from "react-native"; 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); const fetchNotices = useNoticesStore((state) => state.fetchNotices);
@@ -27,13 +26,11 @@ const token = useAuthStore((state) => state.token);
} }
}, [isReady, token, router]); }, [isReady, token, router]);
useEffect(() => { useEffect(() => {
if (token) { if (token) {
fetchNotices(); fetchNotices();
} }
}, [token, fetchNotices]); }, [token, fetchNotices]);
const notices = useNoticesStore((state) => state.notices); const notices = useNoticesStore((state) => state.notices);
// console.log("Notices:", notices); // console.log("Notices:", notices);
@@ -45,16 +42,23 @@ const token = useAuthStore((state) => state.token);
.sort(() => Math.random() - 0.5) .sort(() => Math.random() - 0.5)
.slice(0, 6); .slice(0, 6);
return ( return (
<SafeAreaView className="flex-1 m-2"> <SafeAreaView className="flex-1 m-2">
{/* <View> */} {/* <View> */}
<SearchSection/> <SearchSection />
<ScrollView showsVerticalScrollIndicator={false} > <ScrollView showsVerticalScrollIndicator={false}>
<CategorySection title="Polecane kategorie" notices={notices} /> <CategorySection title="Polecane kategorie" notices={notices} />
<NoticeSection title="Najnowsze ogłoszenia" notices={latestNotices} ctaLink="/notices?sort=latest"/> <NoticeSection
title="Najnowsze ogłoszenia"
notices={latestNotices}
ctaLink="/notices?sort=latest"
/>
<UserSection title="Popularni sprzedawcy" notices={notices} /> <UserSection title="Popularni sprzedawcy" notices={notices} />
<NoticeSection title="Proponowane ogłoszenia" notices={recomendedNotices} ctaLink="/notices"/> <NoticeSection
title="Proponowane ogłoszenia"
notices={recomendedNotices}
ctaLink="/notices"
/>
</ScrollView> </ScrollView>
{/* </View> */} {/* </View> */}
</SafeAreaView> </SafeAreaView>

View File

@@ -13,6 +13,8 @@ export default function Wishlist() {
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

@@ -1,23 +1,28 @@
import {Link, Stack, useLocalSearchParams} from "expo-router"; import { Link, 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 {ActivityIndicator, Dimensions, FlatList, View, TextInput} from "react-native"; import {
import {useEffect, useState, useRef} from "react"; ActivityIndicator,
import {useNoticesStore} from "@/store/noticesStore"; Dimensions,
import {useWishlist} from "@/store/wishlistStore"; FlatList,
import {Pressable, ScrollView} from "react-native"; View,
import {getUserById} from "@/api/client"; TextInput,
} from "react-native";
const {width} = Dimensions.get("window"); 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 [images, setImages] = useState([]);
const [isImageLoading, setIsImageLoading] = useState(true); const [isImageLoading, setIsImageLoading] = useState(true);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -28,34 +33,35 @@ export default function NoticeDetails() {
const flatListRef = useRef(null); const flatListRef = useRef(null);
const [currentIndex, setCurrentIndex] = useState(0); const [currentIndex, setCurrentIndex] = useState(0);
const [isMessageFormVisible, setIsMessageFormVisible] = useState(false); const [isMessageFormVisible, setIsMessageFormVisible] = useState(false);
const [message, setMessage] = useState(''); const [message, setMessage] = useState("");
const [Email, setEmail] = useState(''); const [Email, setEmail] = useState("");
const handleSendMessage = () => { const handleSendMessage = () => {
console.log('Wiadomość do:', user?.email); console.log("Wiadomość do:", user?.email);
console.log('Email nadawcy:', Email); console.log("Email nadawcy:", Email);
console.log('Treść:', message); console.log("Treść:", message);
setIsMessageFormVisible(false); setIsMessageFormVisible(false);
setMessage(''); setMessage("");
setEmail(''); setEmail("");
}; };
const formatDate = (dateString) => { const formatDate = (dateString) => {
const date = new Date(dateString); const date = new Date(dateString);
return date.toLocaleDateString('pl-PL', { return date.toLocaleDateString("pl-PL", {
year: 'numeric', year: "numeric",
month: '2-digit', month: "2-digit",
day: '2-digit' day: "2-digit",
}); });
}; };
const {getNoticeById, getAllImagesByNoticeId} = useNoticesStore(); const { getNoticeById, getAllImagesByNoticeId } = useNoticesStore();
const addNoticeToWishlist = useWishlist((state) => state.addNoticeToWishlist); const toggleNoticeInWishlist = useWishlist(
const removeNoticeFromWishlist = useWishlist((state) => state.removeNoticeFromWishlist); (state) => state.toggleNoticeInWishlist
);
const isInWishlist = useWishlist((state) => const isInWishlist = useWishlist((state) =>
notice ? state.wishlistNotices.some((item) => item.noticeId === notice.noticeId) : false id ? state.wishlistNotices.some((item) => item.noticeId == id) : false
); );
const onViewableItemsChanged = useRef(({ viewableItems }) => { const onViewableItemsChanged = useRef(({ viewableItems }) => {
if (viewableItems.length > 0) { if (viewableItems.length > 0) {
@@ -67,7 +73,6 @@ export default function NoticeDetails() {
itemVisiblePercentThreshold: 70, itemVisiblePercentThreshold: 70,
}).current; }).current;
useEffect(() => { useEffect(() => {
const fetchNotice = async () => { const fetchNotice = async () => {
setIsLoading(true); setIsLoading(true);
@@ -95,8 +100,11 @@ export default function NoticeDetails() {
if (notice) { if (notice) {
try { try {
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId); const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
setImages(fetchedImages && fetchedImages.length > 0 ? fetchedImages : ["https://http.cat/404.jpg"]); setImages(
fetchedImages && fetchedImages.length > 0
? fetchedImages
: ["https://http.cat/404.jpg"]
);
} catch (err) { } catch (err) {
console.error("Error while loading images:", err); console.error("Error while loading images:", err);
setImage("https://http.cat/404.jpg"); setImage("https://http.cat/404.jpg");
@@ -129,9 +137,8 @@ export default function NoticeDetails() {
fetchUser(); fetchUser();
}, [notice]); }, [notice]);
if (isLoading) { if (isLoading) {
return <ActivityIndicator/>; return <ActivityIndicator />;
} }
if (error) { if (error) {
@@ -183,7 +190,9 @@ export default function NoticeDetails() {
{images.map((_, index) => ( {images.map((_, index) => (
<Box <Box
key={index} key={index}
className={`w-2 h-2 rounded-full mx-1 ${index === currentIndex ? 'bg-primary-500' : 'bg-gray-300'}`} className={`w-2 h-2 rounded-full mx-1 ${
index === currentIndex ? "bg-primary-500" : "bg-gray-300"
}`}
/> />
))} ))}
</Box> </Box>
@@ -191,9 +200,7 @@ export default function NoticeDetails() {
</Box> </Box>
)} )}
<ScrollView <ScrollView showsVerticalScrollIndicator={false}>
showsVerticalScrollIndicator={false}
>
<VStack className="p-2"> <VStack className="p-2">
<Text className="text-sm font-normal mb-2 text-typography-700"> <Text className="text-sm font-normal mb-2 text-typography-700">
{formatDate(notice.publishDate)} {formatDate(notice.publishDate)}
@@ -210,11 +217,7 @@ export default function NoticeDetails() {
<Pressable <Pressable
onPress={() => { onPress={() => {
if (isInWishlist) { toggleNoticeInWishlist(id);
removeNoticeFromWishlist(notice.noticeId);
} else {
addNoticeToWishlist(notice);
}
}} }}
> >
<Ionicons <Ionicons
@@ -226,29 +229,30 @@ export default function NoticeDetails() {
</Box> </Box>
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm"> <Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-sm text-typography-500"> <Text className="text-sm text-typography-500">
Kategoria: <Text className="font-bold text-gray-950">{notice.category}</Text> Kategoria:{" "}
<Text className="font-bold text-gray-950">{notice.category}</Text>
</Text> </Text>
</Box> </Box>
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm"> <Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-2xl text-gray-950"> <Text className="text-2xl text-gray-950">Opis ogloszenia</Text>
Opis ogloszenia
</Text>
<Text className="text-sm text-typography-700"> <Text className="text-sm text-typography-700">
{notice.description} {notice.description}
</Text> </Text>
</Box> </Box>
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm"> <Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
<Text className="text-sm text-typography-500"> <Text className="text-sm text-typography-500">Uzytkownik:</Text>
Uzytkownik:
</Text>
{isUserLoading ? ( {isUserLoading ? (
<ActivityIndicator /> <ActivityIndicator />
) : user ? ( ) : user ? (
<> <>
<Box className="mr-4"> <Box className="mr-4">
<Image <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 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" className="h-12 w-12 rounded-full"
alt="Zdjęcie profilowe" alt="Zdjęcie profilowe"
/> />
@@ -265,7 +269,9 @@ export default function NoticeDetails() {
onPress={() => setIsMessageFormVisible(true)} onPress={() => setIsMessageFormVisible(true)}
className="mt-3 bg-primary-500 py-2 px-4 rounded-md" className="mt-3 bg-primary-500 py-2 px-4 rounded-md"
> >
<Text className="text-white text-center font-bold">Wyślij wiadomość</Text> <Text className="text-white text-center font-bold">
Wyślij wiadomość
</Text>
</Pressable> </Pressable>
<Link href={`/user/${notice.clientId}`}> <Link href={`/user/${notice.clientId}`}>
<Text className="text-xl p-3 font-bold text-center text-typography-700 mt-3"> <Text className="text-xl p-3 font-bold text-center text-typography-700 mt-3">
@@ -277,15 +283,15 @@ export default function NoticeDetails() {
) : ( ) : (
<Text>Błąd podczas ładowania danych użytkownika</Text> <Text>Błąd podczas ładowania danych użytkownika</Text>
)} )}
</Box> </Box>
</VStack> </VStack>
</ScrollView> </ScrollView>
{isMessageFormVisible && ( {isMessageFormVisible && (
<View className="absolute inset-0 bg-black bg-opacity-50 justify-center items-center z-20"> <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"> <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-lg font-bold mb-4">
Wyślij wiadomość do {user?.firstName}
</Text>
<Text className="text-sm font-medium mb-1">Do:</Text> <Text className="text-sm font-medium mb-1">Do:</Text>
<Text className="bg-gray-100 p-3 rounded text-gray-500"> <Text className="bg-gray-100 p-3 rounded text-gray-500">
@@ -318,14 +324,14 @@ export default function NoticeDetails() {
<Pressable <Pressable
onPress={handleSendMessage} onPress={handleSendMessage}
className="bg-primary-500 py-2 px-4 rounded-md"> className="bg-primary-500 py-2 px-4 rounded-md"
>
<Text className="text-white">Wyślij</Text> <Text className="text-white">Wyślij</Text>
</Pressable> </Pressable>
</View> </View>
</View> </View>
</View> </View>
)} )}
</Card> </Card>
); );
} }

View File

@@ -1,32 +1,25 @@
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 { 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";
import {listCategories} from "@/api/categories";
export function CategorySection({notices, title}) {
const token = useAuthStore((state) => state.token);
export function CategorySection({ notices, title }) {
const [categoryMap, setCategoryMap] = useState({}); const [categoryMap, setCategoryMap] = useState({});
useEffect(() => { useEffect(() => {
if(token){
const fetchCategories = async () => { const fetchCategories = async () => {
let data = await listCategories(); let data = await listCategories();
if (Array.isArray(data)) { if (Array.isArray(data)) {
setCategoryMap(data); setCategoryMap(data);
} }
} };
fetchCategories(); fetchCategories();
} });
}, [token]);
const categories = Array.from( const categories = Array.from(
new Set(notices.map((notice) => notice.category)) new Set(notices.map((notice) => notice.category))
@@ -35,13 +28,11 @@ export function CategorySection({notices, title}) {
const getCount = (category) => const getCount = (category) =>
notices.filter((notice) => notice.category === category).length; notices.filter((notice) => notice.category === category).length;
console.log("CategoryMap:", categoryMap); if (!categoryMap || Object.keys(categoryMap).length === 0) {
if(!categoryMap) {
return null; return null;
} }
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
@@ -65,5 +56,4 @@ return (
/> />
</View> </View>
); );
} }

View File

@@ -1,27 +1,27 @@
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"; import { useAuthStore } from "@/store/authStore";
export function UserSection({ notices, title }) {
export function UserSection({notices, title}) {
const token = useAuthStore((state) => state.token); const token = useAuthStore((state) => state.token);
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
useEffect(() => { useEffect(() => {
if (token){ if (token) {
axios.get('https://testowe.zikor.pl/api/v1/clients/get/all', { headers }) axios
.then(res => setUsers(res.data)) .get("https://hopp.zikor.pl/api/v1/clients/get/all", { headers })
.then((res) => setUsers(res.data))
.catch(() => setUsers([])); .catch(() => setUsers([]));
} }
}, [token]); }, [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 +29,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,12 +38,9 @@ return (
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
contentContainerStyle={{ paddingHorizontal: 8, gap: 12 }} contentContainerStyle={{ paddingHorizontal: 8, gap: 12 }}
renderItem={({ item }) => { renderItem={({ item }) => {
return ( return <UserBlock user={item} />;
<UserBlock user={item} />
);
}} }}
/> />
</View> </View>
); );
} }

21
ArtisanConnect/eas.json Normal file
View File

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

View File

@@ -39,7 +39,7 @@
"expo": "^53.0.0", "expo": "^53.0.0",
"expo-auth-session": "~6.1.5", "expo-auth-session": "~6.1.5",
"expo-camera": "~16.1.6", "expo-camera": "~16.1.6",
"expo-constants": "~17.1.5", "expo-constants": "~17.1.6",
"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",
@@ -57,11 +57,12 @@
"react-native-keyboard-aware-scroll-view": "^0.9.5", "react-native-keyboard-aware-scroll-view": "^0.9.5",
"react-native-reanimated": "~3.17.4", "react-native-reanimated": "~3.17.4",
"react-native-safe-area-context": "5.4.0", "react-native-safe-area-context": "5.4.0",
"react-native-screens": "~4.10.0", "react-native-screens": "~4.11.1",
"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,107 +1,138 @@
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://testowe.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set) => ({ (set, get) => {
user: null, // Dodaj interceptor tylko raz
if (!axios.interceptors.response.handlers.length) {
axios.interceptors.response.use(
(response) => response,
(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 {
user_id: null,
token: null, token: null,
isLoading: false, isLoading: false,
error: null, error: null,
signIn: async (email, password) => { signIn: async (email, password) => {
set({isLoading: true, error: null}); set({ isLoading: true, error: null });
try { try {
const response = await axios.post(`${API_URL}/auth/login`, { const response = await axios.post(`${API_URL}/auth/login`, {
email, email,
password password,
}); });
const user = response.data.user; const user_id = response.data.user_id;
const token = response.data.token; const token = response.data.token;
set({user, token, isLoading: false}); set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) { } catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false}); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error; throw error;
} }
}, },
signUp: async (userData) => { signUp: async (userData) => {
set({isLoading: true, error: null}); set({ isLoading: true, error: null });
try { try {
console.log(userData); const response = await axios.post(
`${API_URL}/auth/register`,
userData,
{
headers: { "Content-Type": "application/json" },
}
);
const response = await axios.post(`${API_URL}/auth/register`, userData, { const user_id = response.data.user_id;
headers: {'Content-Type': 'application/json'}
});
console.log(response.data);
const user = response.data.user;
const token = response.data.token; const token = response.data.token;
set({user, token, isLoading: false}); set({ user_id: user_id, token: token, isLoading: false });
return user; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) { } catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false}); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error; 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(`${API_URL}/auth/google`, {token: googleToken}); const response = await axios.post(
`${API_URL}/auth/google`,
const {user, token} = response.data; { googleToken: googleToken },
set({user, token, isLoading: false}); {
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}`; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return user;
} catch (error) { } catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false}); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error; throw error;
} }
}, },
signOut: async () => { signOut: async () => {
try { try {
const {token} = useAuthStore.getState(); await axios.post(`${API_URL}/auth/logout`);
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
// Можно отправить запрос на бэкенд для инвалидации токена
await axios.post(`${API_URL}/auth/logout`, {}, { headers });
} catch (error) { } catch (error) {
console.error("Logout error:", error); console.error("Logout error:", error);
} finally { } finally {
delete axios.defaults.headers.common["Authorization"]; delete axios.defaults.headers.common["Authorization"];
set({user: null, token: null}); set({ user_id: null, token: null });
} }
}, },
checkAuth: async () => { // checkAuth: async () => {
const {token} = useAuthStore.getState(); // const { token } = useAuthStore.getState();
if (!token) return null; // if (!token) return null;
set({isLoading: true}); // set({ isLoading: true });
try { // try {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; // axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
const response = await axios.get(`${API_URL}/auth/me`); // const response = await axios.get(`${API_URL}/auth/me`);
set({user: response.data, isLoading: false}); // set({ user_id: response.data, isLoading: false });
return response.data; // return response.data;
} catch (error) { // } catch (error) {
delete axios.defaults.headers.common["Authorization"]; // delete axios.defaults.headers.common["Authorization"];
set({user: null, token: null, isLoading: false}); // set({ user_id: null, token: null, isLoading: false });
return null; // return null;
} // }
// },
};
}, },
}),
{ {
name: "auth-storage", name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage), storage: createJSONStorage(() => AsyncStorage),