Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugFix(allPage): Fix all remain bug into champs Bay #72

Merged
merged 1 commit into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 21 additions & 46 deletions src/app/(profile)/profile-edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,19 @@ import React, { useEffect, useState, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/redux/store';
import { getUserProfile, updateUserProfile } from '@/redux/slices/profileSlice';

import { toast } from 'react-toastify';
import { showToast } from '@/helpers/toast';
import { useForm, SubmitHandler, useWatch } from 'react-hook-form';

import updateSchema from '@/validations/userProfileSchema';
import { useRouter } from 'next/navigation';
import type { z } from 'zod';

import { zodResolver } from '@hookform/resolvers/zod';

import InputBox from '@/components/InputBox';
import UpdatePasswords from '@/components/updatepassword';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { User, Cake, Award } from 'lucide-react'
import { User, Cake, Award } from 'lucide-react';
type FormSchemaType = z.infer<typeof updateSchema>;

const UserProfileForm: React.FC = () => {
const route = useRouter();
const [showlModal, setShowmodal] = useState(false);
Expand All @@ -43,26 +38,22 @@ const UserProfileForm: React.FC = () => {
firstName: '',
lastName: '',
phone: '',
address:'',
address: '',
birthDate: '',
preferredLanguage: '',
whereYouLive: '',
preferredCurrency: '',
preferredCurrency: 'RWf',
billingAddress: '',
},
});

const watchedValues = useWatch({ control });

const [profileImage, setProfileImage] = useState('');
const [imageFile, setImageFile] = useState<File | null>(null);
const [isLoading, setIsLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
dispatch(getUserProfile());
}, [dispatch]);

useEffect(() => {
if (user && user.User) {
setValue('firstName', user.User.firstName || '');
Expand All @@ -76,7 +67,6 @@ const UserProfileForm: React.FC = () => {
setProfileImage(user.User.profileImage || '');
}
}, [user, setValue]);

const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target?.files?.length === 1) {
const file = e.target.files[0];
Expand All @@ -88,14 +78,11 @@ const UserProfileForm: React.FC = () => {
reader.readAsDataURL(file);
}
};

const handleImageClick = () => {
fileInputRef.current?.click();
};

const getExistingImage = async (): Promise<File | null> => {
if (!user?.User?.profileImage) return null;

try {
const response = await fetch(user.User.profileImage);
const blob = await response.blob();
Expand All @@ -105,26 +92,20 @@ const UserProfileForm: React.FC = () => {
return null;
}
};

const onSubmit: SubmitHandler<FormSchemaType> = async (data) => {
const formDataToSend = new FormData();

Object.entries(data).forEach(([key, value]) => {
formDataToSend.append(key, value as string);
});

let imageToUpload: File | null = null;

if (imageFile) {
imageToUpload = imageFile;
} else {
imageToUpload = await getExistingImage();
}

if (imageToUpload) {
formDataToSend.append('profileImage', imageToUpload);
}

try {
setIsLoading(true);
const response = await dispatch(updateUserProfile(formDataToSend));
Expand All @@ -137,7 +118,6 @@ const UserProfileForm: React.FC = () => {
currentProfile.User = response.payload.User;
localStorage.setItem('profile', JSON.stringify(currentProfile));
}

toast.success('Profile updated successfully');
route.push('/profile');
} else if (updateUserProfile.rejected.match(response)) {
Expand All @@ -158,30 +138,30 @@ const UserProfileForm: React.FC = () => {
toast.error(`Failed to update profile: ${errorMessage}`);
}
};

if (error) {
console.error('Error fetching user data:', error);
showToast(
typeof error === 'string' ? error : JSON.stringify(error),
'error',
);
}

if (!user) {
return(<div className="min-h-screen w-full justify-center items-center flex">
<div className="border-t-4 border-b-4 border-blue-600 rounded-full w-20 h-20 animate-spin m-auto"></div>
</div>)
return (
<div className="min-h-screen w-full justify-center items-center flex">
<div className="border-t-4 border-b-4 border-blue-600 rounded-full w-20 h-20 animate-spin m-auto"></div>
</div>
);
}
const getCurrentDate = () => {
const today = new Date();
const year = today.getFullYear() - 10;
const year = today.getFullYear() - 10;
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
function convertToNormalDate(isoTimestamp:any) {
function convertToNormalDate(isoTimestamp: any) {
const date = new Date(isoTimestamp);
const options:any = { year: 'numeric', month: 'long', day: 'numeric' };
const options: any = { year: 'numeric', month: 'long', day: 'numeric' };
return date.toLocaleDateString('en-US', options);
}
function formatDate(dateString: string) {
Expand All @@ -191,10 +171,8 @@ const UserProfileForm: React.FC = () => {
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const formattedDate = `${day}-${month}-${year}`;

return formattedDate;
}

return (
<div className="flex flex-col min-h-screen w-full">
<Header />
Expand All @@ -206,13 +184,12 @@ const UserProfileForm: React.FC = () => {
<div className="relative mb-4 w-32 h-32">
<img
className="w-full h-full rounded-full cursor-pointer object-cover"
src={profileImage}
src={profileImage || '/unknown.jpg'}
alt="Profile"
onClick={handleImageClick}
onError={(e) => {
e.currentTarget.src = '/unknown.jpg';
}}

/>
<input
type="file"
Expand Down Expand Up @@ -247,7 +224,6 @@ const UserProfileForm: React.FC = () => {
{user?.User?.Role.name || 'buyer'}
</p>
</div>

<ul className="hidden md:block text-sm space-y-2">
<li className="flex items-center text-gray-600">
<svg
Expand All @@ -264,7 +240,11 @@ const UserProfileForm: React.FC = () => {
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
{convertToNormalDate(watchedValues.birthDate) || watchedValues.birthDate || 'YYYY-MM-DD'}
{watchedValues.birthDate
? watchedValues.birthDate.match(/^\d{2}-\d{2}-\d{4}$/)
? watchedValues.birthDate
: formatDate(watchedValues.birthDate)
: 'YYYY-MM-DD'}
</li>
<li className="flex items-center text-gray-600">
<svg
Expand Down Expand Up @@ -327,7 +307,6 @@ const UserProfileForm: React.FC = () => {
</li>
</ul>
</aside>

<div className="w-full md:w-3/4 p-6">
<h2 className="text-2xl font-bold mb-6">Update Profile</h2>
<form onSubmit={handleSubmit(onSubmit)}>
Expand Down Expand Up @@ -361,7 +340,6 @@ const UserProfileForm: React.FC = () => {
placeholder="Birth date"
{...register('birthDate')}
error={errors.birthDate?.message}

max={getCurrentDate()}
/>
</div>
Expand All @@ -370,7 +348,7 @@ const UserProfileForm: React.FC = () => {
nameuse="Address"
type="text"
placeholder="Address"
error ={errors.address?.message}
error={errors.address?.message}
/>
</div>
<div className="mb-4">
Expand Down Expand Up @@ -431,14 +409,11 @@ const UserProfileForm: React.FC = () => {
</div>
</div>
</main>
<div className=''>
<UpdatePasswords handleshow={handleshow} showlModal={showlModal}/>
<div className="">
<UpdatePasswords handleshow={handleshow} showlModal={showlModal} />
</div>


<Footer />
</div>
);
};

export default UserProfileForm;
export default UserProfileForm;
2 changes: 0 additions & 2 deletions src/app/(profile)/profile/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use client';
// pages/profile.tsx
import About from '@/components/profile/About';
import ActiveUser from '@/components/profile/ActiveUsers';
import Order from '@/components/profile/Order';
import ProfileHeader from '@/components/profile/ProfileHeader';
import Wishlist from '@/components/profile/wishlist';
Expand All @@ -23,7 +22,6 @@ const ProfilePage = () => {
</div>
<div className="md:col-span-1 flex flex-col gap-4 mb-4">
<Order />

</div>
</div>
</div>
Expand Down
1 change: 0 additions & 1 deletion src/app/dashboard/profile/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import React, { useEffect, useState } from 'react';
import LayoutDashboard from '@/components/LayoutDashboard';
import About from '@/components/profile/About';
import ActiveUser from '@/components/profile/ActiveUsers';
import Order from '@/components/profile/Order';
import ProfileHeader from '@/components/profile/ProfileHeader';
import Wishlist from '@/components/profile/wishlist';
Expand Down
3 changes: 3 additions & 0 deletions src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ body {}
.hide-scrollbar::-webkit-scrollbar {
display: none;
}
.capitalize-first::first-letter {
text-transform: uppercase;
}

/* Hide scrollbar for IE, Edge and Firefox */
.hide-scrollbar {
Expand Down
58 changes: 32 additions & 26 deletions src/app/products/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,19 @@ import ReviewWrapper from '@/components/ReviewsWrapper';
//import StripeProvider from '@/components/StripeProvider';

function Page() {
const { wishNumber } = useAppSelector(
(state: RootState) => state.wishlist
)
const { wishNumber } = useAppSelector((state: RootState) => state.wishlist);
const [thumbsSwiper, setThumbsSwiper] = useState(null);
const [addProductToCart, setAddProductToCart]=useState(false)

const {cart} = useAppSelector(
(state: RootState) => state.userCartData,
);
const [addProductToCart, setAddProductToCart] = useState(false);

const { cart } = useAppSelector((state: RootState) => state.userCartData);

const carts=cart as IUSERCART
const { id } :any= useParams();
const carts = cart as IUSERCART;
const { id }: any = useParams();
const handleSwiper = (swiper: any) => {
setThumbsSwiper(swiper);
};
const _id: string = id.toLocaleString();
const { data, isLoading, error , refetch} = useQuery<any>({
const { data, isLoading, error, refetch } = useQuery<any>({
queryKey: ['product', id],
queryFn: async () => {
try {
Expand All @@ -71,17 +67,20 @@ function Page() {
const productId = data.product.id;
dispatch(handleUserAddCart({ productPrice, productId }));
};
const handleAddRemoveWish = async(event: { preventDefault: () => void; })=>{
const handleAddRemoveWish = async (event: { preventDefault: () => void }) => {
event.preventDefault();
const response:any = await request.post('/wishes', { productId:id });
if(response.status == 200 || response.status == 203){
const response: any = await request.post('/wishes', { productId: id });
if (response.status == 200 || response.status == 203) {
const { status } = response;
dispatch(handleWishlistCount(status == 200 ? await wishNumber + 1 : await wishNumber - 1));
showToast(response.message, 'success')
dispatch(
handleWishlistCount(
status == 200 ? (await wishNumber) + 1 : (await wishNumber) - 1,
),
);
showToast(response.message, 'success');
}
console.log('this is response', response)

}

};
return (
<div>
{/* // <StripeProvider> */}
Expand Down Expand Up @@ -163,18 +162,22 @@ function Page() {
</div>
<div className="w-full">
<div>
<h1 className="font-bold mt-5 text-2xl capitalize">
<h1 className="font-bold mt-5 text-2xl capitalize-first">
{productName}
</h1>
</div>
<div className="flex flex-col gap-4">
<div className="flex gap-2 mt-5">
<div className="p-3 rounded-full bg-gray-200 hover:bg-green-500 hover:text-white cursor-pointer" onClick={handleAddRemoveWish}>
<div
className="p-3 rounded-full bg-gray-200 hover:bg-green-500 hover:text-white cursor-pointer"
onClick={handleAddRemoveWish}
>
<FaRegHeart />
</div>
<div className={`p-3 rounded-full hover:bg-green-500 hover:text-white cursor-pointer '${(addProductToCart || carts.product.some(item => item.product ===data.product.id)) ?' bg-red-500 pointer-events-none':'pointer-events-auto bg-gray-200'}`}>
<div
className={`p-3 rounded-full hover:bg-green-500 hover:text-white cursor-pointer '${addProductToCart || carts.product.some((item) => item.product === data.product.id) ? ' bg-red-500 pointer-events-none' : 'pointer-events-auto bg-gray-200'}`}
>
<MdOutlineShoppingCart

onClick={() => {
handleNewItem();
}}
Expand Down Expand Up @@ -227,10 +230,13 @@ function Page() {
</div>
</div>
<div className="w-full flex flex-col mt-10">
<ReviewWrapper productId={_id.trim()} refetch={refetch} reviews={reviews} />
<ReviewWrapper
productId={_id.trim()}
refetch={refetch}
reviews={reviews}
/>
</div>
</div>

</div>
)}
</>
Expand All @@ -239,4 +245,4 @@ function Page() {
</div>
);
}
export default Page;
export default Page;
2 changes: 1 addition & 1 deletion src/components/AssigningRoles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const AssigningRole: React.FC<AssignRoleInterface> = ({
<>
{isLoading || mutation.isPending ? (
<div>
<div className="border-t-4 border-b-4 border-black rounded-full w-5 h-5 animate-spin m-auto"></div>
<div className="border-t-4 border-b-4 border-blue-600 rounded-full w-5 h-5 animate-spin m-auto"></div>
</div>
) : (
<select
Expand Down
Loading
Loading