Skip to content

Commit

Permalink
shipping + auth bug fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
ShinichiShi committed Sep 23, 2024
1 parent 12faefb commit c7a470b
Show file tree
Hide file tree
Showing 17 changed files with 1,209 additions and 164 deletions.
53 changes: 44 additions & 9 deletions client/src/components/Buyer/BDashboard.jsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,68 @@
import { useState, useContext, useEffect } from 'react';
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { onAuthStateChanged } from 'firebase/auth';
import BHeader from './BHeader';
import { db } from '../../../firebase';
import { getDoc, doc } from 'firebase/firestore';
import BNavbar from './BNavbar';
import BSettings from './Settings/BSettings';
import BDeals from './Deals/BDeals';
import BContract from './Contract/BContract';
import { AuthContext } from '../context/auth_context';
import TrackList from './Shipping/TrackList';
import { getAuth } from 'firebase/auth';
import ReactLoading from 'react-loading';

function Dashboard() {
const [loading, setLoading] = useState(true);
const navigateRoute = useNavigate();
const [navigate, setNavigate] = useState('settings');
const { currentUser } = useContext(AuthContext);

const auth = getAuth()
useEffect(() => {
if (currentUser === null) {
navigateRoute('/signup');
}
}, [currentUser, navigateRoute]);
const unsubscribe = onAuthStateChanged(auth,async (user) => {
const userRef = doc(db,'users', user.uid);
const docSnap = await getDoc(userRef)
if(docSnap.exists()){
if(docSnap.data().profile.userType === 'buyer'){
console.log('User is signed in');
}
else {
// No user is signed in, redirect to signup or login page
navigateRoute('/signup');
}
}
setLoading(false);
});

// Clean up the subscription when the component unmounts
return () => unsubscribe();
}, [auth, navigateRoute]);
if (loading) {
return (
<div style={{
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<ReactLoading type={'spinningBubbles'} color={'#00b300'} height={'5%'} width={'5%'} />
</div>
);
}
const handleNavigate = (key) => {
setNavigate(key);
};
return (
<>
<BHeader />
<BNavbar handleNavigate={handleNavigate} navigate={navigate} />

{navigate === 'settings' && <BSettings />}
{navigate === 'deals' && <BDeals />}
{navigate === 'contract' && <BContract />}
{navigate === 'track' && <TrackList />}
</>
);
}
Expand Down
70 changes: 4 additions & 66 deletions client/src/components/Buyer/BHeader.jsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,12 @@
// import { MdOutlineTranslate } from 'react-icons/md';
// import { IoIosArrowDropdown, IoIosArrowDropup } from 'react-icons/io';
// import { useState, useEffect, useRef } from 'react';
import { signOut } from 'firebase/auth';
import { auth } from '../../../firebase';
import { useNavigate } from 'react-router-dom';
import { toast, ToastContainer } from 'react-toastify';
import { useTranslation } from 'react-i18next';
import GoogleTranslateWidget from '../GoogleTranslateWidget';
function BHeader() {
// const { i18n } = useTranslation();
const { t } = useTranslation();
// const [dropdownOpen, setDropdownOpen] = useState(false);
// const [language, setLanguage] = useState('Eng')
// const dropdownRef = useRef(null);

const navigate = useNavigate();

// useEffect(() => {
// function handleClickOutside(event) {
// if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
// setDropdownOpen(false);
// }
// }
// // const cachedLanguage = localStorage.getItem('language') || i18n.language;
// // setLanguage(cachedLanguage === 'en' ? 'Eng' : cachedLanguage === 'kn' ? 'ಕನ್ನಡ' : 'हिंदी');
// // i18n.changeLanguage(cachedLanguage); // Apply cached language if it exists
// document.addEventListener('mousedown', handleClickOutside);
// return () => {
// document.removeEventListener('mousedown', handleClickOutside);
// };
// }, [dropdownRef,i18n]);

const handleLogout = async () => {
try {
Expand All @@ -40,64 +18,24 @@ function BHeader() {
}
};

// Language change handler
// const changeLanguage = (lng) => {
// i18n.changeLanguage(lng);
// setLanguage(lng === 'en' ? 'Eng' : lng === 'kn' ? 'ಕನ್ನಡ' : 'हिंदी');
// setDropdownOpen(false); // Close the dropdown after selecting a language
// localStorage.setItem('language', lng); // Cache the selected language
// };

return (
<div className="h-20 font-sans">
<div className="bg-white h-full shadow flex w-full">
<div className=" w-full flex justify-between items-center px-4">
<div className="text-green-500 text-2xl font-bold">{t('header.title')}</div>
<div className="text-green-500 text-2xl font-bold">KrishiSeva</div>
<h1>Welcome to KrishiSeva</h1>
<div>
<div className="flex items-center justify-center gap-4">
<div>
<GoogleTranslateWidget />
</div>
{/* <div ref={dropdownRef} className="relative">
<div
onClick={() => setDropdownOpen(!dropdownOpen)}
className="cursor-pointer flex items-center justify-center gap-2 hover:bg-slate-300 p-2 rounded"
>
<MdOutlineTranslate />
{language}
{dropdownOpen ? <IoIosArrowDropdown /> : <IoIosArrowDropup />}
</div>
{dropdownOpen && (
<div className="absolute left-0 mt-2 w-24 bg-white border rounded shadow-md">
<ul className="py-1">
<li
className="px-4 py-2 hover:bg-slate-100 cursor-pointer"
onClick={() => changeLanguage('en')}
>
English
</li>
<li
className="px-4 py-2 hover:bg-slate-100 cursor-pointer"
onClick={() => changeLanguage('kn')}
>
ಕನ್ನಡ
</li>
<li
className="px-4 py-2 hover:bg-slate-100 cursor-pointer"
onClick={() => changeLanguage('hi')}
>
हिंदी
</li>
</ul>
</div>
)}
</div> */}

<button
className="py-2 px-2 border rounded-lg flex items-center justify-center bg-green-500 hover:bg-green-600 text-white"
onClick={handleLogout}
>
{t('header.logout')}
Logout
</button>
</div>
</div>
Expand Down
9 changes: 8 additions & 1 deletion client/src/components/Buyer/BNavbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,21 @@ export default function BNavbar({ handleNavigate, navigate }) {
{t('navbar.contracts')}

</li>

<li
className={`cursor-pointer py-1 px-2 rounded-lg ${navigate === 'track' ? 'bg-green-300' : ''} hover:bg-green-200`}
onClick={() => handleNavigate('track')}
>
Track Orders
</li>
<li
className={`cursor-pointer py-1 px-2 rounded-lg ${navigate === 'settings' ? 'bg-green-300' : ''} hover:bg-green-200`}
onClick={() => handleNavigate('settings')}
>
{t('navbar.settings')}
</li>

<li

className={`cursor-pointer py-1 px-2 rounded-lg ${navigate === 'chat' ? 'bg-green-300' : ''} hover:bg-green-200`}
onClick={() => {
navigateChat('/chat',{
Expand Down
83 changes: 46 additions & 37 deletions client/src/components/Buyer/Contract/ContractStatus.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { ToastContainer, toast } from 'react-toastify';
import { useTranslation } from 'react-i18next';
import { loadStripe } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import { FaCcStripe } from "react-icons/fa6";

import { FaCcStripe } from 'react-icons/fa6';
import ShippingForm from '../Shipping/ShippingForm';
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISH_KEY); // Publishable Key from your Stripe dashboard
const SERVER_PORT = import.meta.env.VITE_SERVER_PORT;

Expand All @@ -24,6 +24,7 @@ export default function ContractStatus({ contract }) {
const [contractState, setContractState] = useState(null);
const [currentMetaUser, setCurrentMetaUser] = useState('');
const [account, setAccount] = useState('');
const [shipping, setShipping] = useState(false);
useEffect(() => {
const initWeb3 = async () => {
if (window.ethereum) {
Expand Down Expand Up @@ -268,23 +269,26 @@ export default function ContractStatus({ contract }) {
}
};

const makeStripePayment = async()=>{
console.log("stripe payment");
const response = await fetch(`http://localhost:${SERVER_PORT}/create-checkout-session`, {
method: 'POST',
headers : {
"Content-Type" : "application/json",
},
body : JSON.stringify({
product : contract.crop,
total_amount : contract.installmentAmt,
})
});

const {id} = await response.json();
const makeStripePayment = async () => {
console.log('stripe payment');
const response = await fetch(
`http://localhost:${SERVER_PORT}/create-checkout-session`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
product: contract.crop,
total_amount: contract.installmentAmt,
}),
}
);

const { id } = await response.json();
const stripe = await stripePromise;
stripe.redirectToCheckout({sessionId : id});
}
stripe.redirectToCheckout({ sessionId: id });
};

return (
<div className="w-full">
Expand Down Expand Up @@ -319,19 +323,15 @@ export default function ContractStatus({ contract }) {
<div className="absolute w-full inset-0 bg-black opacity-50"></div>
<div className="bg-white p-6 w-full rounded-lg shadow-lg z-10">
<div>
<strong>{t('contract_id')}</strong>{' '}
{contract.contractId || 'N/A'}
<strong>{t('contract_id')}</strong> {contract.contractId || 'N/A'}
</div>
<div>
<strong>{t('crop')}</strong> {contract.crop || 'N/A'}
</div>
<div>
<strong>{t('farmer_name')}</strong>{' '}
{contract.farmerName || 'N/A'}
</div>
<div>
<strong>Farmer&apos;s id</strong> {contract.farmerId || 'N/A'}
<strong>{t('farmer_name')}</strong> {contract.farmerName || 'N/A'}
</div>

<div>
<strong>{t('buyer_name')}</strong> {contract.buyerName || 'N/A'}
</div>
Expand All @@ -343,11 +343,11 @@ export default function ContractStatus({ contract }) {
</div>
<div>
<strong>{t('total_amount')}</strong>{' '}
{"Rs." + contract.totalAmt || 'N/A'}
{'Rs.' + contract.totalAmt || 'N/A'}
</div>
<div>
<strong>{t('installment_amount')}</strong>{' '}
{"Rs." + contract.installmentAmt || 'N/A'}
{'Rs.' + contract.installmentAmt || 'N/A'}
</div>
<div>
<strong>{t('location')}:</strong> {contract.location || 'N/A'}
Expand Down Expand Up @@ -376,17 +376,29 @@ export default function ContractStatus({ contract }) {
)}
{localContract.status === 'Signed' && (
<Elements stripe={stripePromise}>
<button
className="mt-4 px-4 py-2 bg-blue-500 flex items-center justify-center gap-2 text-white rounded hover:bg-blue-600 "
onClick={makeStripePayment}
>
<FaCcStripe />
Make Payment
</button>
</Elements>
)}
{localContract.status === 'Signed' && (
<button
className="mt-4 px-4 py-2 bg-blue-500 flex items-center justify-center gap-2 text-white rounded hover:bg-blue-600 "
onClick={makeStripePayment}
onClick={() => setShipping(true)}
>
<FaCcStripe />

Make Payment
Initiate Shipping
</button>
</Elements>
)}
</div>
{shipping === true && (
<div>
<ShippingForm onClose={() => setShipping(false)}/>
</div>
)}
</div>
</div>
)}
Expand All @@ -399,14 +411,11 @@ ContractStatus.propTypes = {
contract: PropTypes.shape({
date: PropTypes.string.isRequired,
farmerName: PropTypes.string.isRequired,
farmerId: PropTypes.string.isRequired,
buyerName: PropTypes.string.isRequired,
buyerId: PropTypes.string.isRequired,
crop: PropTypes.string.isRequired,
totalAmt: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
totalAmt: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
installmentAmt: PropTypes.string.isRequired,
location: PropTypes.string.isRequired,
contractId: PropTypes.string.isRequired,
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/Buyer/Contract/GenerateContract.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ToastContainer,toast } from 'react-toastify';
export default function GenerateContract() {
const [formData, setFormData] = useState({
date: '',
farmerId: '',
farmerId: '0x5993D0db1b64f5DC1aD2770a889dF6B9D0491449',
buyerId: '',
buyerName: '',
farmerName: '',
Expand Down Expand Up @@ -38,7 +38,7 @@ export default function GenerateContract() {
const handleGenerateNext = () => {
setFormData({
date: '',
farmerId: '',
farmerId: '0x5993D0db1b64f5DC1aD2770a889dF6B9D0491449',
buyerId: '',
buyerName: '',
farmerName: '',
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/Buyer/Contract/Metamask.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function Metamask({ formData, setFormData, setFlag }) {
if (docSnap.exists()) {
setFormData(prevData => ({
...prevData,
buyerName: `${data.profile.displayName} ${data.profile.lname}`
buyerName: `${data.profile.firstname} ${data.profile.lastname}`
}));
}
}
Expand Down
Loading

0 comments on commit c7a470b

Please sign in to comment.