build: 444813b5-5daf-49b2-bf1a-7e4caeab4e17
This commit is contained in:
@@ -0,0 +1,703 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
IonContent,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonRefresher,
|
||||
IonRefresherContent,
|
||||
IonSegment,
|
||||
IonSegmentButton,
|
||||
IonSkeletonText,
|
||||
IonLabel,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import { fileTrayOutline } from 'ionicons/icons';
|
||||
import momImage from '../assets/mom.jpg';
|
||||
import dadImage from '../assets/dad.jpg';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import ActivityListItem from '../components/ActivityListItem';
|
||||
import { setStatusBarStyle, Style } from '../utils/statusBar';
|
||||
import { buildCacheKey, readCache, writeCache } from '../utils/localCache';
|
||||
import '../styles/activity.css';
|
||||
import '../styles/recipients.css';
|
||||
|
||||
type RecipientRow = {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
photo_path: string | null;
|
||||
};
|
||||
|
||||
type MerchantRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
branch_name: string | null;
|
||||
};
|
||||
|
||||
type OrderRow = {
|
||||
id: string;
|
||||
service_type: string;
|
||||
amount: number;
|
||||
status: string;
|
||||
created_at: string;
|
||||
recipient_id: string;
|
||||
merchant_id: string | null;
|
||||
recipients: RecipientRow | null;
|
||||
merchants: MerchantRow | null;
|
||||
};
|
||||
|
||||
type VoucherRow = {
|
||||
id: string;
|
||||
order_id: string;
|
||||
status: string;
|
||||
redeemed_at: string | null;
|
||||
redeemed_merchant_id: string | null;
|
||||
};
|
||||
|
||||
type RedemptionRow = {
|
||||
id: string;
|
||||
voucher_id: string;
|
||||
order_id: string;
|
||||
merchant_id: string;
|
||||
redeemed_at: string;
|
||||
};
|
||||
|
||||
type ActivityMetadata = {
|
||||
statusText?: string;
|
||||
avatarLabel?: string;
|
||||
avatarTone?: string;
|
||||
avatarImage?: string;
|
||||
voucherId?: string;
|
||||
};
|
||||
|
||||
type UnifiedActivityItem = {
|
||||
kind: 'voucher' | 'order';
|
||||
id: string;
|
||||
event_type: string;
|
||||
service_type: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
amount: number | null;
|
||||
event_at: string;
|
||||
order_id: string;
|
||||
metadata: ActivityMetadata;
|
||||
};
|
||||
|
||||
type ActivityTypeFilter =
|
||||
| 'all'
|
||||
| 'orders'
|
||||
| 'vouchers'
|
||||
| 'completed'
|
||||
| 'alerts';
|
||||
|
||||
type ActivityFilterRange = '7' | '30' | '90' | 'all';
|
||||
|
||||
type VoucherActivityStatus = 'created' | 'redeemed' | 'partially';
|
||||
|
||||
const previewUserId = '00000000-0000-0000-0000-000000000000';
|
||||
|
||||
const dayLabel = (dateText: string) => {
|
||||
const date = new Date(dateText);
|
||||
const today = new Date();
|
||||
const yesterday = new Date();
|
||||
yesterday.setDate(today.getDate() - 1);
|
||||
|
||||
if (date.toDateString() === today.toDateString()) return 'Today';
|
||||
if (date.toDateString() === yesterday.toDateString()) return 'Yesterday';
|
||||
return date.toLocaleDateString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
};
|
||||
|
||||
const getMerchantDisplayName = (merchant?: MerchantRow | null) => {
|
||||
if (!merchant) return null;
|
||||
return `${merchant.name}${merchant.branch_name ? ` ${merchant.branch_name}` : ''}`;
|
||||
};
|
||||
|
||||
const getActivityContextLabel = (
|
||||
serviceType: string,
|
||||
statusText: string,
|
||||
merchantName?: string | null
|
||||
) => {
|
||||
const normalizedService = getNormalizedServiceType(serviceType);
|
||||
const normalizedStatus = statusText.toLowerCase();
|
||||
|
||||
if (normalizedService === 'grocery' || normalizedService === 'medication') {
|
||||
if (normalizedStatus.includes('redeemed')) {
|
||||
return merchantName ? `Redeemed at ${merchantName}` : 'Voucher redeemed';
|
||||
}
|
||||
if (normalizedStatus.includes('partial')) {
|
||||
return merchantName
|
||||
? `Partially redeemed at ${merchantName}`
|
||||
: 'Partially redeemed';
|
||||
}
|
||||
return merchantName
|
||||
? `Ready at ${merchantName}`
|
||||
: 'Voucher ready for collection';
|
||||
}
|
||||
|
||||
if (normalizedService === 'electricity') {
|
||||
return normalizedStatus.includes('completed')
|
||||
? 'Meter support delivered'
|
||||
: 'Meter support sent';
|
||||
}
|
||||
|
||||
if (normalizedService === 'airtime') {
|
||||
return normalizedStatus.includes('completed')
|
||||
? 'Top-up delivered'
|
||||
: 'Top-up sent';
|
||||
}
|
||||
|
||||
return 'Support sent';
|
||||
};
|
||||
|
||||
const getRecipientDisplayName = (recipient?: RecipientRow | null) => {
|
||||
if (!recipient) return 'Loved one';
|
||||
return `${recipient.first_name} ${recipient.last_name}`.trim();
|
||||
};
|
||||
|
||||
const getInitials = (name: string) =>
|
||||
name
|
||||
.split(' ')
|
||||
.map((part) => part.charAt(0))
|
||||
.join('')
|
||||
.slice(0, 2)
|
||||
.toUpperCase();
|
||||
|
||||
const getNormalizedServiceType = (value: string) => {
|
||||
const normalized = value.toLowerCase();
|
||||
if (normalized.includes('grocery')) return 'grocery';
|
||||
if (normalized.includes('medication') || normalized.includes('pharmacy')) {
|
||||
return 'medication';
|
||||
}
|
||||
if (normalized.includes('airtime') || normalized.includes('data')) {
|
||||
return 'airtime';
|
||||
}
|
||||
if (normalized.includes('electricity') || normalized.includes('zesa')) {
|
||||
return 'electricity';
|
||||
}
|
||||
return normalized;
|
||||
};
|
||||
|
||||
const getNormalizedServiceLabel = (serviceType: string) => {
|
||||
const normalizedService = getNormalizedServiceType(serviceType);
|
||||
if (normalizedService === 'grocery') return 'Grocery voucher';
|
||||
if (normalizedService === 'medication') return 'Medication voucher';
|
||||
if (normalizedService === 'airtime') return 'Airtime & Data';
|
||||
if (normalizedService === 'electricity') return 'Electricity';
|
||||
return serviceType.charAt(0).toUpperCase() + serviceType.slice(1);
|
||||
};
|
||||
|
||||
const isVoucherService = (serviceType: string) => {
|
||||
const normalizedService = getNormalizedServiceType(serviceType);
|
||||
return normalizedService === 'grocery' || normalizedService === 'medication';
|
||||
};
|
||||
|
||||
const getVoucherStatus = (
|
||||
orderStatus: string,
|
||||
voucher?: VoucherRow,
|
||||
redemptions: RedemptionRow[] = []
|
||||
): VoucherActivityStatus => {
|
||||
const combinedStatus = `${orderStatus} ${voucher?.status ?? ''}`
|
||||
.toLowerCase()
|
||||
.replace(/_/g, ' ');
|
||||
|
||||
if (combinedStatus.includes('partial')) return 'partially';
|
||||
if (
|
||||
combinedStatus.includes('redeemed') ||
|
||||
Boolean(voucher?.redeemed_at) ||
|
||||
Boolean(voucher?.redeemed_merchant_id) ||
|
||||
redemptions.length > 0
|
||||
) {
|
||||
return 'redeemed';
|
||||
}
|
||||
|
||||
return 'created';
|
||||
};
|
||||
|
||||
const getOrderStatus = (status: string) => {
|
||||
const normalizedStatus = status.toLowerCase().replace(/_/g, ' ');
|
||||
if (
|
||||
normalizedStatus.includes('completed') ||
|
||||
normalizedStatus.includes('delivered') ||
|
||||
normalizedStatus.includes('active')
|
||||
) {
|
||||
return 'completed';
|
||||
}
|
||||
return 'created';
|
||||
};
|
||||
|
||||
const getActivityStatusTone = (_serviceType: string, statusText?: string) => {
|
||||
const normalizedStatus = statusText?.toLowerCase() ?? '';
|
||||
|
||||
if (normalizedStatus.includes('redeemed')) return 'success';
|
||||
if (normalizedStatus.includes('partial')) return 'partial';
|
||||
return 'warning';
|
||||
};
|
||||
|
||||
const getSeededRecipientImage = (
|
||||
firstName?: string | null,
|
||||
photoPath?: string | null
|
||||
) => {
|
||||
const normalizedPath = photoPath?.trim().toLowerCase();
|
||||
if (normalizedPath === 'mom.jpg' || normalizedPath === 'mum.jpg') {
|
||||
return momImage;
|
||||
}
|
||||
if (normalizedPath === 'dad.jpg' || normalizedPath === 'father.jpg') {
|
||||
return dadImage;
|
||||
}
|
||||
|
||||
const normalizedName = firstName?.trim().toLowerCase();
|
||||
if (normalizedName === 'mum' || normalizedName === 'mom') return momImage;
|
||||
if (normalizedName === 'dad' || normalizedName === 'father') return dadImage;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const getRecipientAvatarUrl = async (recipient?: RecipientRow | null) => {
|
||||
if (!recipient) return undefined;
|
||||
|
||||
const seededImage = getSeededRecipientImage(
|
||||
recipient.first_name,
|
||||
recipient.photo_path
|
||||
);
|
||||
if (seededImage) return seededImage;
|
||||
|
||||
if (!recipient.photo_path) return undefined;
|
||||
|
||||
const { data } = await supabase.storage
|
||||
.from('recipient-photos')
|
||||
.createSignedUrl(recipient.photo_path, 3600);
|
||||
|
||||
return data?.signedUrl;
|
||||
};
|
||||
|
||||
const getAvatarTone = (serviceType: string) => {
|
||||
const normalizedService = getNormalizedServiceType(serviceType);
|
||||
if (normalizedService === 'medication') return 'mint';
|
||||
if (normalizedService === 'airtime') return 'sky';
|
||||
if (normalizedService === 'electricity') return 'gold';
|
||||
return 'lavender';
|
||||
};
|
||||
|
||||
const ActivityPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user } = useAuth();
|
||||
const [events, setEvents] = useState<UnifiedActivityItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [range, setRange] = useState<ActivityFilterRange>('all');
|
||||
const [typeFilter, setTypeFilter] = useState<ActivityTypeFilter>('all');
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setStatusBarStyle(Style.Light);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
void loadActivity();
|
||||
}, [user?.id]);
|
||||
|
||||
const showError = (message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const fetchOrdersForUser = async (userId: string) => {
|
||||
return supabase
|
||||
.from('support_orders')
|
||||
.select(
|
||||
'id,service_type,amount,status,created_at,recipient_id,merchant_id,recipients(id,first_name,last_name,photo_path),merchants(id,name,branch_name)'
|
||||
)
|
||||
.eq('user_id', userId)
|
||||
.order('created_at', { ascending: false });
|
||||
};
|
||||
|
||||
const loadActivity = async (options?: { forceRefresh?: boolean }) => {
|
||||
const activeUserId = user?.id ?? previewUserId;
|
||||
const cacheKey = buildCacheKey(activeUserId, 'activityList');
|
||||
|
||||
let hasCache = false;
|
||||
if (!options?.forceRefresh) {
|
||||
try {
|
||||
const cached = await readCache<UnifiedActivityItem[]>(cacheKey);
|
||||
if (cached && Array.isArray(cached)) {
|
||||
setEvents(cached);
|
||||
setLoading(false);
|
||||
hasCache = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[activity cache] error', err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasCache) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
let { data: ordersData, error: ordersError } =
|
||||
await fetchOrdersForUser(activeUserId);
|
||||
|
||||
if (!ordersError && user?.id && (ordersData ?? []).length === 0) {
|
||||
const previewResult = await fetchOrdersForUser(previewUserId);
|
||||
ordersData = previewResult.data;
|
||||
ordersError = previewResult.error;
|
||||
}
|
||||
|
||||
if (ordersError) {
|
||||
showError(ordersError.message || 'Failed to load activity');
|
||||
if (!hasCache) setEvents([]);
|
||||
if (!hasCache) setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const orders = (ordersData ?? []) as unknown as OrderRow[];
|
||||
const orderIds = orders.map((order) => order.id);
|
||||
const recipientIds = Array.from(
|
||||
new Set(orders.map((order) => order.recipient_id).filter(Boolean))
|
||||
);
|
||||
|
||||
const [recipientsRes, vouchersRes, redemptionsRes, merchantsRes] =
|
||||
await Promise.all([
|
||||
recipientIds.length > 0
|
||||
? supabase
|
||||
.from('recipients')
|
||||
.select('id,first_name,last_name,photo_path')
|
||||
.in('id', recipientIds)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
orderIds.length > 0
|
||||
? supabase
|
||||
.from('vouchers')
|
||||
.select('id,order_id,status,redeemed_at,redeemed_merchant_id')
|
||||
.in('order_id', orderIds)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
orderIds.length > 0
|
||||
? supabase
|
||||
.from('voucher_redemptions')
|
||||
.select('id,voucher_id,order_id,merchant_id,redeemed_at')
|
||||
.in('order_id', orderIds)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
supabase.from('merchants').select('id,name,branch_name'),
|
||||
]);
|
||||
|
||||
if (
|
||||
recipientsRes.error ||
|
||||
vouchersRes.error ||
|
||||
redemptionsRes.error ||
|
||||
merchantsRes.error
|
||||
) {
|
||||
showError(
|
||||
recipientsRes.error?.message ||
|
||||
vouchersRes.error?.message ||
|
||||
redemptionsRes.error?.message ||
|
||||
merchantsRes.error?.message ||
|
||||
'Failed to load activity details'
|
||||
);
|
||||
if (!hasCache) setEvents([]);
|
||||
if (!hasCache) setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const recipientsById = new Map(
|
||||
((recipientsRes.data ?? []) as RecipientRow[]).map((recipient) => [
|
||||
recipient.id,
|
||||
recipient,
|
||||
])
|
||||
);
|
||||
const vouchersByOrderId = new Map(
|
||||
((vouchersRes.data ?? []) as VoucherRow[]).map((voucher) => [
|
||||
voucher.order_id,
|
||||
voucher,
|
||||
])
|
||||
);
|
||||
const redemptionsByOrderId = (
|
||||
(redemptionsRes.data ?? []) as RedemptionRow[]
|
||||
).reduce<Map<string, RedemptionRow[]>>((acc, redemption) => {
|
||||
const existing = acc.get(redemption.order_id) ?? [];
|
||||
existing.push(redemption);
|
||||
acc.set(redemption.order_id, existing);
|
||||
return acc;
|
||||
}, new Map());
|
||||
const merchantsById = new Map(
|
||||
((merchantsRes.data ?? []) as MerchantRow[]).map((merchant) => [
|
||||
merchant.id,
|
||||
merchant,
|
||||
])
|
||||
);
|
||||
|
||||
const mappedRows = await Promise.all(
|
||||
orders.map(async (order) => {
|
||||
const recipient =
|
||||
order.recipients ?? recipientsById.get(order.recipient_id) ?? null;
|
||||
const recipientName = getRecipientDisplayName(recipient);
|
||||
const serviceType = getNormalizedServiceType(order.service_type);
|
||||
const voucher = vouchersByOrderId.get(order.id);
|
||||
const redemptions = redemptionsByOrderId.get(order.id) ?? [];
|
||||
const latestRedemption = [...redemptions].sort(
|
||||
(a, b) =>
|
||||
new Date(b.redeemed_at).getTime() -
|
||||
new Date(a.redeemed_at).getTime()
|
||||
)[0];
|
||||
const statusText = isVoucherService(serviceType)
|
||||
? getVoucherStatus(order.status, voucher, redemptions)
|
||||
: getOrderStatus(order.status);
|
||||
const redemptionMerchant = latestRedemption?.merchant_id
|
||||
? merchantsById.get(latestRedemption.merchant_id)
|
||||
: null;
|
||||
const voucherMerchant = voucher?.redeemed_merchant_id
|
||||
? merchantsById.get(voucher.redeemed_merchant_id)
|
||||
: null;
|
||||
const orderMerchant =
|
||||
order.merchants ??
|
||||
(order.merchant_id ? merchantsById.get(order.merchant_id) : null);
|
||||
const merchantName =
|
||||
getMerchantDisplayName(redemptionMerchant) ??
|
||||
getMerchantDisplayName(voucherMerchant) ??
|
||||
getMerchantDisplayName(orderMerchant);
|
||||
const subtitle = getActivityContextLabel(
|
||||
serviceType,
|
||||
statusText,
|
||||
merchantName
|
||||
);
|
||||
const avatarImage = await getRecipientAvatarUrl(recipient);
|
||||
|
||||
return {
|
||||
kind: isVoucherService(serviceType) ? 'voucher' : 'order',
|
||||
id: order.id,
|
||||
order_id: order.id,
|
||||
event_type: serviceType,
|
||||
service_type: serviceType,
|
||||
title: getNormalizedServiceLabel(serviceType),
|
||||
subtitle,
|
||||
amount: Number(order.amount ?? 0),
|
||||
event_at: order.created_at,
|
||||
metadata: {
|
||||
statusText,
|
||||
avatarLabel: getInitials(recipientName),
|
||||
avatarTone: getAvatarTone(serviceType),
|
||||
avatarImage,
|
||||
voucherId: voucher?.id,
|
||||
},
|
||||
} satisfies UnifiedActivityItem;
|
||||
})
|
||||
);
|
||||
|
||||
const finalEvents = mappedRows.sort(
|
||||
(a, b) => new Date(b.event_at).getTime() - new Date(a.event_at).getTime()
|
||||
);
|
||||
|
||||
setEvents(finalEvents);
|
||||
setLoading(false);
|
||||
void writeCache(cacheKey, finalEvents);
|
||||
};
|
||||
|
||||
const filteredEvents = useMemo(() => {
|
||||
const threshold = new Date();
|
||||
if (range !== 'all') {
|
||||
const days = Number(range);
|
||||
threshold.setHours(0, 0, 0, 0);
|
||||
threshold.setDate(threshold.getDate() - (days - 1));
|
||||
}
|
||||
|
||||
return events.filter((item) => {
|
||||
if (
|
||||
range !== 'all' &&
|
||||
new Date(item.event_at).getTime() < threshold.getTime()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (typeFilter) {
|
||||
case 'all':
|
||||
return true;
|
||||
case 'orders':
|
||||
return item.kind === 'order';
|
||||
case 'vouchers':
|
||||
return item.kind === 'voucher';
|
||||
case 'completed': {
|
||||
const status = (item.metadata.statusText || '').toLowerCase();
|
||||
return (
|
||||
status.includes('completed') ||
|
||||
status.includes('redeemed') ||
|
||||
status.includes('partial')
|
||||
);
|
||||
}
|
||||
case 'alerts':
|
||||
return false;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}, [events, range, typeFilter]);
|
||||
|
||||
const groups = useMemo(() => {
|
||||
return filteredEvents.reduce<Record<string, UnifiedActivityItem[]>>(
|
||||
(acc, event) => {
|
||||
const label = dayLabel(event.event_at);
|
||||
acc[label] = acc[label] ?? [];
|
||||
acc[label].push(event);
|
||||
return acc;
|
||||
},
|
||||
{}
|
||||
);
|
||||
}, [filteredEvents]);
|
||||
|
||||
const handleRefresh = async (event: CustomEvent) => {
|
||||
await loadActivity({ forceRefresh: true });
|
||||
event.detail.complete();
|
||||
};
|
||||
|
||||
const handleOpenEvent = (event: UnifiedActivityItem) => {
|
||||
history.push(`/orders/${event.order_id}`, { parentRoot: '/activity' });
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonContent
|
||||
fullscreen
|
||||
className="activity-shell"
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': 'calc(var(--ion-safe-area-top, 0px) + 8px)',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
|
||||
<IonRefresherContent />
|
||||
</IonRefresher>
|
||||
|
||||
<div className="activity-top-row" style={{ padding: '18px 0 0' }}>
|
||||
<div className="activity-title-block">
|
||||
<h1 className="activity-page-title">Activity</h1>
|
||||
<p className="activity-page-subtitle">Orders & care timeline</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="activity-type-filter-row">
|
||||
{(
|
||||
[
|
||||
'all',
|
||||
'orders',
|
||||
'vouchers',
|
||||
'completed',
|
||||
'alerts',
|
||||
] as ActivityTypeFilter[]
|
||||
).map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
type="button"
|
||||
className={`activity-type-chip ${typeFilter === type ? 'active' : ''}`}
|
||||
onClick={() => setTypeFilter(type)}
|
||||
>
|
||||
{type.charAt(0).toUpperCase() + type.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="activity-filter-row">
|
||||
<div className="activity-range-shell">
|
||||
<IonSegment
|
||||
value={range}
|
||||
className="activity-range-segment"
|
||||
onIonChange={(event) =>
|
||||
setRange((event.detail.value as ActivityFilterRange) ?? '30')
|
||||
}
|
||||
>
|
||||
<IonSegmentButton value="all">
|
||||
<IonLabel>All</IonLabel>
|
||||
</IonSegmentButton>
|
||||
<IonSegmentButton value="30">
|
||||
<IonLabel>30 days</IonLabel>
|
||||
</IonSegmentButton>
|
||||
<IonSegmentButton value="90">
|
||||
<IonLabel>90 days</IonLabel>
|
||||
</IonSegmentButton>
|
||||
</IonSegment>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p style={{ margin: '0 20px 12px', color: '#dc2626', fontSize: 13 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="activity-grouped-list">
|
||||
{[1, 2, 3].map((item) => (
|
||||
<div key={item} className="activity-list-item">
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 12,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '70%', height: 15 }}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '45%', height: 12 }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : filteredEvents.length === 0 ? (
|
||||
<div className="empty-state-card">
|
||||
<IonIcon icon={fileTrayOutline} className="esc-icon" />
|
||||
<h2 className="esc-title">
|
||||
{typeFilter === 'all'
|
||||
? 'No activity in this range'
|
||||
: 'No matching activity'}
|
||||
</h2>
|
||||
<p className="esc-msg">
|
||||
Try a longer date range or switch the activity filter.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
Object.entries(groups).map(([label, items]) => (
|
||||
<div key={label}>
|
||||
<p className="activity-date-group-label">{label}</p>
|
||||
<div className="activity-grouped-list">
|
||||
{items.map((item) => (
|
||||
<ActivityListItem
|
||||
key={item.id}
|
||||
id={item.id}
|
||||
eventType={item.event_type}
|
||||
title={item.title}
|
||||
subtitle={item.subtitle}
|
||||
amount={item.amount ?? undefined}
|
||||
statusText={item.metadata.statusText}
|
||||
statusTone={getActivityStatusTone(
|
||||
item.event_type,
|
||||
item.metadata.statusText
|
||||
)}
|
||||
avatarLabel={item.metadata.avatarLabel}
|
||||
avatarTone={item.metadata.avatarTone}
|
||||
avatarImage={item.metadata.avatarImage}
|
||||
onClick={() => handleOpenEvent(item)}
|
||||
onStatusClick={() => handleOpenEvent(item)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default ActivityPage;
|
||||
@@ -0,0 +1,355 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { IonPage, IonContent, useIonViewWillEnter } from '@ionic/react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
// import { useAuth } from '../contexts/AuthContext';
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';
|
||||
import AuthFormFields from '../components/AuthFormFields';
|
||||
import SocialAuthButton from '../components/SocialAuthButton';
|
||||
import '../styles/auth.css';
|
||||
|
||||
const AuthPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
// const location = useLocation();
|
||||
// const { user, profile, profileStatus } = useAuth();
|
||||
const signInTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// const navigatedForUserRef = useRef<string | null>(null);
|
||||
|
||||
const [tab, setTab] = useState<'login' | 'register'>('login');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (!user) {
|
||||
// navigatedForUserRef.current = null;
|
||||
// return;
|
||||
// }
|
||||
|
||||
// if (signInTimeoutRef.current) {
|
||||
// clearTimeout(signInTimeoutRef.current);
|
||||
// signInTimeoutRef.current = null;
|
||||
// }
|
||||
|
||||
// if (location.pathname !== '/auth' || profileStatus === 'loading') return;
|
||||
// if (navigatedForUserRef.current === user.id) return;
|
||||
|
||||
// navigatedForUserRef.current = user.id;
|
||||
// setLoading(false);
|
||||
|
||||
// if (
|
||||
// !profile ||
|
||||
// !profile.first_name ||
|
||||
// !profile.last_name ||
|
||||
// !profile.phone ||
|
||||
// !profile.country_of_residence
|
||||
// ) {
|
||||
// history.replace('/setup-profile');
|
||||
// } else {
|
||||
// history.replace('/home');
|
||||
// }
|
||||
// }, [user, profile, profileStatus, location.pathname, history]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (signInTimeoutRef.current) {
|
||||
clearTimeout(signInTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setTab('login');
|
||||
setError(null);
|
||||
});
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setError(msg);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const handleTabChange = (nextTab: 'login' | 'register') => {
|
||||
setTab(nextTab);
|
||||
setError(null);
|
||||
if (nextTab === 'login') {
|
||||
setConfirmPassword('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSignUp = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
|
||||
if (!normalizedEmail) {
|
||||
showError('Please enter your email address.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
showError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const { error: signUpError } = await supabase.auth.signUp({
|
||||
email: normalizedEmail,
|
||||
password,
|
||||
});
|
||||
|
||||
if (signUpError) {
|
||||
showError(signUpError.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
localStorage.setItem('kumusha_pending_verification_email', normalizedEmail);
|
||||
setLoading(false);
|
||||
history.replace('/verify-email', { state: { email: normalizedEmail } });
|
||||
};
|
||||
|
||||
const handleSignIn = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
|
||||
if (signInTimeoutRef.current) {
|
||||
clearTimeout(signInTimeoutRef.current);
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
signInTimeoutRef.current = setTimeout(() => {
|
||||
setLoading(false);
|
||||
showError(
|
||||
'Sign in is taking too long. Please check your connection and try again.'
|
||||
);
|
||||
}, 12000);
|
||||
|
||||
const { error: signInError } = await supabase.auth.signInWithPassword({
|
||||
email: normalizedEmail,
|
||||
password,
|
||||
});
|
||||
|
||||
if (signInError) {
|
||||
if (signInTimeoutRef.current) {
|
||||
clearTimeout(signInTimeoutRef.current);
|
||||
signInTimeoutRef.current = null;
|
||||
}
|
||||
|
||||
if (signInError.message.toLowerCase().includes('email not confirmed')) {
|
||||
await supabase.auth.resend({ type: 'signup', email: normalizedEmail });
|
||||
localStorage.setItem(
|
||||
'kumusha_pending_verification_email',
|
||||
normalizedEmail
|
||||
);
|
||||
history.push('/verify-email', {
|
||||
state: { email: normalizedEmail, resent: true },
|
||||
});
|
||||
} else {
|
||||
showError(signInError.message);
|
||||
}
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
// Success: keep loading=true, wait for user/profile effect or timeout fallback
|
||||
};
|
||||
|
||||
const handleGoogleSignIn = async () => {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
showError(
|
||||
'Google Sign-In is only available in the native app. Use email to sign in here.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await FirebaseAuthentication.signInWithGoogle();
|
||||
if (!result.credential?.idToken) throw new Error('Missing ID token');
|
||||
|
||||
const { error } = await supabase.auth.signInWithIdToken({
|
||||
provider: 'google',
|
||||
token: result.credential.idToken,
|
||||
});
|
||||
if (error) throw error;
|
||||
// keep loading true
|
||||
} catch (err: any) {
|
||||
showError(err.message || 'Google sign in failed');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAppleSignIn = async () => {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
showError(
|
||||
'Apple Sign-In is only available in the native app. Use email to sign in here.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await FirebaseAuthentication.signInWithApple({
|
||||
skipNativeAuth: true,
|
||||
});
|
||||
if (!result.credential?.idToken || !result.credential?.nonce)
|
||||
throw new Error('Missing token or nonce');
|
||||
|
||||
const displayName = result.user?.displayName ?? null;
|
||||
|
||||
const { data, error } = await supabase.auth.signInWithIdToken({
|
||||
provider: 'apple',
|
||||
token: result.credential.idToken,
|
||||
nonce: result.credential.nonce,
|
||||
});
|
||||
if (error) throw error;
|
||||
|
||||
if (displayName && data.user) {
|
||||
const firstName = displayName.split(' ')[0] || 'Apple';
|
||||
const lastName = displayName.split(' ').slice(1).join(' ') || 'User';
|
||||
|
||||
await supabase.from('profiles').upsert(
|
||||
{
|
||||
id: data.user.id,
|
||||
full_name: displayName,
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
phone: 'Pending',
|
||||
country_of_residence: 'Pending',
|
||||
},
|
||||
{ onConflict: 'id' }
|
||||
);
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.message || 'Apple sign in failed');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage>
|
||||
<IonContent
|
||||
className="auth-content"
|
||||
fullscreen
|
||||
style={{
|
||||
'--background':
|
||||
'linear-gradient(180deg, #fafafa 0%, #f6f1ff 52%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '0px',
|
||||
'--padding-bottom': '0px',
|
||||
}}
|
||||
>
|
||||
<div className="auth-shell auth-shell--centered">
|
||||
<div className="auth-brand-block">
|
||||
<p className="auth-eyebrow">Kumusha</p>
|
||||
<h1 className="auth-heading">Take care of home from anywhere</h1>
|
||||
<p className="auth-subtitle">
|
||||
Support your family with trusted vouchers, airtime, medication,
|
||||
and electricity in just a few taps.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="auth-card auth-card--elevated">
|
||||
<div
|
||||
className="auth-mode-toggle"
|
||||
role="tablist"
|
||||
aria-label="Authentication mode"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={`auth-toggle-pill ${tab === 'login' ? 'active' : 'inactive'}`}
|
||||
onClick={() => handleTabChange('login')}
|
||||
disabled={loading}
|
||||
>
|
||||
Sign In
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`auth-toggle-pill ${tab === 'register' ? 'active' : 'inactive'}`}
|
||||
onClick={() => handleTabChange('register')}
|
||||
disabled={loading}
|
||||
>
|
||||
Sign Up
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form
|
||||
className="auth-form-stack"
|
||||
onSubmit={tab === 'login' ? handleSignIn : handleSignUp}
|
||||
>
|
||||
<AuthFormFields
|
||||
mode={tab}
|
||||
email={email}
|
||||
password={password}
|
||||
confirmPassword={confirmPassword}
|
||||
onEmailChange={setEmail}
|
||||
onPasswordChange={setPassword}
|
||||
onConfirmPasswordChange={setConfirmPassword}
|
||||
disabled={loading}
|
||||
/>
|
||||
|
||||
{error ? (
|
||||
<div className="auth-inline-message">{error}</div>
|
||||
) : null}
|
||||
|
||||
{tab === 'login' && (
|
||||
<div className="auth-meta-row">
|
||||
<span className="auth-meta-hint">Secure email sign in</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => history.push('/forgot-password')}
|
||||
className="auth-link-button"
|
||||
disabled={loading}
|
||||
>
|
||||
Forgot password?
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="auth-submit-btn"
|
||||
disabled={
|
||||
loading ||
|
||||
!email ||
|
||||
!password ||
|
||||
(tab === 'register' && !confirmPassword)
|
||||
}
|
||||
>
|
||||
{loading
|
||||
? 'Please wait...'
|
||||
: tab === 'login'
|
||||
? 'Sign In'
|
||||
: 'Create Account'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="auth-divider">
|
||||
<span>Or continue with</span>
|
||||
</div>
|
||||
|
||||
<div className="auth-social-buttons">
|
||||
<SocialAuthButton
|
||||
provider="google"
|
||||
label="Google"
|
||||
onClick={handleGoogleSignIn}
|
||||
disabled={loading}
|
||||
/>
|
||||
<SocialAuthButton
|
||||
provider="apple"
|
||||
label="Apple"
|
||||
onClick={handleAppleSignIn}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default AuthPage;
|
||||
@@ -0,0 +1,344 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonInput,
|
||||
IonPage,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from '@ionic/react';
|
||||
import { chevronBackOutline } from 'ionicons/icons';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import AvatarPicker from '../components/AvatarPicker';
|
||||
import '../styles/profile.css';
|
||||
|
||||
type Profile = {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone: string;
|
||||
country_of_residence: string;
|
||||
avatar_path: string | null;
|
||||
};
|
||||
|
||||
type PreviewProfilePayload = {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone: string;
|
||||
country_of_residence: string;
|
||||
avatar_url: string | null;
|
||||
notification_push_enabled: boolean;
|
||||
notification_email_enabled: boolean;
|
||||
notification_sms_enabled: boolean;
|
||||
};
|
||||
|
||||
const PREVIEW_PROFILE_STORAGE_KEY = 'kumusha-preview-profile';
|
||||
|
||||
const getPreviewProfilePayload = (): PreviewProfilePayload => {
|
||||
const fallback: PreviewProfilePayload = {
|
||||
first_name: 'Sarah',
|
||||
last_name: 'Moyo',
|
||||
phone: '+44 7123 456789',
|
||||
country_of_residence: 'United Kingdom',
|
||||
avatar_url: null,
|
||||
notification_push_enabled: true,
|
||||
notification_email_enabled: true,
|
||||
notification_sms_enabled: false,
|
||||
};
|
||||
|
||||
try {
|
||||
const saved = localStorage.getItem(PREVIEW_PROFILE_STORAGE_KEY);
|
||||
return saved ? { ...fallback, ...JSON.parse(saved) } : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const savePreviewProfilePayload = (payload: PreviewProfilePayload) => {
|
||||
localStorage.setItem(PREVIEW_PROFILE_STORAGE_KEY, JSON.stringify(payload));
|
||||
};
|
||||
|
||||
const EditProfilePage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user, refreshProfile } = useAuth();
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [country, setCountry] = useState('');
|
||||
const [avatarPath, setAvatarPath] = useState<string | null>(null);
|
||||
const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
|
||||
const [avatarFile, setAvatarFile] = useState<File | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void loadProfile();
|
||||
}, [user?.id]);
|
||||
|
||||
const showError = (message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const loadProfile = async () => {
|
||||
setLoading(true);
|
||||
|
||||
if (!user) {
|
||||
const preview = getPreviewProfilePayload();
|
||||
setFirstName(preview.first_name);
|
||||
setLastName(preview.last_name);
|
||||
setPhone(preview.phone);
|
||||
setCountry(preview.country_of_residence);
|
||||
setAvatarPath(null);
|
||||
setAvatarPreview(preview.avatar_url);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { data, error: loadError } = await supabase
|
||||
.from('profiles')
|
||||
.select('id,first_name,last_name,phone,country_of_residence,avatar_path')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
|
||||
if (loadError || !data) {
|
||||
showError(loadError?.message ?? 'Profile not found');
|
||||
const preview = getPreviewProfilePayload();
|
||||
setFirstName(preview.first_name);
|
||||
setLastName(preview.last_name);
|
||||
setPhone(preview.phone);
|
||||
setCountry(preview.country_of_residence);
|
||||
setAvatarPath(null);
|
||||
setAvatarPreview(preview.avatar_url);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const profile = data as Profile;
|
||||
setFirstName(profile.first_name ?? '');
|
||||
setLastName(profile.last_name ?? '');
|
||||
setPhone(profile.phone ?? '');
|
||||
setCountry(profile.country_of_residence ?? '');
|
||||
setAvatarPath(profile.avatar_path);
|
||||
if (profile.avatar_path) {
|
||||
const { data: signed } = await supabase.storage
|
||||
.from('avatars')
|
||||
.createSignedUrl(profile.avatar_path, 3600);
|
||||
setAvatarPreview(signed?.signedUrl ?? null);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleGoBack = () => {
|
||||
if (history.length > 1) {
|
||||
history.goBack();
|
||||
} else {
|
||||
history.replace('/profile');
|
||||
}
|
||||
};
|
||||
|
||||
const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
setAvatarFile(file);
|
||||
setAvatarPreview(
|
||||
typeof reader.result === 'string' ? reader.result : null
|
||||
);
|
||||
};
|
||||
reader.onerror = () => {
|
||||
showError(
|
||||
'We could not preview that image. Please choose another photo.'
|
||||
);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
const cleanFirstName = firstName.trim();
|
||||
const cleanLastName = lastName.trim();
|
||||
const cleanPhone = phone.trim();
|
||||
const cleanCountry = country.trim();
|
||||
|
||||
if (!cleanFirstName || !cleanLastName || !cleanPhone || !cleanCountry) {
|
||||
showError('Please complete all fields');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
setSaving(true);
|
||||
savePreviewProfilePayload({
|
||||
...getPreviewProfilePayload(),
|
||||
first_name: cleanFirstName,
|
||||
last_name: cleanLastName,
|
||||
phone: cleanPhone,
|
||||
country_of_residence: cleanCountry,
|
||||
avatar_url: avatarPreview,
|
||||
});
|
||||
setSaving(false);
|
||||
history.replace('/profile');
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
let nextAvatarPath = avatarPath;
|
||||
if (avatarFile) {
|
||||
const extension = avatarFile.name.split('.').pop() || 'jpg';
|
||||
nextAvatarPath = `${user.id}/${Date.now()}.${extension}`;
|
||||
const { error: uploadError } = await supabase.storage
|
||||
.from('avatars')
|
||||
.upload(nextAvatarPath, avatarFile);
|
||||
if (uploadError) {
|
||||
showError(uploadError.message);
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('profiles')
|
||||
.update({
|
||||
first_name: cleanFirstName,
|
||||
last_name: cleanLastName,
|
||||
full_name: `${cleanFirstName} ${cleanLastName}`,
|
||||
phone: cleanPhone,
|
||||
country_of_residence: cleanCountry,
|
||||
avatar_path: nextAvatarPath,
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', user.id);
|
||||
|
||||
if (updateError) {
|
||||
showError(updateError.message);
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await refreshProfile();
|
||||
setSaving(false);
|
||||
history.replace('/profile');
|
||||
};
|
||||
|
||||
const initials = `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--border-width': '0px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonButtons slot="start">
|
||||
<IonButton
|
||||
className="profile-back-button"
|
||||
fill="clear"
|
||||
onClick={handleGoBack}
|
||||
aria-label="Go back"
|
||||
style={
|
||||
{
|
||||
'--profile-action-accent': '#6d28d9',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: 18, fontWeight: 700 }}>
|
||||
Edit profile
|
||||
</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
className="edit-profile-shell"
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--padding-top': '8px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="edit-profile-card">
|
||||
<AvatarPicker
|
||||
previewUrl={avatarPreview}
|
||||
onFileChange={handleAvatarChange}
|
||||
initials={initials || undefined}
|
||||
disabled={loading || saving}
|
||||
/>
|
||||
<IonInput
|
||||
className="epc-field"
|
||||
type="text"
|
||||
label="First name"
|
||||
labelPlacement="floating"
|
||||
placeholder="e.g. Tadiwa"
|
||||
value={firstName}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) => setFirstName(event.detail.value ?? '')}
|
||||
/>
|
||||
<IonInput
|
||||
className="epc-field"
|
||||
type="text"
|
||||
label="Last name"
|
||||
labelPlacement="floating"
|
||||
placeholder="e.g. Moyo"
|
||||
value={lastName}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) => setLastName(event.detail.value ?? '')}
|
||||
/>
|
||||
<IonInput
|
||||
className="epc-field"
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
label="Mobile number"
|
||||
labelPlacement="floating"
|
||||
placeholder="e.g. +44 7123 456789"
|
||||
value={phone}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) => setPhone(event.detail.value ?? '')}
|
||||
/>
|
||||
<IonInput
|
||||
className="epc-field"
|
||||
type="text"
|
||||
label="Country of residence"
|
||||
labelPlacement="floating"
|
||||
placeholder="e.g. United Kingdom"
|
||||
value={country}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) => setCountry(event.detail.value ?? '')}
|
||||
/>
|
||||
{error && (
|
||||
<p style={{ margin: 0, color: '#dc2626', fontSize: 13 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<IonButton
|
||||
type="submit"
|
||||
expand="block"
|
||||
className="epc-save-btn"
|
||||
disabled={loading || saving}
|
||||
>
|
||||
{saving ? 'Saving...' : 'Save profile'}
|
||||
</IonButton>
|
||||
</form>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditProfilePage;
|
||||
@@ -0,0 +1,207 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonInput,
|
||||
IonPage,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from '@ionic/react';
|
||||
import { chevronBackOutline, keyOutline } from 'ionicons/icons';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import '../styles/auth.css';
|
||||
|
||||
const ForgotPasswordPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const [email, setEmail] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
|
||||
const showMessage = (message: string, kind: 'error' | 'status') => {
|
||||
if (kind === 'error') {
|
||||
setError(message);
|
||||
setStatus(null);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
} else {
|
||||
setStatus(message);
|
||||
setError(null);
|
||||
setTimeout(() => setStatus(null), 4000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
if (!normalizedEmail) {
|
||||
showMessage('Enter your email address to continue', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setStatus(null);
|
||||
|
||||
const { error: resetError } =
|
||||
await supabase.auth.resetPasswordForEmail(normalizedEmail);
|
||||
|
||||
if (resetError) {
|
||||
showMessage(resetError.message, 'error');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
showMessage('Reset code sent', 'status');
|
||||
setLoading(false);
|
||||
history.push('/verify-reset', { state: { email: normalizedEmail } });
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar
|
||||
style={
|
||||
{
|
||||
'--background': 'transparent',
|
||||
'--border-width': '0px',
|
||||
'--color': '#111827',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonButtons slot="start">
|
||||
<IonButton
|
||||
fill="clear"
|
||||
onClick={() => history.goBack()}
|
||||
style={
|
||||
{
|
||||
'--color': '#111827',
|
||||
'--border-radius': '12px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
aria-label="Go back"
|
||||
>
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: '18px', fontWeight: 700 }}>
|
||||
Reset password
|
||||
</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
className="auth-content"
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '0px',
|
||||
'--padding-bottom': '0px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<div className="auth-shell">
|
||||
<div
|
||||
className="auth-intro-block"
|
||||
style={{ alignItems: 'flex-start', textAlign: 'left' }}
|
||||
>
|
||||
<div className="auth-icon-container">
|
||||
<IonIcon icon={keyOutline} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="auth-intro-heading">Forgot your password?</h1>
|
||||
<p className="auth-intro-body" style={{ marginTop: '8px' }}>
|
||||
Enter your account email and we'll send you a 6-digit reset
|
||||
code.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="auth-form-card"
|
||||
style={{ gap: '16px' }}
|
||||
>
|
||||
<IonInput
|
||||
type="email"
|
||||
label="Email address"
|
||||
labelPlacement="floating"
|
||||
value={email}
|
||||
onIonInput={(event) => setEmail(event.detail.value ?? '')}
|
||||
disabled={loading}
|
||||
placeholder="you@example.com"
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--border-radius': '12px',
|
||||
'--padding-start': '14px',
|
||||
'--padding-end': '14px',
|
||||
'--highlight-color-focused': '#6d28d9',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p className="auth-status-text" style={{ color: '#dc2626' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{status && (
|
||||
<p className="auth-status-text" style={{ color: '#16a34a' }}>
|
||||
{status}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<IonButton
|
||||
type="submit"
|
||||
expand="block"
|
||||
disabled={loading || !email.trim()}
|
||||
style={
|
||||
{
|
||||
'--background': '#6d28d9',
|
||||
'--background-activated': '#5b21b6',
|
||||
'--border-radius': '999px',
|
||||
'--box-shadow': 'none',
|
||||
'--color': '#ffffff',
|
||||
height: '52px',
|
||||
fontSize: '15px',
|
||||
fontWeight: 700,
|
||||
marginTop: '4px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
{loading ? 'Sending code...' : 'Send reset code'}
|
||||
</IonButton>
|
||||
</form>
|
||||
|
||||
<div className="auth-footer">
|
||||
<p className="auth-footer-text">
|
||||
Remembered it?{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="auth-footer-link"
|
||||
onClick={() => history.replace('/auth')}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
padding: 0,
|
||||
}}
|
||||
disabled={loading}
|
||||
>
|
||||
Back to sign in
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default ForgotPasswordPage;
|
||||
@@ -0,0 +1,30 @@
|
||||
import React from "react";
|
||||
import {
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonPage,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from "@ionic/react";
|
||||
|
||||
const Home: React.FC = () => (
|
||||
<IonPage>
|
||||
<IonHeader translucent className="home-header">
|
||||
<IonToolbar className="home-toolbar">
|
||||
<IonTitle>Home</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
<IonContent fullscreen className="home-content">
|
||||
<div className="home-shell minimal-home-shell">
|
||||
<section className="minimal-welcome-card subtle-welcome-card">
|
||||
<h1>Welcome to your new app</h1>
|
||||
<p className="minimal-subtitle">
|
||||
Chat with the assistant to start adding features and pages
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
|
||||
export default Home;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,480 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
IonActionSheet,
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonSkeletonText,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import {
|
||||
chevronBackOutline,
|
||||
chevronForwardOutline,
|
||||
ellipsisHorizontal,
|
||||
flashOutline,
|
||||
medkitOutline,
|
||||
notificationsOutline,
|
||||
phonePortraitOutline,
|
||||
receiptOutline,
|
||||
trashOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import basketIcon from '../assets/basket.png';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import '../styles/activity.css';
|
||||
import '../styles/recipients.css';
|
||||
|
||||
type ServiceType =
|
||||
| 'grocery'
|
||||
| 'medication'
|
||||
| 'airtime'
|
||||
| 'electricity'
|
||||
| 'support';
|
||||
|
||||
type NotificationRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
body: string;
|
||||
priority: string;
|
||||
type: string;
|
||||
read_at: string | null;
|
||||
created_at: string;
|
||||
order_id: string | null;
|
||||
voucher_id: string | null;
|
||||
support_orders: { service_type: string | null } | null;
|
||||
vouchers: { voucher_type: string | null } | null;
|
||||
};
|
||||
|
||||
const previewUserId = '00000000-0000-0000-0000-000000000000';
|
||||
|
||||
const notificationSelect =
|
||||
'id,title,body,priority,type,read_at,created_at,order_id,voucher_id';
|
||||
|
||||
const normalizeServiceType = (value?: string | null): ServiceType => {
|
||||
const normalized = value?.toLowerCase() ?? '';
|
||||
if (normalized.includes('med')) return 'medication';
|
||||
if (normalized.includes('air') || normalized.includes('data'))
|
||||
return 'airtime';
|
||||
if (normalized.includes('electric')) return 'electricity';
|
||||
if (normalized.includes('grocery') || normalized.includes('voucher')) {
|
||||
return 'grocery';
|
||||
}
|
||||
return 'support';
|
||||
};
|
||||
|
||||
const inferServiceType = (notification: NotificationRow): ServiceType => {
|
||||
const joinedType = notification.support_orders?.service_type;
|
||||
if (joinedType) return normalizeServiceType(joinedType);
|
||||
|
||||
const voucherType = notification.vouchers?.voucher_type;
|
||||
if (voucherType) return normalizeServiceType(voucherType);
|
||||
|
||||
return normalizeServiceType(
|
||||
`${notification.title} ${notification.body} ${notification.type}`
|
||||
);
|
||||
};
|
||||
|
||||
const getServicePresentation = (serviceType: ServiceType) => {
|
||||
if (serviceType === 'medication') {
|
||||
return {
|
||||
className: 'notification-service-medication',
|
||||
icon: medkitOutline,
|
||||
};
|
||||
}
|
||||
|
||||
if (serviceType === 'airtime') {
|
||||
return {
|
||||
className: 'notification-service-airtime',
|
||||
icon: phonePortraitOutline,
|
||||
};
|
||||
}
|
||||
|
||||
if (serviceType === 'electricity') {
|
||||
return {
|
||||
className: 'notification-service-electricity',
|
||||
icon: flashOutline,
|
||||
};
|
||||
}
|
||||
|
||||
if (serviceType === 'grocery') {
|
||||
return {
|
||||
className: 'notification-service-grocery',
|
||||
iconImageSrc: basketIcon,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
className: 'notification-service-support',
|
||||
icon: receiptOutline,
|
||||
};
|
||||
};
|
||||
|
||||
const NotificationsPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user } = useAuth();
|
||||
const isPreviewMode = !user;
|
||||
const [notifications, setNotifications] = useState<NotificationRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showActions, setShowActions] = useState(false);
|
||||
|
||||
const showError = useCallback((message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
}, []);
|
||||
|
||||
const loadNotifications = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const activeUserId = user?.id ?? previewUserId;
|
||||
let { data, error: loadError } = await supabase
|
||||
.from('notifications')
|
||||
.select(notificationSelect)
|
||||
.eq('user_id', activeUserId)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (!loadError && user?.id && (data ?? []).length === 0) {
|
||||
const previewResult = await supabase
|
||||
.from('notifications')
|
||||
.select(notificationSelect)
|
||||
.eq('user_id', previewUserId)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
data = previewResult.data;
|
||||
loadError = previewResult.error;
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
showError(loadError.message);
|
||||
setNotifications([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const baseNotifications = (data ?? []) as unknown as NotificationRow[];
|
||||
const orderIds = Array.from(
|
||||
new Set(
|
||||
baseNotifications
|
||||
.map((notification) => notification.order_id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
)
|
||||
);
|
||||
const voucherIds = Array.from(
|
||||
new Set(
|
||||
baseNotifications
|
||||
.map((notification) => notification.voucher_id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
)
|
||||
);
|
||||
|
||||
const [ordersResult, vouchersResult] = await Promise.all([
|
||||
orderIds.length > 0
|
||||
? supabase
|
||||
.from('support_orders')
|
||||
.select('id,service_type')
|
||||
.in('id', orderIds)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
voucherIds.length > 0
|
||||
? supabase
|
||||
.from('vouchers')
|
||||
.select('id,voucher_type')
|
||||
.in('id', voucherIds)
|
||||
: Promise.resolve({ data: [], error: null }),
|
||||
]);
|
||||
|
||||
if (ordersResult.error || vouchersResult.error) {
|
||||
console.warn(
|
||||
'[NotificationsPage] Notification detail lookup failed',
|
||||
ordersResult.error ?? vouchersResult.error
|
||||
);
|
||||
}
|
||||
|
||||
const serviceTypesByOrderId = new Map(
|
||||
(
|
||||
(ordersResult.data ?? []) as {
|
||||
id: string;
|
||||
service_type: string | null;
|
||||
}[]
|
||||
).map((order) => [order.id, order.service_type])
|
||||
);
|
||||
const voucherTypesById = new Map(
|
||||
(
|
||||
(vouchersResult.data ?? []) as {
|
||||
id: string;
|
||||
voucher_type: string | null;
|
||||
}[]
|
||||
).map((voucher) => [voucher.id, voucher.voucher_type])
|
||||
);
|
||||
|
||||
setNotifications(
|
||||
baseNotifications.map((notification) => ({
|
||||
...notification,
|
||||
support_orders: notification.order_id
|
||||
? {
|
||||
service_type:
|
||||
serviceTypesByOrderId.get(notification.order_id) ?? null,
|
||||
}
|
||||
: null,
|
||||
vouchers: notification.voucher_id
|
||||
? {
|
||||
voucher_type:
|
||||
voucherTypesById.get(notification.voucher_id) ?? null,
|
||||
}
|
||||
: null,
|
||||
}))
|
||||
);
|
||||
} catch (loadCrash) {
|
||||
console.error(
|
||||
'[NotificationsPage] Failed to load notifications',
|
||||
loadCrash
|
||||
);
|
||||
showError('Notifications could not be loaded. Pull back and try again.');
|
||||
setNotifications([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [showError, user?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadNotifications();
|
||||
}, [loadNotifications]);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
void loadNotifications();
|
||||
});
|
||||
|
||||
const markRead = async (notificationId: string) => {
|
||||
const readAt = new Date().toISOString();
|
||||
setNotifications((current) =>
|
||||
current.map((item) =>
|
||||
item.id === notificationId ? { ...item, read_at: readAt } : item
|
||||
)
|
||||
);
|
||||
|
||||
if (isPreviewMode) {
|
||||
const { error: updateError } = await supabase
|
||||
.from('notifications')
|
||||
.update({ read_at: readAt })
|
||||
.eq('id', notificationId)
|
||||
.eq('user_id', previewUserId);
|
||||
|
||||
if (updateError) {
|
||||
showError(updateError.message);
|
||||
void loadNotifications();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { error: invokeError } = await supabase.functions.invoke(
|
||||
'mark-notification-read',
|
||||
{
|
||||
body: { notificationId },
|
||||
}
|
||||
);
|
||||
if (invokeError) {
|
||||
showError(invokeError.message);
|
||||
void loadNotifications();
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenNotification = async (notification: NotificationRow) => {
|
||||
if (!notification.read_at) {
|
||||
await markRead(notification.id);
|
||||
}
|
||||
if (notification.order_id) {
|
||||
history.push(`/orders/${notification.order_id}`, {
|
||||
parentRoot: '/profile',
|
||||
});
|
||||
} else if (notification.voucher_id) {
|
||||
history.push(`/voucher/${notification.voucher_id}`, {
|
||||
parentRoot: '/profile',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearNotifications = async () => {
|
||||
const targetUserId = user?.id ?? previewUserId;
|
||||
|
||||
const { error: deleteError } = await supabase
|
||||
.from('notifications')
|
||||
.delete()
|
||||
.eq('user_id', targetUserId);
|
||||
|
||||
if (deleteError) {
|
||||
showError(deleteError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
setNotifications([]);
|
||||
setShowActions(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--border-width': '0px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonButtons slot="start">
|
||||
<IonButton
|
||||
fill="clear"
|
||||
onClick={() =>
|
||||
history.length > 1
|
||||
? history.goBack()
|
||||
: history.replace('/profile')
|
||||
}
|
||||
aria-label="Go back"
|
||||
>
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: 18, fontWeight: 700 }}>
|
||||
Notifications
|
||||
</IonTitle>
|
||||
<IonButtons slot="end">
|
||||
<IonButton
|
||||
fill="clear"
|
||||
onClick={() => setShowActions(true)}
|
||||
aria-label="Notification actions"
|
||||
disabled={loading || notifications.length === 0}
|
||||
>
|
||||
<IonIcon icon={ellipsisHorizontal} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--padding-top': '8px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonActionSheet
|
||||
isOpen={showActions}
|
||||
onDidDismiss={() => setShowActions(false)}
|
||||
header="Notifications"
|
||||
cssClass="app-action-sheet"
|
||||
buttons={[
|
||||
{
|
||||
text: 'Clear notifications',
|
||||
role: 'destructive',
|
||||
icon: trashOutline,
|
||||
handler: () => {
|
||||
void handleClearNotifications();
|
||||
},
|
||||
},
|
||||
{
|
||||
text: 'Cancel',
|
||||
role: 'cancel',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{error && (
|
||||
<p style={{ margin: '12px 20px', color: '#dc2626', fontSize: 13 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="notifications-list-card">
|
||||
{[1, 2, 3].map((item) => (
|
||||
<div className="notification-row" key={item}>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 12,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '65%', height: 15 }}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '90%', height: 12 }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : notifications.length === 0 ? (
|
||||
<div className="empty-state-card" style={{ marginTop: 20 }}>
|
||||
<IonIcon icon={notificationsOutline} className="esc-icon" />
|
||||
<h2 className="esc-title">No notifications yet</h2>
|
||||
<p className="esc-msg">
|
||||
Important payment and voucher updates will appear here.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="notifications-list-card">
|
||||
{notifications.map((notification) => {
|
||||
const service = getServicePresentation(
|
||||
inferServiceType(notification)
|
||||
);
|
||||
|
||||
return (
|
||||
<button
|
||||
key={notification.id}
|
||||
type="button"
|
||||
className="notification-row"
|
||||
onClick={() => handleOpenNotification(notification)}
|
||||
style={{
|
||||
width: '100%',
|
||||
border: 'none',
|
||||
background: 'transparent',
|
||||
textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className={`nr-status-dot ${notification.read_at ? 'is-read' : 'is-unread'}`}
|
||||
/>
|
||||
<div
|
||||
className={`nr-icon-box ${service.className} ${notification.read_at ? 'is-read' : ''}`}
|
||||
>
|
||||
{service.iconImageSrc ? (
|
||||
<img src={service.iconImageSrc} alt="" />
|
||||
) : (
|
||||
<IonIcon icon={service.icon} />
|
||||
)}
|
||||
</div>
|
||||
<div className="nr-content">
|
||||
<h3 className="nr-title">{notification.title}</h3>
|
||||
<p className="nr-body">{notification.body}</p>
|
||||
<span className="nr-time">
|
||||
{new Date(notification.created_at).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<IonIcon
|
||||
icon={chevronForwardOutline}
|
||||
className="nr-link-icon"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotificationsPage;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,253 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
IonContent,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonRefresher,
|
||||
IonRefresherContent,
|
||||
IonSkeletonText,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import { receiptOutline } from 'ionicons/icons';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import ListSearchRow from '../components/ListSearchRow';
|
||||
import OrderSummaryCard, { OrderSummary } from '../components/OrderSummaryCard';
|
||||
import { formatMoney } from '../utils/formatMoney';
|
||||
import '../styles/support.css';
|
||||
import '../styles/recipients.css';
|
||||
|
||||
type OrderRow = {
|
||||
id: string;
|
||||
service_type: string;
|
||||
amount: number;
|
||||
status: string;
|
||||
created_at: string;
|
||||
recipient_id: string;
|
||||
merchant_id: string | null;
|
||||
recipients?: {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
photo_path: string | null;
|
||||
} | null;
|
||||
merchants?: { name: string; branch_name: string | null } | null;
|
||||
};
|
||||
|
||||
const statusFilters = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'paid', label: 'Paid' },
|
||||
{ value: 'ready_for_redemption', label: 'Ready' },
|
||||
{ value: 'redeemed', label: 'Redeemed' },
|
||||
{ value: 'delivered', label: 'Delivered' },
|
||||
{ value: 'expired', label: 'Expired' },
|
||||
];
|
||||
|
||||
const OrdersPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user } = useAuth();
|
||||
const [orders, setOrders] = useState<OrderSummary[]>([]);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [activeStatus, setActiveStatus] = useState('all');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
void loadOrders();
|
||||
});
|
||||
|
||||
const showError = (message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const loadOrders = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const { data, error: ordersError } = await supabase
|
||||
.from('support_orders')
|
||||
.select(
|
||||
'id,service_type,amount,status,created_at,recipient_id,merchant_id,recipients(first_name,last_name,photo_path),merchants(name,branch_name)'
|
||||
)
|
||||
.eq('user_id', user.id)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (ordersError) {
|
||||
showError(ordersError.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = (data ?? []) as unknown as OrderRow[];
|
||||
const normalized = await Promise.all(
|
||||
rows.map(async (row) => {
|
||||
const recipientName = row.recipients
|
||||
? `${row.recipients.first_name} ${row.recipients.last_name}`
|
||||
: 'Loved one';
|
||||
const avatarUrl = row.recipients?.photo_path
|
||||
? ((
|
||||
await supabase.storage
|
||||
.from('recipient-photos')
|
||||
.createSignedUrl(row.recipients.photo_path, 3600)
|
||||
).data?.signedUrl ?? null)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
recipientName,
|
||||
serviceType:
|
||||
row.service_type.charAt(0).toUpperCase() +
|
||||
row.service_type.slice(1),
|
||||
merchantName: row.merchants
|
||||
? `${row.merchants.name}${row.merchants.branch_name ? ` — ${row.merchants.branch_name}` : ''}`
|
||||
: undefined,
|
||||
amount: Number(row.amount ?? 0),
|
||||
amountLabel: formatMoney(Number(row.amount ?? 0)),
|
||||
status: row.status,
|
||||
createdAt: row.created_at,
|
||||
avatarUrl,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
setOrders(normalized);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const visibleOrders = useMemo(() => {
|
||||
const query = searchTerm.trim().toLowerCase();
|
||||
return orders.filter((order) => {
|
||||
const statusMatch =
|
||||
activeStatus === 'all' || order.status === activeStatus;
|
||||
const searchMatch =
|
||||
!query ||
|
||||
[
|
||||
order.recipientName,
|
||||
order.serviceType,
|
||||
order.merchantName,
|
||||
order.status,
|
||||
]
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(query);
|
||||
return statusMatch && searchMatch;
|
||||
});
|
||||
}, [orders, activeStatus, searchTerm]);
|
||||
|
||||
const handleRefresh = async (event: CustomEvent) => {
|
||||
await loadOrders();
|
||||
event.detail.complete();
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonContent
|
||||
fullscreen
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '8px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
|
||||
<IonRefresherContent />
|
||||
</IonRefresher>
|
||||
|
||||
<div
|
||||
className="recipients-top-row"
|
||||
style={{ padding: 'calc(16px + var(--ion-safe-area-top)) 0 12px' }}
|
||||
>
|
||||
<div>
|
||||
<h1 className="recipients-page-title">Activity</h1>
|
||||
<p className="rlc-location" style={{ marginTop: 4 }}>
|
||||
{orders.length} support updates
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ListSearchRow
|
||||
value={searchTerm}
|
||||
onChange={setSearchTerm}
|
||||
placeholder="Search orders..."
|
||||
/>
|
||||
|
||||
<div className="orders-filter-row">
|
||||
{statusFilters.map((filter) => (
|
||||
<button
|
||||
key={filter.value}
|
||||
type="button"
|
||||
className={`status-filter-chip ${activeStatus === filter.value ? 'active' : 'inactive'}`}
|
||||
onClick={() => setActiveStatus(filter.value)}
|
||||
style={{ border: 'none' }}
|
||||
>
|
||||
{filter.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p style={{ margin: '0 20px 12px', color: '#dc2626', fontSize: 13 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div>
|
||||
{[1, 2, 3].map((item) => (
|
||||
<div key={item} className="order-summary-card">
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 16,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '70%', height: 15 }}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '45%', height: 12 }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : visibleOrders.length === 0 ? (
|
||||
<div className="empty-state-card">
|
||||
<IonIcon icon={receiptOutline} className="esc-icon" />
|
||||
<h2 className="esc-title">
|
||||
{orders.length === 0 ? 'No orders yet' : 'No matching orders'}
|
||||
</h2>
|
||||
<p className="esc-msg">
|
||||
{orders.length === 0
|
||||
? 'Your support transactions will appear here.'
|
||||
: 'Try changing your search or status filter.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{visibleOrders.map((order) => (
|
||||
<OrderSummaryCard
|
||||
key={order.id}
|
||||
order={order}
|
||||
onClick={(id) => history.push(`/orders/${id}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrdersPage;
|
||||
@@ -0,0 +1,451 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonContent,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonSkeletonText,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import {
|
||||
cardOutline,
|
||||
createOutline,
|
||||
documentTextOutline,
|
||||
helpCircleOutline,
|
||||
informationCircleOutline,
|
||||
logoWhatsapp,
|
||||
logOutOutline,
|
||||
mailOutline,
|
||||
notificationsOutline,
|
||||
personOutline,
|
||||
phonePortraitOutline,
|
||||
shieldCheckmarkOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { FirebaseAuthentication } from '@capacitor-firebase/authentication';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import SettingsRow from '../components/SettingsRow';
|
||||
import sarahAvatarImage from '../assets/sarah.jpg';
|
||||
import '../styles/profile.css';
|
||||
|
||||
type Profile = {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
full_name: string;
|
||||
phone: string;
|
||||
country_of_residence: string;
|
||||
avatar_path: string | null;
|
||||
notification_push_enabled: boolean;
|
||||
notification_email_enabled: boolean;
|
||||
notification_sms_enabled: boolean;
|
||||
};
|
||||
|
||||
type PreviewProfilePayload = {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone: string;
|
||||
country_of_residence: string;
|
||||
avatar_url: string | null;
|
||||
notification_push_enabled: boolean;
|
||||
notification_email_enabled: boolean;
|
||||
notification_sms_enabled: boolean;
|
||||
};
|
||||
|
||||
const PREVIEW_PROFILE_STORAGE_KEY = 'kumusha-preview-profile';
|
||||
|
||||
const getPreviewProfilePayload = (): PreviewProfilePayload => {
|
||||
const fallback: PreviewProfilePayload = {
|
||||
first_name: 'Sarah',
|
||||
last_name: 'Moyo',
|
||||
phone: '+44 7123 456789',
|
||||
country_of_residence: 'United Kingdom',
|
||||
avatar_url: sarahAvatarImage,
|
||||
notification_push_enabled: true,
|
||||
notification_email_enabled: true,
|
||||
notification_sms_enabled: false,
|
||||
};
|
||||
|
||||
try {
|
||||
const saved = localStorage.getItem(PREVIEW_PROFILE_STORAGE_KEY);
|
||||
return saved ? { ...fallback, ...JSON.parse(saved) } : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const savePreviewProfilePayload = (
|
||||
profile: Profile,
|
||||
avatarUrl: string | null
|
||||
) => {
|
||||
const payload: PreviewProfilePayload = {
|
||||
first_name: profile.first_name,
|
||||
last_name: profile.last_name,
|
||||
phone: profile.phone,
|
||||
country_of_residence: profile.country_of_residence,
|
||||
avatar_url: avatarUrl,
|
||||
notification_push_enabled: profile.notification_push_enabled,
|
||||
notification_email_enabled: profile.notification_email_enabled,
|
||||
notification_sms_enabled: profile.notification_sms_enabled,
|
||||
};
|
||||
localStorage.setItem(PREVIEW_PROFILE_STORAGE_KEY, JSON.stringify(payload));
|
||||
};
|
||||
|
||||
const buildPreviewProfile = () => {
|
||||
const payload = getPreviewProfilePayload();
|
||||
const profile: Profile = {
|
||||
id: 'preview-profile',
|
||||
first_name: payload.first_name,
|
||||
last_name: payload.last_name,
|
||||
full_name: `${payload.first_name} ${payload.last_name}`,
|
||||
phone: payload.phone,
|
||||
country_of_residence: payload.country_of_residence,
|
||||
avatar_path: null,
|
||||
notification_push_enabled: payload.notification_push_enabled,
|
||||
notification_email_enabled: payload.notification_email_enabled,
|
||||
notification_sms_enabled: payload.notification_sms_enabled,
|
||||
};
|
||||
|
||||
return { profile, avatarUrl: payload.avatar_url };
|
||||
};
|
||||
|
||||
const ProfilePage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user, signOut, refreshProfile } = useAuth();
|
||||
const [profile, setProfile] = useState<Profile | null>(null);
|
||||
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
void loadProfile();
|
||||
});
|
||||
|
||||
const showError = (message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const loadProfile = async () => {
|
||||
setLoading(true);
|
||||
|
||||
if (!user) {
|
||||
const preview = buildPreviewProfile();
|
||||
setProfile(preview.profile);
|
||||
setAvatarUrl(preview.avatarUrl);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { data, error: profileError } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.eq('id', user.id)
|
||||
.single();
|
||||
|
||||
if (profileError || !data) {
|
||||
showError(profileError?.message ?? 'Profile not found');
|
||||
const preview = buildPreviewProfile();
|
||||
setProfile(preview.profile);
|
||||
setAvatarUrl(preview.avatarUrl);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const nextProfile = data as Profile;
|
||||
setProfile(nextProfile);
|
||||
if (nextProfile.avatar_path) {
|
||||
const { data: signed } = await supabase.storage
|
||||
.from('avatars')
|
||||
.createSignedUrl(nextProfile.avatar_path, 3600);
|
||||
setAvatarUrl(signed?.signedUrl ?? null);
|
||||
} else {
|
||||
setAvatarUrl(null);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleTogglePreference = async (
|
||||
field:
|
||||
| 'notification_push_enabled'
|
||||
| 'notification_email_enabled'
|
||||
| 'notification_sms_enabled',
|
||||
checked: boolean
|
||||
) => {
|
||||
if (!profile) return;
|
||||
const previous = profile;
|
||||
const next = { ...profile, [field]: checked };
|
||||
setProfile(next);
|
||||
|
||||
if (!user) {
|
||||
savePreviewProfilePayload(next, avatarUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
const updates: any =
|
||||
field === 'notification_push_enabled'
|
||||
? { notification_push_enabled: checked, updated_at: updatedAt }
|
||||
: field === 'notification_email_enabled'
|
||||
? { notification_email_enabled: checked, updated_at: updatedAt }
|
||||
: { notification_sms_enabled: checked, updated_at: updatedAt };
|
||||
|
||||
if (field === 'notification_push_enabled' && !checked) {
|
||||
updates.fcm_token = null;
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('profiles')
|
||||
.update(updates)
|
||||
.eq('id', profile.id);
|
||||
|
||||
if (updateError) {
|
||||
setProfile(previous);
|
||||
showError(updateError.message);
|
||||
return;
|
||||
}
|
||||
await refreshProfile();
|
||||
};
|
||||
|
||||
const handleSignOut = async () => {
|
||||
setSigningOut(true);
|
||||
try {
|
||||
await FirebaseAuthentication.signOut().catch(() => undefined);
|
||||
await signOut();
|
||||
history.replace('/auth');
|
||||
} finally {
|
||||
setSigningOut(false);
|
||||
}
|
||||
};
|
||||
|
||||
const initials =
|
||||
profile?.full_name
|
||||
?.split(' ')
|
||||
.map((part) => part.charAt(0))
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase() || '?';
|
||||
|
||||
const paymentMethodsCount = 0;
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonContent
|
||||
fullscreen
|
||||
className="profile-shell"
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': 'calc(var(--ion-safe-area-top, 0px) + 8px)',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<h1 className="profile-page-title">Profile</h1>
|
||||
{error && (
|
||||
<p style={{ margin: '0 20px 12px', color: '#dc2626', fontSize: 13 }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="profile-summary-card">
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: 72, height: 72, borderRadius: 24, flexShrink: 0 }}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<IonSkeletonText animated style={{ width: '70%', height: 22 }} />
|
||||
<IonSkeletonText animated style={{ width: '90%', height: 14 }} />
|
||||
</div>
|
||||
</div>
|
||||
) : profile ? (
|
||||
<>
|
||||
<div className="profile-summary-card">
|
||||
<div className="psc-avatar-shell">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={avatarUrl}
|
||||
alt={profile.full_name}
|
||||
className="psc-avatar"
|
||||
/>
|
||||
) : (
|
||||
<div className="psc-avatar-placeholder">{initials}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="psc-info">
|
||||
<h2 className="psc-name">{profile.full_name}</h2>
|
||||
<p className="psc-location">{profile.country_of_residence}</p>
|
||||
</div>
|
||||
<IonButton
|
||||
className="psc-edit-btn"
|
||||
onClick={() => history.push('/profile/edit')}
|
||||
>
|
||||
<IonIcon icon={createOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</div>
|
||||
|
||||
<h2 className="settings-section-title">Payments</h2>
|
||||
<div className="settings-card">
|
||||
<SettingsRow
|
||||
icon={cardOutline}
|
||||
title="Saved cards"
|
||||
subtitle={
|
||||
paymentMethodsCount > 0
|
||||
? `${paymentMethodsCount} saved for faster checkout`
|
||||
: 'No saved cards yet'
|
||||
}
|
||||
onClick={() =>
|
||||
showError(
|
||||
'Saved cards will be added when payments are connected in a later phase'
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2 className="settings-section-title">Account</h2>
|
||||
<div className="settings-card">
|
||||
<SettingsRow
|
||||
icon={personOutline}
|
||||
title="Edit profile"
|
||||
subtitle="Name, phone, country, avatar"
|
||||
onClick={() => history.push('/profile/edit')}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={notificationsOutline}
|
||||
title="Notifications"
|
||||
subtitle="Open your notification inbox"
|
||||
onClick={() => history.push('/notifications')}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={shieldCheckmarkOutline}
|
||||
title="Security settings"
|
||||
subtitle="Password and account safety"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
showError(
|
||||
'Security settings will be available after MVP launch'
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2 className="settings-section-title">Support</h2>
|
||||
<div className="settings-card">
|
||||
<SettingsRow
|
||||
icon={helpCircleOutline}
|
||||
title="Help centre"
|
||||
subtitle="Get answers about vouchers and support"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
showError(
|
||||
'Help centre articles will be added in a later phase'
|
||||
)
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={logoWhatsapp}
|
||||
iconColor="#6d28d9"
|
||||
iconBg="rgba(109,40,217,0.1)"
|
||||
title="Contact support"
|
||||
subtitle="Talk to Kumusha if something goes wrong"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
showError('Support chat will be connected in a later phase')
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={informationCircleOutline}
|
||||
title="How Kumusha works"
|
||||
subtitle="Learn how vouchers, delivery and redemption work"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
showError(
|
||||
'Guided product explainers will be added in a later phase'
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2 className="settings-section-title">Legal</h2>
|
||||
<div className="settings-card">
|
||||
<SettingsRow
|
||||
icon={documentTextOutline}
|
||||
title="Terms of service"
|
||||
subtitle="Read the rules for using Kumusha"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
showError('Terms of service will be added in a later phase')
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={shieldCheckmarkOutline}
|
||||
title="Privacy policy"
|
||||
subtitle="See how your account and recipient data is handled"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
showError('Privacy policy will be added in a later phase')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2 className="settings-section-title">Preferences</h2>
|
||||
<div className="settings-card">
|
||||
<SettingsRow
|
||||
icon={notificationsOutline}
|
||||
title="Push notifications"
|
||||
type="toggle"
|
||||
checked={profile.notification_push_enabled}
|
||||
onToggle={(checked) =>
|
||||
handleTogglePreference('notification_push_enabled', checked)
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={mailOutline}
|
||||
title="Email updates"
|
||||
type="toggle"
|
||||
checked={profile.notification_email_enabled}
|
||||
onToggle={(checked) =>
|
||||
handleTogglePreference('notification_email_enabled', checked)
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
icon={phonePortraitOutline}
|
||||
title="SMS updates"
|
||||
type="toggle"
|
||||
checked={profile.notification_sms_enabled}
|
||||
onToggle={(checked) =>
|
||||
handleTogglePreference('notification_sms_enabled', checked)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="settings-card">
|
||||
<SettingsRow
|
||||
icon={logOutOutline}
|
||||
title={signingOut ? 'Signing out...' : 'Sign out'}
|
||||
type="button"
|
||||
destructive
|
||||
onClick={handleSignOut}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="profile-footer-mark">
|
||||
<div className="profile-footer-logo">K</div>
|
||||
<p className="profile-footer-name">Kumusha</p>
|
||||
<p className="profile-footer-meta">Version 1.0.0</p>
|
||||
<p className="profile-footer-copyright">
|
||||
© 2026 Kumusha. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfilePage;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,728 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonInput,
|
||||
IonList,
|
||||
IonModal,
|
||||
IonPage,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from '@ionic/react';
|
||||
import {
|
||||
cameraOutline,
|
||||
chevronBackOutline,
|
||||
closeOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { useHistory, useParams } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import AvatarPicker from '../components/AvatarPicker';
|
||||
import momImage from '../assets/mom.jpg';
|
||||
import dadImage from '../assets/dad.jpg';
|
||||
import '../styles/recipients.css';
|
||||
|
||||
type Params = { id?: string };
|
||||
|
||||
type RecipientRow = {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
relationship: string;
|
||||
country: string;
|
||||
city: string;
|
||||
mobile_number: string;
|
||||
photo_path: string | null;
|
||||
};
|
||||
|
||||
const countryOptions = [
|
||||
{ name: 'Zimbabwe', flag: '🇿🇼', dialCode: '+263' },
|
||||
{ name: 'South Africa', flag: '🇿🇦', dialCode: '+27' },
|
||||
{ name: 'Zambia', flag: '🇿🇲', dialCode: '+260' },
|
||||
{ name: 'Botswana', flag: '🇧🇼', dialCode: '+267' },
|
||||
{ name: 'Mozambique', flag: '🇲🇿', dialCode: '+258' },
|
||||
{ name: 'United Kingdom', flag: '🇬🇧', dialCode: '+44' },
|
||||
{ name: 'United States', flag: '🇺🇸', dialCode: '+1' },
|
||||
{ name: 'Canada', flag: '🇨🇦', dialCode: '+1' },
|
||||
{ name: 'Australia', flag: '🇦🇺', dialCode: '+61' },
|
||||
];
|
||||
|
||||
const locationOptionsByCountry: Record<
|
||||
string,
|
||||
Array<{
|
||||
group: string;
|
||||
options: Array<{ name: string; description: string }>;
|
||||
}>
|
||||
> = {
|
||||
Zimbabwe: [
|
||||
{
|
||||
group: 'Major cities',
|
||||
options: [
|
||||
{ name: 'Harare', description: 'Capital city coverage' },
|
||||
{ name: 'Bulawayo', description: 'City merchants and pharmacies' },
|
||||
{ name: 'Mutare', description: 'Eastern Highlands coverage' },
|
||||
{ name: 'Gweru', description: 'Midlands city coverage' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Towns',
|
||||
options: [
|
||||
{ name: 'Chitungwiza', description: 'Harare metro support' },
|
||||
{ name: 'Masvingo', description: 'Town and surrounding areas' },
|
||||
{ name: 'Kwekwe', description: 'Supported collection points' },
|
||||
{ name: 'Kadoma', description: 'Supported collection points' },
|
||||
{ name: 'Victoria Falls', description: 'Town coverage' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Rural districts',
|
||||
options: [
|
||||
{ name: 'Murehwa District', description: 'Rural collection support' },
|
||||
{ name: 'Gokwe District', description: 'Rural collection support' },
|
||||
{ name: 'Buhera District', description: 'Rural collection support' },
|
||||
{ name: 'Zaka District', description: 'Rural collection support' },
|
||||
{ name: 'Guruve District', description: 'Rural collection support' },
|
||||
{
|
||||
name: 'Tsholotsho District',
|
||||
description: 'Rural collection support',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
Zambia: [
|
||||
{
|
||||
group: 'Major cities',
|
||||
options: [
|
||||
{ name: 'Lusaka', description: 'Capital city coverage' },
|
||||
{ name: 'Ndola', description: 'Copperbelt coverage' },
|
||||
{ name: 'Kitwe', description: 'Copperbelt coverage' },
|
||||
{ name: 'Livingstone', description: 'Town coverage' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Rural districts',
|
||||
options: [
|
||||
{ name: 'Chongwe District', description: 'Rural collection support' },
|
||||
{ name: 'Monze District', description: 'Rural collection support' },
|
||||
],
|
||||
},
|
||||
],
|
||||
Botswana: [
|
||||
{
|
||||
group: 'Cities and towns',
|
||||
options: [
|
||||
{ name: 'Gaborone', description: 'Capital city coverage' },
|
||||
{ name: 'Francistown', description: 'Town coverage' },
|
||||
{ name: 'Maun', description: 'Town coverage' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Rural districts',
|
||||
options: [
|
||||
{ name: 'Kweneng District', description: 'Rural collection support' },
|
||||
{ name: 'Central District', description: 'Rural collection support' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const fallbackLocationGroups = [
|
||||
{
|
||||
group: 'Supported areas',
|
||||
options: [
|
||||
{ name: 'Main city', description: 'Available merchant coverage' },
|
||||
{ name: 'Nearby town', description: 'Supported collection points' },
|
||||
{ name: 'Rural district', description: 'Rural collection support' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const getCountryMeta = (countryName: string) =>
|
||||
countryOptions.find((option) => option.name === countryName) ??
|
||||
countryOptions[0];
|
||||
|
||||
const getLocationGroups = (countryName: string) =>
|
||||
locationOptionsByCountry[countryName] ?? fallbackLocationGroups;
|
||||
|
||||
const getSeededRecipientImage = (
|
||||
firstName?: string | null,
|
||||
photoPath?: string | null
|
||||
) => {
|
||||
const normalizedPath = photoPath?.trim().toLowerCase();
|
||||
if (normalizedPath === 'mom.jpg' || normalizedPath === 'mum.jpg') {
|
||||
return momImage;
|
||||
}
|
||||
if (normalizedPath === 'dad.jpg' || normalizedPath === 'father.jpg') {
|
||||
return dadImage;
|
||||
}
|
||||
|
||||
const normalizedName = firstName?.trim().toLowerCase();
|
||||
if (normalizedName === 'mum' || normalizedName === 'mom') {
|
||||
return momImage;
|
||||
}
|
||||
if (normalizedName === 'dad' || normalizedName === 'father') {
|
||||
return dadImage;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const stripDialCode = (value: string, dialCode: string) => {
|
||||
const normalizedValue = value.trim();
|
||||
if (normalizedValue.startsWith(dialCode)) {
|
||||
return normalizedValue.slice(dialCode.length).trimStart();
|
||||
}
|
||||
return normalizedValue;
|
||||
};
|
||||
|
||||
const sanitizePhoneInput = (value: string) =>
|
||||
value.replace(/[^\d\s()-]/g, '').replace(/\s{2,}/g, ' ');
|
||||
|
||||
const normalizePhoneInput = (value: string) =>
|
||||
sanitizePhoneInput(value).replace(/^0+/, '');
|
||||
|
||||
const formatNameInput = (value: string) =>
|
||||
value
|
||||
.toLowerCase()
|
||||
.replace(
|
||||
/(^|[\s'-])([a-z])/g,
|
||||
(_match, separator: string, letter: string) =>
|
||||
`${separator}${letter.toUpperCase()}`
|
||||
);
|
||||
|
||||
const RecipientFormPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { id } = useParams<Params>();
|
||||
const { user } = useAuth();
|
||||
const isEdit = Boolean(id);
|
||||
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [relationship, setRelationship] = useState('');
|
||||
const [country, setCountry] = useState('Zimbabwe');
|
||||
const [city, setCity] = useState('');
|
||||
const [mobileNumber, setMobileNumber] = useState('');
|
||||
const [showCountrySheet, setShowCountrySheet] = useState(false);
|
||||
const [showLocationSheet, setShowLocationSheet] = useState(false);
|
||||
const selectedCountry = getCountryMeta(country);
|
||||
const locationGroups = getLocationGroups(country);
|
||||
const [photoFile, setPhotoFile] = useState<File | null>(null);
|
||||
const [photoPreview, setPhotoPreview] = useState<string | null>(null);
|
||||
const previewObjectUrlRef = useRef<string | null>(null);
|
||||
const [existingPhotoPath, setExistingPhotoPath] = useState<string | null>(
|
||||
null
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const firstNameInputRef = useRef<HTMLIonInputElement>(null);
|
||||
const lastNameInputRef = useRef<HTMLIonInputElement>(null);
|
||||
const relationshipInputRef = useRef<HTMLIonInputElement>(null);
|
||||
const mobileInputRef = useRef<HTMLIonInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isEdit) {
|
||||
void loadRecipient();
|
||||
}
|
||||
}, [id, isEdit]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (previewObjectUrlRef.current) {
|
||||
URL.revokeObjectURL(previewObjectUrlRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleGoBack = () => {
|
||||
if (history.length > 1) {
|
||||
history.goBack();
|
||||
} else {
|
||||
history.replace('/recipients');
|
||||
}
|
||||
};
|
||||
|
||||
const showError = (message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const applyRecipientToForm = async (recipient: RecipientRow) => {
|
||||
setFirstName(recipient.first_name);
|
||||
setLastName(recipient.last_name);
|
||||
setRelationship(recipient.relationship);
|
||||
setCountry(recipient.country);
|
||||
setCity(recipient.city);
|
||||
const recipientCountry = getCountryMeta(recipient.country);
|
||||
setMobileNumber(
|
||||
stripDialCode(recipient.mobile_number, recipientCountry.dialCode)
|
||||
);
|
||||
setExistingPhotoPath(recipient.photo_path);
|
||||
|
||||
const seededImage = getSeededRecipientImage(
|
||||
recipient.first_name,
|
||||
recipient.photo_path
|
||||
);
|
||||
if (seededImage) {
|
||||
setPhotoPreview(seededImage);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!recipient.photo_path) {
|
||||
setPhotoPreview(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const { data: signed } = await supabase.storage
|
||||
.from('recipient-photos')
|
||||
.createSignedUrl(recipient.photo_path, 3600);
|
||||
setPhotoPreview(signed?.signedUrl ?? null);
|
||||
};
|
||||
|
||||
const loadRecipient = async () => {
|
||||
if (!id) return;
|
||||
setLoading(true);
|
||||
|
||||
const ownerId = user?.id ?? '00000000-0000-0000-0000-000000000000';
|
||||
|
||||
const { data, error: loadError } = await supabase
|
||||
.from('recipients')
|
||||
.select(
|
||||
'id,first_name,last_name,relationship,country,city,mobile_number,photo_path'
|
||||
)
|
||||
.eq('id', id)
|
||||
.eq('user_id', ownerId)
|
||||
.single();
|
||||
|
||||
if (loadError || !data) {
|
||||
showError(loadError?.message ?? 'Recipient not found');
|
||||
setLoading(false);
|
||||
history.replace('/recipients');
|
||||
return;
|
||||
}
|
||||
|
||||
const recipient = data as RecipientRow;
|
||||
await applyRecipientToForm(recipient);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handlePhotoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
if (previewObjectUrlRef.current) {
|
||||
URL.revokeObjectURL(previewObjectUrlRef.current);
|
||||
}
|
||||
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
previewObjectUrlRef.current = objectUrl;
|
||||
setPhotoFile(file);
|
||||
setPhotoPreview(objectUrl);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!user) {
|
||||
showError('Please sign in again to save this loved one');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
first_name: firstName.trim(),
|
||||
last_name: lastName.trim(),
|
||||
relationship: relationship.trim(),
|
||||
country: country.trim(),
|
||||
city: city.trim(),
|
||||
mobile_number:
|
||||
`${selectedCountry.dialCode} ${mobileNumber.trim()}`.trim(),
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (
|
||||
!payload.first_name ||
|
||||
!payload.last_name ||
|
||||
!payload.relationship ||
|
||||
!payload.country ||
|
||||
!payload.city ||
|
||||
!payload.mobile_number
|
||||
) {
|
||||
showError('Please complete all required fields');
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
let photoPath = existingPhotoPath;
|
||||
if (photoFile) {
|
||||
const extension = photoFile.name.split('.').pop() || 'jpg';
|
||||
photoPath = `${user.id}/${Date.now()}.${extension}`;
|
||||
const { error: uploadError } = await supabase.storage
|
||||
.from('recipient-photos')
|
||||
.upload(photoPath, photoFile);
|
||||
|
||||
if (uploadError) {
|
||||
showError(uploadError.message);
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (isEdit && id) {
|
||||
const { error: updateError } = await supabase
|
||||
.from('recipients')
|
||||
.update({ ...payload, photo_path: photoPath })
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (updateError) {
|
||||
showError(updateError.message);
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(false);
|
||||
history.push(`/recipients/${id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const { data, error: insertError } = await supabase
|
||||
.from('recipients')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
...payload,
|
||||
photo_path: photoPath,
|
||||
})
|
||||
.select('id')
|
||||
.single();
|
||||
|
||||
if (insertError || !data) {
|
||||
showError(insertError?.message ?? 'Could not create recipient');
|
||||
setSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(false);
|
||||
history.replace(`/recipients/${data.id}`);
|
||||
};
|
||||
|
||||
const initials = `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--border-width': '0px',
|
||||
'--color': '#111827',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonButtons slot="start">
|
||||
<IonButton
|
||||
className="recipients-back-button"
|
||||
fill="clear"
|
||||
onClick={handleGoBack}
|
||||
aria-label="Go back"
|
||||
>
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: '18px', fontWeight: 700 }}>
|
||||
{isEdit ? 'Edit loved one' : 'Add loved one'}
|
||||
</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '8px',
|
||||
'--padding-bottom': 'calc(32px + var(--ion-safe-area-bottom, 0px))',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="recipient-form-card">
|
||||
<div className="rf-photo-picker">
|
||||
<IonIcon icon={cameraOutline} style={{ display: 'none' }} />
|
||||
<AvatarPicker
|
||||
previewUrl={photoPreview}
|
||||
onFileChange={handlePhotoChange}
|
||||
initials={initials || undefined}
|
||||
disabled={loading || saving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="rf-input-shell rf-text-shell"
|
||||
onClick={() => void firstNameInputRef.current?.setFocus()}
|
||||
disabled={loading || saving}
|
||||
aria-label="Enter first name"
|
||||
>
|
||||
<span className="rf-field-label">First name</span>
|
||||
<IonInput
|
||||
ref={firstNameInputRef}
|
||||
className="rf-field"
|
||||
type="text"
|
||||
placeholder="Sarah"
|
||||
value={firstName}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) =>
|
||||
setFirstName(formatNameInput(event.detail.value ?? ''))
|
||||
}
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rf-input-shell rf-text-shell"
|
||||
onClick={() => void lastNameInputRef.current?.setFocus()}
|
||||
disabled={loading || saving}
|
||||
aria-label="Enter last name"
|
||||
>
|
||||
<span className="rf-field-label">Last name</span>
|
||||
<IonInput
|
||||
ref={lastNameInputRef}
|
||||
className="rf-field"
|
||||
type="text"
|
||||
placeholder="Moyo"
|
||||
value={lastName}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) =>
|
||||
setLastName(formatNameInput(event.detail.value ?? ''))
|
||||
}
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rf-input-shell rf-text-shell"
|
||||
onClick={() => void relationshipInputRef.current?.setFocus()}
|
||||
disabled={loading || saving}
|
||||
aria-label="Enter relationship"
|
||||
>
|
||||
<span className="rf-field-label">Relationship</span>
|
||||
<IonInput
|
||||
ref={relationshipInputRef}
|
||||
className="rf-field"
|
||||
type="text"
|
||||
placeholder="Mum, Brother, Aunt"
|
||||
value={relationship}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) =>
|
||||
setRelationship(formatNameInput(event.detail.value ?? ''))
|
||||
}
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rf-country-trigger"
|
||||
onClick={() => setShowCountrySheet(true)}
|
||||
disabled={loading || saving}
|
||||
aria-label="Select country"
|
||||
>
|
||||
<span className="rf-country-label">Country</span>
|
||||
<span className="rf-country-value-row">
|
||||
<span className="rf-country-value">
|
||||
{`${selectedCountry.flag} ${selectedCountry.name} (${selectedCountry.dialCode})`}
|
||||
</span>
|
||||
<IonIcon
|
||||
icon={chevronBackOutline}
|
||||
className="rf-country-chevron"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rf-country-trigger"
|
||||
onClick={() => setShowLocationSheet(true)}
|
||||
disabled={loading || saving}
|
||||
aria-label="Select recipient location"
|
||||
>
|
||||
<span className="rf-country-label">Location</span>
|
||||
<span className="rf-country-value-row">
|
||||
<span
|
||||
className={`rf-country-value${city ? '' : ' is-placeholder'}`}
|
||||
>
|
||||
{city || 'City, town, or rural area'}
|
||||
</span>
|
||||
<IonIcon
|
||||
icon={chevronBackOutline}
|
||||
className="rf-country-chevron"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rf-input-shell rf-phone-shell"
|
||||
onClick={() => void mobileInputRef.current?.setFocus()}
|
||||
disabled={loading || saving}
|
||||
aria-label="Enter mobile number"
|
||||
>
|
||||
<span className="rf-field-label">Mobile number</span>
|
||||
<div className="rf-phone-row">
|
||||
<div className="rf-phone-prefix" aria-hidden="true">
|
||||
<span className="rf-phone-flag">{selectedCountry.flag}</span>
|
||||
<span className="rf-phone-code">
|
||||
{selectedCountry.dialCode}
|
||||
</span>
|
||||
</div>
|
||||
<IonInput
|
||||
ref={mobileInputRef}
|
||||
className="rf-field rf-phone-field"
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
placeholder="77 123 4567"
|
||||
value={mobileNumber}
|
||||
disabled={loading || saving}
|
||||
onIonInput={(event) =>
|
||||
setMobileNumber(
|
||||
normalizePhoneInput(event.detail.value ?? '')
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
{error && (
|
||||
<p style={{ margin: 0, color: '#dc2626', fontSize: '13px' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rf-actions">
|
||||
<IonButton
|
||||
type="submit"
|
||||
expand="block"
|
||||
className="rf-submit-btn"
|
||||
disabled={loading || saving}
|
||||
>
|
||||
{saving ? 'Saving...' : isEdit ? 'Save changes' : 'Add loved one'}
|
||||
</IonButton>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<IonModal
|
||||
isOpen={showCountrySheet}
|
||||
onDidDismiss={() => setShowCountrySheet(false)}
|
||||
initialBreakpoint={1}
|
||||
breakpoints={[0, 1]}
|
||||
handle={true}
|
||||
className="country-sheet-modal"
|
||||
>
|
||||
<div className="country-sheet-shell">
|
||||
<div className="country-sheet-header">
|
||||
<h2>Select country</h2>
|
||||
<IonButton
|
||||
fill="clear"
|
||||
className="country-sheet-close"
|
||||
onClick={() => setShowCountrySheet(false)}
|
||||
aria-label="Close country selector"
|
||||
>
|
||||
<IonIcon icon={closeOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</div>
|
||||
<div className="country-sheet-scroll">
|
||||
<IonList lines="none" className="country-sheet-list">
|
||||
{countryOptions.map((option) => {
|
||||
const isSelected = option.name === country;
|
||||
return (
|
||||
<button
|
||||
key={option.name}
|
||||
type="button"
|
||||
className={`country-sheet-option${isSelected ? ' is-selected' : ''}`}
|
||||
onClick={() => {
|
||||
setCountry(option.name);
|
||||
setCity('');
|
||||
setShowCountrySheet(false);
|
||||
}}
|
||||
>
|
||||
<span className="country-sheet-option-text">
|
||||
<span className="country-sheet-flag">
|
||||
{option.flag}
|
||||
</span>
|
||||
<span className="country-sheet-name">
|
||||
{option.name}
|
||||
</span>
|
||||
<span className="country-sheet-code">
|
||||
({option.dialCode})
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</IonList>
|
||||
</div>
|
||||
</div>
|
||||
</IonModal>
|
||||
|
||||
<IonModal
|
||||
isOpen={showLocationSheet}
|
||||
onDidDismiss={() => setShowLocationSheet(false)}
|
||||
initialBreakpoint={1}
|
||||
breakpoints={[0, 1]}
|
||||
handle={true}
|
||||
className="country-sheet-modal"
|
||||
>
|
||||
<div className="country-sheet-shell">
|
||||
<div className="country-sheet-header">
|
||||
<h2>Select location</h2>
|
||||
<IonButton
|
||||
fill="clear"
|
||||
className="country-sheet-close"
|
||||
onClick={() => setShowLocationSheet(false)}
|
||||
aria-label="Close location selector"
|
||||
>
|
||||
<IonIcon icon={closeOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</div>
|
||||
<div className="country-sheet-scroll">
|
||||
<div className="location-sheet-helper">
|
||||
Choose a city, town, or rural district where support collection
|
||||
is available.
|
||||
</div>
|
||||
{locationGroups.map((group) => (
|
||||
<div key={group.group} className="location-sheet-group">
|
||||
<p className="location-sheet-group-title">{group.group}</p>
|
||||
{group.options.map((option) => {
|
||||
const isSelected = option.name === city;
|
||||
return (
|
||||
<button
|
||||
key={option.name}
|
||||
type="button"
|
||||
className={`country-sheet-option location-sheet-option${isSelected ? ' is-selected' : ''}`}
|
||||
onClick={() => {
|
||||
setCity(option.name);
|
||||
setShowLocationSheet(false);
|
||||
}}
|
||||
>
|
||||
<span className="location-sheet-option-text">
|
||||
<span className="location-sheet-name">
|
||||
{option.name}
|
||||
</span>
|
||||
<span className="location-sheet-description">
|
||||
{option.description}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</IonModal>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecipientFormPage;
|
||||
@@ -0,0 +1,306 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonContent,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonRefresher,
|
||||
IonRefresherContent,
|
||||
IonSkeletonText,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import { addOutline, peopleOutline } from 'ionicons/icons';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import dadImage from '../assets/dad.jpg';
|
||||
import momImage from '../assets/mom.jpg';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { buildCacheKey, readCache, writeCache } from '../utils/localCache';
|
||||
import ListSearchRow from '../components/ListSearchRow';
|
||||
import RecipientListCard, {
|
||||
RecipientListItem,
|
||||
} from '../components/RecipientListCard';
|
||||
import '../styles/recipients.css';
|
||||
|
||||
type RecipientRow = {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
relationship: string;
|
||||
country: string;
|
||||
city: string;
|
||||
photo_path: string | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
type ActivityRow = {
|
||||
recipient_id: string | null;
|
||||
event_at: string;
|
||||
};
|
||||
|
||||
const formatLastActivity = (dateText?: string) => {
|
||||
if (!dateText) return 'No support yet';
|
||||
const diffMs = Date.now() - new Date(dateText).getTime();
|
||||
const diffDays = Math.max(0, Math.floor(diffMs / 86400000));
|
||||
if (diffDays === 0) return 'Today';
|
||||
if (diffDays === 1) return 'Yesterday';
|
||||
return `${diffDays} days ago`;
|
||||
};
|
||||
|
||||
const getSeededRecipientImage = (firstName?: string | null) => {
|
||||
const normalized = firstName?.trim().toLowerCase();
|
||||
if (normalized === 'mum' || normalized === 'mom') return momImage;
|
||||
if (normalized === 'dad' || normalized === 'father') return dadImage;
|
||||
return null;
|
||||
};
|
||||
|
||||
const RecipientsPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user } = useAuth();
|
||||
const [recipients, setRecipients] = useState<RecipientListItem[]>([]);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
void loadRecipients();
|
||||
});
|
||||
|
||||
const showError = (message: string) => {
|
||||
setError(message);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const loadRecipients = async (options?: { forceRefresh?: boolean }) => {
|
||||
const activeUserId = user?.id ?? '00000000-0000-0000-0000-000000000000';
|
||||
const cacheKey = buildCacheKey(activeUserId, 'recipientsList');
|
||||
|
||||
let hasCache = false;
|
||||
if (!options?.forceRefresh) {
|
||||
try {
|
||||
const cached = await readCache<RecipientListItem[]>(cacheKey);
|
||||
if (cached && Array.isArray(cached)) {
|
||||
setRecipients(cached);
|
||||
setLoading(false);
|
||||
hasCache = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[recipients cache] error', err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasCache) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
const [recipientsResult, activityResult] = await Promise.all([
|
||||
supabase
|
||||
.from('recipients')
|
||||
.select(
|
||||
'id,first_name,last_name,relationship,country,city,photo_path,created_at,is_active'
|
||||
)
|
||||
.eq('user_id', activeUserId)
|
||||
.order('created_at', { ascending: false }),
|
||||
supabase
|
||||
.from('activity_events')
|
||||
.select('recipient_id,event_at')
|
||||
.eq('user_id', activeUserId)
|
||||
.order('event_at', { ascending: false })
|
||||
.limit(100),
|
||||
]);
|
||||
|
||||
const queryError = recipientsResult.error ?? activityResult.error;
|
||||
if (queryError) {
|
||||
showError(queryError.message);
|
||||
if (!hasCache) setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const activities = (activityResult.data ?? []) as ActivityRow[];
|
||||
// Filter active on the client if it's the real user; preview user bypass may not have is_active set consistently
|
||||
const rows = (recipientsResult.data ?? []) as (RecipientRow & {
|
||||
is_active: boolean | null;
|
||||
})[];
|
||||
const activeRows = user ? rows.filter((r) => r.is_active !== false) : rows;
|
||||
|
||||
const list = await Promise.all(
|
||||
activeRows.map(async (recipient) => {
|
||||
const latestActivity = activities.find(
|
||||
(a) => a.recipient_id === recipient.id
|
||||
);
|
||||
|
||||
let avatarUrl = null;
|
||||
if (recipient.photo_path) {
|
||||
const { data: urlData } = await supabase.storage
|
||||
.from('recipient-photos')
|
||||
.createSignedUrl(recipient.photo_path, 3600);
|
||||
avatarUrl = urlData?.signedUrl ?? null;
|
||||
}
|
||||
|
||||
if (!avatarUrl) {
|
||||
avatarUrl = getSeededRecipientImage(recipient.first_name);
|
||||
}
|
||||
|
||||
return {
|
||||
id: recipient.id,
|
||||
firstName: recipient.first_name,
|
||||
lastName: recipient.last_name,
|
||||
relationship: recipient.relationship,
|
||||
location: `${recipient.city}, ${recipient.country}`,
|
||||
lastActivityText: formatLastActivity(latestActivity?.event_at),
|
||||
avatarUrl,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
setRecipients(list);
|
||||
setLoading(false);
|
||||
void writeCache(cacheKey, list);
|
||||
};
|
||||
|
||||
const visibleRecipients = useMemo(() => {
|
||||
const query = searchTerm.trim().toLowerCase();
|
||||
if (!query) return recipients;
|
||||
return recipients.filter((recipient) =>
|
||||
[
|
||||
recipient.firstName,
|
||||
recipient.lastName,
|
||||
recipient.relationship,
|
||||
recipient.location,
|
||||
]
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(query)
|
||||
);
|
||||
}, [recipients, searchTerm]);
|
||||
|
||||
const handleRefresh = async (event: CustomEvent) => {
|
||||
await loadRecipients({ forceRefresh: true });
|
||||
event.detail.complete();
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonContent
|
||||
fullscreen
|
||||
className="recipients-shell"
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': 'calc(var(--ion-safe-area-top, 0px) + 8px)',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
|
||||
<IonRefresherContent />
|
||||
</IonRefresher>
|
||||
|
||||
<div className="recipients-top-row" style={{ padding: '16px 0 12px' }}>
|
||||
<div>
|
||||
<h1 className="recipients-page-title">Loved ones</h1>
|
||||
<p className="rlc-location" style={{ marginTop: '4px' }}>
|
||||
Manage family and care recipients
|
||||
</p>
|
||||
</div>
|
||||
<IonButton
|
||||
className="recipients-add-btn"
|
||||
onClick={() => history.push('/recipients/new')}
|
||||
>
|
||||
<IonIcon icon={addOutline} slot="start" />
|
||||
Add
|
||||
</IonButton>
|
||||
</div>
|
||||
|
||||
<ListSearchRow
|
||||
value={searchTerm}
|
||||
onChange={setSearchTerm}
|
||||
placeholder="Search loved ones..."
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p
|
||||
style={{
|
||||
margin: '0 20px 12px',
|
||||
color: '#dc2626',
|
||||
fontSize: '13px',
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div>
|
||||
{[1, 2, 3].map((item) => (
|
||||
<div key={item} className="recipient-list-card">
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: '52px',
|
||||
height: '52px',
|
||||
borderRadius: '16px',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '60%', height: '16px' }}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: '40%', height: '12px' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : visibleRecipients.length === 0 ? (
|
||||
<div className="empty-state-card">
|
||||
<IonIcon icon={peopleOutline} className="esc-icon" />
|
||||
<h2 className="esc-title">
|
||||
{recipients.length === 0
|
||||
? 'No loved ones yet'
|
||||
: 'No matches found'}
|
||||
</h2>
|
||||
<p className="esc-msg">
|
||||
{recipients.length === 0
|
||||
? 'Add your first loved one so you can send support with confidence.'
|
||||
: 'Try a different name, relationship, or city.'}
|
||||
</p>
|
||||
{recipients.length === 0 && (
|
||||
<IonButton
|
||||
onClick={() => history.push('/recipients/new')}
|
||||
style={
|
||||
{
|
||||
'--background': '#6d28d9',
|
||||
'--border-radius': '999px',
|
||||
'--box-shadow': 'none',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonIcon icon={addOutline} slot="start" />
|
||||
Add loved one
|
||||
</IonButton>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{visibleRecipients.map((recipient) => (
|
||||
<RecipientListCard
|
||||
key={recipient.id}
|
||||
recipient={recipient}
|
||||
onClick={(id) => history.push(`/recipients/${id}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecipientsPage;
|
||||
@@ -0,0 +1,366 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { IonButton, IonContent, IonInput, IonPage } from '@ionic/react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import AvatarPicker from '../components/AvatarPicker';
|
||||
import '../styles/auth.css';
|
||||
|
||||
type ProfileDraft = {
|
||||
first_name?: string | null;
|
||||
last_name?: string | null;
|
||||
phone?: string | null;
|
||||
country_of_residence?: string | null;
|
||||
avatar_path?: string | null;
|
||||
};
|
||||
|
||||
const SetupProfilePage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const { user, setProfile, signOut } = useAuth();
|
||||
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [country, setCountry] = useState('');
|
||||
const [avatarFile, setAvatarFile] = useState<File | null>(null);
|
||||
const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
|
||||
const messageTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const mountedRef = useRef(true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [prefilling, setPrefilling] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
if (messageTimerRef.current) {
|
||||
clearTimeout(messageTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadExistingProfile();
|
||||
}, [user?.id]);
|
||||
|
||||
const showError = (message: string) => {
|
||||
if (messageTimerRef.current) {
|
||||
clearTimeout(messageTimerRef.current);
|
||||
}
|
||||
setError(message);
|
||||
messageTimerRef.current = setTimeout(() => {
|
||||
if (mountedRef.current) {
|
||||
setError(null);
|
||||
}
|
||||
}, 4000);
|
||||
};
|
||||
|
||||
const loadExistingProfile = async () => {
|
||||
if (!user) {
|
||||
setPrefilling(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setPrefilling(true);
|
||||
let profile: ProfileDraft | null = null;
|
||||
let profileLoadError: unknown = null;
|
||||
|
||||
try {
|
||||
const profileLoadRequest = supabase
|
||||
.from('profiles')
|
||||
.select('first_name,last_name,phone,country_of_residence,avatar_path')
|
||||
.eq('id', user.id)
|
||||
.maybeSingle();
|
||||
|
||||
const result = await Promise.race([
|
||||
profileLoadRequest,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(
|
||||
() => reject(new Error('Profile setup loading timed out.')),
|
||||
8000
|
||||
)
|
||||
),
|
||||
]);
|
||||
|
||||
profile = result.data as ProfileDraft | null;
|
||||
profileLoadError = result.error;
|
||||
} catch (loadError) {
|
||||
profileLoadError = loadError;
|
||||
}
|
||||
|
||||
if (!mountedRef.current) return;
|
||||
|
||||
if (profileLoadError) {
|
||||
console.error(
|
||||
'[SetupProfilePage] Failed to load existing profile',
|
||||
profileLoadError
|
||||
);
|
||||
showError(
|
||||
'We could not load your profile yet. You can still finish setup.'
|
||||
);
|
||||
}
|
||||
if (profile) {
|
||||
setFirstName(profile.first_name ?? '');
|
||||
setLastName(profile.last_name ?? '');
|
||||
setPhone(profile.phone ?? '');
|
||||
setCountry(profile.country_of_residence ?? '');
|
||||
if (profile.avatar_path) {
|
||||
const { data: publicUrlData } = supabase.storage
|
||||
.from('avatars')
|
||||
.getPublicUrl(profile.avatar_path);
|
||||
setAvatarPreview(publicUrlData.publicUrl);
|
||||
}
|
||||
} else if (user.user_metadata?.full_name) {
|
||||
const parts = String(user.user_metadata.full_name).split(' ');
|
||||
setFirstName(parts[0] ?? '');
|
||||
setLastName(parts.slice(1).join(' '));
|
||||
}
|
||||
setPrefilling(false);
|
||||
};
|
||||
|
||||
const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
if (!mountedRef.current) return;
|
||||
setAvatarFile(file);
|
||||
setAvatarPreview(
|
||||
typeof reader.result === 'string' ? reader.result : null
|
||||
);
|
||||
};
|
||||
reader.onerror = () => {
|
||||
showError(
|
||||
'We could not preview that image. Please choose another photo.'
|
||||
);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!user) {
|
||||
showError('Please sign in again to complete your profile');
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanFirstName = firstName.trim();
|
||||
const cleanLastName = lastName.trim();
|
||||
const cleanPhone = phone.trim();
|
||||
const cleanCountry = country.trim();
|
||||
|
||||
if (!cleanFirstName || !cleanLastName || !cleanPhone || !cleanCountry) {
|
||||
showError('Please complete all profile fields');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
let avatarPath: string | null = null;
|
||||
if (avatarFile) {
|
||||
const extension = avatarFile.name.split('.').pop() || 'jpg';
|
||||
avatarPath = `${user.id}/${Date.now()}.${extension}`;
|
||||
const uploadRequest = supabase.storage
|
||||
.from('avatars')
|
||||
.upload(avatarPath, avatarFile);
|
||||
const { error: uploadError } = await Promise.race([
|
||||
uploadRequest,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(
|
||||
() =>
|
||||
reject(new Error('Photo upload timed out. Please try again.')),
|
||||
12000
|
||||
)
|
||||
),
|
||||
]);
|
||||
|
||||
if (uploadError) {
|
||||
showError(uploadError.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const profilePayload = {
|
||||
id: user.id,
|
||||
first_name: cleanFirstName,
|
||||
last_name: cleanLastName,
|
||||
full_name: `${cleanFirstName} ${cleanLastName}`,
|
||||
phone: cleanPhone,
|
||||
country_of_residence: cleanCountry,
|
||||
...(avatarPath ? { avatar_path: avatarPath } : {}),
|
||||
notification_push_enabled: true,
|
||||
notification_email_enabled: true,
|
||||
notification_sms_enabled: false,
|
||||
updated_at: now,
|
||||
};
|
||||
|
||||
const profileSaveRequest = supabase
|
||||
.from('profiles')
|
||||
.upsert(profilePayload, { onConflict: 'id' })
|
||||
.select('*')
|
||||
.single();
|
||||
|
||||
const { data: savedProfile, error: profileError } = await Promise.race([
|
||||
profileSaveRequest,
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(
|
||||
() =>
|
||||
reject(new Error('Profile save timed out. Please try again.')),
|
||||
12000
|
||||
)
|
||||
),
|
||||
]);
|
||||
|
||||
if (profileError) {
|
||||
showError(profileError.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mountedRef.current) return;
|
||||
|
||||
setLoading(false);
|
||||
setProfile(savedProfile);
|
||||
history.replace('/home');
|
||||
} catch (submitError: any) {
|
||||
if (!mountedRef.current) return;
|
||||
showError(
|
||||
submitError.message || 'Profile setup failed. Please try again.'
|
||||
);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const initials = `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
|
||||
|
||||
const handleLogout = async () => {
|
||||
if (loading || prefilling) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await signOut();
|
||||
history.replace('/auth');
|
||||
} catch (logoutError: any) {
|
||||
showError(
|
||||
logoutError?.message || 'We could not sign you out. Please try again.'
|
||||
);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonContent
|
||||
className="auth-content"
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '0px',
|
||||
'--padding-bottom': '0px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<div className="auth-shell">
|
||||
<div className="auth-brand-block">
|
||||
<h4 className="auth-eyebrow">Profile setup</h4>
|
||||
<h1 className="auth-heading">Tell us about you</h1>
|
||||
<p className="auth-subtitle">
|
||||
We use this to personalise your Kumusha dashboard and keep your
|
||||
account secure.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="auth-form-card">
|
||||
<AvatarPicker
|
||||
previewUrl={avatarPreview}
|
||||
onFileChange={handleAvatarChange}
|
||||
initials={initials || undefined}
|
||||
disabled={loading || prefilling}
|
||||
/>
|
||||
|
||||
<IonInput
|
||||
type="text"
|
||||
label="First name"
|
||||
labelPlacement="floating"
|
||||
value={firstName}
|
||||
onIonInput={(event) => setFirstName(event.detail.value ?? '')}
|
||||
disabled={loading || prefilling}
|
||||
placeholder="e.g. Tadiwa"
|
||||
className="auth-field"
|
||||
/>
|
||||
<IonInput
|
||||
type="text"
|
||||
label="Last name"
|
||||
labelPlacement="floating"
|
||||
value={lastName}
|
||||
onIonInput={(event) => setLastName(event.detail.value ?? '')}
|
||||
disabled={loading || prefilling}
|
||||
placeholder="e.g. Moyo"
|
||||
className="auth-field"
|
||||
/>
|
||||
<IonInput
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
label="Mobile number"
|
||||
labelPlacement="floating"
|
||||
value={phone}
|
||||
onIonInput={(event) => setPhone(event.detail.value ?? '')}
|
||||
disabled={loading || prefilling}
|
||||
placeholder="e.g. +44 7123 456789"
|
||||
className="auth-field"
|
||||
/>
|
||||
<IonInput
|
||||
type="text"
|
||||
label="Country of residence"
|
||||
labelPlacement="floating"
|
||||
value={country}
|
||||
onIonInput={(event) => setCountry(event.detail.value ?? '')}
|
||||
disabled={loading || prefilling}
|
||||
placeholder="e.g. United Kingdom"
|
||||
className="auth-field"
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p className="auth-status-text" style={{ color: '#dc2626' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="setup-profile-actions-row">
|
||||
<IonButton
|
||||
type="button"
|
||||
fill="outline"
|
||||
disabled={loading || prefilling}
|
||||
onClick={handleLogout}
|
||||
className="setup-profile-secondary-btn"
|
||||
>
|
||||
Logout
|
||||
</IonButton>
|
||||
<IonButton
|
||||
type="submit"
|
||||
expand="block"
|
||||
disabled={loading || prefilling}
|
||||
className="setup-profile-primary-btn"
|
||||
>
|
||||
{loading ? 'Saving profile...' : 'Finish setup'}
|
||||
</IonButton>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default SetupProfilePage;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,297 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
IonPage,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonToolbar,
|
||||
IonButtons,
|
||||
IonTitle,
|
||||
IonButton,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import { useHistory, useLocation } from 'react-router-dom';
|
||||
import { IonIcon } from '@ionic/react';
|
||||
import { chevronBackOutline, mailOutline } from 'ionicons/icons';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import OtpInputSlots from '../components/OtpInputSlots';
|
||||
import '../styles/auth.css';
|
||||
|
||||
interface LocationState {
|
||||
email?: string;
|
||||
resent?: boolean;
|
||||
}
|
||||
|
||||
const VerifyEmailPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const location = useLocation<LocationState>();
|
||||
const { user, profile, profileStatus } = useAuth();
|
||||
|
||||
const email =
|
||||
location.state?.email?.trim().toLowerCase() ||
|
||||
localStorage.getItem('kumusha_pending_verification_email') ||
|
||||
'';
|
||||
const wasResent = location.state?.resent;
|
||||
|
||||
const [code, setCode] = useState<string[]>(['', '', '', '', '', '']);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(
|
||||
wasResent ? 'We sent a fresh code to your email.' : null
|
||||
);
|
||||
const [cooldown, setCooldown] = useState(wasResent ? 60 : 0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!email) {
|
||||
showError(
|
||||
'We could not find the email used for sign up. Please sign up again.'
|
||||
);
|
||||
}
|
||||
}, [email]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || profileStatus === 'loading') return;
|
||||
|
||||
if (
|
||||
!profile ||
|
||||
!profile.first_name ||
|
||||
!profile.last_name ||
|
||||
!profile.phone ||
|
||||
!profile.country_of_residence
|
||||
) {
|
||||
history.replace('/setup-profile');
|
||||
} else {
|
||||
history.replace('/home');
|
||||
}
|
||||
}, [user, profile, profileStatus, history]);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setError(null);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
if (cooldown > 0) {
|
||||
timer = setTimeout(() => setCooldown((c) => c - 1), 1000);
|
||||
}
|
||||
return () => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
}, [cooldown]);
|
||||
|
||||
const showError = (msg: string) => {
|
||||
setStatus(null);
|
||||
setError(msg);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
};
|
||||
|
||||
const showStatus = (msg: string) => {
|
||||
setError(null);
|
||||
setStatus(msg);
|
||||
setTimeout(() => setStatus(null), 4000);
|
||||
};
|
||||
|
||||
const handleDigitChange = (index: number, val: string) => {
|
||||
const newCode = [...code];
|
||||
newCode[index] = val;
|
||||
setCode(newCode);
|
||||
};
|
||||
|
||||
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
e.preventDefault();
|
||||
const pastedData = e.clipboardData
|
||||
.getData('Text')
|
||||
.replace(/[^0-9]/g, '')
|
||||
.slice(0, 6);
|
||||
if (!pastedData) return;
|
||||
const newCode = [...code];
|
||||
for (let i = 0; i < pastedData.length; i++) {
|
||||
newCode[i] = pastedData[i];
|
||||
}
|
||||
setCode(newCode);
|
||||
};
|
||||
|
||||
const handleVerifyOtp = async () => {
|
||||
const token = code.join('');
|
||||
if (token.length !== 6) {
|
||||
showError('Please enter the full 6-digit code.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
showError(
|
||||
'We could not find the email used for sign up. Please go back and create your account again.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setStatus(null);
|
||||
|
||||
const { error: verifyError } = await supabase.auth.verifyOtp({
|
||||
email,
|
||||
token,
|
||||
type: 'email',
|
||||
});
|
||||
|
||||
if (verifyError) {
|
||||
showError(verifyError.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
localStorage.removeItem('kumusha_pending_verification_email');
|
||||
showStatus('Email verified. Finishing your sign in...');
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleResend = async () => {
|
||||
if (cooldown > 0) return;
|
||||
if (!email) {
|
||||
showError(
|
||||
'We could not find the email used for sign up. Please go back and create your account again.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
setError(null);
|
||||
setStatus(null);
|
||||
|
||||
const { error: resendError } = await supabase.auth.resend({
|
||||
type: 'signup',
|
||||
email,
|
||||
});
|
||||
|
||||
if (resendError) {
|
||||
showError(resendError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
setCode(['', '', '', '', '', '']);
|
||||
setCooldown(60);
|
||||
showStatus('A new 6-digit code has been sent.');
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar style={{ '--background': 'transparent' }}>
|
||||
<IonButtons slot="start">
|
||||
<IonButton fill="clear" onClick={() => history.goBack()}>
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: '0px' }}>Verify email</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
className="auth-content"
|
||||
style={{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '0px',
|
||||
'--padding-bottom': '0px',
|
||||
}}
|
||||
>
|
||||
<div className="auth-shell">
|
||||
<div
|
||||
className="auth-brand-block"
|
||||
style={{ gap: '12px', marginTop: '20px' }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: '56px',
|
||||
height: '56px',
|
||||
borderRadius: '24px',
|
||||
backgroundColor: 'rgba(109,40,217,0.12)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<IonIcon
|
||||
icon={mailOutline}
|
||||
style={{ fontSize: '26px', color: '#6d28d9' }}
|
||||
/>
|
||||
</div>
|
||||
<h1 className="auth-heading" style={{ fontSize: '28px' }}>
|
||||
Check your email
|
||||
</h1>
|
||||
<p className="auth-subtitle" style={{ maxWidth: '340px' }}>
|
||||
{email ? (
|
||||
<>
|
||||
We sent a 6-digit code to <strong>{email}</strong>. Enter it
|
||||
below to confirm your account and continue.
|
||||
</>
|
||||
) : (
|
||||
'We could not find the email used for sign up. Go back and create your account again.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="auth-card auth-card--elevated">
|
||||
<div
|
||||
style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}
|
||||
>
|
||||
<OtpInputSlots
|
||||
value={code}
|
||||
onChange={handleDigitChange}
|
||||
onPaste={handlePaste}
|
||||
disabled={loading}
|
||||
/>
|
||||
|
||||
{status ? (
|
||||
<div
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
background: 'rgba(109,40,217,0.08)',
|
||||
color: '#6d28d9',
|
||||
padding: '12px 14px',
|
||||
fontSize: '13px',
|
||||
fontWeight: '600',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="auth-inline-message">{error}</div>
|
||||
) : null}
|
||||
|
||||
<button
|
||||
className="auth-submit-btn"
|
||||
onClick={handleVerifyOtp}
|
||||
disabled={loading || code.join('').length !== 6}
|
||||
>
|
||||
{loading ? 'Verifying...' : 'Verify Code'}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleResend}
|
||||
disabled={cooldown > 0 || loading}
|
||||
className="auth-link-button"
|
||||
style={{
|
||||
alignSelf: 'center',
|
||||
fontSize: '14px',
|
||||
padding: '4px 0',
|
||||
color: cooldown > 0 || loading ? '#9ca3af' : '#6d28d9',
|
||||
}}
|
||||
>
|
||||
{cooldown > 0 ? `Resend code in ${cooldown}s` : 'Resend code'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default VerifyEmailPage;
|
||||
@@ -0,0 +1,317 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonInput,
|
||||
IonPage,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from '@ionic/react';
|
||||
import { chevronBackOutline, lockClosedOutline } from 'ionicons/icons';
|
||||
import { useHistory, useLocation } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import OtpInputSlots from '../components/OtpInputSlots';
|
||||
import '../styles/auth.css';
|
||||
|
||||
interface LocationState {
|
||||
email?: string;
|
||||
}
|
||||
|
||||
const VerifyResetPage: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const location = useLocation<LocationState>();
|
||||
const { user, refreshProfile, profileStatus } = useAuth();
|
||||
const email = location.state?.email;
|
||||
|
||||
const [code, setCode] = useState<string[]>(['', '', '', '', '', '']);
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const [cooldown, setCooldown] = useState(0);
|
||||
const [passwordUpdated, setPasswordUpdated] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!email) {
|
||||
history.replace('/forgot-password');
|
||||
}
|
||||
}, [email, history]);
|
||||
|
||||
useEffect(() => {
|
||||
if (cooldown <= 0) return;
|
||||
const timer = setTimeout(() => setCooldown((current) => current - 1), 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [cooldown]);
|
||||
|
||||
useEffect(() => {
|
||||
if (user && passwordUpdated && profileStatus !== 'loading') {
|
||||
loadProfileAndNavigate();
|
||||
}
|
||||
}, [user, passwordUpdated, profileStatus]);
|
||||
|
||||
const showMessage = (message: string, kind: 'error' | 'status') => {
|
||||
if (kind === 'error') {
|
||||
setError(message);
|
||||
setStatus(null);
|
||||
setTimeout(() => setError(null), 4000);
|
||||
} else {
|
||||
setStatus(message);
|
||||
setError(null);
|
||||
setTimeout(() => setStatus(null), 4000);
|
||||
}
|
||||
};
|
||||
|
||||
const loadProfileAndNavigate = async () => {
|
||||
if (!user) return;
|
||||
|
||||
const data = await refreshProfile();
|
||||
|
||||
if (
|
||||
!data ||
|
||||
!data.first_name ||
|
||||
!data.last_name ||
|
||||
!data.phone ||
|
||||
!data.country_of_residence
|
||||
) {
|
||||
history.replace('/setup-profile');
|
||||
} else {
|
||||
history.replace('/home');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDigitChange = (index: number, value: string) => {
|
||||
const nextCode = [...code];
|
||||
nextCode[index] = value.replace(/\D/g, '').slice(-1);
|
||||
setCode(nextCode);
|
||||
};
|
||||
|
||||
const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
event.preventDefault();
|
||||
const digits = event.clipboardData
|
||||
.getData('Text')
|
||||
.replace(/\D/g, '')
|
||||
.slice(0, 6);
|
||||
if (!digits) return;
|
||||
|
||||
const nextCode = ['', '', '', '', '', ''];
|
||||
digits.split('').forEach((digit, index) => {
|
||||
nextCode[index] = digit;
|
||||
});
|
||||
setCode(nextCode);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
const token = code.join('');
|
||||
if (token.length !== 6) {
|
||||
showMessage('Please enter the 6-digit reset code', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
showMessage('Password must be at least 6 characters', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setStatus(null);
|
||||
|
||||
const { error: verifyError } = await supabase.auth.verifyOtp({
|
||||
email: email!,
|
||||
token,
|
||||
type: 'recovery',
|
||||
});
|
||||
|
||||
if (verifyError) {
|
||||
showMessage(verifyError.message, 'error');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase.auth.updateUser({
|
||||
password: newPassword,
|
||||
});
|
||||
|
||||
if (updateError) {
|
||||
showMessage(updateError.message, 'error');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
showMessage('Password updated', 'status');
|
||||
setPasswordUpdated(true);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleResend = async () => {
|
||||
if (cooldown > 0 || !email) return;
|
||||
|
||||
const { error: resendError } =
|
||||
await supabase.auth.resetPasswordForEmail(email);
|
||||
if (resendError) {
|
||||
showMessage(resendError.message, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
showMessage('A new reset code has been sent', 'status');
|
||||
setCooldown(60);
|
||||
};
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar
|
||||
style={
|
||||
{
|
||||
'--background': 'transparent',
|
||||
'--border-width': '0px',
|
||||
'--color': '#111827',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonButtons slot="start">
|
||||
<IonButton
|
||||
fill="clear"
|
||||
onClick={() => history.goBack()}
|
||||
style={
|
||||
{
|
||||
'--color': '#111827',
|
||||
'--border-radius': '12px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
aria-label="Go back"
|
||||
>
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: '18px', fontWeight: 700 }}>
|
||||
New password
|
||||
</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
className="auth-content"
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-start': '0px',
|
||||
'--padding-end': '0px',
|
||||
'--padding-top': '0px',
|
||||
'--padding-bottom': '0px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<div className="auth-shell">
|
||||
<div
|
||||
className="auth-intro-block"
|
||||
style={{ alignItems: 'flex-start', textAlign: 'left' }}
|
||||
>
|
||||
<div className="auth-icon-container">
|
||||
<IonIcon icon={lockClosedOutline} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="auth-intro-heading">Enter your reset code</h1>
|
||||
<p className="auth-intro-body" style={{ marginTop: '8px' }}>
|
||||
Use the 6-digit code sent to <strong>{email}</strong>, then
|
||||
choose a new password.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="auth-form-card" style={{ marginBottom: '12px' }}>
|
||||
<OtpInputSlots
|
||||
value={code}
|
||||
onChange={handleDigitChange}
|
||||
onPaste={handlePaste}
|
||||
disabled={loading}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleResend}
|
||||
disabled={cooldown > 0 || loading}
|
||||
style={{
|
||||
backgroundColor: 'transparent',
|
||||
border: 'none',
|
||||
padding: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 700,
|
||||
color: cooldown > 0 ? '#9ca3af' : '#6d28d9',
|
||||
}}
|
||||
>
|
||||
{cooldown > 0 ? `Resend code in ${cooldown}s` : 'Resend code'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="auth-form-card">
|
||||
<IonInput
|
||||
type="password"
|
||||
label="New password"
|
||||
labelPlacement="floating"
|
||||
value={newPassword}
|
||||
onIonInput={(event) => setNewPassword(event.detail.value ?? '')}
|
||||
disabled={loading}
|
||||
placeholder="Enter a new password"
|
||||
style={
|
||||
{
|
||||
'--background': '#fafafa',
|
||||
'--border-radius': '12px',
|
||||
'--padding-start': '14px',
|
||||
'--padding-end': '14px',
|
||||
'--highlight-color-focused': '#6d28d9',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p className="auth-status-text" style={{ color: '#dc2626' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{status && (
|
||||
<p className="auth-status-text" style={{ color: '#16a34a' }}>
|
||||
{status}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<IonButton
|
||||
type="submit"
|
||||
expand="block"
|
||||
disabled={
|
||||
loading ||
|
||||
code.join('').length !== 6 ||
|
||||
newPassword.length < 6
|
||||
}
|
||||
style={
|
||||
{
|
||||
'--background': '#6d28d9',
|
||||
'--background-activated': '#5b21b6',
|
||||
'--border-radius': '999px',
|
||||
'--box-shadow': 'none',
|
||||
'--color': '#ffffff',
|
||||
height: '52px',
|
||||
fontSize: '15px',
|
||||
fontWeight: 700,
|
||||
marginTop: '4px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
{loading ? 'Updating password...' : 'Update password'}
|
||||
</IonButton>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default VerifyResetPage;
|
||||
@@ -0,0 +1,295 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonSkeletonText,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import {
|
||||
chevronBackOutline,
|
||||
copyOutline,
|
||||
listOutline,
|
||||
qrCodeOutline,
|
||||
shieldCheckmarkOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { useHistory, useLocation, useParams } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { formatMoney } from '../utils/formatMoney';
|
||||
import '../styles/support.css';
|
||||
|
||||
type Params = { id: string };
|
||||
|
||||
type RedemptionEntry = {
|
||||
id: string;
|
||||
redeemed_amount: number;
|
||||
redeemed_at: string;
|
||||
merchant_name: string | null;
|
||||
status: string | null;
|
||||
};
|
||||
|
||||
type Voucher = {
|
||||
id: string;
|
||||
voucher_code: string;
|
||||
status: string;
|
||||
expires_at: string;
|
||||
qr_payload: string;
|
||||
voucher_type: string;
|
||||
redeemed_amount?: number;
|
||||
remaining_amount?: number;
|
||||
voucher_redemptions?: RedemptionEntry[] | null;
|
||||
support_orders?: {
|
||||
service_type: string;
|
||||
amount: number;
|
||||
recipients?: { first_name: string; last_name: string } | null;
|
||||
merchants?: { name: string; branch_name: string | null } | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
const VoucherDetailPage: React.FC = () => {
|
||||
const { id } = useParams<Params>();
|
||||
const history = useHistory();
|
||||
const location = useLocation<{ parentRoot?: string }>();
|
||||
const { user } = useAuth();
|
||||
const [voucher, setVoucher] = useState<Voucher | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
void loadVoucher();
|
||||
});
|
||||
|
||||
const handleGoBack = () => {
|
||||
if (history.length > 1) {
|
||||
history.goBack();
|
||||
} else {
|
||||
history.replace('/activity');
|
||||
}
|
||||
};
|
||||
|
||||
const parentRoot = location.state?.parentRoot ?? '/activity';
|
||||
|
||||
const handleGoToParentRoot = () => {
|
||||
history.replace(parentRoot);
|
||||
};
|
||||
|
||||
const showMessage = (text: string) => {
|
||||
setMessage(text);
|
||||
setTimeout(() => setMessage(null), 4000);
|
||||
};
|
||||
|
||||
const loadVoucher = async () => {
|
||||
if (!user) return;
|
||||
setLoading(true);
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('vouchers')
|
||||
.select(
|
||||
'id,voucher_code,status,expires_at,qr_payload,voucher_type,redeemed_amount,remaining_amount,voucher_redemptions(id,redeemed_amount,redeemed_at,merchant_name,status),support_orders!inner(service_type,amount,user_id,recipients(first_name,last_name),merchants(name,branch_name))'
|
||||
)
|
||||
.eq('id', id)
|
||||
.eq('support_orders.user_id', user.id)
|
||||
.single();
|
||||
|
||||
if (error || !data) {
|
||||
showMessage(error?.message ?? 'Voucher not found');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setVoucher(data as unknown as Voucher);
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleCopyCode = async () => {
|
||||
if (!voucher) return;
|
||||
await navigator.clipboard.writeText(voucher.voucher_code);
|
||||
showMessage('Voucher code copied');
|
||||
};
|
||||
|
||||
const totalAmount = Number(voucher?.support_orders?.amount ?? 0);
|
||||
const redeemedAmount = Number(voucher?.redeemed_amount ?? 0);
|
||||
const fallbackRemaining = Math.max(totalAmount - redeemedAmount, 0);
|
||||
const remainingAmount = Number(
|
||||
voucher?.remaining_amount ?? fallbackRemaining
|
||||
);
|
||||
const hasPartialRedemption = redeemedAmount > 0 && remainingAmount > 0;
|
||||
const redemptionHistory = [...(voucher?.voucher_redemptions ?? [])].sort(
|
||||
(a, b) =>
|
||||
new Date(b.redeemed_at).getTime() - new Date(a.redeemed_at).getTime()
|
||||
);
|
||||
|
||||
return (
|
||||
<IonPage style={{ backgroundColor: '#fafafa' }}>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar
|
||||
style={
|
||||
{
|
||||
'--background': 'transparent',
|
||||
'--border-width': '0px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonButtons slot="start">
|
||||
<IonButton fill="clear" onClick={handleGoBack} aria-label="Go back">
|
||||
<IonIcon icon={chevronBackOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
<IonTitle style={{ fontSize: 18, fontWeight: 700 }}>Voucher</IonTitle>
|
||||
<IonButtons slot="end">
|
||||
<IonButton
|
||||
fill="clear"
|
||||
onClick={handleGoToParentRoot}
|
||||
aria-label="Back to activity"
|
||||
>
|
||||
<IonIcon icon={listOutline} slot="icon-only" />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent
|
||||
style={
|
||||
{
|
||||
'--background': 'linear-gradient(180deg, #fafafa 0%, #f4f0ff 100%)',
|
||||
'--padding-top': '8px',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="voucher-hero-card">
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: 160, height: 32, borderRadius: 999 }}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{ width: 220, height: 220, borderRadius: 24 }}
|
||||
/>
|
||||
</div>
|
||||
) : voucher ? (
|
||||
<>
|
||||
{message && (
|
||||
<p
|
||||
style={{ margin: '12px 20px', color: '#6d28d9', fontSize: 13 }}
|
||||
>
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
<div className="voucher-hero-card">
|
||||
<span className="vhc-code-pill">{voucher.voucher_code}</span>
|
||||
<div className="vhc-qr-placeholder">
|
||||
<IonIcon icon={qrCodeOutline} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="vhc-expiry">
|
||||
Expires {new Date(voucher.expires_at).toLocaleDateString()}
|
||||
</p>
|
||||
<p className="vhc-merchant">
|
||||
{voucher.support_orders?.merchants
|
||||
? `${voucher.support_orders.merchants.name}${voucher.support_orders.merchants.branch_name ? ` — ${voucher.support_orders.merchants.branch_name}` : ''}`
|
||||
: `Kumusha ${voucher.support_orders?.service_type === 'medication' ? 'pharmacy' : 'grocery'} partner`}
|
||||
</p>
|
||||
<p className="vhc-merchant">
|
||||
For{' '}
|
||||
{voucher.support_orders?.recipients
|
||||
? `${voucher.support_orders.recipients.first_name} ${voucher.support_orders.recipients.last_name}`
|
||||
: 'recipient'}{' '}
|
||||
· {formatMoney(Number(voucher.support_orders?.amount ?? 0))}
|
||||
</p>
|
||||
</div>
|
||||
<IonButton
|
||||
onClick={handleCopyCode}
|
||||
style={
|
||||
{
|
||||
'--background': '#6d28d9',
|
||||
'--border-radius': '999px',
|
||||
'--box-shadow': 'none',
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<IonIcon icon={copyOutline} slot="start" />
|
||||
Copy code
|
||||
</IonButton>
|
||||
</div>
|
||||
|
||||
{(hasPartialRedemption || redemptionHistory.length > 0) && (
|
||||
<div className="voucher-balance-card">
|
||||
<div className="voucher-balance-head">
|
||||
<div>
|
||||
<p className="voucher-balance-title">Voucher balance</p>
|
||||
<p className="voucher-balance-subtitle">
|
||||
Track redeemed and remaining value for this voucher.
|
||||
</p>
|
||||
</div>
|
||||
<div className="voucher-balance-total">
|
||||
{formatMoney(totalAmount)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="voucher-balance-pills">
|
||||
<div className="voucher-balance-pill is-redeemed">
|
||||
Redeemed {formatMoney(redeemedAmount)}
|
||||
</div>
|
||||
<div className="voucher-balance-pill is-remaining">
|
||||
Unredeemed {formatMoney(remainingAmount)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{redemptionHistory.length > 0 && (
|
||||
<div className="voucher-redemption-history">
|
||||
<p className="voucher-redemption-history-title">
|
||||
Redemption history
|
||||
</p>
|
||||
{redemptionHistory.map((entry) => (
|
||||
<div key={entry.id} className="voucher-redemption-row">
|
||||
<div>
|
||||
<p className="voucher-redemption-merchant">
|
||||
{entry.merchant_name ||
|
||||
voucher.support_orders?.merchants?.name ||
|
||||
`Kumusha ${voucher.support_orders?.service_type === 'medication' ? 'pharmacy' : 'grocery'} partner`}
|
||||
</p>
|
||||
<p className="voucher-redemption-date">
|
||||
{new Date(entry.redeemed_at).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<div className="voucher-redemption-right">
|
||||
<p className="voucher-redemption-amount">
|
||||
{formatMoney(entry.redeemed_amount)}
|
||||
</p>
|
||||
<span className="voucher-redemption-status">
|
||||
{entry.status || 'Redeemed'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="security-note-card">
|
||||
<IonIcon icon={shieldCheckmarkOutline} className="snc-icon" />
|
||||
<p className="snc-text">
|
||||
Redeemable at any approved Kumusha{' '}
|
||||
{voucher.support_orders?.service_type === 'medication'
|
||||
? 'pharmacy'
|
||||
: 'grocery'}{' '}
|
||||
partner. Balance updates automatically after partial redemption.
|
||||
Do not share code.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default VoucherDetailPage;
|
||||
Reference in New Issue
Block a user