build: b0d8399f-81d7-4ccc-8711-0f8b1506676e

This commit is contained in:
AppCakes
2026-06-20 01:45:23 +00:00
commit ee7cfdfeaa
140 changed files with 12958 additions and 0 deletions
+576
View File
@@ -0,0 +1,576 @@
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonContent,
IonSpinner,
IonIcon,
useIonViewWillEnter,
} from '@ionic/react';
import { eyeOutline, eyeOffOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfileLoader } from '../hooks/useProfileLoader';
const Auth: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { loadProfileAndNavigate } = useProfileLoader();
const [tab, setTab] = useState<'login' | 'register'>('login');
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [showLoginPassword, setShowLoginPassword] = useState(false);
const [registerEmail, setRegisterEmail] = useState('');
const [registerPassword, setRegisterPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showRegisterPassword, setShowRegisterPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [overlayVisible, setOverlayVisible] = useState(false);
const [overlayError, setOverlayError] = useState(false);
useIonViewWillEnter(() => {
setTab('login');
});
useEffect(() => {
if (user) {
loadProfileAndNavigate(setOverlayVisible, setOverlayError);
}
}, [user, loadProfileAndNavigate]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSignIn = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
const { error } = await supabase.auth.signInWithPassword({
email: loginEmail,
password: loginPassword,
});
if (error) {
if (error.message.toLowerCase().includes('email not confirmed')) {
await supabase.auth.resend({ type: 'signup', email: loginEmail });
history.push('/verify-email', { email: loginEmail, resent: true });
} else {
showError(error.message);
}
setLoading(false);
return;
}
// keep loading true waiting for user effect
};
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault();
if (registerPassword !== confirmPassword) {
showError('Passwords do not match');
return;
}
setLoading(true);
setError('');
const { error } = await supabase.auth.signUp({
email: registerEmail,
password: registerPassword,
});
if (error) {
showError(error.message);
setLoading(false);
return;
}
setLoading(false);
history.push('/verify-email', { email: registerEmail });
};
const handleForgotPassword = () => {
history.push('/forgot-password');
};
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': '0px',
}}
>
<div
style={{
padding:
'calc(var(--ion-safe-area-top, 0px) + 18px) 20px calc(var(--ion-safe-area-bottom, 0px) + 28px)',
minHeight: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
gap: '24px',
}}
>
<div
style={{
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '14px',
}}
>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '10px',
alignSelf: 'flex-start',
background: 'var(--color-surface)',
color: 'var(--color-brand)',
borderRadius: '999px',
padding: '8px 14px',
fontSize: '12px',
fontWeight: '700',
letterSpacing: '0.06em',
textTransform: 'uppercase',
}}
>
QuoteLink
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div
style={{
fontSize: '18px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1.2',
}}
>
Instant prices.{' '}
<span
style={{ color: 'var(--color-accent)', fontWeight: '700' }}
>
Smart decisions.
</span>
</div>
<div
style={{
fontSize: '34px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1.02',
letterSpacing: '-0.03em',
maxWidth: '330px',
}}
>
Modern procurement for buyers and suppliers.
</div>
<div
style={{
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
lineHeight: '1.6',
maxWidth: '320px',
}}
>
Send a request, compare real quotes, and move faster with a
clean professional workflow.
</div>
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '24px',
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
<div>
<div
style={{
fontSize: '22px',
fontWeight: '700',
color: 'var(--color-text-primary)',
lineHeight: '1.15',
}}
>
{tab === 'login' ? 'Welcome back' : 'Create your account'}
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
lineHeight: '1.55',
marginTop: '4px',
}}
>
{tab === 'login'
? 'Sign in to manage requests and supplier quotations.'
: 'Join QuoteLink to start sending or responding to RFQs.'}
</div>
</div>
<div
style={{
display: 'flex',
background: 'var(--color-surface-raised)',
borderRadius: '999px',
padding: '4px',
}}
>
<button
onClick={() => setTab('login')}
style={{
flex: 1,
background:
tab === 'login' ? 'var(--color-brand)' : 'transparent',
color:
tab === 'login' ? '#ffffff' : 'var(--color-brand-strong)',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Log In
</button>
<button
onClick={() => setTab('register')}
style={{
flex: 1,
background:
tab === 'register' ? 'var(--color-brand)' : 'transparent',
color:
tab === 'register'
? '#ffffff'
: 'var(--color-brand-strong)',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Register
</button>
</div>
{error && (
<div
style={{
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
{tab === 'login' ? (
<form
onSubmit={handleSignIn}
style={{
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<input
type="email"
placeholder="you@example.com"
value={loginEmail}
onChange={(e) => setLoginEmail(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
<div style={{ position: 'relative' }}>
<input
type={showLoginPassword ? 'text' : 'password'}
placeholder="Password"
value={loginPassword}
onChange={(e) => setLoginPassword(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
<IonIcon
icon={showLoginPassword ? eyeOffOutline : eyeOutline}
onClick={() => setShowLoginPassword(!showLoginPassword)}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: 'var(--color-text-tertiary)',
cursor: 'pointer',
}}
/>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<button
type="button"
onClick={handleForgotPassword}
style={{
background: 'transparent',
border: 'none',
padding: '0',
fontSize: '14px',
fontWeight: '600',
color: 'var(--color-accent)',
cursor: 'pointer',
}}
>
Forgot password?
</button>
</div>
<button
type="submit"
disabled={loading}
style={{
background: 'var(--color-brand)',
border: 'none',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
color: '#ffffff',
cursor: 'pointer',
marginTop: '4px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Sign In'
)}
</button>
</form>
) : (
<form
onSubmit={handleSignUp}
style={{
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<input
type="email"
placeholder="you@example.com"
value={registerEmail}
onChange={(e) => setRegisterEmail(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
<div style={{ position: 'relative' }}>
<input
type={showRegisterPassword ? 'text' : 'password'}
placeholder="Create a password"
value={registerPassword}
onChange={(e) => setRegisterPassword(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
minLength={6}
/>
<IonIcon
icon={showRegisterPassword ? eyeOffOutline : eyeOutline}
onClick={() =>
setShowRegisterPassword(!showRegisterPassword)
}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: 'var(--color-text-tertiary)',
cursor: 'pointer',
}}
/>
</div>
<div style={{ position: 'relative' }}>
<input
type={showConfirmPassword ? 'text' : 'password'}
placeholder="Confirm password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
minLength={6}
/>
<IonIcon
icon={showConfirmPassword ? eyeOffOutline : eyeOutline}
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: 'var(--color-text-tertiary)',
cursor: 'pointer',
}}
/>
</div>
<button
type="submit"
disabled={loading}
style={{
background: 'var(--color-brand)',
border: 'none',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
color: '#ffffff',
cursor: 'pointer',
marginTop: '4px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Create Account'
)}
</button>
</form>
)}
</div>
</div>
{overlayVisible && (
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(18, 18, 18, 0.78)',
backdropFilter: 'blur(10px)',
WebkitBackdropFilter: 'blur(10px)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
zIndex: 9999,
padding: '24px',
}}
>
{overlayError ? (
<div
style={{
color: 'var(--color-danger-text)',
fontSize: '15px',
fontWeight: '600',
textAlign: 'center',
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
}}
>
Error loading profile. Please restart the app.
</div>
) : (
<IonSpinner
name="crescent"
style={{
color: 'var(--color-brand)',
width: '28px',
height: '28px',
}}
/>
)}
</div>
)}
</IonContent>
</IonPage>
);
};
export default Auth;
+324
View File
@@ -0,0 +1,324 @@
import React, { useState } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
useIonViewWillEnter,
} from '@ionic/react';
import { chevronBackOutline, mailOpenOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import QuotationCard from '../components/QuotationCard';
const BuyerQuoteList: React.FC = () => {
const history = useHistory();
const { id } = useParams<{ id: string }>();
const [rfqSummary, setRfqSummary] = useState<{
title: string;
referenceNumber: string;
} | null>(null);
const [quotes, setQuotes] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [sortMode, setSortMode] = useState<'price' | 'supplier'>('price');
useIonViewWillEnter(() => {
loadQuotes();
});
const loadQuotes = async () => {
setLoading(true);
setError('');
try {
const { data: rfq, error: rfqErr } = await supabase
.from('rfqs')
.select('title, reference_number')
.eq('id', id)
.single();
if (rfqErr) throw rfqErr;
setRfqSummary({
title: rfq.title,
referenceNumber: rfq.reference_number,
});
const { data: qData, error: qErr } = await supabase
.from('quotations')
.select(
'id, price_amount, delivery_option, status, supplier_id, profiles(full_name, company_name)'
)
.eq('rfq_id', id);
if (qErr) throw qErr;
const mapped = (qData || []).map((q) => ({
id: q.id,
priceAmount: q.price_amount,
deliveryOption: q.delivery_option,
status: q.status,
supplierName:
q.profiles?.company_name || q.profiles?.full_name || 'Supplier',
}));
setQuotes(mapped);
} catch (err: any) {
console.error(err);
setError('Failed to load quotations.');
} finally {
setLoading(false);
}
};
const getSortedQuotes = () => {
if (sortMode === 'price') {
return [...quotes].sort((a, b) => a.priceAmount - b.priceAmount);
} else {
return [...quotes].sort((a, b) =>
a.supplierName.localeCompare(b.supplierName)
);
}
};
const handleAcceptQuote = async (quoteId: string) => {
try {
setLoading(true);
// Update selected quotation to accepted
const { error: accErr } = await supabase
.from('quotations')
.update({ status: 'accepted', updated_at: new Date().toISOString() })
.eq('id', quoteId);
if (accErr) throw accErr;
// Update sibling quotations to declined
const { error: decErr } = await supabase
.from('quotations')
.update({ status: 'declined', updated_at: new Date().toISOString() })
.eq('rfq_id', id)
.neq('id', quoteId);
if (decErr) throw decErr;
// Close RFQ
const { error: rfqErr } = await supabase
.from('rfqs')
.update({ status: 'closed', updated_at: new Date().toISOString() })
.eq('id', id);
if (rfqErr) throw rfqErr;
await loadQuotes();
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to accept quote.');
setLoading(false);
setTimeout(() => setError(''), 4000);
}
};
const handleDeclineQuote = async (quoteId: string) => {
try {
setLoading(true);
const { error } = await supabase
.from('quotations')
.update({ status: 'declined', updated_at: new Date().toISOString() })
.eq('id', quoteId);
if (error) throw error;
await loadQuotes();
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to decline quote.');
setLoading(false);
setTimeout(() => setError(''), 4000);
}
};
const sortedQuotes = getSortedQuotes();
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Compare Quotes
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
{loading && quotes.length === 0 ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '40px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : (
<>
{rfqSummary && (
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px',
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div
style={{
fontSize: '12px',
fontWeight: '700',
color: '#b45309',
background: 'rgba(245,158,11,0.14)',
borderRadius: '999px',
padding: '4px 10px',
width: 'max-content',
}}
>
{rfqSummary.referenceNumber}
</div>
<div
style={{
fontSize: '16px',
fontWeight: '600',
color: '#0f1720',
}}
>
{rfqSummary.title}
</div>
</div>
)}
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
marginBottom: '12px',
}}
>
{error}
</div>
)}
<div style={{ margin: '0 0 12px', display: 'flex', gap: '8px' }}>
<button
onClick={() => setSortMode('price')}
style={{
background: sortMode === 'price' ? '#166534' : '#ffffff',
color: sortMode === 'price' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '8px 16px',
fontSize: '13px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Sort by Price
</button>
<button
onClick={() => setSortMode('supplier')}
style={{
background: sortMode === 'supplier' ? '#166534' : '#ffffff',
color: sortMode === 'supplier' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '8px 16px',
fontSize: '13px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Sort by Supplier
</button>
</div>
{sortedQuotes.length > 0 ? (
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
{sortedQuotes.map((q) => (
<QuotationCard
key={q.id}
supplierName={q.supplierName}
priceLabel={`$${q.priceAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
deliveryOption={q.deliveryOption}
status={q.status}
onAccept={() => handleAcceptQuote(q.id)}
onDecline={() => handleDeclineQuote(q.id)}
/>
))}
</div>
) : (
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '28px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: '12px',
}}
>
<IonIcon
icon={mailOpenOutline}
style={{ fontSize: '48px', color: '#6c7a71' }}
/>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: '#6c7a71',
}}
>
No quotations available yet.
</div>
</div>
)}
</>
)}
</IonContent>
</IonPage>
);
};
export default BuyerQuoteList;
+343
View File
@@ -0,0 +1,343 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonContent,
IonSpinner,
useIonViewWillEnter,
IonIcon,
} from '@ionic/react';
import {
addOutline,
searchOutline,
optionsOutline,
documentTextOutline,
} from 'ionicons/icons';
import { supabase } from '../supabase';
import { useProfile } from '../contexts/ProfileContext';
import { useAuth } from '../contexts/AuthContext';
import RequestListCard from '../components/RequestListCard';
interface RFQListItem {
id: string;
title: string;
referenceNumber: string;
status: string;
createdAt: string;
}
const BuyerRequests: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { profile } = useProfile();
const [items, setItems] = useState<RFQListItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [searchText, setSearchText] = useState('');
const [activeStatus, setActiveStatus] = useState<
'all' | 'open' | 'quoted' | 'closed'
>('all');
useIonViewWillEnter(() => {
loadRequests();
});
const loadRequests = async () => {
if (!user || !profile) return;
setLoading(true);
setError('');
try {
if (profile.role === 'buyer') {
const { data, error: err } = await supabase
.from('rfqs')
.select('*')
.eq('buyer_id', user.id)
.order('created_at', { ascending: false });
if (err) throw err;
setItems(
data.map((d) => ({
id: d.id,
title: d.title,
referenceNumber: d.reference_number,
status: d.status,
createdAt: d.created_at,
}))
);
} else {
const { data, error: err } = await supabase
.from('rfq_recipients')
.select('id, rfqs!inner(*)')
.eq('supplier_id', user.id)
.order('created_at', { ascending: false });
if (err) throw err;
const mapped = (data || []).map((row: any) => ({
id: row.rfqs.id,
title: row.rfqs.title,
referenceNumber: row.rfqs.reference_number,
status: row.rfqs.status,
createdAt: row.rfqs.created_at,
}));
setItems(mapped);
}
} catch (err: any) {
console.error(err);
setError('Failed to load requests.');
} finally {
setLoading(false);
}
};
const filteredItems = items.filter((item) => {
const matchStatus = activeStatus === 'all' || item.status === activeStatus;
const searchLower = searchText.toLowerCase();
const matchSearch =
item.title.toLowerCase().includes(searchLower) ||
item.referenceNumber.toLowerCase().includes(searchLower);
return matchStatus && matchSearch;
});
const handleResetFilters = () => {
setSearchText('');
setActiveStatus('all');
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 12px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '12px',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
<div
style={{
fontSize: '13px',
fontWeight: '700',
letterSpacing: '0.08em',
textTransform: 'uppercase',
color: 'var(--color-brand)',
}}
>
{profile.role === 'buyer' ? 'Buyer Workspace' : 'Supplier Inbox'}
</div>
<div
style={{
fontSize: '24px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{profile.role === 'buyer' ? 'My Requests' : 'Assigned RFQs'}
</div>
</div>
{profile.role === 'buyer' && (
<div
onClick={() => history.push('/rfq/new')}
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-brand)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
flexShrink: 0,
}}
>
<IonIcon
icon={addOutline}
style={{ color: '#ffffff', fontSize: '24px' }}
/>
</div>
)}
</div>
{error && (
<div
style={{
margin: '0 20px 12px',
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<div style={{ margin: '0 20px 12px', display: 'flex', gap: '10px' }}>
<div style={{ flex: 1, position: 'relative' }}>
<IonIcon
icon={searchOutline}
style={{
position: 'absolute',
left: '14px',
top: '14px',
fontSize: '18px',
color: 'var(--color-text-tertiary)',
}}
/>
<input
type="text"
placeholder="Search by title or reference..."
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
borderRadius: '24px',
border: 'none',
padding: '0 16px 0 40px',
height: '44px',
width: '100%',
fontSize: '14px',
color: 'var(--color-text-primary)',
}}
/>
</div>
<button
onClick={handleResetFilters}
style={{
background: 'var(--color-surface-raised)',
borderRadius: '12px',
border: 'none',
width: '44px',
height: '44px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
flexShrink: 0,
}}
>
<IonIcon
icon={optionsOutline}
style={{ fontSize: '20px', color: 'var(--color-brand)' }}
/>
</button>
</div>
<div
style={{
margin: '0 20px 16px',
display: 'flex',
gap: '8px',
overflowX: 'auto',
paddingBottom: '4px',
}}
>
{(['all', 'open', 'quoted', 'closed'] as const).map((status) => (
<button
key={status}
onClick={() => setActiveStatus(status)}
style={{
background:
activeStatus === status
? 'var(--color-brand)'
: 'var(--color-surface)',
color:
activeStatus === status
? '#ffffff'
: 'var(--color-brand-strong)',
borderRadius: '999px',
padding: '8px 16px',
fontSize: '13px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
whiteSpace: 'nowrap',
textTransform: 'capitalize',
}}
>
{status}
</button>
))}
</div>
{loading ? (
<div
style={{
margin: '0 20px',
display: 'flex',
justifyContent: 'center',
padding: '20px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : filteredItems.length > 0 ? (
<div
style={{
margin: '0 20px',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
{filteredItems.map((item) => (
<RequestListCard
key={item.id}
title={item.title}
subtitle={new Date(item.createdAt).toLocaleDateString()}
referenceNumber={item.referenceNumber}
status={item.status}
onClick={() => history.push(`/rfq/${item.id}`)}
/>
))}
</div>
) : (
<div
style={{
margin: '0 20px',
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '28px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: '12px',
}}
>
<IonIcon
icon={documentTextOutline}
style={{ fontSize: '48px', color: 'var(--color-text-tertiary)' }}
/>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
No requests found.
</div>
</div>
)}
</IonContent>
</IonPage>
);
};
export default BuyerRequests;
+309
View File
@@ -0,0 +1,309 @@
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { Preferences } from '@capacitor/preferences';
const EditProfile: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { profile, setProfile } = useProfile();
const [fullName, setFullName] = useState('');
const [companyName, setCompanyName] = useState('');
const [phone, setPhone] = useState('');
const [city, setCity] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (profile) {
setFullName(profile.full_name || '');
setCompanyName(profile.company_name || '');
setPhone(profile.phone || '');
setCity(profile.city || '');
}
}, [profile]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSaveProfile = async (e: React.FormEvent) => {
e.preventDefault();
if (!user || !profile) return;
if (!fullName) {
showError('Please enter your full name');
return;
}
setSaving(true);
setError('');
const updates = {
full_name: fullName,
company_name: companyName || null,
phone: phone || null,
city: city || null,
updated_at: new Date().toISOString(),
};
const { error: updateError } = await supabase
.from('profiles')
.update(updates)
.eq('id', user.id);
if (updateError) {
showError(updateError.message);
setSaving(false);
return;
}
const updatedProfile = { ...profile, ...updates };
setProfile(updatedProfile);
await Preferences.set({
key: `profile_${user.id}`,
value: JSON.stringify(updatedProfile),
});
setSaving(false);
history.goBack();
};
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonHeader className="ion-no-border">
<IonToolbar
style={{ '--background': 'var(--color-bg)' } as React.CSSProperties}
>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: 'var(--color-brand-strong)' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{
fontSize: '18px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Edit Profile
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': 'var(--color-bg)',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '24px',
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
{error && (
<div
style={{
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
<form
onSubmit={handleSaveProfile}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
Full Name
</label>
<input
type="text"
placeholder="e.g. John Doe"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
Company Name
</label>
<input
type="text"
placeholder="e.g. BuildRight Supplies"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
City
</label>
<input
type="text"
placeholder="e.g. Lagos"
value={city}
onChange={(e) => setCity(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
Phone
</label>
<input
type="tel"
placeholder="e.g. +234 800 000 0000"
value={phone}
onChange={(e) => setPhone(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
/>
</div>
<button
type="submit"
disabled={saving || !fullName}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: saving || !fullName ? 0.7 : 1,
marginTop: '8px',
}}
>
{saving ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Save Changes'
)}
</button>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default EditProfile;
+177
View File
@@ -0,0 +1,177 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
const ForgotPassword: React.FC = () => {
const history = useHistory();
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleRequestReset = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
const { error } = await supabase.auth.resetPasswordForEmail(email);
if (error) {
showError(error.message);
setLoading(false);
return;
}
history.push('/verify-reset', { email });
setLoading(false);
};
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Reset Password
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': '0px',
}}
>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
margin: '20px 20px 0',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div>
<h2
style={{
fontSize: '22px',
fontWeight: '700',
color: '#0f1720',
margin: '0 0 8px 0',
}}
>
Forgot password?
</h2>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
Enter your email address and we'll send you a 6-digit code to
reset your password.
</p>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleRequestReset}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
/>
<button
type="submit"
disabled={loading || !email}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || !email ? 0.7 : 1,
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Send Code'
)}
</button>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default ForgotPassword;
+470
View File
@@ -0,0 +1,470 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonContent,
IonSpinner,
useIonViewWillEnter,
IonIcon,
} from '@ionic/react';
import { documentTextOutline, addOutline, searchOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useProfile } from '../contexts/ProfileContext';
import { useAuth } from '../contexts/AuthContext';
import DashboardMetricCard from '../components/DashboardMetricCard';
import RecentActivityCard from '../components/RecentActivityCard';
import { Database } from '../database.types';
type RfqRow = Database['public']['Tables']['rfqs']['Row'];
const Home: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { profile } = useProfile();
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [rfqSummary, setRfqSummary] = useState({
open: 0,
quoted: 0,
closed: 0,
});
const [supplierSummary, setSupplierSummary] = useState({
assignedOpen: 0,
myQuotes: 0,
accepted: 0,
});
const [recentItems, setRecentItems] = useState<any[]>([]);
useIonViewWillEnter(() => {
loadDashboardData();
});
const loadDashboardData = async () => {
if (!user || !profile) return;
setLoading(true);
setError('');
try {
if (profile.role === 'buyer') {
// Aggregate counts
const { data: allRfqs, error: countErr } = await supabase
.from('rfqs')
.select('id, status')
.eq('buyer_id', user.id);
if (countErr) throw countErr;
let open = 0,
quoted = 0,
closed = 0;
allRfqs?.forEach((r) => {
if (r.status === 'open') open++;
else if (r.status === 'quoted') quoted++;
else if (r.status === 'closed') closed++;
});
setRfqSummary({ open, quoted, closed });
// Recent items
const { data: recent, error: recentErr } = await supabase
.from('rfqs')
.select('*')
.eq('buyer_id', user.id)
.order('created_at', { ascending: false })
.limit(5);
if (recentErr) throw recentErr;
setRecentItems(recent || []);
} else {
// Supplier
const { data: allRecipients, error: recErr } = await supabase
.from('rfq_recipients')
.select('id, rfqs!inner(id, status)')
.eq('supplier_id', user.id);
if (recErr) throw recErr;
let assignedOpen = 0;
allRecipients?.forEach((r: any) => {
if (r.rfqs && r.rfqs.status === 'open') assignedOpen++;
});
const { data: myQuotes, error: qErr } = await supabase
.from('quotations')
.select('id, status')
.eq('supplier_id', user.id);
if (qErr) throw qErr;
let accepted = 0;
myQuotes?.forEach((q) => {
if (q.status === 'accepted') accepted++;
});
setSupplierSummary({
assignedOpen,
myQuotes: myQuotes?.length || 0,
accepted,
});
const { data: recent, error: recentErr } = await supabase
.from('rfq_recipients')
.select('id, rfqs!inner(*)')
.eq('supplier_id', user.id)
.order('created_at', { ascending: false })
.limit(5);
if (recentErr) throw recentErr;
// Map joined data
const mapped = (recent || []).map((r: any) => r.rfqs);
setRecentItems(mapped);
}
} catch (err: any) {
console.error(err);
setError('Failed to load dashboard data.');
} finally {
setLoading(false);
}
};
const handlePrimaryAction = () => {
if (profile?.role === 'buyer') {
history.push('/rfq/new');
} else {
history.push('/requests');
}
};
const handleRecentItemTap = (item: RfqRow) => {
history.push(`/rfq/${item.id}`);
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
<div
style={{
fontSize: '13px',
fontWeight: '700',
letterSpacing: '0.08em',
textTransform: 'uppercase',
color: 'var(--color-brand)',
}}
>
QuoteLink
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-tertiary)',
}}
>
Procurement made simpler
</div>
</div>
<div
onClick={() => history.push('/profile')}
style={{
width: '40px',
height: '40px',
borderRadius: '999px',
background: 'var(--color-brand-medium)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
color: 'var(--color-brand)',
fontSize: '16px',
fontWeight: '700',
textTransform: 'uppercase',
flexShrink: 0,
}}
>
{profile.full_name.charAt(0)}
</div>
</div>
<div
style={{
margin: '0 20px 18px',
display: 'flex',
flexDirection: 'column',
gap: '5px',
}}
>
<div
style={{
fontSize: '26px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1.08',
}}
>
Good to see you,{' '}
<span style={{ fontWeight: '700' }}>
{profile.full_name.split(' ')[0]}
</span>
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
{profile.role === 'buyer'
? 'Track requests, review supplier pricing, and keep decisions moving.'
: 'Review assigned RFQs, send pricing fast, and stay on top of wins.'}
</div>
</div>
{error && (
<div
style={{
margin: '0 20px 12px',
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
<div
style={{
background: 'var(--color-brand-strong)',
borderRadius: '24px',
padding: '22px',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
gap: '14px',
cursor: 'pointer',
}}
onClick={handlePrimaryAction}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
}}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
>
<span
style={{
fontSize: '12px',
fontWeight: '600',
color: 'rgba(255,255,255,0.72)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{profile.role === 'buyer' ? 'Active Requests' : 'Assigned RFQs'}
</span>
<span
style={{
fontSize: '34px',
fontWeight: '400',
color: '#ffffff',
}}
>
{profile.role === 'buyer'
? rfqSummary.open + rfqSummary.quoted
: supplierSummary.assignedOpen}
</span>
</div>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '14px',
background: 'rgba(255,255,255,0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon
icon={profile.role === 'buyer' ? addOutline : searchOutline}
style={{ color: '#ffffff', fontSize: '24px' }}
/>
</div>
</div>
<div
style={{
fontSize: '14px',
fontWeight: '600',
color: 'var(--color-accent)',
}}
>
{profile.role === 'buyer'
? 'Create new request →'
: 'Browse requests →'}
</div>
</div>
<div style={{ display: 'flex', gap: '12px', margin: '0 20px 24px' }}>
{profile.role === 'buyer' ? (
<>
<DashboardMetricCard
label="Received Quotes"
value={rfqSummary.quoted.toString()}
hint="Awaiting decision"
icon={documentTextOutline}
/>
<DashboardMetricCard
label="Completed"
value={rfqSummary.closed.toString()}
hint="Past requests"
icon={documentTextOutline}
/>
</>
) : (
<>
<DashboardMetricCard
label="My Quotes"
value={supplierSummary.myQuotes.toString()}
hint="Submitted"
icon={documentTextOutline}
/>
<DashboardMetricCard
label="Accepted"
value={supplierSummary.accepted.toString()}
hint="Won bids"
icon={documentTextOutline}
/>
</>
)}
</div>
<div
style={{
margin: '16px 20px 8px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-end',
}}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Recent Activity
</div>
<div
onClick={() => history.push('/requests')}
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-brand)',
cursor: 'pointer',
}}
>
See all
</div>
</div>
{loading ? (
<div
style={{
margin: '0 20px',
display: 'flex',
justifyContent: 'center',
padding: '20px',
}}
>
<IonSpinner
name="crescent"
style={{ color: 'var(--color-brand)' }}
/>
</div>
) : recentItems.length > 0 ? (
recentItems.map((item) => (
<RecentActivityCard
key={item.id}
title={item.title}
subtitle={new Date(item.created_at).toLocaleDateString()}
meta={item.status}
onClick={() => handleRecentItemTap(item)}
/>
))
) : (
<div
style={{
margin: '0 20px',
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '28px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: '12px',
}}
>
<IonIcon
icon={documentTextOutline}
style={{ fontSize: '48px', color: 'var(--color-text-tertiary)' }}
/>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
No recent activity yet.
</div>
{profile.role === 'buyer' && (
<button
onClick={handlePrimaryAction}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '10px 20px',
fontSize: '14px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
marginTop: '8px',
}}
>
Create Request
</button>
)}
</div>
)}
</IonContent>
</IonPage>
);
};
export default Home;
+491
View File
@@ -0,0 +1,491 @@
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline, cameraOutline, closeCircle } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import SupplierPickerRow, {
SupplierOption,
} from '../components/SupplierPickerRow';
const NewRfq: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const [title, setTitle] = useState('');
const [requestText, setRequestText] = useState('');
const [supplierOptions, setSupplierOptions] = useState<SupplierOption[]>([]);
const [selectedSupplierIds, setSelectedSupplierIds] = useState<string[]>([]);
const [loadingSuppliers, setLoadingSuppliers] = useState(true);
const [imageFile, setImageFile] = useState<File | null>(null);
const [imagePreviewUrl, setImagePreviewUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
loadSuppliers();
return () => {
cleanupPreview();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const loadSuppliers = async () => {
setLoadingSuppliers(true);
const { data, error: err } = await supabase
.from('profiles')
.select('id, full_name, company_name, city')
.eq('role', 'supplier')
.order('company_name', { ascending: true })
.order('full_name', { ascending: true });
if (!err && data) {
setSupplierOptions(data);
}
setLoadingSuppliers(false);
};
const cleanupPreview = () => {
if (imagePreviewUrl) {
URL.revokeObjectURL(imagePreviewUrl);
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const file = e.target.files[0];
setImageFile(file);
cleanupPreview();
setImagePreviewUrl(URL.createObjectURL(file));
}
};
const toggleSupplier = (id: string) => {
if (selectedSupplierIds.includes(id)) {
setSelectedSupplierIds(selectedSupplierIds.filter((s) => s !== id));
} else {
if (selectedSupplierIds.length >= 5) {
showError('Select up to 5 suppliers');
} else {
setSelectedSupplierIds([...selectedSupplierIds, id]);
}
}
};
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleCreateRfq = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
if (!requestText.trim()) {
showError('Please describe your request.');
return;
}
if (selectedSupplierIds.length === 0) {
showError('Please select at least 1 supplier.');
return;
}
setLoading(true);
setError('');
try {
// 1. Get Reference Number
const { data: refData, error: refError } =
await supabase.functions.invoke('create-rfq-reference', {
body: {},
});
if (refError || !refData?.referenceNumber) {
throw new Error('Failed to generate reference number.');
}
const referenceNumber = refData.referenceNumber;
const derivedTitle =
title.trim() || requestText.trim().substring(0, 30) + '...';
// 2. Insert RFQ
const { data: rfq, error: rfqError } = await supabase
.from('rfqs')
.insert({
buyer_id: user.id,
reference_number: referenceNumber,
title: derivedTitle,
request_text: requestText.trim(),
status: 'open',
})
.select('id')
.single();
if (rfqError) throw rfqError;
// 3. Upload Image if present
if (imageFile) {
const filePath = `${user.id}/${rfq.id}/${Date.now()}-${imageFile.name}`;
const { error: uploadError } = await supabase.storage
.from('rfq-images')
.upload(filePath, imageFile);
if (uploadError) throw uploadError;
const { error: imgMetaError } = await supabase
.from('rfq_images')
.insert({
rfq_id: rfq.id,
owner_id: user.id,
storage_path: filePath,
});
if (imgMetaError) throw imgMetaError;
}
// 4. Insert Recipients
const recipientsToInsert = selectedSupplierIds.map((sid) => ({
rfq_id: rfq.id,
supplier_id: sid,
}));
const { error: recError } = await supabase
.from('rfq_recipients')
.insert(recipientsToInsert);
if (recError) throw recError;
// 5. Navigate
history.replace(`/rfq/${rfq.id}`);
} catch (err: any) {
console.error(err);
showError(err.message || 'Failed to create RFQ.');
} finally {
setLoading(false);
}
};
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
New Request
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div style={{ margin: '0 0 16px', background: 'transparent' }}>
<h1
style={{
fontSize: '26px',
fontWeight: '700',
color: '#0f1720',
margin: '0 0 4px 0',
}}
>
Request Quote
</h1>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
Describe what you need and select suppliers.
</p>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
marginBottom: '16px',
}}
>
{error}
</div>
)}
<form
onSubmit={handleCreateRfq}
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<input
type="text"
placeholder="Title (e.g. 100 Bricks + Cement)"
value={title}
onChange={(e) => setTitle(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
<textarea
placeholder="Describe your request..."
value={requestText}
onChange={(e) => setRequestText(e.target.value)}
rows={4}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '14px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
resize: 'vertical',
}}
required
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<label
style={{ fontSize: '13px', fontWeight: '600', color: '#0f1720' }}
>
Site Photo or Reference (Optional)
</label>
{imagePreviewUrl ? (
<div style={{ position: 'relative', width: 'max-content' }}>
<img
src={imagePreviewUrl}
alt="Preview"
style={{
width: '88px',
height: '88px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
<IonIcon
icon={closeCircle}
onClick={() => {
setImageFile(null);
setImagePreviewUrl(null);
}}
style={{
position: 'absolute',
top: '-8px',
right: '-8px',
fontSize: '24px',
color: '#b91c1c',
cursor: 'pointer',
background: '#fff',
borderRadius: '50%',
}}
/>
</div>
) : (
<label
style={{
background: '#edf4ee',
borderRadius: '24px',
padding: '18px',
display: 'flex',
alignItems: 'center',
gap: '16px',
cursor: 'pointer',
}}
>
<div
style={{
width: '48px',
height: '48px',
borderRadius: '12px',
background: 'rgba(22,101,52,0.12)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon
icon={cameraOutline}
style={{ color: '#166534', fontSize: '24px' }}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<span
style={{
fontSize: '14px',
fontWeight: '600',
color: '#166534',
}}
>
Add a photo
</span>
<span
style={{
fontSize: '12px',
fontWeight: '400',
color: '#6c7a71',
}}
>
Tap to browse
</span>
</div>
<input
type="file"
accept="image/*"
onChange={handleFileChange}
style={{ display: 'none' }}
/>
</label>
)}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-end',
}}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Select Suppliers (Up to 5)
</label>
<span
style={{
fontSize: '12px',
fontWeight: '400',
color: '#6c7a71',
}}
>
{selectedSupplierIds.length}/5 selected
</span>
</div>
<div
style={{
background: '#f9fbf9',
borderRadius: '12px',
padding: '14px',
maxHeight: '200px',
overflowY: 'auto',
}}
>
{loadingSuppliers ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '10px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : supplierOptions.length > 0 ? (
supplierOptions.map((supplier) => (
<SupplierPickerRow
key={supplier.id}
supplier={supplier}
selected={selectedSupplierIds.includes(supplier.id)}
onToggle={() => toggleSupplier(supplier.id)}
/>
))
) : (
<div
style={{
fontSize: '13px',
color: '#6c7a71',
textAlign: 'center',
padding: '10px',
}}
>
No suppliers found.
</div>
)}
</div>
</div>
<button
type="submit"
disabled={loading || selectedSupplierIds.length === 0}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || selectedSupplierIds.length === 0 ? 0.7 : 1,
marginTop: '8px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Send Request'
)}
</button>
</form>
</IonContent>
</IonPage>
);
};
export default NewRfq;
+390
View File
@@ -0,0 +1,390 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { IonPage, IonContent, IonSpinner, IonIcon } from '@ionic/react';
import {
createOutline,
personOutline,
businessOutline,
locationOutline,
callOutline,
moonOutline,
sunnyOutline,
} from 'ionicons/icons';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { Preferences } from '@capacitor/preferences';
import ProfileInfoRow from '../components/ProfileInfoRow';
const Profile: React.FC = () => {
const history = useHistory();
const { signOut } = useAuth();
const { profile, clearProfile, themeMode, setThemeMode } = useProfile();
const [signingOut, setSigningOut] = useState(false);
const [error, setError] = useState('');
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSignOut = async () => {
setSigningOut(true);
try {
if (profile) {
await Preferences.remove({ key: `profile_${profile.id}` });
}
await signOut();
clearProfile();
history.replace('/auth');
} catch (err: any) {
console.error(err);
showError('Failed to sign out.');
} finally {
setSigningOut(false);
}
};
const handleEditProfile = () => {
history.push('/profile/edit');
};
const handleThemeToggle = async () => {
await setThemeMode(themeMode === 'dark' ? 'light' : 'dark');
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
<div
style={{
fontSize: '24px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Profile
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-tertiary)',
}}
>
Professional account details
</div>
</div>
<button
onClick={handleEditProfile}
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'transparent',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
border: 'none',
}}
>
<IonIcon
icon={createOutline}
style={{ color: 'var(--color-brand)', fontSize: '24px' }}
/>
</button>
</div>
{error && (
<div
style={{
margin: '0 20px 12px',
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '24px',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
<div
style={{
width: '72px',
height: '72px',
borderRadius: '999px',
background: 'var(--color-brand-medium)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
fontSize: '32px',
fontWeight: '700',
color: 'var(--color-brand)',
textTransform: 'uppercase',
}}
>
{profile.full_name.charAt(0)}
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
>
<div
style={{
fontSize: '22px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{profile.full_name}
</div>
<div
style={{
background: 'var(--color-accent-soft)',
color: 'var(--color-accent-strong)',
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
width: 'max-content',
textTransform: 'capitalize',
}}
>
{profile.role}
</div>
</div>
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
Member since {new Date(profile.created_at).toLocaleDateString()}
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Appearance
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
Switch between light and dark mode
</div>
</div>
<button
onClick={handleThemeToggle}
style={{
background: 'var(--color-surface-raised)',
borderRadius: '999px',
border: 'none',
padding: '6px',
width: '120px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
cursor: 'pointer',
}}
>
<div
style={{
width: '48px',
height: '36px',
borderRadius: '999px',
background:
themeMode === 'light'
? 'var(--color-brand)'
: 'transparent',
color:
themeMode === 'light'
? '#ffffff'
: 'var(--color-text-secondary)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '6px',
fontSize: '12px',
fontWeight: '700',
transition: 'all 0.2s ease',
}}
>
<IonIcon icon={sunnyOutline} style={{ fontSize: '16px' }} />
</div>
<div
style={{
width: '48px',
height: '36px',
borderRadius: '999px',
background:
themeMode === 'dark' ? 'var(--color-brand)' : 'transparent',
color:
themeMode === 'dark'
? '#ffffff'
: 'var(--color-text-secondary)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '6px',
fontSize: '12px',
fontWeight: '700',
transition: 'all 0.2s ease',
}}
>
<IonIcon icon={moonOutline} style={{ fontSize: '16px' }} />
</div>
</button>
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '8px 0',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
}}
>
<ProfileInfoRow
icon={personOutline}
label="Name"
value={profile.full_name}
onClick={handleEditProfile}
/>
{profile.company_name && (
<ProfileInfoRow
icon={businessOutline}
label="Company"
value={profile.company_name}
onClick={handleEditProfile}
/>
)}
{profile.city && (
<ProfileInfoRow
icon={locationOutline}
label="Location"
value={profile.city}
onClick={handleEditProfile}
/>
)}
{profile.phone && (
<ProfileInfoRow
icon={callOutline}
label="Phone"
value={profile.phone}
onClick={handleEditProfile}
/>
)}
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 20px',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
<button
onClick={handleSignOut}
disabled={signingOut}
style={{
background: 'var(--color-brand-strong)',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: signingOut ? 0.7 : 1,
}}
>
{signingOut ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Sign Out'
)}
</button>
</div>
</IonContent>
</IonPage>
);
};
export default Profile;
+456
View File
@@ -0,0 +1,456 @@
import React, { useState } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
useIonViewWillEnter,
} from '@ionic/react';
import { chevronBackOutline, pricetagOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import QuoteSummaryRow from '../components/QuoteSummaryRow';
const RfqDetail: React.FC = () => {
const history = useHistory();
const { id } = useParams<{ id: string }>();
const { user } = useAuth();
const { profile } = useProfile();
const [rfq, setRfq] = useState<any>(null);
const [images, setImages] = useState<string[]>([]);
const [quotes, setQuotes] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [supplierInvited, setSupplierInvited] = useState(false);
useIonViewWillEnter(() => {
loadRfqDetail();
});
const loadRfqDetail = async () => {
if (!user || !profile) return;
setLoading(true);
setError('');
try {
// Check supplier visibility first if supplier
if (profile.role === 'supplier') {
const { data: rec, error: recErr } = await supabase
.from('rfq_recipients')
.select('id')
.eq('rfq_id', id)
.eq('supplier_id', user.id)
.single();
if (recErr || !rec) {
throw new Error('Not invited to this RFQ');
}
setSupplierInvited(true);
}
// Load RFQ
const { data: rfqData, error: rfqErr } = await supabase
.from('rfqs')
.select('*')
.eq('id', id)
.single();
if (rfqErr) throw rfqErr;
setRfq(rfqData);
// Load Images
const { data: imgData } = await supabase
.from('rfq_images')
.select('storage_path')
.eq('rfq_id', id);
if (imgData && imgData.length > 0) {
const urls = imgData.map((img) => {
const { data } = supabase.storage
.from('rfq-images')
.getPublicUrl(img.storage_path);
return data.publicUrl;
});
setImages(urls);
}
// Load Quotes
if (profile.role === 'buyer') {
const { data: qData, error: qErr } = await supabase
.from('quotations')
.select(
'id, price_amount, delivery_option, status, profiles(full_name, company_name)'
)
.eq('rfq_id', id);
if (qErr) throw qErr;
setQuotes(qData || []);
} else {
const { data: qData, error: qErr } = await supabase
.from('quotations')
.select('id, price_amount, delivery_option, status')
.eq('rfq_id', id)
.eq('supplier_id', user.id);
if (qErr) throw qErr;
setQuotes(qData || []);
}
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to load RFQ details');
} finally {
setLoading(false);
}
};
const handlePrimaryAction = () => {
if (profile?.role === 'buyer') {
history.push(`/quote-list/${id}`);
} else {
if (quotes.length > 0) {
history.push(`/quote/${quotes[0].id}`, { mode: 'edit' });
} else {
history.push(`/quote/${id}`, { mode: 'create' });
}
}
};
const getStatusColor = (status: string) => {
if (status === 'open') {
return {
bg: 'var(--color-success-soft)',
text: 'var(--color-success-text)',
};
}
if (status === 'quoted') {
return {
bg: 'var(--color-warning-soft)',
text: 'var(--color-warning-text)',
};
}
return {
bg: 'var(--color-surface-raised)',
text: 'var(--color-text-secondary)',
};
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonHeader className="ion-no-border">
<IonToolbar
style={{ '--background': 'var(--color-bg)' } as React.CSSProperties}
>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={
{
'--color': 'var(--color-brand-strong)',
} as React.CSSProperties
}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{
fontSize: '18px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Request Details
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(120px + var(--ion-safe-area-bottom))',
}}
>
{loading ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '40px',
}}
>
<IonSpinner
name="crescent"
style={{ color: 'var(--color-brand)' }}
/>
</div>
) : error ? (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
) : (
rfq && (
<>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px 0',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div
style={{
background: 'var(--color-accent-soft)',
color: 'var(--color-warning-text)',
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
}}
>
{rfq.reference_number}
</div>
<div
style={{
background: getStatusColor(rfq.status).bg,
color: getStatusColor(rfq.status).text,
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
textTransform: 'capitalize',
}}
>
{rfq.status}
</div>
</div>
<div
style={{
fontSize: '22px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{rfq.title}
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
Posted {new Date(rfq.created_at).toLocaleDateString()}
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px 0',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Request Details
</div>
<div
style={{
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
lineHeight: '1.6',
whiteSpace: 'pre-wrap',
}}
>
{rfq.request_text}
</div>
</div>
{images.length > 0 && (
<div
style={{
margin: '0 0 12px 0',
display: 'flex',
gap: '10px',
overflowX: 'auto',
}}
>
{images.map((url, i) => (
<img
key={i}
src={url}
alt="Reference"
style={{
width: '120px',
height: '120px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
))}
</div>
)}
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
marginBottom: '20px',
}}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
marginBottom: '16px',
}}
>
{profile.role === 'buyer' ? 'Quotations' : 'Your Quote'}
</div>
{quotes.length > 0 ? (
<div style={{ display: 'flex', flexDirection: 'column' }}>
{quotes.map((q) => (
<QuoteSummaryRow
key={q.id}
supplierName={
profile.role === 'buyer'
? q.profiles?.company_name ||
q.profiles?.full_name ||
'Supplier'
: 'My Quote'
}
priceLabel={`$${q.price_amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
deliveryOption={q.delivery_option}
status={q.status}
/>
))}
</div>
) : (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
}}
>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-surface-raised)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<IonIcon
icon={pricetagOutline}
style={{
color: 'var(--color-brand)',
fontSize: '20px',
}}
/>
</div>
<div
style={{
fontSize: '14px',
color: 'var(--color-text-secondary)',
}}
>
{profile.role === 'buyer'
? 'No quotes received yet.'
: "You haven't submitted a quote yet."}
</div>
</div>
)}
</div>
</>
)
)}
</IonContent>
{!loading && !error && (
<div
style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '16px 20px calc(16px + var(--ion-safe-area-bottom, 0px))',
background: 'var(--color-surface)',
borderTop: '1px solid var(--color-border)',
display: 'flex',
zIndex: 10,
}}
>
<button
onClick={handlePrimaryAction}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
width: '100%',
cursor: 'pointer',
}}
>
{profile.role === 'buyer'
? 'View Quotations'
: quotes.length > 0
? 'Update Quote'
: 'Submit Quote'}
</button>
</div>
)}
</IonPage>
);
};
export default RfqDetail;
+338
View File
@@ -0,0 +1,338 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { Preferences } from '@capacitor/preferences';
const SetupProfile: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { setProfile, setStatus } = useProfile();
const [role, setRole] = useState<'buyer' | 'supplier' | ''>('');
const [fullName, setFullName] = useState('');
const [companyName, setCompanyName] = useState('');
const [phone, setPhone] = useState('');
const [city, setCity] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleProfileSetup = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
if (!role) {
showError('Please select a role');
return;
}
if (!fullName) {
showError('Please enter your full name');
return;
}
setLoading(true);
setError('');
const newProfile = {
id: user.id,
role: role as 'buyer' | 'supplier',
full_name: fullName,
company_name: companyName || null,
phone: phone || null,
city: city || null,
avatar_url: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
const { error: insertError } = await supabase
.from('profiles')
.insert(newProfile);
if (insertError) {
showError(insertError.message);
setLoading(false);
return;
}
await Preferences.set({
key: `profile_${user.id}`,
value: JSON.stringify(newProfile),
});
setProfile(newProfile);
setStatus('loaded');
setLoading(false);
history.replace('/home');
};
return (
<IonPage style={{ background: '#eef4ef' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': 'transparent' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Setup Profile
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': 'linear-gradient(180deg, #eef4ef 0%, #f8fbf8 100%)',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
background: 'transparent',
margin: '0 0 16px 0',
display: 'flex',
flexDirection: 'column',
gap: '4px',
}}
>
<h1
style={{
fontSize: '26px',
fontWeight: '700',
color: '#0f1720',
margin: '0',
}}
>
Welcome!
</h1>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
Complete your profile to get started.
</p>
</div>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleProfileSetup}
style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}
>
<label
style={{
fontSize: '14px',
fontWeight: '600',
color: '#0f1720',
}}
>
I want to...
</label>
<div
style={{
display: 'flex',
background: '#edf4ee',
borderRadius: '999px',
padding: '4px',
}}
>
<button
type="button"
onClick={() => setRole('buyer')}
style={{
flex: 1,
background: role === 'buyer' ? '#166534' : 'transparent',
color: role === 'buyer' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
}}
>
Buy Materials
</button>
<button
type="button"
onClick={() => setRole('supplier')}
style={{
flex: 1,
background: role === 'supplier' ? '#166534' : 'transparent',
color: role === 'supplier' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
}}
>
Sell Materials
</button>
</div>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<input
type="text"
placeholder="Full Name"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
/>
<input
type="text"
placeholder="Company Name (Optional)"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
<input
type="text"
placeholder="City (Optional)"
value={city}
onChange={(e) => setCity(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
<input
type="tel"
placeholder="Phone (Optional)"
value={phone}
onChange={(e) => setPhone(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
</div>
<button
type="submit"
disabled={loading || !role || !fullName}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || !role || !fullName ? 0.7 : 1,
marginTop: '4px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Complete Setup'
)}
</button>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default SetupProfile;
+434
View File
@@ -0,0 +1,434 @@
import React, { useState, useEffect } from 'react';
import { useHistory, useParams, useLocation } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
interface LocationState {
mode?: 'create' | 'edit';
}
const SupplierQuoteForm: React.FC = () => {
const history = useHistory();
const { id } = useParams<{ id: string }>(); // in create mode: id is rfq_id; in edit mode: id is quotation_id
const location = useLocation<LocationState>();
const mode = location.state?.mode || 'create';
const { user } = useAuth();
const [rfqSummary, setRfqSummary] = useState<{
id: string;
referenceNumber: string;
title: string;
} | null>(null);
const [priceDisplay, setPriceDisplay] = useState('');
const [deliveryOption, setDeliveryOption] = useState('');
const [note, setNote] = useState('');
const [existingQuotationId, setExistingQuotationId] = useState<string | null>(
null
);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
loadQuoteFormData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, mode]);
const loadQuoteFormData = async () => {
if (!user) return;
setLoading(true);
setError('');
try {
if (mode === 'edit') {
// id is quotation_id
const { data: quote, error: qErr } = await supabase
.from('quotations')
.select('*, rfqs(id, reference_number, title)')
.eq('id', id)
.single();
if (qErr) throw qErr;
setExistingQuotationId(quote.id);
setPriceDisplay(quote.price_amount.toString());
setDeliveryOption(quote.delivery_option);
setNote(quote.note || '');
setRfqSummary({
id: quote.rfqs.id,
referenceNumber: quote.rfqs.reference_number,
title: quote.rfqs.title,
});
} else {
// id is rfq_id
const { data: rfq, error: rfqErr } = await supabase
.from('rfqs')
.select('id, reference_number, title')
.eq('id', id)
.single();
if (rfqErr) throw rfqErr;
setRfqSummary({
id: rfq.id,
referenceNumber: rfq.reference_number,
title: rfq.title,
});
// Check if there is already a quote (just in case they navigated strangely)
const { data: quote } = await supabase
.from('quotations')
.select('*')
.eq('rfq_id', id)
.eq('supplier_id', user.id)
.maybeSingle();
if (quote) {
setExistingQuotationId(quote.id);
setPriceDisplay(quote.price_amount.toString());
setDeliveryOption(quote.delivery_option);
setNote(quote.note || '');
}
}
} catch (err: any) {
console.error(err);
setError('Failed to load form data.');
} finally {
setLoading(false);
}
};
const sanitizePriceInput = (val: string) => {
let sanitized = val.replace(/[^0-9.]/g, '');
const parts = sanitized.split('.');
if (parts.length > 2) {
sanitized = parts[0] + '.' + parts.slice(1).join('');
}
if (parts.length === 2 && parts[1].length > 2) {
sanitized = parts[0] + '.' + parts[1].substring(0, 2);
}
setPriceDisplay(sanitized);
};
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSaveQuote = async (e: React.FormEvent) => {
e.preventDefault();
if (!user || !rfqSummary) return;
const amount = parseFloat(priceDisplay);
if (isNaN(amount) || amount < 0) {
showError('Please enter a valid amount.');
return;
}
if (!deliveryOption.trim()) {
showError('Please enter a delivery option.');
return;
}
setSaving(true);
setError('');
try {
if (existingQuotationId) {
const { error: updErr } = await supabase
.from('quotations')
.update({
price_amount: amount,
delivery_option: deliveryOption.trim(),
note: note.trim() || null,
updated_at: new Date().toISOString(),
})
.eq('id', existingQuotationId);
if (updErr) throw updErr;
} else {
const { error: insErr } = await supabase.from('quotations').insert({
rfq_id: rfqSummary.id,
supplier_id: user.id,
price_amount: amount,
currency_code: 'USD',
delivery_option: deliveryOption.trim(),
note: note.trim() || null,
status: 'submitted',
});
if (insErr) throw insErr;
}
history.replace(`/rfq/${rfqSummary.id}`);
} catch (err: any) {
console.error(err);
showError(err.message || 'Failed to save quotation.');
setSaving(false);
}
};
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
{existingQuotationId ? 'Update Quote' : 'Submit Quote'}
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
{loading ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '40px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : (
<>
{rfqSummary && (
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px',
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div
style={{
fontSize: '12px',
fontWeight: '700',
color: '#b45309',
background: 'rgba(245,158,11,0.14)',
borderRadius: '999px',
padding: '4px 10px',
width: 'max-content',
}}
>
{rfqSummary.referenceNumber}
</div>
<div
style={{
fontSize: '16px',
fontWeight: '600',
color: '#0f1720',
}}
>
{rfqSummary.title}
</div>
</div>
)}
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
marginBottom: '12px',
}}
>
{error}
</div>
)}
<form
onSubmit={handleSaveQuote}
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Total Price (USD)
</label>
<div
style={{
position: 'relative',
display: 'flex',
alignItems: 'center',
}}
>
<span
style={{
position: 'absolute',
left: '14px',
fontSize: '15px',
color: '#0f1720',
fontWeight: '600',
}}
>
$
</span>
<input
type="text"
inputMode="decimal"
placeholder="0.00"
value={priceDisplay}
onChange={(e) => sanitizePriceInput(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px 0 32px',
height: '48px',
fontSize: '15px',
fontWeight: '600',
color: '#0f1720',
width: '100%',
}}
required
/>
</div>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Delivery Option
</label>
<input
type="text"
placeholder="e.g. Free delivery in 2 days"
value={deliveryOption}
onChange={(e) => setDeliveryOption(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Note for Buyer (Optional)
</label>
<textarea
placeholder="Add any conditions or details..."
value={note}
onChange={(e) => setNote(e.target.value)}
rows={4}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '14px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
resize: 'vertical',
}}
/>
</div>
<button
type="submit"
disabled={saving || !priceDisplay || !deliveryOption}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: saving || !priceDisplay || !deliveryOption ? 0.7 : 1,
marginTop: '8px',
}}
>
{saving ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : existingQuotationId ? (
'Update Quote'
) : (
'Submit Quote'
)}
</button>
</form>
</>
)}
</IonContent>
</IonPage>
);
};
export default SupplierQuoteForm;
+306
View File
@@ -0,0 +1,306 @@
import React, { useState, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { IonPage, IonContent, IonSpinner, IonIcon } from '@ionic/react';
import { arrowBackOutline, checkmarkCircle } from 'ionicons/icons';
import { supabase } from '../supabase';
import OtpInput from '../components/OtpInput';
interface LocationState {
email?: string;
resent?: boolean;
}
const VerifyEmail: React.FC = () => {
const history = useHistory();
const location = useLocation<LocationState>();
const email = location.state?.email || '';
const resent = location.state?.resent || false;
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [cooldown, setCooldown] = useState(resent ? 60 : 0);
const [verified, setVerified] = useState(false);
useEffect(() => {
if (!email) {
history.replace('/auth');
}
}, [email, history]);
useEffect(() => {
if (cooldown > 0) {
const timer = setTimeout(() => setCooldown(cooldown - 1), 1000);
return () => clearTimeout(timer);
}
}, [cooldown]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleVerifyOtp = async (e: React.FormEvent) => {
e.preventDefault();
if (code.length !== 6) {
showError('Please enter the 6-digit code');
return;
}
setLoading(true);
setError('');
const { error } = await supabase.auth.verifyOtp({
email,
token: code,
type: 'email',
});
if (error) {
showError(error.message);
setLoading(false);
return;
}
setVerified(true);
setLoading(false);
};
const handleResend = async () => {
if (cooldown > 0) return;
const { error } = await supabase.auth.resend({
type: 'signup',
email,
});
if (error) {
showError(error.message);
} else {
setCooldown(60);
}
};
const handleBackToSignIn = () => {
history.replace('/auth');
};
if (!email) return null;
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': '0px',
}}
>
<div
style={{
padding:
'calc(var(--ion-safe-area-top, 0px) + 18px) 20px calc(var(--ion-safe-area-bottom, 0px) + 28px)',
minHeight: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
<div
style={{
background: 'transparent',
padding: '0',
margin: '0 0 20px 0',
display: 'flex',
}}
>
<button
onClick={() => history.goBack()}
style={{
background: 'transparent',
border: 'none',
padding: '0',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
color: '#14532d',
}}
>
<IonIcon icon={arrowBackOutline} style={{ fontSize: '24px' }} />
</button>
</div>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
{verified ? (
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '20px',
alignItems: 'center',
textAlign: 'center',
padding: '20px 0',
}}
>
<IonIcon
icon={checkmarkCircle}
style={{ fontSize: '64px', color: '#166534' }}
/>
<div
style={{
background: 'rgba(22,101,52,0.10)',
borderRadius: '12px',
padding: '14px',
width: '100%',
}}
>
<span
style={{
color: '#14532d',
fontSize: '14px',
fontWeight: '600',
}}
>
Email confirmed. You can now sign in.
</span>
</div>
<button
onClick={handleBackToSignIn}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
width: '100%',
cursor: 'pointer',
}}
>
Back to Sign In
</button>
</div>
) : (
<>
<div>
<div
style={{
fontSize: '24px',
fontWeight: '700',
color: '#0f1720',
lineHeight: '1.15',
}}
>
Verify your email
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
lineHeight: '1.55',
marginTop: '8px',
}}
>
We sent a 6-digit code to <strong>{email}</strong>. Enter it
below to confirm your account.
</div>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleVerifyOtp}
style={{
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
<OtpInput
value={code}
onChange={setCode}
disabled={loading}
/>
<button
type="submit"
disabled={loading || code.length !== 6}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || code.length !== 6 ? 0.7 : 1,
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Verify'
)}
</button>
</form>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<button
type="button"
onClick={handleResend}
disabled={cooldown > 0}
style={{
background: 'transparent',
border: 'none',
padding: '0',
fontSize: '14px',
fontWeight: '600',
color: cooldown > 0 ? '#8a978f' : '#f59e0b',
cursor: cooldown > 0 ? 'default' : 'pointer',
}}
>
{cooldown > 0
? `Resend code in ${cooldown}s`
: 'Resend code'}
</button>
</div>
</>
)}
</div>
</div>
</IonContent>
</IonPage>
);
};
export default VerifyEmail;
+311
View File
@@ -0,0 +1,311 @@
import React, { useState, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline, eyeOutline, eyeOffOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useProfileLoader } from '../hooks/useProfileLoader';
import OtpInput from '../components/OtpInput';
interface LocationState {
email?: string;
}
const VerifyReset: React.FC = () => {
const history = useHistory();
const location = useLocation<LocationState>();
const email = location.state?.email || '';
const { loadProfileAndNavigate } = useProfileLoader();
const [code, setCode] = useState('');
const [newPassword, setNewPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [cooldown, setCooldown] = useState(60);
const [overlayVisible, setOverlayVisible] = useState(false);
const [overlayError, setOverlayError] = useState(false);
useEffect(() => {
if (!email) {
history.replace('/forgot-password');
}
}, [email, history]);
useEffect(() => {
if (cooldown > 0) {
const timer = setTimeout(() => setCooldown(cooldown - 1), 1000);
return () => clearTimeout(timer);
}
}, [cooldown]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleVerifyReset = async (e: React.FormEvent) => {
e.preventDefault();
if (code.length !== 6) {
showError('Please enter the 6-digit code');
return;
}
if (newPassword.length < 6) {
showError('Password must be at least 6 characters');
return;
}
setLoading(true);
setError('');
const { error: verifyError } = await supabase.auth.verifyOtp({
email,
token: code,
type: 'recovery',
});
if (verifyError) {
showError(verifyError.message);
setLoading(false);
return;
}
const { error: updateError } = await supabase.auth.updateUser({
password: newPassword,
});
if (updateError) {
showError(updateError.message);
setLoading(false);
return;
}
// Success -> load profile and navigate
loadProfileAndNavigate(setOverlayVisible, setOverlayError);
};
const handleResend = async () => {
if (cooldown > 0) return;
const { error } = await supabase.auth.resetPasswordForEmail(email);
if (error) {
showError(error.message);
} else {
setCooldown(60);
}
};
if (!email) return null;
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Set New Password
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div>
<h2
style={{
fontSize: '22px',
fontWeight: '700',
color: '#0f1720',
margin: '0 0 8px 0',
}}
>
Enter code
</h2>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
We sent a 6-digit code to <strong>{email}</strong>.
</p>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleVerifyReset}
style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}
>
<OtpInput value={code} onChange={setCode} disabled={loading} />
<div style={{ position: 'relative' }}>
<input
type={showPassword ? 'text' : 'password'}
placeholder="New password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
minLength={6}
/>
<IonIcon
icon={showPassword ? eyeOffOutline : eyeOutline}
onClick={() => setShowPassword(!showPassword)}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: '#8a978f',
cursor: 'pointer',
}}
/>
</div>
<button
type="submit"
disabled={loading || code.length !== 6 || !newPassword}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || code.length !== 6 || !newPassword ? 0.7 : 1,
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Reset Password'
)}
</button>
</form>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<button
type="button"
onClick={handleResend}
disabled={cooldown > 0}
style={{
background: 'transparent',
border: 'none',
padding: '0',
fontSize: '14px',
fontWeight: '600',
color: cooldown > 0 ? '#8a978f' : '#f59e0b',
cursor: cooldown > 0 ? 'default' : 'pointer',
}}
>
{cooldown > 0 ? `Resend code in ${cooldown}s` : 'Resend code'}
</button>
</div>
</div>
{overlayVisible && (
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(255,255,255,0.9)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
zIndex: 9999,
}}
>
{overlayError ? (
<div
style={{
color: '#b91c1c',
fontSize: '15px',
fontWeight: '600',
}}
>
Error updating profile.
</div>
) : (
<IonSpinner name="crescent" style={{ color: '#166534' }} />
)}
</div>
)}
</IonContent>
</IonPage>
);
};
export default VerifyReset;