Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2d0f5b9e56 | |||
| dd73dc070d | |||
| 7efe9d91c3 | |||
| 67cf21230d | |||
| 945d225a9f | |||
|
|
0790285ae5 | ||
|
|
e1672ab319 | ||
|
|
2630b35afd | ||
|
|
3c042d2cfb | ||
| b323f02654 | |||
| 59db79eaf7 | |||
| 1d2a2420c2 | |||
|
|
fd1c387cdb | ||
|
|
2871a83470 | ||
| 121d9d1e53 | |||
| 56877548ed | |||
| 90ada963bf | |||
|
|
e0e5d10062 | ||
|
|
bcc646e4ef | ||
| b96e8f264b | |||
| bb9a896161 | |||
|
|
83f105eff1 | ||
|
|
413c9ac5ee | ||
| 735801d14a | |||
| 8f72f28566 | |||
|
|
c0b8800f83 | ||
|
|
97d3927acc | ||
|
|
0157d0015a | ||
|
|
8a2498b467 | ||
|
|
871225ea3a | ||
|
|
1cc0f601fb | ||
|
|
366ea4ada3 | ||
|
|
a527d00e1d | ||
| 301687a609 | |||
| 42408816f4 |
@@ -0,0 +1,63 @@
|
||||
import axios from "axios";
|
||||
|
||||
const API_URL = "https://hopp.zikor.pl/api/v1";
|
||||
|
||||
export async function login(userData) {
|
||||
try {
|
||||
const response = await axios.post(`${API_URL}/auth/login`, userData, {
|
||||
headers: {"Content-Type": "application/json"},
|
||||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Login failed:", error);
|
||||
throw error.response?.data?.message || "Login failed";
|
||||
}
|
||||
}
|
||||
|
||||
export async function register(userData) {
|
||||
try {
|
||||
const response = await axios.post(`${API_URL}/auth/register`, userData, {
|
||||
headers: {"Content-Type": "application/json"},
|
||||
});
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Registration failed:", error);
|
||||
throw error.response?.data?.message || "Registration failed";
|
||||
}
|
||||
}
|
||||
|
||||
export async function googleLogin(googleToken) {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/auth/google`,
|
||||
{ googleToken: googleToken },
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Google login failed:", error);
|
||||
throw error.response?.data?.message || "Google login failed";
|
||||
}
|
||||
}
|
||||
|
||||
export async function logout(token) {
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/auth/logout`,
|
||||
{},
|
||||
{
|
||||
headers: headers,
|
||||
}
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Logout failed:", error);
|
||||
throw error.response?.data?.message || "Logout failed";
|
||||
}
|
||||
}
|
||||
@@ -19,3 +19,21 @@ export async function getUserById(userId) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAllUsers() {
|
||||
const { token } = useAuthStore.getState();
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${API_URL}/clients/get/all`, {
|
||||
headers: headers,
|
||||
});
|
||||
return response.data;
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`Nie udało się pobrać danych o użytkownikach`,
|
||||
err.response.status
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ import axios from "axios";
|
||||
import FormData from "form-data";
|
||||
import { useAuthStore } from "@/store/authStore";
|
||||
|
||||
// const API_URL = "https://hopp.zikor.pl/api/v1";
|
||||
|
||||
const API_URL = "https://hopp.zikor.pl/api/v1";
|
||||
|
||||
export async function listNotices() {
|
||||
@@ -41,8 +39,13 @@ export async function createNotice(notice) {
|
||||
});
|
||||
|
||||
if (response.data.noticeId !== null) {
|
||||
for (const imageUri of notice.image) {
|
||||
await uploadImage(response.data.noticeId, imageUri);
|
||||
for (const image of notice.image) {
|
||||
if (notice.image.indexOf(image) === 0) {
|
||||
await uploadImage(response.data.noticeId, image, true);
|
||||
} else {
|
||||
await uploadImage(response.data.noticeId, image, false);
|
||||
}
|
||||
console.log("Image uploaded successfully");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +66,6 @@ export async function getImageByNoticeId(noticeId) {
|
||||
|
||||
return imageUrl;
|
||||
} catch (err) {
|
||||
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
|
||||
imageUrl = "https://http.cat/404.jpg";
|
||||
return imageUrl;
|
||||
}
|
||||
@@ -98,37 +100,36 @@ export async function getAllImagesByNoticeId(noticeId) {
|
||||
}
|
||||
}
|
||||
|
||||
export const uploadImage = async (noticeId, imageUri) => {
|
||||
export const uploadImage = async (noticeId, imageObj, isFirst) => {
|
||||
const { token } = useAuthStore.getState();
|
||||
const headers = {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
'Content-Type': 'multipart/form-data'
|
||||
"Content-Type": "multipart/form-data",
|
||||
};
|
||||
const formData = new FormData();
|
||||
|
||||
const filename = imageUri.split("/").pop();
|
||||
const filename = imageObj.split("/").pop();
|
||||
|
||||
const match = /\.(\w+)$/.exec(filename);
|
||||
const type = match ? `image/${match[1]}` : "image/jpeg";
|
||||
|
||||
formData.append("file", {
|
||||
uri: imageUri.uri,
|
||||
uri: imageObj,
|
||||
name: filename,
|
||||
type: type,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/images/upload/${noticeId}`,
|
||||
`${API_URL}/images/upload/${noticeId}?isMainImage=${isFirst}`,
|
||||
formData,
|
||||
{
|
||||
headers: headers,
|
||||
}
|
||||
);
|
||||
console.info("Upload successful:", response.data);
|
||||
console.log("Upload successful:", response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log("imageURI:", imageUri);
|
||||
console.error(
|
||||
"Error uploading image:",
|
||||
error.response.data,
|
||||
@@ -145,7 +146,7 @@ export const deleteNotice = async (noticeId) => {
|
||||
try {
|
||||
const response = await axios.delete(
|
||||
`${API_URL}/notices/delete/${noticeId}`,
|
||||
{ headers }
|
||||
{ headers: headers }
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
@@ -157,3 +158,65 @@ export const deleteNotice = async (noticeId) => {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const editNotice = async (noticeId, notice) => {
|
||||
const { token } = useAuthStore.getState();
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
|
||||
try {
|
||||
const response = await axios.put(
|
||||
`${API_URL}/notices/edit/${noticeId}`,
|
||||
{
|
||||
title: notice.title,
|
||||
description: notice.description,
|
||||
price: notice.price,
|
||||
category: notice.category,
|
||||
status: notice.status,
|
||||
attributes: notice.attributes,
|
||||
},
|
||||
{
|
||||
headers: headers,
|
||||
}
|
||||
);
|
||||
|
||||
if (response.data && notice.image && notice.image.length > 0) {
|
||||
for (let i = 0; i < notice.image.length; i++) {
|
||||
const image = notice.image[i];
|
||||
const isFirst = i === 0;
|
||||
|
||||
if (typeof image === "string" && !image.startsWith("http")) {
|
||||
await uploadImage(noticeId, image, isFirst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error editing notice:",
|
||||
error.response?.data,
|
||||
error.response?.status
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteImage = async (filename) => {
|
||||
const { token } = useAuthStore.getState();
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
|
||||
try {
|
||||
const response = await axios.delete(
|
||||
`${API_URL}/images/delete/${filename}`,
|
||||
{ headers: headers }
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error deleting image:",
|
||||
error.response?.data,
|
||||
error.response?.status
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -6,12 +6,11 @@ const API_URL = "https://hopp.zikor.pl/api/v1/orders";
|
||||
export async function createOrder(noticeId, orderType) {
|
||||
const { token } = useAuthStore.getState();
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const clientId = 1;
|
||||
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/add`,
|
||||
{ clientId: clientId, noticeId: noticeId, orderType: orderType },
|
||||
{ noticeId: noticeId, orderType: orderType },
|
||||
{
|
||||
headers: headers,
|
||||
}
|
||||
@@ -27,7 +26,6 @@ export async function createOrder(noticeId, orderType) {
|
||||
export async function createPayment(orderId) {
|
||||
const { token } = useAuthStore.getState();
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const clientId = 1;
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/token?orderId=${orderId}`,
|
||||
@@ -48,7 +46,7 @@ export async function getOrder(orderId) {
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${API_URL}/get/${orderId}`, { headers });
|
||||
const response = await axios.get(`${API_URL}/get/${orderId}`, { headers: headers });
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
@@ -65,7 +63,7 @@ export async function listOrders() {
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${API_URL}/get/all`, { headers });
|
||||
const response = await axios.get(`${API_URL}/get/all`, { headers: headers });
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
|
||||
@@ -12,7 +12,7 @@ export async function toggleNoticeStatus(noticeId) {
|
||||
`${API_URL}/toggle/${noticeId}`,
|
||||
{},
|
||||
{
|
||||
headers,
|
||||
headers: headers,
|
||||
}
|
||||
);
|
||||
return response.data;
|
||||
@@ -27,7 +27,7 @@ export async function getWishlist() {
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${API_URL}/`, { headers });
|
||||
const response = await axios.get(`${API_URL}/`, { headers: headers });
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error("Error fetching wishlist:", error);
|
||||
|
||||
@@ -18,6 +18,18 @@
|
||||
"bundleIdentifier": "com.hamx.artisanconnect"
|
||||
},
|
||||
"android": {
|
||||
"intentFilters": [
|
||||
{
|
||||
"action": "VIEW",
|
||||
"autoVerify": true,
|
||||
"data": [
|
||||
{
|
||||
"scheme": "com.hamx.artisanconnect"
|
||||
}
|
||||
],
|
||||
"category": ["BROWSABLE", "DEFAULT"]
|
||||
}
|
||||
],
|
||||
"adaptiveIcon": {
|
||||
"foregroundImage": "./assets/adaptive-icon.png",
|
||||
"backgroundColor": "#ffffff"
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import React, {useEffect, useState} from 'react';
|
||||
import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform} from 'react-native';
|
||||
import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform, KeyboardAvoidingView} from 'react-native';
|
||||
import {useAuthStore} from '@/store/authStore';
|
||||
import {useRouter, Link} from 'expo-router';
|
||||
import {useRouter} from 'expo-router';
|
||||
|
||||
import {Box} from "@/components/ui/box"
|
||||
import {Button, ButtonText, ButtonIcon} from "@/components/ui/button"
|
||||
import {Center} from "@/components/ui/center"
|
||||
import {Heading} from "@/components/ui/heading"
|
||||
import {Input, InputField} from "@/components/ui/input"
|
||||
import {Input, InputField, InputIcon, InputSlot} from "@/components/ui/input"
|
||||
import {Text} from "@/components/ui/text"
|
||||
import {VStack} from "@/components/ui/vstack"
|
||||
import {HStack} from "@/components/ui/hstack"
|
||||
import {ArrowRightIcon} from "@/components/ui/icon"
|
||||
import {ArrowRightIcon, EyeIcon, EyeOffIcon} from "@/components/ui/icon"
|
||||
import {Divider} from '@/components/ui/divider';
|
||||
import {Ionicons} from "@expo/vector-icons";
|
||||
|
||||
@@ -30,6 +30,8 @@ WebBrowser.maybeCompleteAuthSession();
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [emailError, setEmailError] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const {signIn, isLoading, signInWithGoogle} = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
@@ -52,6 +54,11 @@ export default function Login() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateEmail(email)) {
|
||||
setEmailError('Nieprawidłowy format adresu email');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await signIn(email, password);
|
||||
alert(`Zalogowano jako ${email}`);
|
||||
@@ -69,10 +76,11 @@ export default function Login() {
|
||||
// const user = await AsyncStorage.getItem("@user");
|
||||
let user = null;
|
||||
if (!user) {
|
||||
if(response.type === "success") {
|
||||
if (response.type === "success") {
|
||||
user = await getUserInfo(response.authentication.accessToken)
|
||||
await signInWithGoogle(response.authentication.accessToken);
|
||||
alert(`Zalogowano jako ${user.email}`);
|
||||
router.replace('/');
|
||||
}
|
||||
|
||||
} else {
|
||||
@@ -82,7 +90,7 @@ export default function Login() {
|
||||
};
|
||||
|
||||
const getUserInfo = async (token) => {
|
||||
if(!token) {
|
||||
if (!token) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
@@ -102,6 +110,17 @@ export default function Login() {
|
||||
}
|
||||
}
|
||||
|
||||
const validateEmail = (email) => {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
};
|
||||
|
||||
const handleShowPassword = () => {
|
||||
setShowPassword((showState) => {
|
||||
return !showState
|
||||
})
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
@@ -111,49 +130,70 @@ export default function Login() {
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<Center>
|
||||
<Box className="p-5 max-w-96 border border-background-300 rounded-lg">
|
||||
<VStack className="pb-4" space="xs">
|
||||
<Heading className="leading-[30px]">Logowanie</Heading>
|
||||
<Box className="flex flex-row">
|
||||
{/* <Link href="/registration" asChild> */}
|
||||
<Button variant="link" size="sm" className="p-0" onPress={() => router.replace("/registration")}>
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
style={{flex: 1}}
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 64 : 0}
|
||||
>
|
||||
<SafeAreaView style={styles.container}>
|
||||
<Center>
|
||||
<Box className="p-5 max-w-96 border border-background-300 rounded-lg">
|
||||
<VStack className="pb-4" space="xs">
|
||||
<Heading className="leading-[30px]">Logowanie</Heading>
|
||||
<Box className="flex flex-row">
|
||||
{/* <Link href="/registration" asChild> */}
|
||||
<Button variant="link" size="sm" className="p-0"
|
||||
onPress={() => router.replace("/registration")}>
|
||||
<ButtonText style={styles.signupbutton}>Nie masz jeszcze konta? Załóz je
|
||||
tutaj!</ButtonText>
|
||||
<ButtonIcon className="mr-1" size="md" as={ArrowRightIcon}/>
|
||||
</Button>
|
||||
{/* </Link> */}
|
||||
</Box>
|
||||
</VStack>
|
||||
<VStack space="xl" className="py-2">
|
||||
<Input>
|
||||
<InputField className="py-2" placeholder="Login" onChangeText={setEmail}/>
|
||||
</Input>
|
||||
<Input>
|
||||
<InputField type="password" className="py-2" placeholder="Hasło"
|
||||
onChangeText={setPassword}/>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="lg" className="pt-4">
|
||||
<Button size="sm" onPress={handleInternalLogin}>
|
||||
<ButtonText>Zaloguj się</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
{/* </Link> */}
|
||||
</Box>
|
||||
</VStack>
|
||||
<VStack space="xl" className="py-2">
|
||||
{emailError ? <Text style={styles.errorText}>{emailError}</Text> : null}
|
||||
<Input isRequired={true} isInvalid={!!emailError}>
|
||||
<InputField className="py-2" inputMode="email" placeholder="Login"
|
||||
onChangeText={(text) => {
|
||||
setEmail(text);
|
||||
if (text && !validateEmail(text)) {
|
||||
setEmailError('Nieprawidłowy format adresu email');
|
||||
} else {
|
||||
setEmailError('');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Input>
|
||||
<Input isRequired={true}>
|
||||
<InputField type={showPassword ? "text" : "password"} className="py-2"
|
||||
placeholder="Hasło"
|
||||
onChangeText={setPassword}/>
|
||||
<InputSlot className="pr-3" onPress={handleShowPassword}>
|
||||
<InputIcon as={showPassword ? EyeIcon : EyeOffIcon}/>
|
||||
</InputSlot>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="lg" className="pt-4">
|
||||
<Button size="sm" onPress={handleInternalLogin}>
|
||||
<ButtonText>Zaloguj się</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
|
||||
<HStack alignItems="center" space="sm" className="pt-6 pb-6">
|
||||
<Divider flex={1}/>
|
||||
<Text fontSize="$sm" className="text-gray-300">
|
||||
lub
|
||||
</Text>
|
||||
<Divider flex={1}/>
|
||||
</HStack>
|
||||
<Button size="sm" onPress={() => promptAsync()}>
|
||||
<Ionicons name="logo-google" color="#fff"/>
|
||||
</Button>
|
||||
</Box>
|
||||
</Center>
|
||||
</SafeAreaView>
|
||||
<HStack alignItems="center" space="sm" className="pt-6 pb-6">
|
||||
<Divider flex={1}/>
|
||||
<Text fontSize="$sm" className="text-gray-300">
|
||||
lub
|
||||
</Text>
|
||||
<Divider flex={1}/>
|
||||
</HStack>
|
||||
<Button size="sm" onPress={() => promptAsync()}>
|
||||
<Ionicons name="logo-google" color="#fff"/>
|
||||
</Button>
|
||||
</Box>
|
||||
</Center>
|
||||
</SafeAreaView>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -172,7 +212,7 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
errorText: {
|
||||
color: 'red',
|
||||
marginBottom: 10,
|
||||
fontSize: 12,
|
||||
},
|
||||
signupbutton: {
|
||||
fontWeight: '300',
|
||||
|
||||
@@ -44,7 +44,7 @@ export default function Account() {
|
||||
<Image
|
||||
source={{
|
||||
uri:
|
||||
user.profileImage ||
|
||||
user.image ||
|
||||
"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"
|
||||
@@ -84,7 +84,7 @@ export default function Account() {
|
||||
</Link>
|
||||
|
||||
{/*Tak dodałem, można zmienić na coś innego*/}
|
||||
<Link href="/dashboard/userPaymentHistory" asChild>
|
||||
<Link href="/dashboard/userOrders" 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>
|
||||
|
||||
@@ -1,55 +1,34 @@
|
||||
import { useNoticesStore } from "@/store/noticesStore";
|
||||
import { NoticeCard } from "@/components/NoticeCard";
|
||||
import { Button, ButtonText } from "@/components/ui/button";
|
||||
|
||||
import { usePathname } from "expo-router";
|
||||
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, useRef } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { createOrder, createPayment, getOrder } from "@/api/order";
|
||||
import { Linking } from "react-native";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { useToast, Toast, ToastTitle } from "@/components/ui/toast";
|
||||
import { AppState } from "react-native";
|
||||
import { useAuthStore } from "@/store/authStore";
|
||||
import * as WebBrowser from "expo-web-browser";
|
||||
import { useRouter } from "expo-router";
|
||||
|
||||
export default function UserNotices() {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const { notices, fetchNotices, deleteNotice } = useNoticesStore();
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isRedirecting, setIsRedirecting] = useState(false);
|
||||
const toast = useToast();
|
||||
const appState = useRef(AppState.currentState);
|
||||
const [toastId, setToastId] = useState(0);
|
||||
const { user_id } = useAuthStore.getState();
|
||||
const currentUserId = user_id;
|
||||
const [orderId, setOrderId] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRedirecting) return;
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
(async () => {
|
||||
const lastOrder = await getOrder(orderId);
|
||||
const lastPayments = lastOrder.payments;
|
||||
const paymentStatus =
|
||||
lastPayments.length > 0
|
||||
? lastPayments[lastPayments.length - 1].status
|
||||
: null;
|
||||
setIsRedirecting(false);
|
||||
if (paymentStatus === "INCORRECT") {
|
||||
showNewToast("Płatność została anulowana.");
|
||||
} else if (paymentStatus === "CORRECT") {
|
||||
showNewToast("Płatność została zrealizowana.");
|
||||
} else {
|
||||
showNewToast("Płatność jeszcze nie wpłynęła.");
|
||||
}
|
||||
})();
|
||||
}
|
||||
appState.current = state;
|
||||
});
|
||||
return () => subscription.remove();
|
||||
}, [isRedirecting, toast, orderId]);
|
||||
WebBrowser.maybeCompleteAuthSession();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const loadNotices = async () => {
|
||||
@@ -63,7 +42,7 @@ export default function UserNotices() {
|
||||
}
|
||||
};
|
||||
loadNotices();
|
||||
}, [fetchNotices]);
|
||||
}, [pathname, fetchNotices]);
|
||||
|
||||
const showNewToast = (title) => {
|
||||
const newId = Math.random();
|
||||
@@ -84,28 +63,50 @@ export default function UserNotices() {
|
||||
};
|
||||
|
||||
const handleOrder = async (noticeId, type) => {
|
||||
{
|
||||
try {
|
||||
const result = await createOrder(noticeId, type);
|
||||
if (result) {
|
||||
setOrderId(result);
|
||||
try {
|
||||
const paymentResult = await createPayment(result);
|
||||
if (paymentResult) {
|
||||
setIsRedirecting(true);
|
||||
await Linking.openURL(paymentResult);
|
||||
} else {
|
||||
console.log(`Nie udało się aktywować ogłoszenia 4 ${noticeId}.`);
|
||||
}
|
||||
} catch (err) {
|
||||
// console.log("Błąd podczas aktywacji ogłoszenia 3:", err);
|
||||
try {
|
||||
const result = await createOrder(noticeId, type);
|
||||
if (result) {
|
||||
setOrderId(result);
|
||||
try {
|
||||
const paymentResult = await createPayment(result);
|
||||
if (paymentResult) {
|
||||
setIsRedirecting(true);
|
||||
|
||||
await WebBrowser.openAuthSessionAsync(paymentResult);
|
||||
|
||||
setTimeout(async () => {
|
||||
setIsRedirecting(false);
|
||||
|
||||
try {
|
||||
const lastOrder = await getOrder(result);
|
||||
const lastPayments = lastOrder.payments;
|
||||
const paymentStatus =
|
||||
lastPayments.length > 0
|
||||
? lastPayments[lastPayments.length - 1].status
|
||||
: null;
|
||||
|
||||
if (paymentStatus === "CORRECT") {
|
||||
showNewToast("Płatność została zrealizowana.");
|
||||
await fetchNotices();
|
||||
router.replace("/notices");
|
||||
} else {
|
||||
showNewToast("Sprawdzanie statusu płatności...");
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("Błąd podczas sprawdzania płatności:", err);
|
||||
showNewToast("Nie udało się sprawdzić statusu płatności.");
|
||||
}
|
||||
}, 300);
|
||||
} else {
|
||||
console.log(`Nie udało się aktywować ogłoszenia ${noticeId}.`);
|
||||
}
|
||||
} else {
|
||||
// console.log(`Nie udało się aktywować ogłoszenia 2 ${noticeId}.`);
|
||||
} catch (err) {
|
||||
setIsRedirecting(false);
|
||||
console.log("Błąd podczas aktywacji ogłoszenia:", err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("Błąd podczas aktywacji ogłoszenia 1:", err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("Błąd podczas aktywacji ogłoszenia:", err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -133,7 +134,7 @@ export default function UserNotices() {
|
||||
<VStack className="p-2">
|
||||
{isRedirecting && (
|
||||
<Box className="absolute inset-0 bg-white bg-opacity-30 justify-center items-center z-50">
|
||||
<Ionicons name="card-outline" size="30" className="pt-4" />
|
||||
<Ionicons name="card-outline" size={30} className="pt-4" />
|
||||
<Text className="text-lg font-bold pt-2">
|
||||
Przekierowanie do płatności...
|
||||
</Text>
|
||||
@@ -147,17 +148,32 @@ export default function UserNotices() {
|
||||
<Box className="flex-1 mb-4 pb-2 bg-white rounded-lg">
|
||||
<NoticeCard notice={item} />
|
||||
<Box className="flex-row justify-between mt-2">
|
||||
<Button
|
||||
className="ml-2"
|
||||
onPress={() => handleDeleteNotice(item.noticeId)}
|
||||
size="md"
|
||||
variant="outline"
|
||||
action="primary"
|
||||
>
|
||||
<ButtonText>Usuń</ButtonText>
|
||||
<Ionicons name="trash-outline" size={14} />
|
||||
</Button>
|
||||
|
||||
<Box className="flex-row items-center">
|
||||
<Button
|
||||
className="ml-2"
|
||||
onPress={() => handleDeleteNotice(item.noticeId)}
|
||||
size="md"
|
||||
variant="outline"
|
||||
action="primary"
|
||||
>
|
||||
<ButtonText>Usuń</ButtonText>
|
||||
<Ionicons name="trash-outline" size={14} />
|
||||
</Button>
|
||||
{item.status === "INACTIVE" && (
|
||||
<Button
|
||||
className="ml-2"
|
||||
onPress={() => {
|
||||
router.replace(`notice/edit/${item.noticeId}`);
|
||||
}}
|
||||
size="md"
|
||||
variant="outline"
|
||||
action="primary"
|
||||
>
|
||||
<ButtonText>Edytuj</ButtonText>
|
||||
<Ionicons name="pencil" size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
{item.status === "ACTIVE" ? (
|
||||
<Button
|
||||
className="mr-2"
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { View, Text } from "react-native";
|
||||
import { useState, useEffect, use } from "react";
|
||||
import { FlatList, RefreshControl } from "react-native";
|
||||
import { listOrders } from "@/api/order";
|
||||
import { Box } from "@/components/ui/box";
|
||||
import { VStack } from "@/components/ui/vstack";
|
||||
import { HStack } from "@/components/ui/hstack";
|
||||
|
||||
export default function UserOrders() {
|
||||
const [orders, setOrders] = useState([]);
|
||||
@@ -15,10 +19,31 @@ export default function UserOrders() {
|
||||
fetchOrders();
|
||||
}, []);
|
||||
|
||||
console.log("Orders:", orders);
|
||||
if (orders.length === 0) {
|
||||
return (
|
||||
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
|
||||
<Text>Brak zamówień</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
|
||||
<Text>Orders</Text>
|
||||
</View>
|
||||
<FlatList
|
||||
className="m-2"
|
||||
data={orders}
|
||||
renderItem={({ item }) => (
|
||||
<Box className="p-4 rounded-md bg-white mb-2">
|
||||
<VStack>
|
||||
<HStack>
|
||||
<Text>{item.orderId}</Text>
|
||||
<Text className="ml-2">{item.orderType}</Text>
|
||||
</HStack>
|
||||
<Text className="mt-2">{item.status}</Text>
|
||||
<Text className="mt-2">Cena: {item.amount} zł</Text>
|
||||
<Text className="mt-2">{item.createdAt}</Text>
|
||||
</VStack>
|
||||
</Box>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,21 +15,21 @@ export default function Home() {
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
const fetchNotices = useNoticesStore((state) => state.fetchNotices);
|
||||
|
||||
// useEffect(() => {
|
||||
// setIsReady(true);
|
||||
// }, []);
|
||||
useEffect(() => {
|
||||
setIsReady(true);
|
||||
}, []);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (isReady && !token) {
|
||||
// router.replace("/login");
|
||||
// }
|
||||
// }, [isReady, token, router]);
|
||||
useEffect(() => {
|
||||
if (isReady && !token) {
|
||||
router.replace("/login");
|
||||
}
|
||||
}, [isReady, token, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
fetchNotices();
|
||||
}
|
||||
}, [token, fetchNotices]);
|
||||
}, [token]);
|
||||
|
||||
const notices = useNoticesStore((state) => state.notices);
|
||||
|
||||
|
||||
@@ -1,280 +1,330 @@
|
||||
import {useState, useEffect} from "react";
|
||||
import {Image, StyleSheet, KeyboardAvoidingView, Platform, ActivityIndicator} from "react-native";
|
||||
import {Button, ButtonText} from "@/components/ui/button";
|
||||
import {FormControl} from "@/components/ui/form-control";
|
||||
import {Input, InputField} from "@/components/ui/input";
|
||||
import {Text} from "@/components/ui/text";
|
||||
import {VStack} from "@/components/ui/vstack";
|
||||
import {Textarea, TextareaInput} from "@/components/ui/textarea";
|
||||
import {ScrollView} from "@gluestack-ui/themed";
|
||||
import {Box} from "@/components/ui/box";
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Image,
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
ActivityIndicator,
|
||||
} from "react-native";
|
||||
import { Button, ButtonText } from "@/components/ui/button";
|
||||
import { FormControl } from "@/components/ui/form-control";
|
||||
import { Input, InputField } from "@/components/ui/input";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import { VStack } from "@/components/ui/vstack";
|
||||
import { Textarea, TextareaInput } from "@/components/ui/textarea";
|
||||
import { ScrollView } from "@gluestack-ui/themed";
|
||||
import { Box } from "@/components/ui/box";
|
||||
import * as ImagePicker from "expo-image-picker";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectInput,
|
||||
SelectIcon,
|
||||
SelectPortal,
|
||||
SelectBackdrop,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectScrollView,
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectInput,
|
||||
SelectIcon,
|
||||
SelectPortal,
|
||||
SelectBackdrop,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectScrollView,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
import {ChevronDownIcon} from "@/components/ui/icon";
|
||||
import {useNoticesStore} from "@/store/noticesStore";
|
||||
import {listCategories} from "@/api/categories";
|
||||
import {useRouter} from "expo-router";
|
||||
import { ChevronDownIcon } from "@/components/ui/icon";
|
||||
import { useNoticesStore } from "@/store/noticesStore";
|
||||
import { listCategories } from "@/api/categories";
|
||||
import { useRouter } from "expo-router";
|
||||
import { attributes } from "@/data/attributesData"; // Assuming you have a separate file for attributes data}
|
||||
|
||||
export default function CreateNotice() {
|
||||
const router = useRouter();
|
||||
const {addNotice, fetchNotices} = useNoticesStore();
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [price, setPrice] = useState("");
|
||||
const [category, setCategory] = useState("");
|
||||
const [image, setImage] = useState([]);
|
||||
const [selectItems, setSelectItems] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const { addNotice, fetchNotices } = useNoticesStore();
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [price, setPrice] = useState("");
|
||||
const [category, setCategory] = useState("");
|
||||
const [image, setImage] = useState([]);
|
||||
const [selectItems, setSelectItems] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedAttributes, setSelectedAttributes] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const fetchSelectItems = async () => {
|
||||
try {
|
||||
let data = await listCategories();
|
||||
if (isMounted && Array.isArray(data)) {
|
||||
setSelectItems(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching select items:", error);
|
||||
}
|
||||
};
|
||||
const fetchSelectItems = async () => {
|
||||
try {
|
||||
let data = await listCategories();
|
||||
if (isMounted && Array.isArray(data)) {
|
||||
setSelectItems(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching select items:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSelectItems();
|
||||
fetchSelectItems();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const [error, setError] = useState({
|
||||
title: false,
|
||||
description: false,
|
||||
price: false,
|
||||
category: false,
|
||||
const [error, setError] = useState({
|
||||
title: false,
|
||||
description: false,
|
||||
price: false,
|
||||
category: false,
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
image: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
});
|
||||
|
||||
const handleAddNotice = async () => {
|
||||
setError({
|
||||
title: !title,
|
||||
description: !description,
|
||||
price: !price,
|
||||
category: !category,
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
image: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
});
|
||||
|
||||
const handleAddNotice = async () => {
|
||||
setError({
|
||||
title: !title,
|
||||
description: !description,
|
||||
price: !price,
|
||||
category: !category,
|
||||
});
|
||||
|
||||
if (!title || !description || !price || !category) {
|
||||
console.log("Error in form");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await addNotice({
|
||||
title: title,
|
||||
description: description,
|
||||
price: price,
|
||||
category: category,
|
||||
status: "INACTIVE",
|
||||
image: image,
|
||||
});
|
||||
|
||||
if (result) {
|
||||
console.log("Notice created successfully with ID: ", result.noticeId);
|
||||
await fetchNotices();
|
||||
clearForm();
|
||||
|
||||
router.push("/(tabs)/dashboard/userNotices");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating notice. Error message: ", error.message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const takePicture = async () => {
|
||||
const {status} = await ImagePicker.requestCameraPermissionsAsync();
|
||||
if (status !== "granted") {
|
||||
return;
|
||||
}
|
||||
const result = await ImagePicker.launchCameraAsync({
|
||||
allowsEditing: false,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets) {
|
||||
setImage(result.assets.map((asset) => asset.uri));
|
||||
}
|
||||
};
|
||||
|
||||
const pickImage = async () => {
|
||||
let result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: "images",
|
||||
selectionLimit: 8,
|
||||
allowsEditing: false,
|
||||
allowsMultipleSelection: true,
|
||||
aspect: [4, 3],
|
||||
quality: 0.5,
|
||||
});
|
||||
|
||||
if (!result.canceled) {
|
||||
setImage(result.assets.map((asset) => asset.uri));
|
||||
}
|
||||
};
|
||||
|
||||
const clearForm = () => {
|
||||
setTitle("");
|
||||
setDescription("");
|
||||
setPrice("");
|
||||
setCategory("");
|
||||
setImage([]);
|
||||
setError({
|
||||
title: false,
|
||||
description: false,
|
||||
price: false,
|
||||
category: false,
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box className="items-center justify-center flex-1">
|
||||
<ActivityIndicator size="large" color="#787878"/>
|
||||
<Text size="md" bold="true" className='mt-5'>
|
||||
Dodajemy ogłoszenie...
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
if (!title || !description || !price || !category) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
style={{flex: 1}}
|
||||
keyboardVerticalOffset={Platform.OS === 'ios' ? 64 : 0}
|
||||
>
|
||||
<ScrollView h="$80" w="$80">
|
||||
<FormControl className="p-4 border rounded-lg border-outline-300">
|
||||
<VStack space="xl">
|
||||
<VStack space="md">
|
||||
<Text className="text-typography-500">Zdjęcia</Text>
|
||||
<Button onPress={pickImage}>
|
||||
<ButtonText>Wybierz zdjęcia</ButtonText>
|
||||
</Button>
|
||||
<Button onPress={takePicture}>
|
||||
<ButtonText>Zrób zdjęcie</ButtonText>
|
||||
</Button>
|
||||
<Text size="sm" bold="true">
|
||||
Pierwsze zdjęcie będzie zdjęciem głównym
|
||||
</Text>
|
||||
{image && image.length > 0 && (
|
||||
<VStack space="xs" className="flex-row flex-wrap">
|
||||
{image.map((img, index) => (
|
||||
<Image
|
||||
key={index}
|
||||
source={{uri: img}}
|
||||
style={styles.image}
|
||||
className="m-1"
|
||||
/>
|
||||
))}
|
||||
</VStack>
|
||||
)}
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Tytuł</Text>
|
||||
<Input className="min-w-[250px]" isInvalid={error.title}>
|
||||
<InputField
|
||||
type="text"
|
||||
value={title}
|
||||
onChangeText={(value) => setTitle(value)}
|
||||
/>
|
||||
</Input>
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Opis</Text>
|
||||
<Textarea
|
||||
size="md"
|
||||
className="min-w-[250px] "
|
||||
isInvalid={error.description}
|
||||
>
|
||||
<TextareaInput
|
||||
placeholder="Opisz produkt"
|
||||
value={description}
|
||||
onChangeText={(value) => setDescription(value)}
|
||||
/>
|
||||
</Textarea>
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Cena</Text>
|
||||
<Input className="min-w-[250px]" isInvalid={error.price}>
|
||||
<InputField
|
||||
type="text"
|
||||
value={price}
|
||||
onChangeText={(value) => setPrice(value)}
|
||||
/>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Kategoria</Text>
|
||||
<Select
|
||||
onValueChange={(value) => setCategory(value)}
|
||||
isInvalid={error.category}
|
||||
>
|
||||
<SelectTrigger variant="outline" size="md">
|
||||
<SelectInput placeholder="Wybierz kategorię"/>
|
||||
<SelectIcon className="mr-3" as={ChevronDownIcon}/>
|
||||
</SelectTrigger>
|
||||
<SelectPortal>
|
||||
<SelectBackdrop/>
|
||||
<SelectContent style={{maxHeight: 400}}>
|
||||
<SelectScrollView>
|
||||
{selectItems.map((item) => (
|
||||
<SelectItem
|
||||
key={item.value}
|
||||
label={item.label}
|
||||
value={item.value}
|
||||
/>
|
||||
))}
|
||||
</SelectScrollView>
|
||||
</SelectContent>
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</VStack>
|
||||
<Button
|
||||
className="mt-5 w-full"
|
||||
onPress={handleAddNotice}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<ButtonText className="text-typography-0">Dodaj</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
</FormControl>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
const formattedAttributes = Object.entries(selectedAttributes).map(
|
||||
([name, value]) => ({
|
||||
name: name,
|
||||
value: value,
|
||||
})
|
||||
);
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await addNotice({
|
||||
title: title,
|
||||
description: description,
|
||||
price: price,
|
||||
category: category,
|
||||
status: "INACTIVE",
|
||||
image: image,
|
||||
attributes: formattedAttributes,
|
||||
});
|
||||
|
||||
if (result) {
|
||||
console.log("Notice created successfully with ID: ", result.noticeId);
|
||||
await fetchNotices();
|
||||
clearForm();
|
||||
|
||||
router.push("/(tabs)/dashboard/userNotices");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating notice. Error message: ", error.message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const takePicture = async () => {
|
||||
const { status } = await ImagePicker.requestCameraPermissionsAsync();
|
||||
if (status !== "granted") {
|
||||
return;
|
||||
}
|
||||
const result = await ImagePicker.launchCameraAsync({
|
||||
allowsEditing: false,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets) {
|
||||
setImage(result.assets.map((asset) => asset.uri));
|
||||
}
|
||||
};
|
||||
|
||||
const pickImage = async () => {
|
||||
let result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: "images",
|
||||
selectionLimit: 8,
|
||||
allowsEditing: false,
|
||||
allowsMultipleSelection: true,
|
||||
aspect: [4, 3],
|
||||
quality: 0.5,
|
||||
});
|
||||
|
||||
if (!result.canceled) {
|
||||
setImage(result.assets.map((asset) => asset.uri));
|
||||
}
|
||||
};
|
||||
|
||||
const clearForm = () => {
|
||||
setTitle("");
|
||||
setDescription("");
|
||||
setPrice("");
|
||||
setCategory("");
|
||||
setImage([]);
|
||||
setSelectedAttributes({});
|
||||
setError({
|
||||
title: false,
|
||||
description: false,
|
||||
price: false,
|
||||
category: false,
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box className="items-center justify-center flex-1">
|
||||
<ActivityIndicator size="large" color="#787878" />
|
||||
<Text size="md" bold="true" className="mt-5">
|
||||
Dodajemy ogłoszenie...
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
style={{ flex: 1 }}
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 64 : 0}
|
||||
>
|
||||
<ScrollView h="$80" w="$80">
|
||||
<FormControl className="p-4 border rounded-lg border-outline-300">
|
||||
<VStack space="xl">
|
||||
<VStack space="md">
|
||||
<Text className="text-typography-500">Zdjęcia</Text>
|
||||
<Button onPress={pickImage}>
|
||||
<ButtonText>Wybierz zdjęcia</ButtonText>
|
||||
</Button>
|
||||
<Button onPress={takePicture}>
|
||||
<ButtonText>Zrób zdjęcie</ButtonText>
|
||||
</Button>
|
||||
<Text size="sm" bold="true">
|
||||
Pierwsze zdjęcie będzie zdjęciem głównym
|
||||
</Text>
|
||||
{image && image.length > 0 && (
|
||||
<VStack space="xs" className="flex-row flex-wrap">
|
||||
{image.map((img, index) => (
|
||||
<Image
|
||||
key={index}
|
||||
source={{ uri: img }}
|
||||
style={styles.image}
|
||||
className="m-1"
|
||||
/>
|
||||
))}
|
||||
</VStack>
|
||||
)}
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Tytuł*</Text>
|
||||
<Input className="min-w-[250px]" isInvalid={error.title}>
|
||||
<InputField
|
||||
type="text"
|
||||
value={title}
|
||||
onChangeText={(value) => setTitle(value)}
|
||||
/>
|
||||
</Input>
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Opis*</Text>
|
||||
<Textarea
|
||||
size="md"
|
||||
className="min-w-[250px] "
|
||||
isInvalid={error.description}
|
||||
>
|
||||
<TextareaInput
|
||||
placeholder="Opisz produkt"
|
||||
value={description}
|
||||
onChangeText={(value) => setDescription(value)}
|
||||
/>
|
||||
</Textarea>
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Cena*</Text>
|
||||
<Input className="min-w-[250px]" isInvalid={error.price}>
|
||||
<InputField
|
||||
type="text"
|
||||
value={price}
|
||||
onChangeText={(value) => setPrice(value)}
|
||||
/>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Kategoria*</Text>
|
||||
<Select
|
||||
onValueChange={(value) => setCategory(value)}
|
||||
isInvalid={error.category}
|
||||
>
|
||||
<SelectTrigger variant="outline" size="md">
|
||||
<SelectInput placeholder="Wybierz kategorię" />
|
||||
<SelectIcon className="mr-3" as={ChevronDownIcon} />
|
||||
</SelectTrigger>
|
||||
<SelectPortal>
|
||||
<SelectBackdrop />
|
||||
<SelectContent style={{ maxHeight: 400 }}>
|
||||
<SelectScrollView>
|
||||
{selectItems.map((item) => (
|
||||
<SelectItem
|
||||
key={item.value}
|
||||
label={item.label}
|
||||
value={item.value}
|
||||
/>
|
||||
))}
|
||||
</SelectScrollView>
|
||||
</SelectContent>
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</VStack>
|
||||
|
||||
{Object.entries(attributes).map(([label, options]) => (
|
||||
<VStack key={label} space="xs">
|
||||
<Text className="text-typography-500">{label}</Text>
|
||||
<Select
|
||||
onValueChange={(value) =>
|
||||
setSelectedAttributes((prev) => ({
|
||||
...prev,
|
||||
[label]: value,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger variant="outline" size="md">
|
||||
<SelectInput
|
||||
placeholder={`Wybierz ${label.toLowerCase()}`}
|
||||
/>
|
||||
<SelectIcon className="mr-3" as={ChevronDownIcon} />
|
||||
</SelectTrigger>
|
||||
<SelectPortal>
|
||||
<SelectBackdrop />
|
||||
<SelectContent style={{ maxHeight: 400 }}>
|
||||
<SelectScrollView>
|
||||
{options.map((option) => (
|
||||
<SelectItem
|
||||
key={option}
|
||||
label={option}
|
||||
value={option}
|
||||
/>
|
||||
))}
|
||||
</SelectScrollView>
|
||||
</SelectContent>
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</VStack>
|
||||
))}
|
||||
|
||||
<Button
|
||||
className="mt-5 w-full"
|
||||
onPress={handleAddNotice}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<ButtonText className="text-typography-0">Dodaj</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
</FormControl>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -39,11 +39,11 @@ import {
|
||||
SelectDragIndicator,
|
||||
SelectDragIndicatorWrapper,
|
||||
SelectItem,
|
||||
SelectScrollView,
|
||||
} from "@/components/ui/select";
|
||||
import { ScrollView } from "react-native-gesture-handler";
|
||||
import { attributes } from "@/data/attributesData";
|
||||
|
||||
export default function Notices() {
|
||||
// Hooks
|
||||
const { notices, fetchNotices } = useNoticesStore();
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@@ -52,6 +52,7 @@ export default function Notices() {
|
||||
const [showSortSheet, setShowSortSheet] = useState(false);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [filteredNotices, setFilteredNotices] = useState([]);
|
||||
const [selectedAttributes, setSelectedAttributes] = useState({});
|
||||
const params = useLocalSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
@@ -131,6 +132,20 @@ export default function Notices() {
|
||||
});
|
||||
}
|
||||
|
||||
Object.keys(params).forEach((key) => {
|
||||
if (key.startsWith("attribute_")) {
|
||||
const attributeName = key.replace("attribute_", "");
|
||||
const attributeValue = params[key];
|
||||
|
||||
result = result.filter((notice) =>
|
||||
notice.attributes?.some(
|
||||
(attr) =>
|
||||
attr.name === attributeName && attr.value === attributeValue
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
setFilteredNotices(result);
|
||||
}, [
|
||||
notices,
|
||||
@@ -139,6 +154,8 @@ export default function Notices() {
|
||||
params.priceFrom,
|
||||
params.priceTo,
|
||||
params.search,
|
||||
params.attribute_Kolor,
|
||||
params.attribute_Materiał,
|
||||
]);
|
||||
|
||||
let filterActive =
|
||||
@@ -146,7 +163,8 @@ export default function Notices() {
|
||||
!!params.sort ||
|
||||
!!params.priceFrom ||
|
||||
!!params.priceTo ||
|
||||
!!params.search;
|
||||
!!params.search ||
|
||||
Object.keys(params).some((key) => key.startsWith("attribute_"));
|
||||
|
||||
const loadData = async () => {
|
||||
setIsLoading(true);
|
||||
@@ -181,6 +199,19 @@ export default function Notices() {
|
||||
});
|
||||
};
|
||||
|
||||
const handleAttributeSelect = (attributeName, value) => {
|
||||
const newParams = { ...params };
|
||||
|
||||
if (value) {
|
||||
newParams[`attribute_${attributeName}`] = value;
|
||||
}
|
||||
|
||||
router.replace({
|
||||
pathname: "/notices",
|
||||
params: newParams,
|
||||
});
|
||||
};
|
||||
|
||||
const handleClose = () => setShowActionsheet(false);
|
||||
|
||||
const handleSort = (value) => {
|
||||
@@ -321,6 +352,42 @@ export default function Notices() {
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</Box>
|
||||
<Box>
|
||||
{Object.entries(attributes).map(([label, options]) => (
|
||||
<Box className="mb-4" key={label}>
|
||||
{/* <Text className="text-typography-500">{label}</Text> */}
|
||||
<Select
|
||||
style={{ flex: 1 }}
|
||||
onValueChange={(value) =>
|
||||
handleAttributeSelect(label, value)
|
||||
}
|
||||
>
|
||||
<SelectTrigger variant="outline" size="md">
|
||||
<SelectInput
|
||||
style={{ flex: 1 }}
|
||||
placeholder={`Wybierz ${label.toLowerCase()}`}
|
||||
value={params[`attribute_${label}`] || ""}
|
||||
/>
|
||||
<SelectIcon className="mr-3" as={ChevronDownIcon} />
|
||||
</SelectTrigger>
|
||||
<SelectPortal>
|
||||
<SelectBackdrop />
|
||||
<SelectContent style={{ maxHeight: 400 }}>
|
||||
<SelectScrollView>
|
||||
{options.map((option) => (
|
||||
<SelectItem
|
||||
key={option}
|
||||
label={option}
|
||||
value={option}
|
||||
/>
|
||||
))}
|
||||
</SelectScrollView>
|
||||
</SelectContent>
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</KeyboardAwareScrollView>
|
||||
</ActionsheetContent>
|
||||
</Actionsheet>
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
import { Stack, Redirect } from "expo-router";
|
||||
import {Stack} from "expo-router";
|
||||
import "@/global.css";
|
||||
import { GluestackUIProvider } from "@/components/ui/gluestack-ui-provider";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import {GluestackUIProvider} from "@/components/ui/gluestack-ui-provider";
|
||||
import {QueryClient, QueryClientProvider} from "@tanstack/react-query";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
export default function RootLayout() {
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<GluestackUIProvider>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerTintColor: "#1c1c1e",
|
||||
headerBackTitleVisible: false,
|
||||
headerBackTitle: "Wróć",
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
<Stack.Screen name="user" options={{ headerShown: false }} />
|
||||
<Stack.Screen
|
||||
name="(auth)/login"
|
||||
options={{ headerShown: false }}/>
|
||||
<Stack.Screen
|
||||
name="registration"
|
||||
options={{ headerShown: false }}/>
|
||||
</Stack>
|
||||
</GluestackUIProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<GluestackUIProvider>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerTintColor: "#1c1c1e",
|
||||
headerBackTitleVisible: false,
|
||||
headerBackTitle: "Wróć",
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="(tabs)" options={{headerShown: false}}/>
|
||||
{/*<Stack.Screen name="user" options={{headerShown: false}}/>*/}
|
||||
<Stack.Screen
|
||||
name="(auth)/login"
|
||||
options={{headerShown: false}}/>
|
||||
<Stack.Screen
|
||||
name="registration"
|
||||
options={{headerShown: false}}/>
|
||||
</Stack>
|
||||
</GluestackUIProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,25 +1,37 @@
|
||||
import { Link, Stack, useLocalSearchParams } from "expo-router";
|
||||
import { Stack, useLocalSearchParams } from "expo-router";
|
||||
import { KeyboardAvoidingView, Platform } from "react-native";
|
||||
import { Box } from "@/components/ui/box";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Heading } from "@/components/ui/heading";
|
||||
import { useRouter } from "expo-router";
|
||||
import { Image } from "@/components/ui/image";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import { VStack } from "@/components/ui/vstack";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import {
|
||||
Avatar,
|
||||
AvatarImage,
|
||||
AvatarFallbackText,
|
||||
} from "@/components/ui/avatar";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Dimensions,
|
||||
FlatList,
|
||||
View,
|
||||
TextInput,
|
||||
Alert,
|
||||
} from "react-native";
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { useNoticesStore } from "@/store/noticesStore";
|
||||
import { useWishlist } from "@/store/wishlistStore";
|
||||
import { Pressable, ScrollView } from "react-native";
|
||||
import { getUserById } from "@/api/client";
|
||||
|
||||
const { width } = Dimensions.get("window");
|
||||
import * as ScreenOrientation from "expo-screen-orientation";
|
||||
import { useAuthStore } from "@/store/authStore";
|
||||
import { sendEmail } from "@/api/email";
|
||||
// import { Button } from "@gluestack-ui/themed";
|
||||
import { Button, ButtonText } from "@/components/ui/button";
|
||||
import { SafeAreaView } from "react-native-safe-area-context";
|
||||
|
||||
export default function NoticeDetails() {
|
||||
const { id } = useLocalSearchParams();
|
||||
@@ -30,20 +42,78 @@ export default function NoticeDetails() {
|
||||
const [notice, setNotice] = useState(null);
|
||||
const [user, setUser] = useState(null);
|
||||
const [isUserLoading, setIsUserLoading] = useState(true);
|
||||
const [isLandscape, setIsLandscape] = useState(false);
|
||||
const flatListRef = useRef(null);
|
||||
const [currentIndex, setCurrentIndex] = useState(0);
|
||||
|
||||
const [isMessageFormVisible, setIsMessageFormVisible] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [Email, setEmail] = useState("");
|
||||
const handleSendMessage = () => {
|
||||
console.log("Wiadomość do:", user?.email);
|
||||
console.log("Email nadawcy:", Email);
|
||||
console.log("Treść:", message);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
setIsMessageFormVisible(false);
|
||||
setMessage("");
|
||||
setEmail("");
|
||||
const { width } = Dimensions.get("window");
|
||||
|
||||
const handleSendMessage = async () => {
|
||||
setIsSending(true);
|
||||
|
||||
const { user_id, token } = useAuthStore.getState();
|
||||
|
||||
if (!user_id || !token) {
|
||||
console.error("Brak danych zalogowanego użytkownika.");
|
||||
Alert.alert("Błąd", "Zaloguj się, aby wysłać wiadomość.");
|
||||
setIsSending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let currentUserEmail = "";
|
||||
try {
|
||||
const currentUser = await getUserById(user_id);
|
||||
currentUserEmail = currentUser?.email;
|
||||
if (!currentUserEmail) {
|
||||
console.error("Nie znaleziono adresu email zalogowanego użytkownika.");
|
||||
Alert.alert(
|
||||
"Błąd",
|
||||
"Nie znaleziono adresu email zalogowanego użytkownika."
|
||||
);
|
||||
setIsSending(false);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Błąd podczas pobierania danych użytkownika:", error);
|
||||
Alert.alert(
|
||||
"Błąd",
|
||||
"Nie udało się pobrać danych użytkownika. Spróbuj ponownie później."
|
||||
);
|
||||
setIsSending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const emailData = {
|
||||
to: user?.email || "",
|
||||
subject: `Zapytanie ${currentUserEmail} o ogłoszenie ${notice.title}`,
|
||||
body: message,
|
||||
};
|
||||
|
||||
if (!emailData.to || !emailData.subject || !emailData.body) {
|
||||
console.error("Walidacja nieudana: brakujące pola w emailData.");
|
||||
Alert.alert("Błąd", "Wszystkie pola są wymagane!");
|
||||
setIsSending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await sendEmail(emailData);
|
||||
if (result.success) {
|
||||
setIsMessageFormVisible(false);
|
||||
setMessage("");
|
||||
Alert.alert("Sukces", "Wiadomość została wysłana!");
|
||||
} else {
|
||||
console.error("Błąd podczas wysyłania wiadomości:", result.error);
|
||||
Alert.alert(
|
||||
"Błąd",
|
||||
`Nie udało się wysłać wiadomości
|
||||
: $ { result.error }`
|
||||
);
|
||||
}
|
||||
setIsSending(false);
|
||||
};
|
||||
|
||||
const formatDate = (dateString) => {
|
||||
@@ -73,6 +143,51 @@ export default function NoticeDetails() {
|
||||
itemVisiblePercentThreshold: 70,
|
||||
}).current;
|
||||
|
||||
useEffect(() => {
|
||||
const unlockOrientation = async () => {
|
||||
try {
|
||||
await ScreenOrientation.unlockAsync();
|
||||
} catch (err) {
|
||||
console.error("Error unlocking orientation:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const getInitialOrientation = async () => {
|
||||
try {
|
||||
const orientation = await ScreenOrientation.getOrientationAsync();
|
||||
setIsLandscape(
|
||||
orientation === ScreenOrientation.Orientation.LANDSCAPE_LEFT ||
|
||||
orientation === ScreenOrientation.Orientation.LANDSCAPE_RIGHT
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("Error getting initial orientation:", err);
|
||||
}
|
||||
};
|
||||
|
||||
unlockOrientation();
|
||||
getInitialOrientation();
|
||||
|
||||
const subscription = ScreenOrientation.addOrientationChangeListener(
|
||||
({ orientationInfo }) => {
|
||||
const isLandscapeMode =
|
||||
orientationInfo.orientation ===
|
||||
ScreenOrientation.Orientation.LANDSCAPE_LEFT ||
|
||||
orientationInfo.orientation ===
|
||||
ScreenOrientation.Orientation.LANDSCAPE_RIGHT;
|
||||
setIsLandscape(isLandscapeMode);
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
ScreenOrientation.removeOrientationChangeListener(subscription);
|
||||
ScreenOrientation.lockAsync(
|
||||
ScreenOrientation.OrientationLock.PORTRAIT_UP
|
||||
).catch((err) =>
|
||||
console.error("Error locking orientation on unmount:", err)
|
||||
);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchNotice = async () => {
|
||||
setIsLoading(true);
|
||||
@@ -107,7 +222,7 @@ export default function NoticeDetails() {
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("Error while loading images:", err);
|
||||
setImage({ uri: "https://http.cat/404.jpg" });
|
||||
setImages({ uri: "https://http.cat/404.jpg" });
|
||||
} finally {
|
||||
setIsImageLoading(false);
|
||||
}
|
||||
@@ -150,189 +265,256 @@ export default function NoticeDetails() {
|
||||
}
|
||||
|
||||
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
|
||||
snapToInterval={width}
|
||||
snapToAlignment="start"
|
||||
decelerationRate="fast"
|
||||
showsHorizontalScrollIndicator={false}
|
||||
pagingEnabled
|
||||
onViewableItemsChanged={onViewableItemsChanged}
|
||||
viewabilityConfig={viewabilityConfig}
|
||||
renderItem={({ item, index }) => (
|
||||
<View style={{ width: width }} className="p-1">
|
||||
<Image
|
||||
source={item}
|
||||
className="h-auto w-auto rounded-md aspect-[1/1]"
|
||||
alt={`Zdjęcie ${index + 1}`}
|
||||
resizeMode="cover"
|
||||
/>
|
||||
</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} zł
|
||||
</Heading>
|
||||
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
toggleNoticeInWishlist(id);
|
||||
}}
|
||||
>
|
||||
<Ionicons
|
||||
name={isInWishlist ? "heart" : "heart-outline"}
|
||||
size={24}
|
||||
color={"primary-heading-500"}
|
||||
/>
|
||||
</Pressable>
|
||||
<SafeAreaView className="flex-1" edges={["right", "bottom", "left"]}>
|
||||
<Card className="p-0 rounded-lg m-3 flex-1">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: notice.title,
|
||||
headerShown: !isLandscape,
|
||||
}}
|
||||
/>
|
||||
{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="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">
|
||||
) : (
|
||||
<Box
|
||||
className="sticky top-0 z-10 bg-white"
|
||||
style={
|
||||
isLandscape
|
||||
? {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
zIndex: 30,
|
||||
}
|
||||
: {}
|
||||
}
|
||||
>
|
||||
<FlatList
|
||||
ref={flatListRef}
|
||||
data={images}
|
||||
horizontal
|
||||
snapToAlignment="start"
|
||||
snapToInterval={width}
|
||||
decelerationRate="fast"
|
||||
showsHorizontalScrollIndicator={false}
|
||||
pagingEnabled
|
||||
onViewableItemsChanged={onViewableItemsChanged}
|
||||
viewabilityConfig={viewabilityConfig}
|
||||
style={isLandscape ? { flex: 1 } : {}}
|
||||
renderItem={({ item, index }) => (
|
||||
<View style={{ width: width }} className="p-1">
|
||||
<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"
|
||||
source={item}
|
||||
// className="h-auto w-auto rounded-md aspect-[1/1]"
|
||||
alt={`Zdjęcie ${index + 1}`}
|
||||
resizeMode="cover"
|
||||
renderMode="contain"
|
||||
className={
|
||||
isLandscape
|
||||
? "w-auto h-full"
|
||||
: "h-auto w-auto rounded-md aspect-[1/1]"
|
||||
}
|
||||
style={
|
||||
isLandscape
|
||||
? {
|
||||
resizeMode: "contain",
|
||||
}
|
||||
: {}
|
||||
}
|
||||
// resizeMode={isLandscape ? "cover" : "contain"}
|
||||
/>
|
||||
</Box>
|
||||
</View>
|
||||
)}
|
||||
keyExtractor={(item, index) => index.toString()}
|
||||
/>
|
||||
|
||||
<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>
|
||||
{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>
|
||||
</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}
|
||||
)}
|
||||
|
||||
<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-left bg-gray-50 rounded-md p-2">
|
||||
{notice.title}
|
||||
</Text>
|
||||
|
||||
<Text className="text-sm font-medium mb-1">Do:</Text>
|
||||
<Text className="bg-gray-100 p-3 rounded text-gray-500">
|
||||
{user?.email || "Brak adresu e-mail"}
|
||||
</Text>
|
||||
<Text className="text-sm font-medium mb-1">Twój e-mail:</Text>
|
||||
<TextInput
|
||||
className="border border-gray-300 p-2 rounded"
|
||||
placeholder="Wpisz swój adres e-mail"
|
||||
value={Email}
|
||||
onChangeText={setEmail}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left"
|
||||
multiline
|
||||
numberOfLines={4}
|
||||
placeholder="Napisz swoją wiadomość..."
|
||||
value={message}
|
||||
onChangeText={setMessage}
|
||||
/>
|
||||
|
||||
<View className="flex-row justify-end space-x-2">
|
||||
<Pressable
|
||||
onPress={() => setIsMessageFormVisible(false)}
|
||||
className="bg-gray-300 py-2 px-4 rounded-md"
|
||||
>
|
||||
<Text className="text-gray-800">Anuluj</Text>
|
||||
</Pressable>
|
||||
<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} zł
|
||||
</Heading>
|
||||
|
||||
<Pressable
|
||||
onPress={handleSendMessage}
|
||||
className="bg-primary-500 py-2 px-4 rounded-md"
|
||||
onPress={() => {
|
||||
toggleNoticeInWishlist(id);
|
||||
}}
|
||||
>
|
||||
<Text className="text-white">Wyślij</Text>
|
||||
<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>
|
||||
{notice.attributes && notice.attributes.length > 0 && (
|
||||
<Box className="mt-4 bg-gray-50 p-3 rounded-lg shadow-sm">
|
||||
{notice.attributes.map((attribute, index) => (
|
||||
<Text
|
||||
key={index}
|
||||
className="text-sm text-typography-500 mb-1"
|
||||
>
|
||||
{attribute.name}:{" "}
|
||||
<Text className="font-bold text-gray-950">
|
||||
{attribute.value}
|
||||
</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">
|
||||
<Avatar size="md">
|
||||
<AvatarImage
|
||||
source={{
|
||||
uri:
|
||||
user.image ||
|
||||
"https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain",
|
||||
}}
|
||||
alt="Zdjęcie profilowe"
|
||||
/>
|
||||
<AvatarFallbackText>
|
||||
{user.firstName?.[0]}
|
||||
{user.lastName?.[0]}
|
||||
</AvatarFallbackText>
|
||||
</Avatar>
|
||||
</Box>
|
||||
|
||||
<Box className="flex-1">
|
||||
<Text className="text-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>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-2"
|
||||
onPress={() => router.replace(`/user/${notice.clientId}`)}
|
||||
>
|
||||
<ButtonText>
|
||||
Zobacz więcej ogłoszeń od {user.firstName}
|
||||
</ButtonText>
|
||||
</Button>
|
||||
</Box>
|
||||
</>
|
||||
) : (
|
||||
<Text>Błąd podczas ładowania danych użytkownika</Text>
|
||||
)}
|
||||
</Box>
|
||||
</VStack>
|
||||
</ScrollView>
|
||||
{isMessageFormVisible && (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
className="absolute inset-0 bg-black/50 justify-center items-center z-20"
|
||||
>
|
||||
<View className="bg-white p-4 rounded-lg w-4/5 max-h-4/5">
|
||||
<ScrollView showsVerticalScrollIndicator={false}>
|
||||
<Text className="text-lg font-bold mb-4">
|
||||
Wyślij wiadomość do {user?.firstName}
|
||||
</Text>
|
||||
|
||||
<Text className="text-sm font-medium mb-1">Do:</Text>
|
||||
<Text className="bg-gray-100 p-3 rounded text-gray-500">
|
||||
{user?.email || "Brak adresu e-mail"}
|
||||
</Text>
|
||||
<Text className="text-sm font-medium mb-1">Temat:</Text>
|
||||
<Text className="bg-gray-100 p-3 rounded text-gray-500">
|
||||
Zapytanie o ogłoszenie '
|
||||
{notice.title || "Brak nazwy ogłoszenia"}'
|
||||
</Text>
|
||||
|
||||
<TextInput
|
||||
className="border border-gray-300 rounded-md p-2 mb-4 h-32 text-left"
|
||||
multiline
|
||||
numberOfLines={4}
|
||||
placeholder="Napisz swoją wiadomość..."
|
||||
value={message}
|
||||
onChangeText={setMessage}
|
||||
/>
|
||||
|
||||
<View className="flex-row justify-end space-x-2">
|
||||
<Pressable
|
||||
onPress={() => setIsMessageFormVisible(false)}
|
||||
className="bg-gray-300 py-2 px-4 rounded-md"
|
||||
>
|
||||
<Text className="text-gray-800">Anuluj</Text>
|
||||
</Pressable>
|
||||
|
||||
<Pressable
|
||||
onPress={handleSendMessage}
|
||||
className="bg-blue-500 py-2 px-4 rounded-md"
|
||||
disabled={isSending}
|
||||
>
|
||||
{isSending ? (
|
||||
<ActivityIndicator color="#fff" />
|
||||
) : (
|
||||
<Text className="text-white">Wyślij</Text>
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</Card>
|
||||
</KeyboardAvoidingView>
|
||||
)}
|
||||
</Card>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
389
ArtisanConnect/app/notice/edit/[id].jsx
Normal file
389
ArtisanConnect/app/notice/edit/[id].jsx
Normal file
@@ -0,0 +1,389 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Image,
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
ActivityIndicator,
|
||||
} from "react-native";
|
||||
import { Button, ButtonText } from "@/components/ui/button";
|
||||
import { FormControl } from "@/components/ui/form-control";
|
||||
import { Input, InputField } from "@/components/ui/input";
|
||||
import { Text } from "@/components/ui/text";
|
||||
import { VStack } from "@/components/ui/vstack";
|
||||
import { Textarea, TextareaInput } from "@/components/ui/textarea";
|
||||
import { ScrollView } from "@gluestack-ui/themed";
|
||||
import { Box } from "@/components/ui/box";
|
||||
import * as ImagePicker from "expo-image-picker";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectInput,
|
||||
SelectIcon,
|
||||
SelectPortal,
|
||||
SelectBackdrop,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectScrollView,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
import { ChevronDownIcon } from "@/components/ui/icon";
|
||||
import { useNoticesStore } from "@/store/noticesStore";
|
||||
import { listCategories } from "@/api/categories";
|
||||
import { useRouter } from "expo-router";
|
||||
import { attributes } from "@/data/attributesData";
|
||||
import { useLocalSearchParams, Stack } from "expo-router";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
|
||||
export default function EditNotice() {
|
||||
const { id } = useLocalSearchParams();
|
||||
const router = useRouter();
|
||||
const { editNotice, fetchNotices, notices } = useNoticesStore();
|
||||
const [title, setTitle] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [price, setPrice] = useState("");
|
||||
const [category, setCategory] = useState("");
|
||||
const [image, setImage] = useState([]);
|
||||
const [isImageLoading, setIsImageLoading] = useState(true);
|
||||
const [selectItems, setSelectItems] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [selectedAttributes, setSelectedAttributes] = useState({});
|
||||
const { getNoticeById, getAllImagesByNoticeId } = useNoticesStore();
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
const fetchSelectItems = async () => {
|
||||
try {
|
||||
let data = await listCategories();
|
||||
if (isMounted && Array.isArray(data)) {
|
||||
setSelectItems(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching select items:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSelectItems();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const notice = notices.find((notice) => notice.noticeId == id);
|
||||
if (notice) {
|
||||
setTitle(notice.title || "");
|
||||
setDescription(notice.description || "");
|
||||
setPrice(notice.price?.toString() || "");
|
||||
setCategory(notice.category || "");
|
||||
|
||||
if (notice.attributes && Array.isArray(notice.attributes)) {
|
||||
const attributesObj = {};
|
||||
notice.attributes.forEach((attr) => {
|
||||
attributesObj[attr.name] = attr.value;
|
||||
});
|
||||
setSelectedAttributes(attributesObj);
|
||||
}
|
||||
}
|
||||
|
||||
const fetchImage = async () => {
|
||||
setIsImageLoading(true);
|
||||
try {
|
||||
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
|
||||
if (fetchedImages && fetchedImages.length > 0) {
|
||||
setImage(fetchedImages);
|
||||
} else {
|
||||
setImage([]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error while loading images:", err);
|
||||
setImage([]);
|
||||
} finally {
|
||||
setIsImageLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (notice) {
|
||||
fetchImage();
|
||||
}
|
||||
}, [notices, id]);
|
||||
|
||||
const [error, setError] = useState({
|
||||
title: false,
|
||||
description: false,
|
||||
price: false,
|
||||
category: false,
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
image: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
});
|
||||
|
||||
const handleEditNotice = async () => {
|
||||
setError({
|
||||
title: !title,
|
||||
description: !description,
|
||||
price: !price,
|
||||
category: !category,
|
||||
});
|
||||
|
||||
if (!title || !description || !price || !category) {
|
||||
console.log("Error in form");
|
||||
return;
|
||||
}
|
||||
const formattedAttributes = Object.entries(selectedAttributes).map(
|
||||
([name, value]) => ({
|
||||
name: name,
|
||||
value: value,
|
||||
})
|
||||
);
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await editNotice(id, {
|
||||
title: title,
|
||||
description: description,
|
||||
price: price,
|
||||
category: category,
|
||||
status: "INACTIVE",
|
||||
image: image,
|
||||
attributes: formattedAttributes,
|
||||
});
|
||||
|
||||
if (result) {
|
||||
await fetchNotices();
|
||||
|
||||
router.push("/(tabs)/dashboard/userNotices");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error editing notice. Error message: ", error.message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const takePicture = async () => {
|
||||
const { status } = await ImagePicker.requestCameraPermissionsAsync();
|
||||
if (status !== "granted") {
|
||||
return;
|
||||
}
|
||||
const result = await ImagePicker.launchCameraAsync({
|
||||
allowsEditing: false,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets) {
|
||||
setImage(result.assets.map((asset) => asset.uri));
|
||||
}
|
||||
};
|
||||
|
||||
const pickImage = async () => {
|
||||
let result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: "images",
|
||||
selectionLimit: 8,
|
||||
allowsEditing: false,
|
||||
allowsMultipleSelection: true,
|
||||
aspect: [4, 3],
|
||||
quality: 0.5,
|
||||
});
|
||||
|
||||
if (!result.canceled) {
|
||||
setImage(result.assets.map((asset) => asset.uri));
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box className="items-center justify-center flex-1">
|
||||
<ActivityIndicator size="large" color="#787878" />
|
||||
<Text size="md" bold="true" className="mt-5">
|
||||
Edytuj ogłoszenie...
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
style={{ flex: 1 }}
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 64 : 0}
|
||||
>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Edycja",
|
||||
headerLeft: () => (
|
||||
<Button
|
||||
variant="link"
|
||||
size="sm"
|
||||
onPress={() => router.replace("/(tabs)/dashboard/userNotices")}
|
||||
className="mr-2"
|
||||
>
|
||||
<Ionicons name="arrow-back" size={24} color="#1c1c1e" />
|
||||
<ButtonText className="text-typography-900">Wróć</ButtonText>
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<ScrollView h="$80" w="$80">
|
||||
<FormControl className="p-4 border rounded-lg border-outline-300">
|
||||
<VStack space="xl">
|
||||
<VStack space="md">
|
||||
<Text className="text-typography-500">Zdjęcia</Text>
|
||||
<Button onPress={pickImage}>
|
||||
<ButtonText>Wybierz zdjęcia</ButtonText>
|
||||
</Button>
|
||||
<Button onPress={takePicture}>
|
||||
<ButtonText>Zrób zdjęcie</ButtonText>
|
||||
</Button>
|
||||
<Text size="sm" bold="true">
|
||||
Pierwsze zdjęcie będzie zdjęciem głównym
|
||||
</Text>
|
||||
{image && image.length > 0 && (
|
||||
<VStack space="xs" className="flex-row flex-wrap">
|
||||
{image.map((img, index) => {
|
||||
const imageSource =
|
||||
typeof img === "string" ? { uri: img } : img;
|
||||
|
||||
return (
|
||||
<Image
|
||||
key={index}
|
||||
source={imageSource}
|
||||
style={styles.image}
|
||||
className="m-1"
|
||||
onError={(error) =>
|
||||
console.log(`Image ${index} error:`, error)
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</VStack>
|
||||
)}
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Tytuł*</Text>
|
||||
<Input className="min-w-[250px]" isInvalid={error.title}>
|
||||
<InputField
|
||||
type="text"
|
||||
value={title}
|
||||
onChangeText={(value) => setTitle(value)}
|
||||
/>
|
||||
</Input>
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Opis*</Text>
|
||||
<Textarea
|
||||
size="md"
|
||||
className="min-w-[250px] "
|
||||
isInvalid={error.description}
|
||||
>
|
||||
<TextareaInput
|
||||
placeholder="Opisz produkt"
|
||||
value={description}
|
||||
onChangeText={(value) => setDescription(value)}
|
||||
/>
|
||||
</Textarea>
|
||||
</VStack>
|
||||
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Cena*</Text>
|
||||
<Input className="min-w-[250px]" isInvalid={error.price}>
|
||||
<InputField
|
||||
type="text"
|
||||
value={price}
|
||||
onChangeText={(value) => setPrice(value)}
|
||||
/>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="xs">
|
||||
<Text className="text-typography-500">Kategoria*</Text>
|
||||
<Select
|
||||
onValueChange={(value) => setCategory(value)}
|
||||
isInvalid={error.category}
|
||||
selectedValue={category || ""}
|
||||
>
|
||||
<SelectTrigger variant="outline" size="md">
|
||||
<SelectInput
|
||||
placeholder="Wybierz kategorię"
|
||||
value={
|
||||
selectItems.find((item) => item.value === category)
|
||||
?.label || ""
|
||||
}
|
||||
/>
|
||||
<SelectIcon className="mr-3" as={ChevronDownIcon} />
|
||||
</SelectTrigger>
|
||||
<SelectPortal>
|
||||
<SelectBackdrop />
|
||||
<SelectContent style={{ maxHeight: 400 }}>
|
||||
<SelectScrollView>
|
||||
{selectItems.map((item) => (
|
||||
<SelectItem
|
||||
key={item.value}
|
||||
label={item.label}
|
||||
value={item.value}
|
||||
/>
|
||||
))}
|
||||
</SelectScrollView>
|
||||
</SelectContent>
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</VStack>
|
||||
|
||||
{Object.entries(attributes).map(([label, options]) => (
|
||||
<VStack key={label} space="xs">
|
||||
<Text className="text-typography-500">{label}</Text>
|
||||
<Select
|
||||
selectedValue={selectedAttributes[label] || ""}
|
||||
onValueChange={(value) =>
|
||||
setSelectedAttributes((prev) => ({
|
||||
...prev,
|
||||
[label]: value,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger variant="outline" size="md">
|
||||
<SelectInput
|
||||
placeholder={`Wybierz ${label.toLowerCase()}`}
|
||||
/>
|
||||
<SelectIcon className="mr-3" as={ChevronDownIcon} />
|
||||
</SelectTrigger>
|
||||
<SelectPortal>
|
||||
<SelectBackdrop />
|
||||
<SelectContent style={{ maxHeight: 400 }}>
|
||||
<SelectScrollView>
|
||||
{options.map((option) => (
|
||||
<SelectItem
|
||||
key={option}
|
||||
label={option}
|
||||
value={option}
|
||||
/>
|
||||
))}
|
||||
</SelectScrollView>
|
||||
</SelectContent>
|
||||
</SelectPortal>
|
||||
</Select>
|
||||
</VStack>
|
||||
))}
|
||||
|
||||
<Button
|
||||
className="mt-5 w-full"
|
||||
onPress={handleEditNotice}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<ButtonText className="text-typography-0">Edytuj</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
</FormControl>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +1,24 @@
|
||||
import React, {useState} from 'react';
|
||||
import {StyleSheet, ActivityIndicator, SafeAreaView, View} from 'react-native';
|
||||
import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform, KeyboardAvoidingView} from 'react-native';
|
||||
import {useAuthStore} from '@/store/authStore';
|
||||
import {useRouter} from 'expo-router';
|
||||
|
||||
import {Box} from "@/components/ui/box"
|
||||
import {Button, ButtonText,ButtonIcon} from "@/components/ui/button"
|
||||
import {ArrowRightIcon} from "@/components/ui/icon"
|
||||
import {Button, ButtonText, ButtonIcon} from "@/components/ui/button"
|
||||
import {ArrowRightIcon, EyeIcon, EyeOffIcon} from "@/components/ui/icon"
|
||||
import {Center} from "@/components/ui/center"
|
||||
import {Heading} from "@/components/ui/heading"
|
||||
import {Input, InputField} from "@/components/ui/input"
|
||||
import {Input, InputField, InputIcon, InputSlot} from "@/components/ui/input"
|
||||
import {VStack} from "@/components/ui/vstack"
|
||||
import {Link} from "expo-router"
|
||||
import {Text} from "@/components/ui/text";
|
||||
|
||||
export default function Registration() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [emailError, setEmailError] = useState('');
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const {signUp, isLoading} = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
@@ -26,6 +28,11 @@ export default function Registration() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateEmail(email)) {
|
||||
setEmailError('Nieprawidłowy format adresu email');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await signUp({email, password, firstName, lastName});
|
||||
alert(`Zalogowano jako ${email}`);
|
||||
@@ -35,6 +42,17 @@ export default function Registration() {
|
||||
}
|
||||
}
|
||||
|
||||
const validateEmail = (email) => {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email);
|
||||
};
|
||||
|
||||
const handleShowPassword = () => {
|
||||
setShowPassword((showState) => {
|
||||
return !showState
|
||||
})
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
@@ -44,45 +62,66 @@ export default function Registration() {
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<Center>
|
||||
|
||||
<Box className="p-5 w-[80%] border border-background-300 rounded-lg">
|
||||
<VStack className="pb-4" space="xs">
|
||||
<Heading className="leading-[30px]">Rejestracja</Heading>
|
||||
<Box className="flex flex-row">
|
||||
{/* <Link href="/login" asChild> */}
|
||||
<Button variant="link" size="sm" className="p-0" onPress={() => router.replace("/login")}>
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
style={{flex: 1}}
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 64 : 0}
|
||||
>
|
||||
<SafeAreaView style={styles.container}>
|
||||
<Center>
|
||||
|
||||
<Box className="p-5 w-[80%] border border-background-300 rounded-lg">
|
||||
<VStack className="pb-4" space="xs">
|
||||
<Heading className="leading-[30px]">Rejestracja</Heading>
|
||||
<Box className="flex flex-row">
|
||||
{/* <Link href="/login" asChild> */}
|
||||
<Button variant="link" size="sm" className="p-0"
|
||||
onPress={() => router.replace("/login")}>
|
||||
<ButtonText style={styles.signupbutton}>Masz już konto? Zaloguj się!</ButtonText>
|
||||
<ButtonIcon className="mr-1" size="md" as={ArrowRightIcon}/>
|
||||
</Button>
|
||||
{/* </Link> */}
|
||||
</Box>
|
||||
</VStack>
|
||||
<VStack space="xl" className="py-2">
|
||||
<Input>
|
||||
<InputField type="email" className="py-2" placeholder="E-mail" onChangeText={setEmail}/>
|
||||
</Input>
|
||||
<Input>
|
||||
<InputField className="py-2" placeholder="Imię" onChangeText={setFirstName}/>
|
||||
</Input>
|
||||
<Input>
|
||||
<InputField className="py-2" placeholder="Nazwisko" onChangeText={setLastName}/>
|
||||
</Input>
|
||||
<Input>
|
||||
<InputField type="password" className="py-2" placeholder="Hasło"
|
||||
onChangeText={setPassword}/>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="lg" className="pt-4">
|
||||
<Button size="sm" onPress={handleInternalRegistration}>
|
||||
<ButtonText>Zarejestruj się</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
</Box>
|
||||
|
||||
</Center>
|
||||
</SafeAreaView>
|
||||
{/* </Link> */}
|
||||
</Box>
|
||||
</VStack>
|
||||
<VStack space="xl" className="py-2">
|
||||
{emailError ? <Text className="m-0 color-red-600">{emailError}</Text> : null}
|
||||
<Input isRequired={true}>
|
||||
<InputField type="email" className="py-2" placeholder="E-mail"
|
||||
onChangeText={(text) => {
|
||||
setEmail(text);
|
||||
if (text && !validateEmail(text)) {
|
||||
setEmailError('Nieprawidłowy format adresu email');
|
||||
} else {
|
||||
setEmailError('');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Input>
|
||||
<Input isRequired={true}>
|
||||
<InputField className="py-2" placeholder="Imię" onChangeText={setFirstName}/>
|
||||
</Input>
|
||||
<Input isRequired={true}>
|
||||
<InputField className="py-2" placeholder="Nazwisko" onChangeText={setLastName}/>
|
||||
</Input>
|
||||
<Input isRequired={true}>
|
||||
<InputField type={showPassword ? "text" : "password"} className="py-2"
|
||||
placeholder="Hasło"
|
||||
onChangeText={setPassword}/>
|
||||
<InputSlot className="pr-3" onPress={handleShowPassword}>
|
||||
<InputIcon as={showPassword ? EyeIcon : EyeOffIcon}/>
|
||||
</InputSlot>
|
||||
</Input>
|
||||
</VStack>
|
||||
<VStack space="lg" className="pt-4">
|
||||
<Button size="sm" onPress={handleInternalRegistration}>
|
||||
<ButtonText>Zarejestruj się</ButtonText>
|
||||
</Button>
|
||||
</VStack>
|
||||
</Box>
|
||||
|
||||
</Center>
|
||||
</SafeAreaView>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -105,7 +144,7 @@ const styles = StyleSheet.create({
|
||||
color: 'red',
|
||||
marginBottom: 10,
|
||||
},
|
||||
signupbutton: {
|
||||
signupbutton: {
|
||||
fontWeight: '300',
|
||||
textAlign: 'left',
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import { useLocalSearchParams, Stack } from "expo-router";
|
||||
import { useState, useEffect } from "react";
|
||||
import { FlatList, ActivityIndicator, Text } from "react-native";
|
||||
import {FlatList, ActivityIndicator, Text, SafeAreaView} from "react-native";
|
||||
import { Box } from "@/components/ui/box";
|
||||
import { Image } from "@/components/ui/image";
|
||||
import { VStack } from "@/components/ui/vstack";
|
||||
@@ -10,60 +10,77 @@ 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();
|
||||
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]);
|
||||
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 (isUserLoading) {
|
||||
return <ActivityIndicator />;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Text>Nie znaleziono użytkownika</Text>;
|
||||
}
|
||||
if (!user) {
|
||||
return <Text>Nie znaleziono użytkownika</Text>;
|
||||
}
|
||||
|
||||
const userNotices = notices.filter(notice => notice.clientId === Number(userId));
|
||||
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>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SafeAreaView className="flex-1" edges={['right', 'bottom', 'left']}>
|
||||
<VStack className="p-4">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "Ogłoszenia użytkownika",
|
||||
}}
|
||||
/>
|
||||
<Box className="flex-row items-center mb-4">
|
||||
<Image
|
||||
source={{
|
||||
uri:
|
||||
user.image ||
|
||||
"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",
|
||||
gap: 8,
|
||||
}}
|
||||
renderItem={({ item }) => <NoticeCard notice={item} />}
|
||||
keyExtractor={(item) => item.noticeId.toString()}
|
||||
/>
|
||||
) : (
|
||||
<Text>Ten użytkownik nie ma żadnych ogłoszeń.</Text>
|
||||
)}
|
||||
</VStack>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Stack } from 'expo-router';
|
||||
|
||||
export default function UserLayout() {
|
||||
return (
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerTitle: 'Ogłoszenia użytkownika',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +1,35 @@
|
||||
import { VStack } from '@/components/ui/vstack';
|
||||
import { Avatar, AvatarImage, AvatarFallbackText } from "@/components/ui/avatar";
|
||||
import { VStack } from "@/components/ui/vstack";
|
||||
import {
|
||||
Avatar,
|
||||
AvatarImage,
|
||||
AvatarFallbackText,
|
||||
} from "@/components/ui/avatar";
|
||||
import { Heading } from "@/components/ui/heading";
|
||||
import { Box } from '@/components/ui/box';
|
||||
import { Box } from "@/components/ui/box";
|
||||
import { Link } from "expo-router";
|
||||
|
||||
export default function UserBlock({ user }) {
|
||||
|
||||
return (
|
||||
<Box className="rounded-md bg-white p-4 items-center justify-center mb-6" >
|
||||
<VStack space="md" className='items-center'>
|
||||
<Avatar>
|
||||
<AvatarFallbackText>{user.firstName} {user.lastName}</AvatarFallbackText>
|
||||
<AvatarImage
|
||||
source={{
|
||||
uri: user.image,
|
||||
}}
|
||||
/>
|
||||
</Avatar>
|
||||
<Heading size="sm">{user.firstName} {user.lastName}</Heading>
|
||||
</VStack>
|
||||
return (
|
||||
<Link href={`/user/${user.id}`}>
|
||||
<Box className="rounded-md bg-white p-4 items-center justify-center mb-6">
|
||||
<VStack space="md" className="items-center">
|
||||
<Avatar>
|
||||
<AvatarFallbackText>
|
||||
{user.firstName} {user.lastName}
|
||||
</AvatarFallbackText>
|
||||
<AvatarImage
|
||||
source={{
|
||||
uri:
|
||||
user.image ||
|
||||
"https://th.bing.com/th/id/OIP.3coo_N8sieled8QNroQmkgHaHa?rs=1&pid=ImgDetMain",
|
||||
}}
|
||||
/>
|
||||
</Avatar>
|
||||
<Heading size="sm">
|
||||
{user.firstName} {user.lastName}
|
||||
</Heading>
|
||||
</VStack>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,28 +2,36 @@ import { View } from "react-native";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Heading } from "@/components/ui/heading";
|
||||
import { FlatList } from "react-native";
|
||||
import axios from "axios";
|
||||
import UserBlock from "@/components/UserBlock";
|
||||
import { getAllUsers } from "@/api/client";
|
||||
import { useAuthStore } from "@/store/authStore";
|
||||
|
||||
export function UserSection({ notices, title }) {
|
||||
const token = useAuthStore((state) => state.token);
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
const [users, setUsers] = useState([]);
|
||||
const { token } = useAuthStore.getState();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
const data = await getAllUsers();
|
||||
setUsers(data);
|
||||
} catch (error) {
|
||||
setUsers([]);
|
||||
}
|
||||
};
|
||||
|
||||
if (token) {
|
||||
axios
|
||||
.get("https://hopp.zikor.pl/api/v1/clients/get/all", { headers })
|
||||
.then((res) => setUsers(res.data))
|
||||
.catch(() => setUsers([]));
|
||||
fetchUsers();
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const usersWithNoticeCount = users.map((user) => {
|
||||
const count = notices.filter((n) => n.clientId === user.id).length;
|
||||
return { ...user, noticeCount: count };
|
||||
});
|
||||
const usersWithNoticeCount =
|
||||
users && users.length > 0
|
||||
? users.map((user) => {
|
||||
const count = notices.filter((n) => n.clientId === user.id).length;
|
||||
return { ...user, noticeCount: count };
|
||||
})
|
||||
: [];
|
||||
|
||||
const topUsers = usersWithNoticeCount
|
||||
.sort((a, b) => b.noticeCount - a.noticeCount)
|
||||
|
||||
28
ArtisanConnect/data/attributesData.jsx
Normal file
28
ArtisanConnect/data/attributesData.jsx
Normal file
@@ -0,0 +1,28 @@
|
||||
export const attributes = {
|
||||
Kolor: [
|
||||
"Zielony",
|
||||
"Czerwony",
|
||||
"Niebieski",
|
||||
"Żółty",
|
||||
"Biały",
|
||||
"Czarny",
|
||||
"Różowy",
|
||||
"Szary",
|
||||
"Fioletowy",
|
||||
"Pomarańczowy",
|
||||
"Inny",
|
||||
],
|
||||
Materiał: [
|
||||
"Bawełna",
|
||||
"Wełna",
|
||||
"Syntetyk",
|
||||
"Skóra",
|
||||
"Len",
|
||||
"Jedwab",
|
||||
"Poliester",
|
||||
"Akryl",
|
||||
"Wiskoza",
|
||||
"Nylon",
|
||||
"Inny",
|
||||
],
|
||||
};
|
||||
@@ -2,10 +2,9 @@ import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import axios from "axios";
|
||||
import * as api from "@/api/auth";
|
||||
import { router } from "expo-router";
|
||||
|
||||
const API_URL = "https://hopp.zikor.pl/api/v1";
|
||||
|
||||
let interceptorInitialized = false;
|
||||
|
||||
export const useAuthStore = create(
|
||||
@@ -19,6 +18,7 @@ export const useAuthStore = create(
|
||||
(error.response && error.response.status === 401) ||
|
||||
error.response.status === 403
|
||||
) {
|
||||
console.warn(error.response.data);
|
||||
set({ user_id: null, token: null, isLoading: false });
|
||||
delete axios.defaults.headers.common["Authorization"];
|
||||
router.replace("/login");
|
||||
@@ -37,16 +37,8 @@ export const useAuthStore = create(
|
||||
signIn: async (email, password) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const response = await axios.post(`${API_URL}/auth/login`, {
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
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 response = await api.login({email, password});
|
||||
set({ user_id: response.user_id, token: response.token, isLoading: false });
|
||||
} catch (error) {
|
||||
set({
|
||||
error: error.response?.data?.message || error.message,
|
||||
@@ -59,19 +51,8 @@ export const useAuthStore = create(
|
||||
signUp: async (userData) => {
|
||||
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 token = response.data.token;
|
||||
set({ user_id: user_id, token: token, isLoading: false });
|
||||
|
||||
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
|
||||
const response = await api.register(userData);
|
||||
set({ user_id: response.user_id, token: response.token, isLoading: false });
|
||||
} catch (error) {
|
||||
set({
|
||||
error: error.response?.data?.message || error.message,
|
||||
@@ -84,18 +65,8 @@ export const useAuthStore = create(
|
||||
signInWithGoogle: async (googleToken) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${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 response = await api.googleLogin(googleToken);
|
||||
set({ user_id: response.user_id, token: response.token, isLoading: false });
|
||||
} catch (error) {
|
||||
set({
|
||||
error: error.response?.data?.message || error.message,
|
||||
@@ -107,19 +78,11 @@ export const useAuthStore = create(
|
||||
|
||||
signOut: async () => {
|
||||
const { token } = get();
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
||||
try {
|
||||
await axios.post(
|
||||
`${API_URL}/auth/logout`,
|
||||
{},
|
||||
{
|
||||
headers: headers,
|
||||
}
|
||||
);
|
||||
await api.logout(token);
|
||||
} catch (error) {
|
||||
console.error("Logout error:", error);
|
||||
} finally {
|
||||
delete axios.defaults.headers.common["Authorization"];
|
||||
set({ user_id: null, token: null });
|
||||
router.replace("/login");
|
||||
}
|
||||
|
||||
@@ -26,6 +26,34 @@ export const useNoticesStore = create((set, get) => ({
|
||||
}
|
||||
},
|
||||
|
||||
editNotice: async (noticeId, notice) => {
|
||||
try {
|
||||
if (notice.image.length > 0 && typeof notice.image[0] == "string") {
|
||||
const currentImages = await api.getAllImagesByNoticeId(noticeId);
|
||||
if (currentImages && currentImages.length > 0) {
|
||||
for (const image of currentImages) {
|
||||
const filename = image.uri
|
||||
? image.uri.split("/").pop()
|
||||
: image.split("/").pop();
|
||||
|
||||
await api.deleteImage(filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
const updatedNotice = await api.editNotice(noticeId, notice);
|
||||
set((state) => ({
|
||||
notices: state.notices.map((n) =>
|
||||
n.noticeId == noticeId ? updatedNotice : n
|
||||
),
|
||||
}));
|
||||
return updatedNotice;
|
||||
} catch (error) {
|
||||
console.error("Error editing notice:", error);
|
||||
set({ error });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
getNoticeById: (noticeId) => {
|
||||
return get().notices.find(
|
||||
(notice) => String(notice.noticeId) === String(noticeId)
|
||||
|
||||
Reference in New Issue
Block a user