Compare commits

..

1 Commits

Author SHA1 Message Date
AppCakes 98554b0086 build: 444813b5-5daf-49b2-bf1a-7e4caeab4e17 2026-07-04 11:56:40 +00:00
137 changed files with 20139 additions and 6449 deletions
Binary file not shown.
+2 -2
View File
@@ -4,10 +4,10 @@ android {
namespace = "io.ionic.starter"
compileSdk = rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.qoutelink.app"
applicationId "com.kumusha.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 3
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [googleMapsApiKey: System.getenv("VITE_GOOGLE_MAPS_KEY") ?: ""]
+1 -1
View File
@@ -25,7 +25,7 @@
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="com.qoutelink.app" />
<data android:scheme="com.kumusha.app" />
</intent-filter>
</activity>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 16 KiB

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="splashBackground">#FFFFFF</color>
</resources>
+2 -2
View File
@@ -1,7 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">Qoutelink</string>
<string name="title_activity_main">Qoutelink</string>
<string name="app_name">kumusha</string>
<string name="title_activity_main">kumusha</string>
<string name="package_name">io.ionic.starter</string>
<string name="custom_url_scheme">io.ionic.starter</string>
</resources>
+1 -3
View File
@@ -17,8 +17,6 @@
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/splashBackground</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/splash_logo</item>
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
<item name="android:background">@drawable/splash</item>
</style>
</resources>
+5 -2
View File
@@ -1,14 +1,17 @@
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.qoutelink.app',
appName: 'Qoutelink',
appId: 'com.kumusha.app',
appName: 'kumusha',
webDir: 'dist',
plugins: {
FirebaseAuthentication: {
skipNativeAuth: false,
providers: [],
},
PushNotifications: {
presentationOptions: ['badge', 'sound', 'banner'],
},
},
};
+4 -4
View File
@@ -299,7 +299,7 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
@@ -308,7 +308,7 @@
);
MARKETING_VERSION = 1.0;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = com.qoutelink.app;
PRODUCT_BUNDLE_IDENTIFIER = com.kumusha.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_VERSION = 5.0;
@@ -322,7 +322,7 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
@@ -330,7 +330,7 @@
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.qoutelink.app;
PRODUCT_BUNDLE_IDENTIFIER = com.kumusha.app;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
SWIFT_VERSION = 5.0;
+18 -1
View File
@@ -1,5 +1,7 @@
import UIKit
import Capacitor
import FirebaseCore
import FirebaseMessaging
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -7,7 +9,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
return true
}
@@ -46,4 +48,19 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
Messaging.messaging().token { token, error in
if let error = error {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
} else if let token = token {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: token)
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
}
@@ -1,122 +1,14 @@
{
"images" : [
{
"idiom": "iphone",
"scale": "1x",
"size": "20x20",
"filename": "icon-20.png"
},
{
"idiom": "ipad",
"scale": "1x",
"size": "20x20",
"filename": "icon-20.png"
},
{
"idiom": "iphone",
"scale": "1x",
"size": "29x29",
"filename": "icon-29.png"
},
{
"idiom": "ipad",
"scale": "1x",
"size": "29x29",
"filename": "icon-29.png"
},
{
"idiom": "ipad",
"scale": "1x",
"size": "40x40",
"filename": "icon-40.png"
},
{
"idiom": "iphone",
"scale": "2x",
"size": "20x20",
"filename": "icon-40.png"
},
{
"idiom": "iphone",
"scale": "2x",
"size": "29x29",
"filename": "icon-58.png"
},
{
"idiom": "ipad",
"scale": "2x",
"size": "29x29",
"filename": "icon-58.png"
},
{
"idiom": "iphone",
"scale": "3x",
"size": "20x20",
"filename": "icon-60.png"
},
{
"idiom": "ipad",
"scale": "1x",
"size": "76x76",
"filename": "icon-76.png"
},
{
"idiom": "iphone",
"scale": "2x",
"size": "40x40",
"filename": "icon-80.png"
},
{
"idiom": "ipad",
"scale": "2x",
"size": "40x40",
"filename": "icon-80.png"
},
{
"idiom": "iphone",
"scale": "3x",
"size": "29x29",
"filename": "icon-87.png"
},
{
"idiom": "iphone",
"scale": "2x",
"size": "60x60",
"filename": "icon-120.png"
},
{
"idiom": "iphone",
"scale": "3x",
"size": "40x40",
"filename": "icon-120.png"
},
{
"idiom": "ipad",
"scale": "2x",
"size": "76x76",
"filename": "icon-152.png"
},
{
"idiom": "ipad",
"scale": "2x",
"size": "83.5x83.5",
"filename": "icon-167.png"
},
{
"idiom": "iphone",
"scale": "3x",
"size": "60x60",
"filename": "icon-180.png"
},
{
"idiom": "ios-marketing",
"scale": "1x",
"size": "1024x1024",
"filename": "icon-1024.png"
"filename" : "AppIcon-512@2x.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author": "appsuite",
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 890 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 809 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

+13 -3
View File
@@ -2,12 +2,22 @@
"images" : [
{
"idiom" : "universal",
"filename": "splash.png",
"filename" : "splash-2732x2732-2.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "splash-2732x2732-1.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "splash-2732x2732.png",
"scale" : "3x"
}
],
"info" : {
"author": "appsuite",
"version": 1
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 480 KiB

+5 -5
View File
@@ -7,7 +7,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>Qoutelink</string>
<string>kumusha</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -48,17 +48,17 @@
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library so you can attach site photos and references to your requests.</string>
<string>Kumusha needs access to your photo library so you can add profile and recipient photos.</string>
<key>NSCameraUsageDescription</key>
<string>We need access to your camera so you can take site photos for your requests.</string>
<string>Kumusha needs camera access so you can add profile and recipient photos.</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.qoutelink.app</string>
<string>com.kumusha.app</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.qoutelink.app</string>
<string>com.kumusha.app</string>
</array>
</dict>
</array>
+3
View File
@@ -14,12 +14,14 @@
"@capacitor/android": "8.3.4",
"@capacitor/app": "8.1.0",
"@capacitor/core": "8.3.4",
"@capacitor/filesystem": "^8.1.2",
"@capacitor/google-maps": "^8.0.0",
"@capacitor/haptics": "8.0.2",
"@capacitor/ios": "8.3.4",
"@capacitor/keyboard": "8.0.3",
"@capacitor/preferences": "^8.0.1",
"@capacitor/push-notifications": "^8.1.1",
"@capacitor/share": "^8.0.1",
"@capacitor/status-bar": "8.0.2",
"@hookform/resolvers": "^3.9.0",
"@ionic/pwa-elements": "^3.0.0",
@@ -29,6 +31,7 @@
"firebase": "^11.0.0",
"ionicons": "^7.4.0",
"katex": "^0.16.0",
"qrcode.react": "^4.2.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.54.0",
+286 -25
View File
@@ -1,53 +1,314 @@
import React, { useEffect } from 'react';
import { IonApp } from '@ionic/react';
import { Redirect, Route, useHistory, useLocation } from 'react-router-dom';
import {
IonApp,
IonIcon,
IonLabel,
IonRouterOutlet,
IonTabBar,
IonTabButton,
IonTabs,
} from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router';
import { Capacitor } from '@capacitor/core';
import { PushNotifications } from '@capacitor/push-notifications';
import type {
ActionPerformed,
PushNotificationSchema,
} from '@capacitor/push-notifications';
import { supabase } from './supabase';
import {
heart,
heartOutline,
listOutline,
peopleOutline,
personOutline,
} from 'ionicons/icons';
import { AuthProvider } from './contexts/AuthContext';
import { ProfileProvider, useProfile } from './contexts/ProfileContext';
import AppRoutes from './AppRoutes';
import { setStatusBarStyle, Style } from './utils/statusBar';
/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';
/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';
/* Optional CSS utils that can be commented out */
import '@ionic/react/css/padding.css';
import '@ionic/react/css/float-elements.css';
import '@ionic/react/css/text-alignment.css';
import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';
/* Theme variables */
import '@ionic/react/css/palettes/dark.system.css';
import './theme/variables.css';
const AppShell: React.FC = () => {
const { themeMode } = useProfile();
import { setStatusBarStyle, Style } from './utils/statusBar';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import ProtectedRoute from './components/ProtectedRoute';
useEffect(() => {
document.body.classList.toggle('dark', themeMode === 'dark');
setStatusBarStyle(themeMode === 'dark' ? Style.Dark : Style.Light);
}, [themeMode]);
// Auth Pages
import AuthPage from './pages/AuthPage';
import VerifyEmailPage from './pages/VerifyEmailPage';
import ForgotPasswordPage from './pages/ForgotPasswordPage';
import VerifyResetPage from './pages/VerifyResetPage';
import SetupProfilePage from './pages/SetupProfilePage';
// Main App Pages
import HomePage from './pages/HomePage';
import RecipientsPage from './pages/RecipientsPage';
import RecipientFormPage from './pages/RecipientFormPage';
import RecipientDetailPage from './pages/RecipientDetailPage';
import SupportFlowPage from './pages/SupportFlowPage';
import OrderDetailPage from './pages/OrderDetailPage';
import VoucherDetailPage from './pages/VoucherDetailPage';
import ActivityPage from './pages/ActivityPage';
import NotificationsPage from './pages/NotificationsPage';
import ProfilePage from './pages/ProfilePage';
import EditProfilePage from './pages/EditProfilePage';
const SetupProfileRoute: React.FC = () => {
const { user, profileStatus } = useAuth();
return (
<IonReactRouter>
<AppRoutes />
</IonReactRouter>
<Route
path="/setup-profile"
render={() => {
if (!user) return <Redirect to="/auth" />;
if (profileStatus === 'loading') return null;
if (profileStatus === 'loaded') return <Redirect to="/home" />;
return <SetupProfilePage />;
}}
exact
/>
);
};
const SendSupportFab: React.FC = () => {
const history = useHistory();
const location = useLocation();
const hiddenPaths = [
'/auth',
'/verify-email',
'/forgot-password',
'/verify-reset',
'/setup-profile',
'/support/new',
];
const showOnPaths = ['/home', '/recipients', '/activity', '/profile'];
const isVisibleRoute =
showOnPaths.includes(location.pathname) ||
/^\/recipients\/[0-9a-fA-F-]{36}$/.test(location.pathname);
if (!isVisibleRoute || hiddenPaths.includes(location.pathname)) return null;
return (
<button
type="button"
className="app-send-support-fab"
aria-label="Send support"
onClick={() => history.push('/support/new')}
>
<IonIcon icon={heart} />
</button>
);
};
const PushNotificationHandler: React.FC = () => {
const { user, profile } = useAuth();
const history = useHistory();
useEffect(() => {
if (!Capacitor.isNativePlatform() || !user || !profile) return;
const setupPush = async () => {
const handleNotificationTap = (notification: PushNotificationSchema) => {
const { orderId, voucherId, screen } = notification.data || {};
if (voucherId) {
history.push(`/voucher/${voucherId}`, { parentRoot: '/home' });
} else if (orderId) {
history.push(`/orders/${orderId}`, { parentRoot: '/home' });
} else if (screen) {
history.push(screen, { parentRoot: '/home' });
}
};
// Capacitor automatically triggers pushNotificationActionPerformed
// for the notification that launched the app once the listener is attached.
// Check if user has explicitly enabled push notifications
if (!profile.notification_push_enabled) return;
const status = await PushNotifications.checkPermissions();
if (status.receive === 'granted') {
await PushNotifications.register();
} else if (status.receive === 'prompt') {
const result = await PushNotifications.requestPermissions();
if (result.receive === 'granted') {
await PushNotifications.register();
}
}
PushNotifications.addListener('registration', async (token) => {
await supabase
.from('profiles')
.update({ fcm_token: token.value })
.eq('id', user.id);
});
PushNotifications.addListener('registrationError', (err) => {
console.error('Push registration error:', err);
});
PushNotifications.addListener('pushNotificationReceived', () => {
// Handled natively via presentationOptions banner
});
PushNotifications.addListener(
'pushNotificationActionPerformed',
(action: ActionPerformed) => {
handleNotificationTap(action.notification);
}
);
await PushNotifications.removeAllDeliveredNotifications();
};
setupPush();
return () => {
if (Capacitor.isNativePlatform()) {
PushNotifications.removeAllListeners();
}
};
}, [user, profile, history]);
return null;
};
const RootRedirect: React.FC = () => {
const { user, profileStatus } = useAuth();
if (!user) return <Redirect to="/auth" />;
if (profileStatus === 'loading') return null;
if (profileStatus === 'missing') {
return <Redirect to="/setup-profile" />;
}
return <Redirect to="/home" />;
};
const App: React.FC = () => {
useEffect(() => {
setStatusBarStyle(Style.Light);
}, []);
return (
<IonApp>
<AuthProvider>
<ProfileProvider>
<AppShell />
</ProfileProvider>
<IonReactRouter>
<IonRouterOutlet>
{/* Auth Routes */}
<Route path="/auth" component={AuthPage} exact />
<Route path="/verify-email" component={VerifyEmailPage} exact />
<Route
path="/forgot-password"
component={ForgotPasswordPage}
exact
/>
<Route path="/verify-reset" component={VerifyResetPage} exact />
{/* Setup Profile Route - Requires authenticated user but not necessarily complete profile */}
<SetupProfileRoute />
{/* Top-level Protected Routes (no tab bar) */}
<ProtectedRoute
path="/support/new"
component={SupportFlowPage}
exact
/>
<ProtectedRoute
path="/orders/:id([0-9a-fA-F-]{36})"
component={OrderDetailPage}
exact
/>
<ProtectedRoute
path="/recipients/new"
component={RecipientFormPage}
exact
/>
<ProtectedRoute
path="/recipients/:id([0-9a-fA-F-]{36})"
component={RecipientDetailPage}
exact
/>
<ProtectedRoute
path="/recipients/:id([0-9a-fA-F-]{36})/edit"
component={RecipientFormPage}
exact
/>
<ProtectedRoute
path="/profile/edit"
component={EditProfilePage}
exact
/>
<ProtectedRoute
path="/notifications"
component={NotificationsPage}
exact
/>
<ProtectedRoute
path="/voucher/:id([0-9a-fA-F-]{36})"
component={VoucherDetailPage}
exact
/>
{/* Tab Routes */}
<ProtectedRoute
path={['/home', '/recipients', '/activity', '/profile']}
exact
component={() => (
<IonTabs>
<IonRouterOutlet>
<Route path="/home" component={HomePage} exact />
<Route
path="/recipients"
component={RecipientsPage}
exact
/>
<Route path="/activity" component={ActivityPage} exact />
<Route path="/profile" component={ProfilePage} exact />
</IonRouterOutlet>
<IonTabBar slot="bottom" className="app-tab-bar">
<IonTabButton tab="home" href="/home">
<IonIcon icon={heartOutline} />
<IonLabel>Care</IonLabel>
</IonTabButton>
<IonTabButton tab="recipients" href="/recipients">
<IonIcon icon={peopleOutline} />
<IonLabel>Recipients</IonLabel>
</IonTabButton>
<IonTabButton disabled tab="send-support-fab" />
<IonTabButton tab="activity" href="/activity">
<IonIcon icon={listOutline} />
<IonLabel>Activity</IonLabel>
</IonTabButton>
<IonTabButton tab="profile" href="/profile">
<IonIcon icon={personOutline} />
<IonLabel>Profile</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
)}
/>
{/* Orders Redirect */}
<Route
exact
path="/orders"
render={() => <Redirect to="/activity" />}
/>
{/* Root Redirect */}
<Route exact path="/" component={RootRedirect} />
</IonRouterOutlet>
<SendSupportFab />
<PushNotificationHandler />
</IonReactRouter>
</AuthProvider>
</IonApp>
);
-105
View File
@@ -1,105 +0,0 @@
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import {
IonRouterOutlet,
IonTabs,
IonTabBar,
IonTabButton,
IonIcon,
IonLabel,
} from '@ionic/react';
import {
homeOutline,
documentTextOutline,
personOutline,
} from 'ionicons/icons';
import { useAuth } from './contexts/AuthContext';
import Auth from './pages/Auth';
import VerifyEmail from './pages/VerifyEmail';
import ForgotPassword from './pages/ForgotPassword';
import VerifyReset from './pages/VerifyReset';
import SetupProfile from './pages/SetupProfile';
import Home from './pages/Home';
import BuyerRequests from './pages/BuyerRequests';
import NewRfq from './pages/NewRfq';
import RfqDetail from './pages/RfqDetail';
import SupplierQuoteForm from './pages/SupplierQuoteForm';
import BuyerQuoteList from './pages/BuyerQuoteList';
import Profile from './pages/Profile';
import EditProfile from './pages/EditProfile';
import ProtectedRoute from './components/ProtectedRoute';
const AppRoutes: React.FC = () => {
const { user } = useAuth();
return (
<IonRouterOutlet>
{/* Auth routes */}
<Route path="/auth" component={Auth} exact />
<Route path="/verify-email" component={VerifyEmail} exact />
<Route path="/forgot-password" component={ForgotPassword} exact />
<Route path="/verify-reset" component={VerifyReset} exact />
{/* Setup Profile (guarded manually by user presence, not ProtectedRoute to avoid loop) */}
<Route
path="/setup-profile"
exact
render={() => (!user ? <Redirect to="/auth" /> : <SetupProfile />)}
/>
{/* Pushed routes without tab bar */}
<ProtectedRoute path="/rfq/new" component={NewRfq} exact />
<ProtectedRoute
path="/rfq/:id([0-9a-fA-F-]{36})"
component={RfqDetail}
exact
/>
<ProtectedRoute
path="/quote/:id([0-9a-fA-F-]{36})"
component={SupplierQuoteForm}
exact
/>
<ProtectedRoute
path="/quote-list/:id([0-9a-fA-F-]{36})"
component={BuyerQuoteList}
exact
/>
<ProtectedRoute path="/profile/edit" component={EditProfile} exact />
{/* Tabs */}
<ProtectedRoute
path={['/home', '/requests', '/profile']}
component={() => (
<IonTabs>
<IonRouterOutlet>
<Route path="/home" component={Home} exact />
<Route path="/requests" component={BuyerRequests} exact />
<Route path="/profile" component={Profile} exact />
</IonRouterOutlet>
<IonTabBar slot="bottom">
<IonTabButton tab="home" href="/home">
<IonIcon icon={homeOutline} />
<IonLabel>Home</IonLabel>
</IonTabButton>
<IonTabButton tab="requests" href="/requests">
<IonIcon icon={documentTextOutline} />
<IonLabel>Requests</IonLabel>
</IonTabButton>
<IonTabButton tab="profile" href="/profile">
<IonIcon icon={personOutline} />
<IonLabel>Profile</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
)}
/>
{/* Default Redirect */}
<Route exact path="/" render={() => <Redirect to="/home" />} />
</IonRouterOutlet>
);
};
export default AppRoutes;
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

+155
View File
@@ -0,0 +1,155 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import {
medkitOutline,
flashOutline,
phonePortraitOutline,
chevronForwardOutline,
} from 'ionicons/icons';
import momImage from '../assets/mom.jpg';
import dadImage from '../assets/dad.jpg';
import basketIcon from '../assets/basket.png';
interface ActivityListItemProps {
id: string;
eventType: string;
title: string;
subtitle: string;
amount?: number;
statusText?: string;
statusTone?: 'success' | 'warning' | 'partial';
avatarLabel?: string;
avatarTone?: string;
avatarImage?: string;
onClick?: (id: string) => void;
onStatusClick?: () => void;
}
const ActivityListItem: React.FC<ActivityListItemProps> = ({
id,
eventType,
title,
subtitle,
amount,
statusText,
statusTone = 'warning',
avatarLabel,
avatarTone = 'brand',
avatarImage,
onClick,
onStatusClick,
}) => {
const getIconAndColor = () => {
if (
eventType.includes('grocery') ||
title.toLowerCase().includes('grocer')
) {
return {
iconSrc: basketIcon,
badgeClass: 'grocery',
};
}
if (
eventType.includes('medication') ||
title.toLowerCase().includes('medic')
) {
return {
icon: medkitOutline,
badgeClass: 'medication',
};
}
if (
eventType.includes('airtime') ||
title.toLowerCase().includes('airtime')
) {
return {
icon: phonePortraitOutline,
badgeClass: 'airtime',
};
}
return {
icon: flashOutline,
badgeClass: 'electricity',
};
};
const { icon, iconSrc, badgeClass } = getIconAndColor();
const avatarSearchText =
`${title} ${subtitle} ${avatarLabel ?? ''}`.toLowerCase();
const resolvedAvatar =
avatarImage ??
(avatarSearchText.includes('mum') || avatarSearchText.includes('mom')
? momImage
: avatarSearchText.includes('dad') || avatarSearchText.includes('father')
? dadImage
: undefined);
return (
<button
type="button"
onClick={() => onClick && onClick(id)}
className="activity-feed-item"
disabled={!onClick}
>
<div className="activity-feed-avatar-wrap">
<div
className={`activity-feed-avatar activity-feed-avatar-${avatarTone}`}
>
{resolvedAvatar ? (
<img
src={resolvedAvatar}
alt=""
className="activity-feed-avatar-image"
/>
) : (
<span>{avatarLabel ?? 'KU'}</span>
)}
<div
className={`activity-feed-avatar-badge activity-feed-avatar-badge-${badgeClass}`}
>
{iconSrc ? (
<img src={iconSrc} alt="" className="activity-feed-badge-image" />
) : (
<IonIcon icon={icon} />
)}
</div>
</div>
</div>
<div className="activity-feed-main">
<div className="activity-feed-row">
<div className="activity-feed-copy">
<p className="activity-feed-title">{title}</p>
<p className="activity-feed-subtitle">{subtitle}</p>
</div>
<div className="activity-feed-right">
{amount !== undefined && (
<p className="activity-feed-amount">${amount.toFixed(2)}</p>
)}
{statusText && (
<button
type="button"
className={`activity-feed-status activity-feed-status-${statusTone}`}
onClick={(event) => {
event.stopPropagation();
if (onStatusClick) {
onStatusClick();
return;
}
onClick?.(id);
}}
>
<span>{statusText}</span>
<IonIcon icon={chevronForwardOutline} />
</button>
)}
</div>
</div>
</div>
</button>
);
};
export default ActivityListItem;
+116
View File
@@ -0,0 +1,116 @@
import React, { useState } from 'react';
import { eyeOffOutline, eyeOutline } from 'ionicons/icons';
import { IonIcon } from '@ionic/react';
interface AuthFormFieldsProps {
mode: 'login' | 'register';
email: string;
password: string;
confirmPassword?: string;
onEmailChange: (val: string) => void;
onPasswordChange: (val: string) => void;
onConfirmPasswordChange?: (val: string) => void;
errors?: { [key: string]: string };
disabled?: boolean;
}
const AuthFormFields: React.FC<AuthFormFieldsProps> = ({
mode,
email,
password,
confirmPassword,
onEmailChange,
onPasswordChange,
onConfirmPasswordChange,
errors = {},
disabled = false,
}) => {
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
return (
<div className="auth-form-fields">
<div className="field-group">
<label className="auth-field-label">Email address</label>
<input
className={`auth-text-input ${errors.email ? 'has-error' : ''}`}
type="email"
value={email}
onChange={(e) => onEmailChange(e.target.value)}
disabled={disabled}
placeholder="you@example.com"
autoComplete="email"
/>
{errors.email ? (
<p className="auth-field-error">{errors.email}</p>
) : null}
</div>
<div className="field-group">
<label className="auth-field-label">Password</label>
<div className="auth-password-wrap">
<input
className={`auth-text-input ${errors.password ? 'has-error' : ''}`}
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => onPasswordChange(e.target.value)}
disabled={disabled}
placeholder="Enter your password"
autoComplete={
mode === 'login' ? 'current-password' : 'new-password'
}
/>
<button
type="button"
className="auth-password-toggle"
onClick={() => setShowPassword((value) => !value)}
disabled={disabled}
aria-label={showPassword ? 'Hide password' : 'Show password'}
>
<IonIcon icon={showPassword ? eyeOffOutline : eyeOutline} />
</button>
</div>
{errors.password ? (
<p className="auth-field-error">{errors.password}</p>
) : null}
</div>
{mode === 'register' && onConfirmPasswordChange && (
<div className="field-group">
<label className="auth-field-label">Confirm password</label>
<div className="auth-password-wrap">
<input
className={`auth-text-input ${errors.confirmPassword ? 'has-error' : ''}`}
type={showConfirmPassword ? 'text' : 'password'}
value={confirmPassword}
onChange={(e) => onConfirmPasswordChange(e.target.value)}
disabled={disabled}
placeholder="Re-enter your password"
autoComplete="new-password"
/>
<button
type="button"
className="auth-password-toggle"
onClick={() => setShowConfirmPassword((value) => !value)}
disabled={disabled}
aria-label={
showConfirmPassword
? 'Hide confirm password'
: 'Show confirm password'
}
>
<IonIcon
icon={showConfirmPassword ? eyeOffOutline : eyeOutline}
/>
</button>
</div>
{errors.confirmPassword ? (
<p className="auth-field-error">{errors.confirmPassword}</p>
) : null}
</div>
)}
</div>
);
};
export default AuthFormFields;
+121
View File
@@ -0,0 +1,121 @@
import React, { useRef } from 'react';
import { IonIcon } from '@ionic/react';
import { camera, personOutline } from 'ionicons/icons';
interface AvatarPickerProps {
previewUrl: string | null;
onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
initials?: string;
disabled?: boolean;
}
const AvatarPicker: React.FC<AvatarPickerProps> = ({
previewUrl,
onFileChange,
initials,
disabled = false,
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const handleClick = () => {
if (!disabled) {
fileInputRef.current?.click();
}
};
return (
<div
className="avatar-picker-container"
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
margin: '8px 0 4px',
}}
>
<button
type="button"
aria-label={previewUrl ? 'Change photo' : 'Add photo'}
onClick={handleClick}
disabled={disabled}
style={{
position: 'relative',
width: '96px',
height: '96px',
padding: 0,
border: 'none',
background: 'transparent',
cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.6 : 1,
}}
>
<div
className="avatar-preview-circle"
style={{
width: '88px',
height: '88px',
margin: '0 auto',
borderRadius: '24px',
backgroundColor: previewUrl
? 'transparent'
: 'rgba(109,40,217,0.10)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
}}
>
{previewUrl ? (
<img
src={previewUrl}
alt="Avatar preview"
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : initials ? (
<span
style={{ fontSize: '28px', fontWeight: '700', color: '#6d28d9' }}
>
{initials}
</span>
) : (
<IonIcon
icon={personOutline}
style={{ fontSize: '32px', color: '#6d28d9' }}
/>
)}
</div>
<div
style={{
position: 'absolute',
right: '0px',
bottom: '0px',
width: '36px',
height: '36px',
borderRadius: '12px',
background: '#ffffff',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
boxShadow: '0 8px 16px rgba(109, 40, 217, 0.15)',
}}
>
<IonIcon
icon={camera}
style={{ fontSize: '20px', color: '#6d28d9' }}
/>
</div>
</button>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={onFileChange}
disabled={disabled}
style={{ display: 'none' }}
/>
</div>
);
};
export default AvatarPicker;
+88
View File
@@ -0,0 +1,88 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import {
chevronForwardOutline,
timeOutline,
flashOutline,
wifiOutline,
medkitOutline,
} from 'ionicons/icons';
interface CareAlertPillProps {
id: string;
type: string;
title: string;
severity: 'warning' | 'neutral';
onClick: (id: string) => void;
}
const CareAlertPill: React.FC<CareAlertPillProps> = ({
id,
type,
title,
severity,
onClick,
}) => {
const getIconForType = () => {
switch (type) {
case 'electricity_low':
return flashOutline;
case 'airtime_expiring':
return wifiOutline;
case 'medication_due':
return medkitOutline;
default:
return timeOutline;
}
};
const getColors = () => {
if (severity === 'warning') {
return { bg: 'rgba(245,158,11,0.08)', icon: '#f59e0b', text: '#111827' };
}
return { bg: '#ffffff', icon: '#6d28d9', text: '#111827' };
};
const colors = getColors();
return (
<button
onClick={() => onClick(id)}
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
backgroundColor: colors.bg,
borderRadius: '24px',
padding: '14px 16px',
border: 'none',
flexShrink: 0,
maxWidth: '280px',
cursor: 'pointer',
}}
>
<IonIcon
icon={getIconForType()}
style={{ fontSize: '20px', color: colors.icon, flexShrink: 0 }}
/>
<span
style={{
fontSize: '13px',
fontWeight: '600',
color: colors.text,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{title}
</span>
<IonIcon
icon={chevronForwardOutline}
style={{ fontSize: '16px', color: '#9ca3af', marginLeft: 'auto' }}
/>
</button>
);
};
export default CareAlertPill;
-97
View File
@@ -1,97 +0,0 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
interface DashboardMetricCardProps {
label: string;
value: string;
hint: string;
icon: string;
onClick?: () => void;
}
const DashboardMetricCard: React.FC<DashboardMetricCardProps> = ({
label,
value,
hint,
icon,
onClick,
}) => {
return (
<div
onClick={onClick}
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
flex: '1',
display: 'flex',
flexDirection: 'column',
gap: '12px',
cursor: onClick ? 'pointer' : 'default',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
gap: '12px',
}}
>
<span
style={{
fontSize: '12px',
fontWeight: '700',
color: 'var(--color-text-tertiary)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{label}
</span>
<div
style={{
width: '36px',
height: '36px',
borderRadius: '12px',
background: 'var(--color-brand-medium)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<IonIcon
icon={icon}
style={{ color: 'var(--color-brand)', fontSize: '18px' }}
/>
</div>
</div>
<div>
<div
style={{
fontSize: '28px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1',
fontVariantNumeric: 'tabular-nums',
}}
>
{value}
</div>
<div
style={{
fontSize: '12px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
marginTop: '8px',
}}
>
{hint}
</div>
</div>
</div>
);
};
export default DashboardMetricCard;
+246
View File
@@ -0,0 +1,246 @@
import React from 'react';
import { IonSkeletonText } from '@ionic/react';
const DashboardSkeleton: React.FC = () => {
return (
<div style={{ padding: '0' }}>
{/* Top Greeting Row */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '16px 20px 12px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<IonSkeletonText
animated
style={{ width: '48px', height: '48px', borderRadius: '50%' }}
/>
<div>
<IonSkeletonText
animated
style={{
width: '120px',
height: '18px',
borderRadius: '4px',
marginBottom: '8px',
}}
/>
<IonSkeletonText
animated
style={{ width: '80px', height: '14px', borderRadius: '4px' }}
/>
</div>
</div>
</div>
{/* Loved Ones Carousel */}
<div
style={{
padding: '0 20px 6px',
display: 'flex',
gap: '12px',
overflowX: 'hidden',
}}
>
<div
style={{
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
width: '292px',
flexShrink: 0,
display: 'flex',
flexDirection: 'column',
gap: '14px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<IonSkeletonText
animated
style={{ width: '48px', height: '48px', borderRadius: '16px' }}
/>
<div style={{ flex: 1 }}>
<IonSkeletonText
animated
style={{
width: '100px',
height: '16px',
borderRadius: '4px',
marginBottom: '4px',
}}
/>
<IonSkeletonText
animated
style={{ width: '80px', height: '12px', borderRadius: '4px' }}
/>
</div>
</div>
<IonSkeletonText
animated
style={{ width: '100%', height: '48px', borderRadius: '12px' }}
/>
<IonSkeletonText
animated
style={{
width: '100%',
height: '48px',
borderRadius: '999px',
marginTop: 'auto',
}}
/>
</div>
<div
style={{
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
width: '292px',
flexShrink: 0,
display: 'flex',
flexDirection: 'column',
gap: '14px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<IonSkeletonText
animated
style={{ width: '48px', height: '48px', borderRadius: '16px' }}
/>
<div style={{ flex: 1 }}>
<IonSkeletonText
animated
style={{
width: '100px',
height: '16px',
borderRadius: '4px',
marginBottom: '4px',
}}
/>
<IonSkeletonText
animated
style={{ width: '80px', height: '12px', borderRadius: '4px' }}
/>
</div>
</div>
<IonSkeletonText
animated
style={{ width: '100%', height: '48px', borderRadius: '12px' }}
/>
<IonSkeletonText
animated
style={{
width: '100%',
height: '48px',
borderRadius: '999px',
marginTop: 'auto',
}}
/>
</div>
</div>
{/* Quick Actions */}
<div style={{ padding: '0 20px', margin: '20px 0' }}>
<IonSkeletonText
animated
style={{
width: '120px',
height: '16px',
borderRadius: '4px',
marginBottom: '16px',
}}
/>
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(2, 1fr)',
gap: '12px',
}}
>
{[1, 2, 3, 4].map((i) => (
<div
key={i}
style={{
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
display: 'flex',
alignItems: 'center',
gap: '12px',
}}
>
<IonSkeletonText
animated
style={{ width: '44px', height: '44px', borderRadius: '12px' }}
/>
<IonSkeletonText
animated
style={{ width: '60px', height: '14px', borderRadius: '4px' }}
/>
</div>
))}
</div>
</div>
{/* Activity List */}
<div style={{ padding: '0 20px', margin: '20px 0' }}>
<IonSkeletonText
animated
style={{
width: '100px',
height: '16px',
borderRadius: '4px',
marginBottom: '16px',
}}
/>
<div
style={{
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '8px 0',
}}
>
{[1, 2, 3].map((i) => (
<div
key={i}
style={{
display: 'flex',
alignItems: 'center',
padding: '14px 16px',
gap: '12px',
}}
>
<IonSkeletonText
animated
style={{ width: '40px', height: '40px', borderRadius: '12px' }}
/>
<div style={{ flex: 1 }}>
<IonSkeletonText
animated
style={{
width: '140px',
height: '14px',
borderRadius: '4px',
marginBottom: '6px',
}}
/>
<IonSkeletonText
animated
style={{
width: '100px',
height: '12px',
borderRadius: '4px',
}}
/>
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default DashboardSkeleton;
+86
View File
@@ -0,0 +1,86 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import { searchOutline, optionsOutline } from 'ionicons/icons';
interface ListSearchRowProps {
value: string;
onChange: (val: string) => void;
placeholder?: string;
onFilterClick?: () => void;
showFilter?: boolean;
}
const ListSearchRow: React.FC<ListSearchRowProps> = ({
value,
onChange,
placeholder = 'Search...',
onFilterClick,
showFilter = false,
}) => {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
margin: '0 20px 12px',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
flex: 1,
backgroundColor: '#ffffff',
borderRadius: '16px',
padding: '0 16px',
height: '48px',
}}
>
<IonIcon
icon={searchOutline}
style={{ fontSize: '20px', color: '#9ca3af', flexShrink: 0 }}
/>
<input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
style={{
flex: 1,
border: 'none',
outline: 'none',
backgroundColor: 'transparent',
padding: '0 12px',
fontSize: '15px',
color: '#111827',
}}
/>
</div>
{showFilter && (
<button
onClick={onFilterClick}
style={{
width: '48px',
height: '48px',
borderRadius: '16px',
backgroundColor: '#ffffff',
border: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
cursor: 'pointer',
}}
>
<IonIcon
icon={optionsOutline}
style={{ fontSize: '20px', color: '#6d28d9' }}
/>
</button>
)}
</div>
);
};
export default ListSearchRow;
+210
View File
@@ -0,0 +1,210 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import {
chevronForwardOutline,
checkmarkCircleOutline,
timeOutline,
closeCircleOutline,
} from 'ionicons/icons';
export interface OrderSummary {
id: string;
recipientName: string;
serviceType: string;
merchantName?: string;
amount: number;
amountLabel?: string;
status: string;
createdAt: string;
avatarUrl?: string | null;
}
interface OrderSummaryCardProps {
order: OrderSummary;
onClick: (id: string) => void;
}
const OrderSummaryCard: React.FC<OrderSummaryCardProps> = ({
order,
onClick,
}) => {
const getStatusDisplay = (status: string) => {
switch (status) {
case 'paid':
return {
text: 'Paid',
color: '#3b82f6',
bg: 'rgba(59,130,246,0.1)',
icon: checkmarkCircleOutline,
};
case 'ready_for_redemption':
return {
text: 'Ready',
color: '#16a34a',
bg: 'rgba(22,163,74,0.1)',
icon: checkmarkCircleOutline,
};
case 'redeemed':
return {
text: 'Redeemed',
color: '#16a34a',
bg: 'rgba(22,163,74,0.1)',
icon: checkmarkCircleOutline,
};
case 'delivered':
return {
text: 'Delivered',
color: '#16a34a',
bg: 'rgba(22,163,74,0.1)',
icon: checkmarkCircleOutline,
};
case 'pending_payment':
return {
text: 'Pending',
color: '#f59e0b',
bg: 'rgba(245,158,11,0.1)',
icon: timeOutline,
};
case 'failed':
case 'cancelled':
return {
text: 'Failed',
color: '#ef4444',
bg: 'rgba(239,68,68,0.1)',
icon: closeCircleOutline,
};
default:
return {
text: status,
color: '#6b7280',
bg: '#f3f4f6',
icon: timeOutline,
};
}
};
const statusDisplay = getStatusDisplay(order.status);
return (
<div
onClick={() => onClick(order.id)}
style={{
display: 'flex',
alignItems: 'center',
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
margin: '0 20px 12px',
gap: '14px',
cursor: 'pointer',
}}
>
<div
style={{
width: '48px',
height: '48px',
borderRadius: '16px',
backgroundColor: 'rgba(109,40,217,0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
flexShrink: 0,
}}
>
{order.avatarUrl ? (
<img
src={order.avatarUrl}
alt={order.recipientName}
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : (
<span
style={{ fontSize: '18px', fontWeight: '700', color: '#6d28d9' }}
>
{order.recipientName.charAt(0)}
</span>
)}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: '#111827',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{order.serviceType} for {order.recipientName}
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: '#6b7280',
marginTop: '2px',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{order.merchantName || 'Service provider'}
</div>
<div
style={{
fontSize: '12px',
fontWeight: '400',
color: '#9ca3af',
marginTop: '4px',
}}
>
{new Date(order.createdAt).toLocaleDateString()}
</div>
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-end',
gap: '6px',
}}
>
<span style={{ fontSize: '15px', fontWeight: '700', color: '#111827' }}>
{order.amountLabel ?? `${order.amount.toFixed(2)}`}
</span>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '4px',
backgroundColor: statusDisplay.bg,
padding: '2px 8px',
borderRadius: '999px',
}}
>
<span
style={{
fontSize: '11px',
fontWeight: '700',
color: statusDisplay.color,
}}
>
{statusDisplay.text}
</span>
<IonIcon
icon={statusDisplay.icon}
style={{ fontSize: '12px', color: statusDisplay.color }}
/>
</div>
</div>
<IonIcon
icon={chevronForwardOutline}
style={{ fontSize: '16px', color: '#9ca3af', marginLeft: '4px' }}
/>
</div>
);
};
export default OrderSummaryCard;
-82
View File
@@ -1,82 +0,0 @@
import React, { useRef, useState } from 'react';
import { IonInput } from '@ionic/react';
interface OtpInputProps {
value: string;
onChange: (value: string) => void;
disabled?: boolean;
}
const OtpInput: React.FC<OtpInputProps> = ({ value, onChange, disabled }) => {
const inputsRef = useRef<(HTMLInputElement | null)[]>([]);
// Convert current value string into an array of 6 chars
const digits = value.split('').concat(Array(6).fill('')).slice(0, 6);
const handleChange = (e: any, index: number) => {
let val = e.target.value;
// Allow only numeric
if (!/^[0-9]*$/.test(val)) return;
// Grab the last character if they typed multiple
val = val.substring(val.length - 1);
const newDigits = [...digits];
newDigits[index] = val;
onChange(newDigits.join(''));
// Move to next input if filled
if (val !== '' && index < 5) {
const nextInput = inputsRef.current[index + 1];
if (nextInput) nextInput.focus();
}
};
const handleKeyDown = (
e: React.KeyboardEvent<HTMLInputElement>,
index: number
) => {
if (e.key === 'Backspace' && !digits[index] && index > 0) {
// Move to previous input on backspace if current is empty
const prevInput = inputsRef.current[index - 1];
if (prevInput) {
prevInput.focus();
}
}
};
return (
<div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
{digits.map((digit, index) => (
<input
key={index}
ref={(el) => {
inputsRef.current[index] = el;
}}
type="text"
inputMode="numeric"
pattern="[0-9]*"
maxLength={2}
value={digit}
onChange={(e) => handleChange(e, index)}
onKeyDown={(e) => handleKeyDown(e, index)}
disabled={disabled}
style={{
width: '100%',
maxWidth: '48px',
height: '52px',
borderRadius: '12px',
border: 'none',
background: '#f4f7f4',
color: '#0f1720',
textAlign: 'center',
fontSize: '24px',
fontWeight: '600',
}}
/>
))}
</div>
);
};
export default OtpInput;
+82
View File
@@ -0,0 +1,82 @@
import React, { useRef } from 'react';
interface OtpInputSlotsProps {
value: string[];
onChange: (index: number, val: string) => void;
onPaste: (e: React.ClipboardEvent<HTMLInputElement>) => void;
disabled?: boolean;
}
const OtpInputSlots: React.FC<OtpInputSlotsProps> = ({
value,
onChange,
onPaste,
disabled = false,
}) => {
const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
const handleKeyDown = (
index: number,
e: React.KeyboardEvent<HTMLInputElement>
) => {
if (e.key === 'Backspace' && value[index] === '') {
if (index > 0) {
inputRefs.current[index - 1]?.focus();
}
}
};
const handleInput = (
index: number,
e: React.ChangeEvent<HTMLInputElement>
) => {
const val = e.target.value.replace(/[^0-9]/g, '');
const lastChar = val.slice(-1);
onChange(index, lastChar);
if (lastChar && index < 5) {
inputRefs.current[index + 1]?.focus();
}
};
return (
<div
className="otp-input-row"
style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}
>
{[0, 1, 2, 3, 4, 5].map((index) => (
<input
key={index}
ref={(el) => {
inputRefs.current[index] = el;
}}
type="text"
inputMode="numeric"
pattern="[0-9]*"
maxLength={1}
value={value[index] || ''}
onChange={(e) => handleInput(index, e)}
onKeyDown={(e) => handleKeyDown(index, e)}
onPaste={onPaste}
disabled={disabled}
style={{
width: '44px',
height: '56px',
textAlign: 'center',
fontSize: '24px',
fontWeight: '700',
color: value[index] ? '#6d28d9' : '#111827',
backgroundColor: value[index] ? 'rgba(109,40,217,0.08)' : '#fafafa',
border: 'none',
borderRadius: '12px',
outline: 'none',
}}
className="otp-slot"
/>
))}
</div>
);
};
export default OtpInputSlots;
-92
View File
@@ -1,92 +0,0 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
interface ProfileInfoRowProps {
icon: string;
label: string;
value?: string;
onClick?: () => void;
}
const ProfileInfoRow: React.FC<ProfileInfoRowProps> = ({
icon,
label,
value,
onClick,
}) => {
return (
<div
onClick={onClick}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
minHeight: '64px',
padding: '10px 20px',
cursor: onClick ? 'pointer' : 'default',
gap: '12px',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '14px',
minWidth: 0,
flex: 1,
}}
>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-surface-raised)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<IonIcon
icon={icon}
style={{ color: 'var(--color-brand)', fontSize: '20px' }}
/>
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '2px',
minWidth: 0,
}}
>
<span
style={{
fontSize: '12px',
fontWeight: '700',
color: 'var(--color-text-tertiary)',
textTransform: 'uppercase',
letterSpacing: '0.04em',
}}
>
{label}
</span>
{value && (
<span
style={{
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
}}
>
{value}
</span>
)}
</div>
</div>
</div>
);
};
export default ProfileInfoRow;
+16 -33
View File
@@ -1,28 +1,22 @@
import React, { useEffect } from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { IonSpinner } from '@ionic/react';
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { useProfileLoader } from '../hooks/useProfileLoader';
import SplashPage from '../pages/SplashPage';
interface ProtectedRouteProps extends RouteProps {
interface Props {
component: React.ComponentType<any>;
path: string | string[];
exact?: boolean;
}
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
component: Component,
...rest
}) => {
const { user } = useAuth();
const { status } = useProfile();
const { loadProfileAndNavigate } = useProfileLoader();
const BYPASS_AUTH = false;
useEffect(() => {
// If user is logged in but profile is still loading (e.g. cold start direct link)
if (user && status === 'loading') {
loadProfileAndNavigate();
}
}, [user, status, loadProfileAndNavigate]);
const ProtectedRouteLoader: React.FC = () => (
<SplashPage title="Send support to loved ones from anywhere" />
);
const ProtectedRoute: React.FC<Props> = ({ component: Component, ...rest }) => {
const { user, profile, profileStatus } = useAuth();
return (
<Route
@@ -31,21 +25,10 @@ const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
if (!user) {
return <Redirect to="/auth" />;
}
if (status === 'loading') {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
}}
>
<IonSpinner name="crescent" />
</div>
);
if (profileStatus === 'loading') {
return <ProtectedRouteLoader />;
}
if (status === 'missing') {
if (profileStatus === 'missing') {
return <Redirect to="/setup-profile" />;
}
return <Component {...props} />;
+94
View File
@@ -0,0 +1,94 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import {
cartOutline,
medkitOutline,
phonePortraitOutline,
flashOutline,
} from 'ionicons/icons';
interface QuickSupportActionCardProps {
serviceType: 'grocery' | 'medication' | 'airtime' | 'electricity';
label: string;
onClick: () => void;
}
const QuickSupportActionCard: React.FC<QuickSupportActionCardProps> = ({
serviceType,
label,
onClick,
}) => {
const getIconAndColor = () => {
switch (serviceType) {
case 'grocery':
return {
icon: cartOutline,
color: '#6d28d9',
bg: 'rgba(109,40,217,0.1)',
};
case 'medication':
return {
icon: medkitOutline,
color: '#ef4444',
bg: 'rgba(239,68,68,0.1)',
};
case 'airtime':
return {
icon: phonePortraitOutline,
color: '#3b82f6',
bg: 'rgba(59,130,246,0.1)',
};
case 'electricity':
return {
icon: flashOutline,
color: '#f59e0b',
bg: 'rgba(245,158,11,0.1)',
};
default:
return {
icon: cartOutline,
color: '#6d28d9',
bg: 'rgba(109,40,217,0.1)',
};
}
};
const { icon, color, bg } = getIconAndColor();
return (
<button
onClick={onClick}
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
border: 'none',
width: '100%',
cursor: 'pointer',
}}
>
<div
style={{
width: '44px',
height: '44px',
borderRadius: '12px',
backgroundColor: bg,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<IonIcon icon={icon} style={{ fontSize: '20px', color }} />
</div>
<span style={{ fontSize: '14px', fontWeight: '700', color: '#111827' }}>
{label}
</span>
</button>
);
};
export default QuickSupportActionCard;
-121
View File
@@ -1,121 +0,0 @@
import React from 'react';
interface QuotationCardProps {
supplierName: string;
priceLabel: string;
deliveryOption: string;
status: string;
onAccept: () => void;
onDecline: () => void;
}
const QuotationCard: React.FC<QuotationCardProps> = ({
supplierName,
priceLabel,
deliveryOption,
status,
onAccept,
onDecline,
}) => {
return (
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
}}
>
<div
style={{
fontSize: '16px',
fontWeight: '600',
color: 'var(--color-text-primary)',
marginBottom: '8px',
}}
>
{supplierName}
</div>
<div
style={{
fontSize: '30px',
fontWeight: '400',
color: 'var(--color-brand-strong)',
fontVariantNumeric: 'tabular-nums',
marginBottom: '6px',
}}
>
{priceLabel}
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
marginBottom: '18px',
}}
>
{deliveryOption}
</div>
{status === 'submitted' ? (
<div style={{ display: 'flex', gap: '12px' }}>
<button
onClick={onAccept}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '12px 16px',
border: 'none',
flex: 1,
fontWeight: '600',
fontSize: '14px',
cursor: 'pointer',
}}
>
Accept
</button>
<button
onClick={onDecline}
style={{
background: 'var(--color-surface-raised)',
color: 'var(--color-brand)',
borderRadius: '999px',
padding: '12px 16px',
border: 'none',
flex: 1,
fontWeight: '600',
fontSize: '14px',
cursor: 'pointer',
}}
>
Decline
</button>
</div>
) : (
<div
style={{
display: 'inline-block',
background:
status === 'accepted'
? 'var(--color-success-soft)'
: 'rgba(23,33,43,0.10)',
color:
status === 'accepted' ? 'var(--color-success-text)' : '#4b5563',
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
textTransform: 'capitalize',
}}
>
{status}
</div>
)}
</div>
);
};
export default QuotationCard;
-90
View File
@@ -1,90 +0,0 @@
import React from 'react';
interface QuoteSummaryRowProps {
supplierName: string;
priceLabel: string;
deliveryOption: string;
status: string;
onClick?: () => void;
}
const QuoteSummaryRow: React.FC<QuoteSummaryRowProps> = ({
supplierName,
priceLabel,
deliveryOption,
status,
onClick,
}) => {
return (
<div
onClick={onClick}
style={{
display: 'flex',
flexDirection: 'column',
gap: '4px',
padding: '12px 0',
borderBottom: '1px solid var(--color-border)',
cursor: onClick ? 'pointer' : 'default',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<span
style={{
fontSize: '15px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
{supplierName}
</span>
<span
style={{
fontSize: '15px',
fontWeight: '600',
color: 'var(--color-brand-strong)',
}}
>
{priceLabel}
</span>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<span
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
{deliveryOption}
</span>
<span
style={{
fontSize: '12px',
fontWeight: '600',
color:
status === 'accepted'
? 'var(--color-success-text)'
: 'var(--color-text-secondary)',
textTransform: 'capitalize',
}}
>
{status}
</span>
</div>
</div>
);
};
export default QuoteSummaryRow;
-83
View File
@@ -1,83 +0,0 @@
import React from 'react';
interface RecentActivityCardProps {
title: string;
subtitle: string;
meta: string;
onClick: () => void;
}
const RecentActivityCard: React.FC<RecentActivityCardProps> = ({
title,
subtitle,
meta,
onClick,
}) => {
return (
<div
onClick={onClick}
style={{
background: 'var(--color-shell)',
borderRadius: '38px',
padding: '5px',
margin: '0 20px 12px',
boxShadow: 'var(--color-shadow-lg)',
cursor: 'pointer',
}}
>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '32px',
padding: '18px 20px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '12px',
boxShadow: 'var(--color-shadow-sm)',
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '4px',
minWidth: 0,
}}
>
<span
style={{
fontSize: '16px',
fontWeight: '400',
color: 'var(--color-text-primary)',
}}
>
{title}
</span>
<span
style={{
fontSize: '12px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
{subtitle}
</span>
</div>
<div
style={{
fontSize: '18px',
fontWeight: '400',
color: 'var(--color-brand-strong)',
textTransform: 'capitalize',
flexShrink: 0,
}}
>
{meta}
</div>
</div>
</div>
);
};
export default RecentActivityCard;
+239
View File
@@ -0,0 +1,239 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import {
cartOutline,
medkitOutline,
flashOutline,
timeOutline,
checkmarkCircleOutline,
ellipsisVertical,
} from 'ionicons/icons';
export interface CareStatus {
serviceType: 'grocery' | 'medication' | 'electricity' | 'airtime';
label: string;
statusText: string;
isOk: boolean;
}
export interface RecipientSummary {
id: string;
firstName: string;
lastName: string;
location: string;
avatarUrl: string | null;
statuses: CareStatus[];
}
interface RecipientCareCardProps {
recipient: RecipientSummary;
onSendSupport: (id: string) => void;
onMenuClick?: (id: string) => void;
}
const getIconForService = (type: string) => {
switch (type) {
case 'grocery':
return cartOutline;
case 'medication':
return medkitOutline;
case 'electricity':
return flashOutline;
default:
return cartOutline;
}
};
const getColorForService = (type: string) => {
switch (type) {
case 'grocery':
return '#6d28d9';
case 'medication':
return '#ef4444';
case 'electricity':
return '#f59e0b';
default:
return '#3b82f6';
}
};
const RecipientCareCard: React.FC<RecipientCareCardProps> = ({
recipient,
onSendSupport,
onMenuClick,
}) => {
return (
<div
style={{
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
width: '292px',
display: 'flex',
flexDirection: 'column',
gap: '14px',
flexShrink: 0,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<div
style={{
width: '48px',
height: '48px',
borderRadius: '16px',
backgroundColor: 'rgba(109,40,217,0.1)',
overflow: 'hidden',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{recipient.avatarUrl ? (
<img
src={recipient.avatarUrl}
alt={recipient.firstName}
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : (
<span
style={{
fontSize: '18px',
fontWeight: '700',
color: '#6d28d9',
}}
>
{recipient.firstName.charAt(0)}
</span>
)}
</div>
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<h3
style={{
margin: 0,
fontSize: '16px',
fontWeight: '700',
color: '#111827',
}}
>
{recipient.firstName}
</h3>
<div
style={{
width: '8px',
height: '8px',
borderRadius: '50%',
backgroundColor: '#16a34a',
}}
/>
</div>
<p
style={{
margin: '2px 0 0',
fontSize: '13px',
fontWeight: '400',
color: '#6b7280',
}}
>
{recipient.location}
</p>
</div>
</div>
<button
onClick={() => onMenuClick && onMenuClick(recipient.id)}
style={{ background: 'transparent', border: 'none', padding: '4px' }}
>
<IonIcon
icon={ellipsisVertical}
style={{ fontSize: '20px', color: '#6b7280' }}
/>
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{recipient.statuses.map((status, idx) => (
<div
key={idx}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
backgroundColor: '#fafafa',
borderRadius: '12px',
padding: '12px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<IonIcon
icon={getIconForService(status.serviceType)}
style={{
fontSize: '18px',
color: getColorForService(status.serviceType),
}}
/>
<div>
<div
style={{
fontSize: '13px',
fontWeight: '700',
color: '#111827',
}}
>
{status.label}
</div>
<div
style={{
fontSize: '12px',
fontWeight: '500',
color: status.isOk ? '#16a34a' : '#f59e0b',
marginTop: '2px',
}}
>
{status.statusText}
</div>
</div>
</div>
<IonIcon
icon={status.isOk ? checkmarkCircleOutline : timeOutline}
style={{
fontSize: '18px',
color: status.isOk ? '#16a34a' : '#f59e0b',
}}
/>
</div>
))}
</div>
<button
onClick={() => onSendSupport(recipient.id)}
style={{
width: '100%',
padding: '14px',
backgroundColor: '#6d28d9',
color: '#ffffff',
border: 'none',
borderRadius: '999px',
fontSize: '14px',
fontWeight: '700',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
marginTop: 'auto',
}}
>
<IonIcon icon={cartOutline} style={{ fontSize: '18px' }} />
Send Again
</button>
</div>
);
};
export default RecipientCareCard;
+121
View File
@@ -0,0 +1,121 @@
import React, { useState } from 'react';
import { IonIcon } from '@ionic/react';
import { chevronForwardOutline } from 'ionicons/icons';
export interface RecipientListItem {
id: string;
firstName: string;
lastName: string;
relationship: string;
location: string;
lastActivityText?: string;
avatarUrl: string | null;
}
interface RecipientListCardProps {
recipient: RecipientListItem;
onClick: (id: string) => void;
}
const RecipientListCard: React.FC<RecipientListCardProps> = ({
recipient,
onClick,
}) => {
const [imageFailed, setImageFailed] = useState(false);
const shouldShowAvatar = Boolean(recipient.avatarUrl) && !imageFailed;
return (
<div
onClick={() => onClick(recipient.id)}
style={{
display: 'flex',
alignItems: 'center',
backgroundColor: '#ffffff',
borderRadius: '24px',
padding: '16px',
margin: '0 20px 12px',
gap: '14px',
cursor: 'pointer',
}}
>
<div
style={{
width: '52px',
height: '52px',
borderRadius: '16px',
backgroundColor: 'rgba(109,40,217,0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
flexShrink: 0,
}}
>
{shouldShowAvatar ? (
<img
src={recipient.avatarUrl ?? ''}
alt={recipient.firstName}
onError={() => setImageFailed(true)}
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : (
<span
style={{ fontSize: '20px', fontWeight: '700', color: '#6d28d9' }}
>
{recipient.firstName.charAt(0)}
</span>
)}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<h3
style={{
margin: 0,
fontSize: '16px',
fontWeight: '700',
color: '#111827',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{recipient.firstName} {recipient.lastName}
</h3>
<span
style={{ fontSize: '13px', fontWeight: '600', color: '#6d28d9' }}
>
{recipient.relationship}
</span>
</div>
<div
style={{
margin: '4px 0 0',
fontSize: '13px',
fontWeight: '400',
color: '#6b7280',
}}
>
{recipient.location}
</div>
{recipient.lastActivityText && (
<div
style={{
marginTop: '2px',
fontSize: '12px',
fontWeight: '400',
color: '#6b7280',
}}
>
Last activity: {recipient.lastActivityText}
</div>
)}
</div>
<IonIcon
icon={chevronForwardOutline}
style={{ fontSize: '18px', color: '#9ca3af', flexShrink: 0 }}
/>
</div>
);
};
export default RecipientListCard;
-135
View File
@@ -1,135 +0,0 @@
import React from 'react';
interface RequestListCardProps {
title: string;
subtitle: string;
referenceNumber: string;
status: string;
trailingText?: string;
onClick: () => void;
}
const RequestListCard: React.FC<RequestListCardProps> = ({
title,
subtitle,
referenceNumber,
status,
trailingText,
onClick,
}) => {
let statusBg = 'rgba(23,33,43,0.10)';
let statusColor = '#4b5563';
if (status === 'open') {
statusBg = 'var(--color-success-soft)';
statusColor = 'var(--color-success-text)';
} else if (status === 'quoted') {
statusBg = 'var(--color-warning-soft)';
statusColor = 'var(--color-warning-text)';
} else if (status === 'closed') {
statusBg = 'rgba(23,33,43,0.10)';
statusColor = '#4b5563';
}
return (
<div
onClick={onClick}
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
gap: '14px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
gap: '12px',
}}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '4px',
flex: 1,
minWidth: 0,
}}
>
<span
style={{
fontSize: '16px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
{title}
</span>
<span
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
{subtitle}
</span>
</div>
{trailingText && (
<span
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-brand-strong)',
marginLeft: '12px',
flexShrink: 0,
}}
>
{trailingText}
</span>
)}
</div>
<div
style={{
display: 'flex',
gap: '8px',
alignItems: 'center',
flexWrap: 'wrap',
}}
>
<div
style={{
background: 'var(--color-accent-soft)',
color: 'var(--color-warning-text)',
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
}}
>
{referenceNumber}
</div>
<div
style={{
background: statusBg,
color: statusColor,
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
textTransform: 'capitalize',
}}
>
{status}
</div>
</div>
</div>
);
};
export default RequestListCard;
+115
View File
@@ -0,0 +1,115 @@
import React from 'react';
import { IonIcon, IonToggle } from '@ionic/react';
import { chevronForwardOutline } from 'ionicons/icons';
interface SettingsRowProps {
icon: string;
iconColor?: string;
iconBg?: string;
title: string;
subtitle?: string;
onClick?: () => void;
type?: 'link' | 'toggle' | 'button';
checked?: boolean;
onToggle?: (checked: boolean) => void;
destructive?: boolean;
}
const SettingsRow: React.FC<SettingsRowProps> = ({
icon,
iconColor = '#6d28d9',
iconBg = 'rgba(109,40,217,0.1)',
title,
subtitle,
onClick,
type = 'link',
checked = false,
onToggle,
destructive = false,
}) => {
const content = (
<>
<div
style={{
width: '36px',
height: '36px',
borderRadius: '12px',
backgroundColor: destructive ? 'rgba(239,68,68,0.1)' : iconBg,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<IonIcon
icon={icon}
style={{
fontSize: '18px',
color: destructive ? '#ef4444' : iconColor,
}}
/>
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontSize: '15px',
fontWeight: '600',
color: destructive ? '#ef4444' : '#111827',
}}
>
{title}
</div>
{subtitle && (
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: '#6b7280',
marginTop: '2px',
}}
>
{subtitle}
</div>
)}
</div>
{type === 'link' && (
<IonIcon
icon={chevronForwardOutline}
style={{ fontSize: '18px', color: '#9ca3af' }}
/>
)}
{type === 'toggle' && (
<IonToggle
checked={checked}
onIonChange={(e) => onToggle && onToggle(e.detail.checked)}
style={{ padding: 0 }}
/>
)}
</>
);
const containerStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
padding: '12px 16px',
gap: '14px',
minHeight: '56px',
cursor: onClick || type === 'toggle' ? 'pointer' : 'default',
backgroundColor: 'transparent',
border: 'none',
width: '100%',
textAlign: 'left',
};
if (type === 'link' || type === 'button') {
return (
<button onClick={onClick} style={containerStyle}>
{content}
</button>
);
}
return <div style={containerStyle}>{content}</div>;
};
export default SettingsRow;
+55
View File
@@ -0,0 +1,55 @@
import React from 'react';
interface SocialAuthButtonProps {
provider: 'google' | 'apple';
label: string;
onClick: () => void;
disabled?: boolean;
}
const SocialAuthButton: React.FC<SocialAuthButtonProps> = ({
provider,
label,
onClick,
disabled = false,
}) => {
return (
<button
type="button"
className="social-auth-button"
onClick={onClick}
disabled={disabled}
>
<span className="social-auth-button__icon" aria-hidden="true">
{provider === 'google' && (
<svg width="18" height="18" viewBox="0 0 24 24">
<path
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
fill="#4285F4"
/>
<path
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
fill="#34A853"
/>
<path
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"
fill="#FBBC05"
/>
<path
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
fill="#EA4335"
/>
</svg>
)}
{provider === 'apple' && (
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
<path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.8-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" />
</svg>
)}
</span>
<span className="social-auth-button__label">Continue with {label}</span>
</button>
);
};
export default SocialAuthButton;
-63
View File
@@ -1,63 +0,0 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import { checkmarkCircle, ellipseOutline } from 'ionicons/icons';
export interface SupplierOption {
id: string;
full_name: string;
company_name: string | null;
city: string | null;
}
interface SupplierPickerRowProps {
supplier: SupplierOption;
selected: boolean;
onToggle: () => void;
}
const SupplierPickerRow: React.FC<SupplierPickerRowProps> = ({
supplier,
selected,
onToggle,
}) => {
return (
<div
onClick={onToggle}
style={{
display: 'flex',
alignItems: 'center',
padding: '12px 0',
borderBottom: '1px solid #edf4ee',
cursor: 'pointer',
}}
>
<IonIcon
icon={selected ? checkmarkCircle : ellipseOutline}
style={{
fontSize: '24px',
color: selected ? '#166534' : '#8a978f',
marginRight: '12px',
flexShrink: 0,
}}
/>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '2px',
flex: 1,
}}
>
<span style={{ fontSize: '15px', fontWeight: '600', color: '#0f1720' }}>
{supplier.company_name || supplier.full_name}
</span>
<span style={{ fontSize: '13px', fontWeight: '400', color: '#6c7a71' }}>
{supplier.company_name ? supplier.full_name : 'Independent'}
{supplier.city ? `${supplier.city}` : ''}
</span>
</div>
</div>
);
};
export default SupplierPickerRow;
+277 -15
View File
@@ -1,51 +1,313 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
import { User } from '@supabase/supabase-js';
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import SplashPage from '../pages/SplashPage';
import type { User } from '@supabase/supabase-js';
import { supabase } from '../supabase';
import {
buildCacheKey,
readCache,
writeCache,
clearUserCache,
} from '../utils/localCache';
export interface Profile {
id: string;
first_name: string;
last_name: string;
full_name: string;
phone: string;
country_of_residence: string;
avatar_path: string | null;
fcm_token: string | null;
notification_push_enabled: boolean;
notification_email_enabled: boolean;
notification_sms_enabled: boolean;
created_at: string;
updated_at: string;
}
export type ProfileStatus = 'idle' | 'loading' | 'loaded' | 'missing' | 'error';
interface AuthContextType {
user: User | null;
profile: Profile | null;
profileStatus: ProfileStatus;
refreshProfile: () => Promise<Profile | null>;
setProfile: (profile: Profile | null) => void;
signOut: () => Promise<void>;
}
const BYPASS_AUTH = false;
const AuthContext = createContext<AuthContextType>({
user: null,
profile: null,
profileStatus: BYPASS_AUTH ? 'idle' : 'loading',
refreshProfile: async () => null,
setProfile: () => {},
signOut: async () => {},
});
const withTimeout = async <T,>(
request: PromiseLike<T>,
timeoutMs: number,
label: string
): Promise<T> => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
reject(
new Error(
`${label} timed out. Please check your connection and try again.`
)
);
}, timeoutMs);
});
try {
return await Promise.race([Promise.resolve(request), timeout]);
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
};
export const useAuth = () => useContext(AuthContext);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [user, setUser] = useState<User | null>(null);
const [initializing, setInitializing] = useState(true);
const [profile, setProfileState] = useState<Profile | null>(null);
const [profileStatus, setProfileStatus] = useState<ProfileStatus>(
BYPASS_AUTH ? 'idle' : 'loading'
);
const [initializing, setInitializing] = useState(!BYPASS_AUTH);
const activeProfileFetchRef = useRef(0);
const mountedRef = useRef(false);
const currentUserIdRef = useRef<string | null>(null);
const applyProfile = useCallback((nextProfile: Profile | null) => {
if (!mountedRef.current) return;
setProfileState(nextProfile);
setProfileStatus(nextProfile ? 'loaded' : 'missing');
}, []);
const setProfile = useCallback(
(nextProfile: Profile | null) => {
activeProfileFetchRef.current += 1;
applyProfile(nextProfile);
},
[applyProfile]
);
const fetchProfile = useCallback(
async (
userId: string,
options?: { showLoading?: boolean }
): Promise<Profile | null> => {
const fetchId = activeProfileFetchRef.current + 1;
activeProfileFetchRef.current = fetchId;
if ((options?.showLoading ?? true) && mountedRef.current) {
setProfileStatus('loading');
}
const cacheKey = buildCacheKey(userId, 'profile');
try {
const cachedProfile = await readCache<Profile>(cacheKey);
if (
cachedProfile &&
mountedRef.current &&
fetchId === activeProfileFetchRef.current &&
currentUserIdRef.current === userId
) {
applyProfile(cachedProfile);
}
} catch (err) {
console.error('[AuthProvider] Failed to read cached profile', err);
}
try {
const { data, error } = await withTimeout(
supabase.from('profiles').select('*').eq('id', userId).maybeSingle(),
8000,
'Profile loading'
);
if (
!mountedRef.current ||
fetchId !== activeProfileFetchRef.current ||
currentUserIdRef.current !== userId
) {
return data ? (data as Profile) : null;
}
if (error) {
console.error('[AuthProvider] Failed to fetch profile', error);
setProfileState(null);
setProfileStatus('error');
return null;
}
const nextProfile = data ? (data as Profile) : null;
applyProfile(nextProfile);
if (nextProfile) {
void writeCache(cacheKey, nextProfile);
}
return nextProfile;
} catch (error) {
if (
mountedRef.current &&
fetchId === activeProfileFetchRef.current &&
currentUserIdRef.current === userId
) {
console.error('[AuthProvider] Profile fetch crashed', error);
setProfileState(null);
setProfileStatus('error');
}
return null;
}
},
[applyProfile]
);
useEffect(() => {
supabase.auth.getSession().then(({ data }) => {
setUser(data.session?.user ?? null);
mountedRef.current = true;
if (BYPASS_AUTH) {
setInitializing(false);
setProfileStatus('idle');
return () => {
mountedRef.current = false;
activeProfileFetchRef.current += 1;
};
}
let cancelled = false;
supabase.auth
.getSession()
.then(async ({ data }) => {
if (cancelled || !mountedRef.current) return;
const currentUser = data.session?.user ?? null;
const keepSignedIn = localStorage.getItem('kumusha_keep_signed_in');
if (currentUser && keepSignedIn === 'false') {
currentUserIdRef.current = null;
setUser(null);
setProfileState(null);
setProfileStatus('idle');
await clearUserCache(currentUser.id);
await supabase.auth.signOut();
if (!cancelled && mountedRef.current) {
setInitializing(false);
}
return;
}
currentUserIdRef.current = currentUser?.id ?? null;
setUser(currentUser);
if (currentUser) {
await fetchProfile(currentUser.id, { showLoading: false });
} else {
setProfileState(null);
setProfileStatus('idle');
}
})
.catch((error) => {
console.error('[AuthProvider] Failed to initialise session', error);
if (!cancelled && mountedRef.current) {
currentUserIdRef.current = null;
setUser(null);
setProfileState(null);
setProfileStatus('missing');
}
})
.finally(() => {
if (!cancelled && mountedRef.current) {
setInitializing(false);
}
});
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null);
} = supabase.auth.onAuthStateChange(async (_event, session) => {
const nextUser = session?.user ?? null;
if (!mountedRef.current) return;
const previousUserId = currentUserIdRef.current;
currentUserIdRef.current = nextUser?.id ?? null;
if (nextUser) {
if (nextUser.id !== previousUserId) {
setProfileState(null);
setProfileStatus('loading');
}
setUser(nextUser);
await fetchProfile(nextUser.id, { showLoading: false });
} else {
activeProfileFetchRef.current += 1;
setUser(null);
setProfileState(null);
setProfileStatus('idle');
if (previousUserId) {
await clearUserCache(previousUserId);
}
}
});
return () => subscription.unsubscribe();
return () => {
cancelled = true;
mountedRef.current = false;
activeProfileFetchRef.current += 1;
subscription.unsubscribe();
};
}, [fetchProfile]);
const signOut = useCallback(async () => {
activeProfileFetchRef.current += 1;
const currentUserId = currentUserIdRef.current;
currentUserIdRef.current = null;
setUser(null);
setProfileState(null);
setProfileStatus('idle');
if (currentUserId) {
await clearUserCache(currentUserId);
}
localStorage.removeItem('kumusha_keep_signed_in');
await supabase.auth.signOut();
}, []);
const signOut = async () => {
await supabase.auth.signOut();
};
const refreshProfile = useCallback(() => {
return user
? fetchProfile(user.id, { showLoading: false })
: Promise.resolve(null);
}, [fetchProfile, user]);
const contextValue = useMemo(
() => ({
user,
profile,
profileStatus,
refreshProfile,
setProfile,
signOut,
}),
[profile, profileStatus, refreshProfile, setProfile, signOut, user]
);
if (initializing) {
return null; // Or a simple spinner if preferred, but usually handled nicely
return <SplashPage title="Send support to loved ones from anywhere" />;
}
return (
<AuthContext.Provider value={{ user, signOut }}>
{children}
</AuthContext.Provider>
<AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
);
};
-81
View File
@@ -1,81 +0,0 @@
import React, {
createContext,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { Preferences } from '@capacitor/preferences';
import { Database } from '../database.types';
export type Profile = Database['public']['Tables']['profiles']['Row'];
export type ThemeMode = 'light' | 'dark';
interface ProfileContextType {
profile: Profile | null;
status: 'loading' | 'loaded' | 'missing';
themeMode: ThemeMode;
setProfile: (profile: Profile | null) => void;
setStatus: (status: 'loading' | 'loaded' | 'missing') => void;
setThemeMode: (mode: ThemeMode) => Promise<void>;
clearProfile: () => void;
}
const ProfileContext = createContext<ProfileContextType>({
profile: null,
status: 'loading',
themeMode: 'light',
setProfile: () => {},
setStatus: () => {},
setThemeMode: async () => {},
clearProfile: () => {},
});
export const useProfile = () => useContext(ProfileContext);
export const ProfileProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const [profile, setProfile] = useState<Profile | null>(null);
const [status, setStatus] = useState<'loading' | 'loaded' | 'missing'>(
'loading'
);
const [themeModeState, setThemeModeState] = useState<ThemeMode>('light');
useEffect(() => {
const loadThemeMode = async () => {
const { value } = await Preferences.get({ key: 'theme_mode' });
const mode = value === 'dark' ? 'dark' : 'light';
setThemeModeState(mode);
};
loadThemeMode();
}, []);
const setThemeMode = async (mode: ThemeMode) => {
setThemeModeState(mode);
await Preferences.set({ key: 'theme_mode', value: mode });
};
const clearProfile = () => {
setProfile(null);
setStatus('loading');
};
const value = useMemo(
() => ({
profile,
status,
themeMode: themeModeState,
setProfile,
setStatus,
setThemeMode,
clearProfile,
}),
[profile, status, themeModeState]
);
return (
<ProfileContext.Provider value={value}>{children}</ProfileContext.Provider>
);
};
+486 -151
View File
@@ -14,205 +14,540 @@ export type Database = {
}
public: {
Tables: {
activity_events: {
Row: {
amount: number | null
created_at: string
event_at: string
event_type: string
id: string
metadata: Json
order_id: string | null
recipient_id: string | null
subtitle: string
title: string
user_id: string
}
Insert: {
amount?: number | null
created_at?: string
event_at?: string
event_type: string
id?: string
metadata?: Json
order_id?: string | null
recipient_id?: string | null
subtitle: string
title: string
user_id: string
}
Update: {
amount?: number | null
created_at?: string
event_at?: string
event_type?: string
id?: string
metadata?: Json
order_id?: string | null
recipient_id?: string | null
subtitle?: string
title?: string
user_id?: string
}
Relationships: []
}
care_alerts: {
Row: {
alert_type: string
body: string
created_at: string
dismissed_at: string | null
due_at: string | null
id: string
recipient_id: string
schedule_id: string | null
service_type: string | null
severity: string
title: string
user_id: string
}
Insert: {
alert_type: string
body: string
created_at?: string
dismissed_at?: string | null
due_at?: string | null
id?: string
recipient_id: string
schedule_id?: string | null
service_type?: string | null
severity: string
title: string
user_id: string
}
Update: {
alert_type?: string
body?: string
created_at?: string
dismissed_at?: string | null
due_at?: string | null
id?: string
recipient_id?: string
schedule_id?: string | null
service_type?: string | null
severity?: string
title?: string
user_id?: string
}
Relationships: [
{
foreignKeyName: "care_alerts_schedule_id_fkey"
columns: ["schedule_id"]
isOneToOne: false
referencedRelation: "support_schedules"
referencedColumns: ["id"]
},
]
}
merchants: {
Row: {
branch_name: string | null
city: string
country: string
created_at: string
id: string
is_active: boolean
merchant_type: string
name: string
}
Insert: {
branch_name?: string | null
city: string
country: string
created_at?: string
id?: string
is_active?: boolean
merchant_type: string
name: string
}
Update: {
branch_name?: string | null
city?: string
country?: string
created_at?: string
id?: string
is_active?: boolean
merchant_type?: string
name?: string
}
Relationships: []
}
notifications: {
Row: {
body: string
created_at: string
id: string
order_id: string | null
priority: string
read_at: string | null
recipient_id: string | null
title: string
type: string
user_id: string
voucher_id: string | null
}
Insert: {
body: string
created_at?: string
id?: string
order_id?: string | null
priority: string
read_at?: string | null
recipient_id?: string | null
title: string
type: string
user_id: string
voucher_id?: string | null
}
Update: {
body?: string
created_at?: string
id?: string
order_id?: string | null
priority?: string
read_at?: string | null
recipient_id?: string | null
title?: string
type?: string
user_id?: string
voucher_id?: string | null
}
Relationships: [
{
foreignKeyName: "notifications_voucher_id_fkey"
columns: ["voucher_id"]
isOneToOne: false
referencedRelation: "vouchers"
referencedColumns: ["id"]
},
]
}
payment_methods: {
Row: {
brand: string | null
created_at: string
expiry_month: number | null
expiry_year: number | null
id: string
is_default: boolean
last4: string | null
provider: string
user_id: string
}
Insert: {
brand?: string | null
created_at?: string
expiry_month?: number | null
expiry_year?: number | null
id?: string
is_default?: boolean
last4?: string | null
provider: string
user_id: string
}
Update: {
brand?: string | null
created_at?: string
expiry_month?: number | null
expiry_year?: number | null
id?: string
is_default?: boolean
last4?: string | null
provider?: string
user_id?: string
}
Relationships: []
}
profiles: {
Row: {
avatar_url: string | null
city: string | null
company_name: string | null
avatar_path: string | null
country_of_residence: string
created_at: string
fcm_token: string | null
first_name: string
full_name: string
id: string
phone: string | null
role: string
last_name: string
notification_email_enabled: boolean
notification_push_enabled: boolean
notification_sms_enabled: boolean
phone: string
updated_at: string
}
Insert: {
avatar_url?: string | null
city?: string | null
company_name?: string | null
avatar_path?: string | null
country_of_residence: string
created_at?: string
fcm_token?: string | null
first_name: string
full_name: string
id: string
phone?: string | null
role: string
last_name: string
notification_email_enabled?: boolean
notification_push_enabled?: boolean
notification_sms_enabled?: boolean
phone: string
updated_at?: string
}
Update: {
avatar_url?: string | null
city?: string | null
company_name?: string | null
avatar_path?: string | null
country_of_residence?: string
created_at?: string
fcm_token?: string | null
first_name?: string
full_name?: string
id?: string
phone?: string | null
role?: string
last_name?: string
notification_email_enabled?: boolean
notification_push_enabled?: boolean
notification_sms_enabled?: boolean
phone?: string
updated_at?: string
}
Relationships: []
}
quotations: {
recipients: {
Row: {
archived_at: string | null
city: string
country: string
created_at: string
currency_code: string
delivery_option: string
first_name: string
id: string
is_active: boolean
is_archived: boolean
last_name: string
mobile_number: string
photo_path: string | null
pinned_at: string | null
relationship: string
sort_order: number
updated_at: string
user_id: string
}
Insert: {
archived_at?: string | null
city: string
country: string
created_at?: string
first_name: string
id?: string
is_active?: boolean
is_archived?: boolean
last_name: string
mobile_number: string
photo_path?: string | null
pinned_at?: string | null
relationship: string
sort_order?: number
updated_at?: string
user_id: string
}
Update: {
archived_at?: string | null
city?: string
country?: string
created_at?: string
first_name?: string
id?: string
is_active?: boolean
is_archived?: boolean
last_name?: string
mobile_number?: string
photo_path?: string | null
pinned_at?: string | null
relationship?: string
sort_order?: number
updated_at?: string
user_id?: string
}
Relationships: []
}
support_orders: {
Row: {
amount: number
created_at: string
currency: string
delivery_channel: string
id: string
merchant_id: string | null
meter_number: string | null
network: string | null
note: string | null
price_amount: number
rfq_id: string
payment_method: string | null
platform_fee: number
recipient_id: string
recurring_schedule_id: string | null
service_type: string
status: string
supplier_id: string
total_amount: number
updated_at: string
user_id: string
}
Insert: {
amount: number
created_at?: string
currency_code?: string
delivery_option: string
currency?: string
delivery_channel?: string
id?: string
merchant_id?: string | null
meter_number?: string | null
network?: string | null
note?: string | null
price_amount: number
rfq_id: string
status?: string
supplier_id: string
updated_at?: string
}
Update: {
created_at?: string
currency_code?: string
delivery_option?: string
id?: string
note?: string | null
price_amount?: number
rfq_id?: string
status?: string
supplier_id?: string
updated_at?: string
}
Relationships: [
{
foreignKeyName: "quotations_rfq_id_fkey"
columns: ["rfq_id"]
isOneToOne: false
referencedRelation: "rfqs"
referencedColumns: ["id"]
},
{
foreignKeyName: "quotations_supplier_id_fkey"
columns: ["supplier_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
]
}
rfq_images: {
Row: {
created_at: string
id: string
owner_id: string
rfq_id: string
storage_path: string
}
Insert: {
created_at?: string
id?: string
owner_id: string
rfq_id: string
storage_path: string
}
Update: {
created_at?: string
id?: string
owner_id?: string
rfq_id?: string
storage_path?: string
}
Relationships: [
{
foreignKeyName: "rfq_images_rfq_id_fkey"
columns: ["rfq_id"]
isOneToOne: false
referencedRelation: "rfqs"
referencedColumns: ["id"]
},
]
}
rfq_recipients: {
Row: {
created_at: string
id: string
rfq_id: string
supplier_id: string
}
Insert: {
created_at?: string
id?: string
rfq_id: string
supplier_id: string
}
Update: {
created_at?: string
id?: string
rfq_id?: string
supplier_id?: string
}
Relationships: [
{
foreignKeyName: "rfq_recipients_rfq_id_fkey"
columns: ["rfq_id"]
isOneToOne: false
referencedRelation: "rfqs"
referencedColumns: ["id"]
},
{
foreignKeyName: "rfq_recipients_supplier_id_fkey"
columns: ["supplier_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
]
}
rfqs: {
Row: {
buyer_id: string
created_at: string
id: string
reference_number: string
request_text: string
payment_method?: string | null
platform_fee: number
recipient_id: string
recurring_schedule_id?: string | null
service_type: string
status: string
title: string
updated_at: string
}
Insert: {
buyer_id: string
created_at?: string
id?: string
reference_number: string
request_text: string
status?: string
title: string
total_amount: number
updated_at?: string
user_id: string
}
Update: {
buyer_id?: string
amount?: number
created_at?: string
currency?: string
delivery_channel?: string
id?: string
reference_number?: string
request_text?: string
merchant_id?: string | null
meter_number?: string | null
network?: string | null
note?: string | null
payment_method?: string | null
platform_fee?: number
recipient_id?: string
recurring_schedule_id?: string | null
service_type?: string
status?: string
title?: string
total_amount?: number
updated_at?: string
user_id?: string
}
Relationships: [
{
foreignKeyName: "rfqs_buyer_id_fkey"
columns: ["buyer_id"]
foreignKeyName: "support_orders_merchant_id_fkey"
columns: ["merchant_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedRelation: "merchants"
referencedColumns: ["id"]
},
{
foreignKeyName: "support_orders_recipient_id_fkey"
columns: ["recipient_id"]
isOneToOne: false
referencedRelation: "recipients"
referencedColumns: ["id"]
},
{
foreignKeyName: "support_orders_recurring_schedule_id_fkey"
columns: ["recurring_schedule_id"]
isOneToOne: false
referencedRelation: "support_schedules"
referencedColumns: ["id"]
},
]
}
support_schedules: {
Row: {
created_at: string | null
frequency_interval: number
frequency_unit: string
id: string
is_active: boolean
last_supported_at: string | null
next_due_at: string
recipient_id: string
service_type: string
updated_at: string | null
user_id: string
}
Insert: {
created_at?: string | null
frequency_interval: number
frequency_unit: string
id?: string
is_active?: boolean
last_supported_at?: string | null
next_due_at: string
recipient_id: string
service_type: string
updated_at?: string | null
user_id: string
}
Update: {
created_at?: string | null
frequency_interval?: number
frequency_unit?: string
id?: string
is_active?: boolean
last_supported_at?: string | null
next_due_at?: string
recipient_id?: string
service_type?: string
updated_at?: string | null
user_id?: string
}
Relationships: [
{
foreignKeyName: "support_schedules_recipient_id_fkey"
columns: ["recipient_id"]
isOneToOne: false
referencedRelation: "recipients"
referencedColumns: ["id"]
},
]
}
voucher_redemptions: {
Row: {
created_at: string
id: string
merchant_id: string
order_id: string
receipt_reference: string | null
redeemed_amount: number
redeemed_at: string
voucher_id: string
}
Insert: {
created_at?: string
id?: string
merchant_id: string
order_id: string
receipt_reference?: string | null
redeemed_amount: number
redeemed_at?: string
voucher_id: string
}
Update: {
created_at?: string
id?: string
merchant_id?: string
order_id?: string
receipt_reference?: string | null
redeemed_amount?: number
redeemed_at?: string
voucher_id?: string
}
Relationships: [
{
foreignKeyName: "voucher_redemptions_voucher_id_fkey"
columns: ["voucher_id"]
isOneToOne: false
referencedRelation: "vouchers"
referencedColumns: ["id"]
},
]
}
vouchers: {
Row: {
created_at: string
expires_at: string
id: string
order_id: string
qr_payload: string
redeemed_at: string | null
redeemed_merchant_id: string | null
status: string
voucher_code: string
voucher_type: string
}
Insert: {
created_at?: string
expires_at: string
id?: string
order_id: string
qr_payload: string
redeemed_at?: string | null
redeemed_merchant_id?: string | null
status: string
voucher_code: string
voucher_type: string
}
Update: {
created_at?: string
expires_at?: string
id?: string
order_id?: string
qr_payload?: string
redeemed_at?: string | null
redeemed_merchant_id?: string | null
status?: string
voucher_code?: string
voucher_type?: string
}
Relationships: []
}
}
Views: {
[_ in never]: never
-86
View File
@@ -1,86 +0,0 @@
import { useHistory } from 'react-router-dom';
import { Preferences } from '@capacitor/preferences';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfile, Profile } from '../contexts/ProfileContext';
export const useProfileLoader = () => {
const history = useHistory();
const { user } = useAuth();
const { setProfile, setStatus } = useProfile();
const loadProfileAndNavigate = async (
setOverlayVisible?: (v: boolean) => void,
setOverlayError?: (v: boolean) => void
) => {
if (!user) return;
try {
// 1. Check cache
const { value } = await Preferences.get({ key: `profile_${user.id}` });
if (value) {
const cachedProfile = JSON.parse(value) as Profile;
setProfile(cachedProfile);
setStatus('loaded');
history.replace('/home');
// Silent refresh
const { data } = await supabase
.from('profiles')
.select('*')
.eq('id', user.id)
.single();
if (data) {
setProfile(data);
await Preferences.set({
key: `profile_${user.id}`,
value: JSON.stringify(data),
});
} else {
// If silent refresh finds no row, they somehow lost their profile (or deleted it)
// We can handle this by redirecting them next time, or immediately
setStatus('missing');
history.replace('/setup-profile');
}
return;
}
// 2. Cache miss, fetch from remote
if (setOverlayVisible) setOverlayVisible(true);
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('id', user.id)
.single();
if (error && error.code !== 'PGRST116') {
// PGRST116 means no rows found
console.error('Error fetching profile:', error);
if (setOverlayError) setOverlayError(true);
return; // Keep overlay visible so they see the error or can retry
}
if (data) {
// Row found
setProfile(data);
setStatus('loaded');
await Preferences.set({
key: `profile_${user.id}`,
value: JSON.stringify(data),
});
if (setOverlayVisible) setOverlayVisible(false);
history.replace('/home');
} else {
// No row found
setStatus('missing');
if (setOverlayVisible) setOverlayVisible(false);
history.replace('/setup-profile');
}
} catch (err) {
console.error('Unexpected error loading profile:', err);
if (setOverlayError) setOverlayError(true);
}
};
return { loadProfileAndNavigate };
};
+12 -10
View File
@@ -56,16 +56,18 @@ if (import.meta.hot) {
if ('./supabase.ts' in mods) {
try {
const { supabase } = await mods['./supabase.ts']() as { supabase: any };
supabase.auth.onAuthStateChange((_event: unknown, session: any) => {
window.parent.postMessage(
{
type: '__apsuite_session',
access_token: session?.access_token ?? null,
email: session?.user?.email ?? null,
},
studioOrigin,
);
});
// supabase.auth.onAuthStateChange((_event: unknown, session: any) => {
// setTimeout(() => {
// window.parent.postMessage(
// {
// type: '__apsuite_session',
// access_token: session?.access_token ?? null,
// email: session?.user?.email ?? null,
// },
// studioOrigin,
// );
// }, 0);
// });
} catch {
// supabase client failed to initialise — session bridge unavailable
}
+722
View File
@@ -0,0 +1,722 @@
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 activityListMemory = new Map<string, UnifiedActivityItem[]>();
const ActivityPage: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const initialUserId = user?.id ?? previewUserId;
const initialEvents = activityListMemory.get(initialUserId) ?? [];
const [events, setEvents] = useState<UnifiedActivityItem[]>(initialEvents);
const [loading, setLoading] = useState(initialEvents.length === 0);
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) {
const memoryCached = activityListMemory.get(activeUserId);
if (memoryCached) {
setEvents(memoryCached);
setLoading(false);
hasCache = true;
}
try {
const cached = await readCache<UnifiedActivityItem[]>(cacheKey);
if (cached && Array.isArray(cached)) {
activityListMemory.set(activeUserId, 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()
);
const nextHash = JSON.stringify(finalEvents);
const currentHash = JSON.stringify(
activityListMemory.get(activeUserId) ?? events
);
activityListMemory.set(activeUserId, finalEvents);
if (nextHash !== currentHash) {
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;
-576
View File
@@ -1,576 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonContent,
IonSpinner,
IonIcon,
useIonViewWillEnter,
} from '@ionic/react';
import { eyeOutline, eyeOffOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfileLoader } from '../hooks/useProfileLoader';
const Auth: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { loadProfileAndNavigate } = useProfileLoader();
const [tab, setTab] = useState<'login' | 'register'>('login');
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [showLoginPassword, setShowLoginPassword] = useState(false);
const [registerEmail, setRegisterEmail] = useState('');
const [registerPassword, setRegisterPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showRegisterPassword, setShowRegisterPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [overlayVisible, setOverlayVisible] = useState(false);
const [overlayError, setOverlayError] = useState(false);
useIonViewWillEnter(() => {
setTab('login');
});
useEffect(() => {
if (user) {
loadProfileAndNavigate(setOverlayVisible, setOverlayError);
}
}, [user, loadProfileAndNavigate]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSignIn = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
const { error } = await supabase.auth.signInWithPassword({
email: loginEmail,
password: loginPassword,
});
if (error) {
if (error.message.toLowerCase().includes('email not confirmed')) {
await supabase.auth.resend({ type: 'signup', email: loginEmail });
history.push('/verify-email', { email: loginEmail, resent: true });
} else {
showError(error.message);
}
setLoading(false);
return;
}
// keep loading true waiting for user effect
};
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault();
if (registerPassword !== confirmPassword) {
showError('Passwords do not match');
return;
}
setLoading(true);
setError('');
const { error } = await supabase.auth.signUp({
email: registerEmail,
password: registerPassword,
});
if (error) {
showError(error.message);
setLoading(false);
return;
}
setLoading(false);
history.push('/verify-email', { email: registerEmail });
};
const handleForgotPassword = () => {
history.push('/forgot-password');
};
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': '0px',
}}
>
<div
style={{
padding:
'calc(var(--ion-safe-area-top, 0px) + 18px) 20px calc(var(--ion-safe-area-bottom, 0px) + 28px)',
minHeight: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
gap: '24px',
}}
>
<div
style={{
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '14px',
}}
>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: '10px',
alignSelf: 'flex-start',
background: 'var(--color-surface)',
color: 'var(--color-brand)',
borderRadius: '999px',
padding: '8px 14px',
fontSize: '12px',
fontWeight: '700',
letterSpacing: '0.06em',
textTransform: 'uppercase',
}}
>
QuoteLink
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div
style={{
fontSize: '18px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1.2',
}}
>
Instant prices.{' '}
<span
style={{ color: 'var(--color-accent)', fontWeight: '700' }}
>
Smart decisions.
</span>
</div>
<div
style={{
fontSize: '34px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1.02',
letterSpacing: '-0.03em',
maxWidth: '330px',
}}
>
Modern procurement for buyers and suppliers.
</div>
<div
style={{
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
lineHeight: '1.6',
maxWidth: '320px',
}}
>
Send a request, compare real quotes, and move faster with a
clean professional workflow.
</div>
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '24px',
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
<div>
<div
style={{
fontSize: '22px',
fontWeight: '700',
color: 'var(--color-text-primary)',
lineHeight: '1.15',
}}
>
{tab === 'login' ? 'Welcome back' : 'Create your account'}
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
lineHeight: '1.55',
marginTop: '4px',
}}
>
{tab === 'login'
? 'Sign in to manage requests and supplier quotations.'
: 'Join QuoteLink to start sending or responding to RFQs.'}
</div>
</div>
<div
style={{
display: 'flex',
background: 'var(--color-surface-raised)',
borderRadius: '999px',
padding: '4px',
}}
>
<button
onClick={() => setTab('login')}
style={{
flex: 1,
background:
tab === 'login' ? 'var(--color-brand)' : 'transparent',
color:
tab === 'login' ? '#ffffff' : 'var(--color-brand-strong)',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Log In
</button>
<button
onClick={() => setTab('register')}
style={{
flex: 1,
background:
tab === 'register' ? 'var(--color-brand)' : 'transparent',
color:
tab === 'register'
? '#ffffff'
: 'var(--color-brand-strong)',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Register
</button>
</div>
{error && (
<div
style={{
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
{tab === 'login' ? (
<form
onSubmit={handleSignIn}
style={{
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<input
type="email"
placeholder="you@example.com"
value={loginEmail}
onChange={(e) => setLoginEmail(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
<div style={{ position: 'relative' }}>
<input
type={showLoginPassword ? 'text' : 'password'}
placeholder="Password"
value={loginPassword}
onChange={(e) => setLoginPassword(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
<IonIcon
icon={showLoginPassword ? eyeOffOutline : eyeOutline}
onClick={() => setShowLoginPassword(!showLoginPassword)}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: 'var(--color-text-tertiary)',
cursor: 'pointer',
}}
/>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<button
type="button"
onClick={handleForgotPassword}
style={{
background: 'transparent',
border: 'none',
padding: '0',
fontSize: '14px',
fontWeight: '600',
color: 'var(--color-accent)',
cursor: 'pointer',
}}
>
Forgot password?
</button>
</div>
<button
type="submit"
disabled={loading}
style={{
background: 'var(--color-brand)',
border: 'none',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
color: '#ffffff',
cursor: 'pointer',
marginTop: '4px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Sign In'
)}
</button>
</form>
) : (
<form
onSubmit={handleSignUp}
style={{
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<input
type="email"
placeholder="you@example.com"
value={registerEmail}
onChange={(e) => setRegisterEmail(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
<div style={{ position: 'relative' }}>
<input
type={showRegisterPassword ? 'text' : 'password'}
placeholder="Create a password"
value={registerPassword}
onChange={(e) => setRegisterPassword(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
minLength={6}
/>
<IonIcon
icon={showRegisterPassword ? eyeOffOutline : eyeOutline}
onClick={() =>
setShowRegisterPassword(!showRegisterPassword)
}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: 'var(--color-text-tertiary)',
cursor: 'pointer',
}}
/>
</div>
<div style={{ position: 'relative' }}>
<input
type={showConfirmPassword ? 'text' : 'password'}
placeholder="Confirm password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
minLength={6}
/>
<IonIcon
icon={showConfirmPassword ? eyeOffOutline : eyeOutline}
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: 'var(--color-text-tertiary)',
cursor: 'pointer',
}}
/>
</div>
<button
type="submit"
disabled={loading}
style={{
background: 'var(--color-brand)',
border: 'none',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
color: '#ffffff',
cursor: 'pointer',
marginTop: '4px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Create Account'
)}
</button>
</form>
)}
</div>
</div>
{overlayVisible && (
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(18, 18, 18, 0.78)',
backdropFilter: 'blur(10px)',
WebkitBackdropFilter: 'blur(10px)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
zIndex: 9999,
padding: '24px',
}}
>
{overlayError ? (
<div
style={{
color: 'var(--color-danger-text)',
fontSize: '15px',
fontWeight: '600',
textAlign: 'center',
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
}}
>
Error loading profile. Please restart the app.
</div>
) : (
<IonSpinner
name="crescent"
style={{
color: 'var(--color-brand)',
width: '28px',
height: '28px',
}}
/>
)}
</div>
)}
</IonContent>
</IonPage>
);
};
export default Auth;
+542
View File
@@ -0,0 +1,542 @@
import React, { useState, useEffect, useRef } from 'react';
import SplashPage from './SplashPage';
import {
IonPage,
IonContent,
useIonViewWillEnter,
IonIcon,
} from '@ionic/react';
import { useHistory, useLocation } 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 momImage from '../assets/mom.jpg';
import dadImage from '../assets/dad.jpg';
import { checkmark, heart } from 'ionicons/icons';
import '../styles/auth.css';
import {
fetchHomeSnapshot,
preloadImageUrls,
setWarmedHomeSnapshot,
} from '../utils/homeSnapshot';
import { hydrateHomeSnapshotImages } from '../utils/imageCache';
import { buildCacheKey, writeCache } from '../utils/localCache';
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 signInStartedAtRef = useRef<number | null>(null);
const splashMinCompleteRef = useRef(false);
const splashTimerRef = useRef<ReturnType<typeof setTimeout> | 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);
const [keepSignedIn, setKeepSignedIn] = useState(true);
const [showPostLoginSplash, setShowPostLoginSplash] = useState(false);
const [dashboardReady, setDashboardReady] = useState(false);
const [splashMinReady, setSplashMinReady] = useState(false);
const prefetchStartedRef = useRef(false);
useEffect(() => {
if (!user) {
navigatedForUserRef.current = null;
signInStartedAtRef.current = null;
splashMinCompleteRef.current = false;
prefetchStartedRef.current = false;
if (splashTimerRef.current) {
clearTimeout(splashTimerRef.current);
splashTimerRef.current = null;
}
setShowPostLoginSplash(false);
setDashboardReady(false);
setSplashMinReady(false);
return;
}
if (signInTimeoutRef.current) {
clearTimeout(signInTimeoutRef.current);
signInTimeoutRef.current = null;
}
if (location.pathname !== '/auth' || profileStatus === 'loading') return;
if (navigatedForUserRef.current === user.id) return;
if (profileStatus === 'missing') {
if (showPostLoginSplash && !splashMinReady) return;
navigatedForUserRef.current = user.id;
setLoading(false);
setShowPostLoginSplash(false);
history.replace('/setup-profile');
return;
}
if (profileStatus === 'loaded' && profile) {
if (!prefetchStartedRef.current) {
prefetchStartedRef.current = true;
prefetchHomeDashboard(user.id).then(() => {
setDashboardReady(true);
});
}
if (!dashboardReady || (showPostLoginSplash && !splashMinReady)) {
return;
}
navigatedForUserRef.current = user.id;
setLoading(false);
setShowPostLoginSplash(false);
history.replace('/home');
}
}, [
user,
profile,
profileStatus,
location.pathname,
history,
showPostLoginSplash,
dashboardReady,
splashMinReady,
]);
useEffect(() => {
return () => {
if (signInTimeoutRef.current) {
clearTimeout(signInTimeoutRef.current);
}
if (splashTimerRef.current) {
clearTimeout(splashTimerRef.current);
}
};
}, []);
useIonViewWillEnter(() => {
setTab('login');
setError(null);
});
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(null), 4000);
};
const getRecipientAvatarUrl = async (
photoPath?: string | null,
firstName?: string | null
) => {
const normalizedPath = photoPath?.trim().toLowerCase();
const normalizedName = firstName?.trim().toLowerCase();
if (normalizedPath === 'mom.jpg' || normalizedPath === 'mum.jpg') {
return momImage;
}
if (normalizedPath === 'dad.jpg' || normalizedPath === 'father.jpg') {
return dadImage;
}
if (normalizedName === 'mum' || normalizedName === 'mom') {
return momImage;
}
if (normalizedName === 'dad' || normalizedName === 'father') {
return dadImage;
}
if (photoPath) {
const { data } = supabase.storage
.from('recipient-photos')
.getPublicUrl(photoPath);
if (data?.publicUrl) return data.publicUrl;
}
return null;
};
const prefetchHomeDashboard = async (userId: string) => {
try {
const snapshot = await fetchHomeSnapshot(userId, getRecipientAvatarUrl);
const hydratedSnapshot = await hydrateHomeSnapshotImages(
userId,
snapshot
);
await preloadImageUrls([
...hydratedSnapshot.imageUrls,
...hydratedSnapshot.lovedOnes
.map((person) => person.avatar)
.filter(Boolean),
...hydratedSnapshot.activities
.map((activity) => activity.avatar)
.filter(Boolean),
]);
const warmedSnapshot = setWarmedHomeSnapshot(userId, hydratedSnapshot);
const cacheKey = buildCacheKey(userId, 'homeSnapshot');
await writeCache(cacheKey, warmedSnapshot);
return true;
} catch (err) {
console.error('[prefetch] failed', err);
return false;
}
};
const startPostLoginSplash = () => {
signInStartedAtRef.current = Date.now();
splashMinCompleteRef.current = false;
setShowPostLoginSplash(true);
setSplashMinReady(false);
if (splashTimerRef.current) {
clearTimeout(splashTimerRef.current);
}
splashTimerRef.current = setTimeout(() => {
splashMinCompleteRef.current = true;
setSplashMinReady(true);
}, 6000);
};
const stopPostLoginSplash = () => {
signInStartedAtRef.current = null;
splashMinCompleteRef.current = false;
prefetchStartedRef.current = false;
if (splashTimerRef.current) {
clearTimeout(splashTimerRef.current);
splashTimerRef.current = null;
}
setShowPostLoginSplash(false);
setDashboardReady(false);
setSplashMinReady(false);
};
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);
stopPostLoginSplash();
showError(
'Sign in is taking too long. Please check your connection and try again.'
);
}, 30000);
const { error: signInError } = await supabase.auth.signInWithPassword({
email: normalizedEmail,
password,
});
if (signInError) {
if (signInTimeoutRef.current) {
clearTimeout(signInTimeoutRef.current);
signInTimeoutRef.current = null;
}
stopPostLoginSplash();
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;
}
localStorage.setItem(
'kumusha_keep_signed_in',
keepSignedIn ? 'true' : 'false'
);
startPostLoginSplash();
// 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;
localStorage.setItem('kumusha_keep_signed_in', 'true');
startPostLoginSplash();
// keep loading true
} catch (err: any) {
stopPostLoginSplash();
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;
localStorage.setItem('kumusha_keep_signed_in', 'true');
startPostLoginSplash();
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) {
stopPostLoginSplash();
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">
<div className="auth-brand-header">
<span className="auth-brand-name">Kumusha</span>
</div>
<h1 className="auth-heading">Care for home</h1>
<p className="auth-subtitle">
Trusted support for family back home.
</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}
/>
{tab === 'login' && (
<button
type="button"
className="auth-keep-signed-in"
onClick={() => !loading && setKeepSignedIn((prev) => !prev)}
disabled={loading}
>
<div className="auth-keep-text">
<span className="auth-keep-title">Keep me signed in</span>
<span className="auth-keep-subtitle">
Stay logged in on this device
</span>
</div>
<div
className={`auth-keep-check ${keepSignedIn ? 'active' : 'inactive'}`}
>
{keepSignedIn && <IonIcon icon={checkmark} />}
</div>
</button>
)}
{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>
{showPostLoginSplash && (
<div className="auth-splash-overlay">
<SplashPage title="Send support to loved ones from anywhere" />
</div>
)}
</IonContent>
</IonPage>
);
};
export default AuthPage;
-324
View File
@@ -1,324 +0,0 @@
import React, { useState } from 'react';
import { useHistory, useParams } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
useIonViewWillEnter,
} from '@ionic/react';
import { chevronBackOutline, mailOpenOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import QuotationCard from '../components/QuotationCard';
const BuyerQuoteList: React.FC = () => {
const history = useHistory();
const { id } = useParams<{ id: string }>();
const [rfqSummary, setRfqSummary] = useState<{
title: string;
referenceNumber: string;
} | null>(null);
const [quotes, setQuotes] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [sortMode, setSortMode] = useState<'price' | 'supplier'>('price');
useIonViewWillEnter(() => {
loadQuotes();
});
const loadQuotes = async () => {
setLoading(true);
setError('');
try {
const { data: rfq, error: rfqErr } = await supabase
.from('rfqs')
.select('title, reference_number')
.eq('id', id)
.single();
if (rfqErr) throw rfqErr;
setRfqSummary({
title: rfq.title,
referenceNumber: rfq.reference_number,
});
const { data: qData, error: qErr } = await supabase
.from('quotations')
.select(
'id, price_amount, delivery_option, status, supplier_id, profiles(full_name, company_name)'
)
.eq('rfq_id', id);
if (qErr) throw qErr;
const mapped = (qData || []).map((q) => ({
id: q.id,
priceAmount: q.price_amount,
deliveryOption: q.delivery_option,
status: q.status,
supplierName:
q.profiles?.company_name || q.profiles?.full_name || 'Supplier',
}));
setQuotes(mapped);
} catch (err: any) {
console.error(err);
setError('Failed to load quotations.');
} finally {
setLoading(false);
}
};
const getSortedQuotes = () => {
if (sortMode === 'price') {
return [...quotes].sort((a, b) => a.priceAmount - b.priceAmount);
} else {
return [...quotes].sort((a, b) =>
a.supplierName.localeCompare(b.supplierName)
);
}
};
const handleAcceptQuote = async (quoteId: string) => {
try {
setLoading(true);
// Update selected quotation to accepted
const { error: accErr } = await supabase
.from('quotations')
.update({ status: 'accepted', updated_at: new Date().toISOString() })
.eq('id', quoteId);
if (accErr) throw accErr;
// Update sibling quotations to declined
const { error: decErr } = await supabase
.from('quotations')
.update({ status: 'declined', updated_at: new Date().toISOString() })
.eq('rfq_id', id)
.neq('id', quoteId);
if (decErr) throw decErr;
// Close RFQ
const { error: rfqErr } = await supabase
.from('rfqs')
.update({ status: 'closed', updated_at: new Date().toISOString() })
.eq('id', id);
if (rfqErr) throw rfqErr;
await loadQuotes();
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to accept quote.');
setLoading(false);
setTimeout(() => setError(''), 4000);
}
};
const handleDeclineQuote = async (quoteId: string) => {
try {
setLoading(true);
const { error } = await supabase
.from('quotations')
.update({ status: 'declined', updated_at: new Date().toISOString() })
.eq('id', quoteId);
if (error) throw error;
await loadQuotes();
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to decline quote.');
setLoading(false);
setTimeout(() => setError(''), 4000);
}
};
const sortedQuotes = getSortedQuotes();
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Compare Quotes
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
{loading && quotes.length === 0 ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '40px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : (
<>
{rfqSummary && (
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px',
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div
style={{
fontSize: '12px',
fontWeight: '700',
color: '#b45309',
background: 'rgba(245,158,11,0.14)',
borderRadius: '999px',
padding: '4px 10px',
width: 'max-content',
}}
>
{rfqSummary.referenceNumber}
</div>
<div
style={{
fontSize: '16px',
fontWeight: '600',
color: '#0f1720',
}}
>
{rfqSummary.title}
</div>
</div>
)}
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
marginBottom: '12px',
}}
>
{error}
</div>
)}
<div style={{ margin: '0 0 12px', display: 'flex', gap: '8px' }}>
<button
onClick={() => setSortMode('price')}
style={{
background: sortMode === 'price' ? '#166534' : '#ffffff',
color: sortMode === 'price' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '8px 16px',
fontSize: '13px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Sort by Price
</button>
<button
onClick={() => setSortMode('supplier')}
style={{
background: sortMode === 'supplier' ? '#166534' : '#ffffff',
color: sortMode === 'supplier' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '8px 16px',
fontSize: '13px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
}}
>
Sort by Supplier
</button>
</div>
{sortedQuotes.length > 0 ? (
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
{sortedQuotes.map((q) => (
<QuotationCard
key={q.id}
supplierName={q.supplierName}
priceLabel={`$${q.priceAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
deliveryOption={q.deliveryOption}
status={q.status}
onAccept={() => handleAcceptQuote(q.id)}
onDecline={() => handleDeclineQuote(q.id)}
/>
))}
</div>
) : (
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '28px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: '12px',
}}
>
<IonIcon
icon={mailOpenOutline}
style={{ fontSize: '48px', color: '#6c7a71' }}
/>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: '#6c7a71',
}}
>
No quotations available yet.
</div>
</div>
)}
</>
)}
</IonContent>
</IonPage>
);
};
export default BuyerQuoteList;
-343
View File
@@ -1,343 +0,0 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonContent,
IonSpinner,
useIonViewWillEnter,
IonIcon,
} from '@ionic/react';
import {
addOutline,
searchOutline,
optionsOutline,
documentTextOutline,
} from 'ionicons/icons';
import { supabase } from '../supabase';
import { useProfile } from '../contexts/ProfileContext';
import { useAuth } from '../contexts/AuthContext';
import RequestListCard from '../components/RequestListCard';
interface RFQListItem {
id: string;
title: string;
referenceNumber: string;
status: string;
createdAt: string;
}
const BuyerRequests: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { profile } = useProfile();
const [items, setItems] = useState<RFQListItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [searchText, setSearchText] = useState('');
const [activeStatus, setActiveStatus] = useState<
'all' | 'open' | 'quoted' | 'closed'
>('all');
useIonViewWillEnter(() => {
loadRequests();
});
const loadRequests = async () => {
if (!user || !profile) return;
setLoading(true);
setError('');
try {
if (profile.role === 'buyer') {
const { data, error: err } = await supabase
.from('rfqs')
.select('*')
.eq('buyer_id', user.id)
.order('created_at', { ascending: false });
if (err) throw err;
setItems(
data.map((d) => ({
id: d.id,
title: d.title,
referenceNumber: d.reference_number,
status: d.status,
createdAt: d.created_at,
}))
);
} else {
const { data, error: err } = await supabase
.from('rfq_recipients')
.select('id, rfqs!inner(*)')
.eq('supplier_id', user.id)
.order('created_at', { ascending: false });
if (err) throw err;
const mapped = (data || []).map((row: any) => ({
id: row.rfqs.id,
title: row.rfqs.title,
referenceNumber: row.rfqs.reference_number,
status: row.rfqs.status,
createdAt: row.rfqs.created_at,
}));
setItems(mapped);
}
} catch (err: any) {
console.error(err);
setError('Failed to load requests.');
} finally {
setLoading(false);
}
};
const filteredItems = items.filter((item) => {
const matchStatus = activeStatus === 'all' || item.status === activeStatus;
const searchLower = searchText.toLowerCase();
const matchSearch =
item.title.toLowerCase().includes(searchLower) ||
item.referenceNumber.toLowerCase().includes(searchLower);
return matchStatus && matchSearch;
});
const handleResetFilters = () => {
setSearchText('');
setActiveStatus('all');
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 12px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '12px',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
<div
style={{
fontSize: '13px',
fontWeight: '700',
letterSpacing: '0.08em',
textTransform: 'uppercase',
color: 'var(--color-brand)',
}}
>
{profile.role === 'buyer' ? 'Buyer Workspace' : 'Supplier Inbox'}
</div>
<div
style={{
fontSize: '24px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{profile.role === 'buyer' ? 'My Requests' : 'Assigned RFQs'}
</div>
</div>
{profile.role === 'buyer' && (
<div
onClick={() => history.push('/rfq/new')}
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-brand)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
flexShrink: 0,
}}
>
<IonIcon
icon={addOutline}
style={{ color: '#ffffff', fontSize: '24px' }}
/>
</div>
)}
</div>
{error && (
<div
style={{
margin: '0 20px 12px',
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<div style={{ margin: '0 20px 12px', display: 'flex', gap: '10px' }}>
<div style={{ flex: 1, position: 'relative' }}>
<IonIcon
icon={searchOutline}
style={{
position: 'absolute',
left: '14px',
top: '14px',
fontSize: '18px',
color: 'var(--color-text-tertiary)',
}}
/>
<input
type="text"
placeholder="Search by title or reference..."
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
borderRadius: '24px',
border: 'none',
padding: '0 16px 0 40px',
height: '44px',
width: '100%',
fontSize: '14px',
color: 'var(--color-text-primary)',
}}
/>
</div>
<button
onClick={handleResetFilters}
style={{
background: 'var(--color-surface-raised)',
borderRadius: '12px',
border: 'none',
width: '44px',
height: '44px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
flexShrink: 0,
}}
>
<IonIcon
icon={optionsOutline}
style={{ fontSize: '20px', color: 'var(--color-brand)' }}
/>
</button>
</div>
<div
style={{
margin: '0 20px 16px',
display: 'flex',
gap: '8px',
overflowX: 'auto',
paddingBottom: '4px',
}}
>
{(['all', 'open', 'quoted', 'closed'] as const).map((status) => (
<button
key={status}
onClick={() => setActiveStatus(status)}
style={{
background:
activeStatus === status
? 'var(--color-brand)'
: 'var(--color-surface)',
color:
activeStatus === status
? '#ffffff'
: 'var(--color-brand-strong)',
borderRadius: '999px',
padding: '8px 16px',
fontSize: '13px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
whiteSpace: 'nowrap',
textTransform: 'capitalize',
}}
>
{status}
</button>
))}
</div>
{loading ? (
<div
style={{
margin: '0 20px',
display: 'flex',
justifyContent: 'center',
padding: '20px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : filteredItems.length > 0 ? (
<div
style={{
margin: '0 20px',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
{filteredItems.map((item) => (
<RequestListCard
key={item.id}
title={item.title}
subtitle={new Date(item.createdAt).toLocaleDateString()}
referenceNumber={item.referenceNumber}
status={item.status}
onClick={() => history.push(`/rfq/${item.id}`)}
/>
))}
</div>
) : (
<div
style={{
margin: '0 20px',
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '28px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: '12px',
}}
>
<IonIcon
icon={documentTextOutline}
style={{ fontSize: '48px', color: 'var(--color-text-tertiary)' }}
/>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
No requests found.
</div>
</div>
)}
</IonContent>
</IonPage>
);
};
export default BuyerRequests;
-309
View File
@@ -1,309 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { Preferences } from '@capacitor/preferences';
const EditProfile: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { profile, setProfile } = useProfile();
const [fullName, setFullName] = useState('');
const [companyName, setCompanyName] = useState('');
const [phone, setPhone] = useState('');
const [city, setCity] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (profile) {
setFullName(profile.full_name || '');
setCompanyName(profile.company_name || '');
setPhone(profile.phone || '');
setCity(profile.city || '');
}
}, [profile]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSaveProfile = async (e: React.FormEvent) => {
e.preventDefault();
if (!user || !profile) return;
if (!fullName) {
showError('Please enter your full name');
return;
}
setSaving(true);
setError('');
const updates = {
full_name: fullName,
company_name: companyName || null,
phone: phone || null,
city: city || null,
updated_at: new Date().toISOString(),
};
const { error: updateError } = await supabase
.from('profiles')
.update(updates)
.eq('id', user.id);
if (updateError) {
showError(updateError.message);
setSaving(false);
return;
}
const updatedProfile = { ...profile, ...updates };
setProfile(updatedProfile);
await Preferences.set({
key: `profile_${user.id}`,
value: JSON.stringify(updatedProfile),
});
setSaving(false);
history.goBack();
};
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonHeader className="ion-no-border">
<IonToolbar
style={{ '--background': 'var(--color-bg)' } as React.CSSProperties}
>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: 'var(--color-brand-strong)' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{
fontSize: '18px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Edit Profile
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': 'var(--color-bg)',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '24px',
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
{error && (
<div
style={{
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
<form
onSubmit={handleSaveProfile}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
Full Name
</label>
<input
type="text"
placeholder="e.g. John Doe"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
required
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
Company Name
</label>
<input
type="text"
placeholder="e.g. BuildRight Supplies"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
City
</label>
<input
type="text"
placeholder="e.g. Lagos"
value={city}
onChange={(e) => setCity(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-text-primary)',
}}
>
Phone
</label>
<input
type="tel"
placeholder="e.g. +234 800 000 0000"
value={phone}
onChange={(e) => setPhone(e.target.value)}
style={{
background: 'var(--color-surface-raised)',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-primary)',
width: '100%',
}}
/>
</div>
<button
type="submit"
disabled={saving || !fullName}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: saving || !fullName ? 0.7 : 1,
marginTop: '8px',
}}
>
{saving ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Save Changes'
)}
</button>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default EditProfile;
+344
View File
@@ -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;
-177
View File
@@ -1,177 +0,0 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
const ForgotPassword: React.FC = () => {
const history = useHistory();
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleRequestReset = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
const { error } = await supabase.auth.resetPasswordForEmail(email);
if (error) {
showError(error.message);
setLoading(false);
return;
}
history.push('/verify-reset', { email });
setLoading(false);
};
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Reset Password
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': '0px',
}}
>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
margin: '20px 20px 0',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div>
<h2
style={{
fontSize: '22px',
fontWeight: '700',
color: '#0f1720',
margin: '0 0 8px 0',
}}
>
Forgot password?
</h2>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
Enter your email address and we'll send you a 6-digit code to
reset your password.
</p>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleRequestReset}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<input
type="email"
placeholder="you@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
/>
<button
type="submit"
disabled={loading || !email}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || !email ? 0.7 : 1,
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Send Code'
)}
</button>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default ForgotPassword;
+207
View File
@@ -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;
+21 -461
View File
@@ -1,470 +1,30 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import React from "react";
import {
IonPage,
IonContent,
IonSpinner,
useIonViewWillEnter,
IonIcon,
} from '@ionic/react';
import { documentTextOutline, addOutline, searchOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useProfile } from '../contexts/ProfileContext';
import { useAuth } from '../contexts/AuthContext';
import DashboardMetricCard from '../components/DashboardMetricCard';
import RecentActivityCard from '../components/RecentActivityCard';
import { Database } from '../database.types';
IonHeader,
IonPage,
IonTitle,
IonToolbar,
} from "@ionic/react";
type RfqRow = Database['public']['Tables']['rfqs']['Row'];
const Home: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { profile } = useProfile();
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [rfqSummary, setRfqSummary] = useState({
open: 0,
quoted: 0,
closed: 0,
});
const [supplierSummary, setSupplierSummary] = useState({
assignedOpen: 0,
myQuotes: 0,
accepted: 0,
});
const [recentItems, setRecentItems] = useState<any[]>([]);
useIonViewWillEnter(() => {
loadDashboardData();
});
const loadDashboardData = async () => {
if (!user || !profile) return;
setLoading(true);
setError('');
try {
if (profile.role === 'buyer') {
// Aggregate counts
const { data: allRfqs, error: countErr } = await supabase
.from('rfqs')
.select('id, status')
.eq('buyer_id', user.id);
if (countErr) throw countErr;
let open = 0,
quoted = 0,
closed = 0;
allRfqs?.forEach((r) => {
if (r.status === 'open') open++;
else if (r.status === 'quoted') quoted++;
else if (r.status === 'closed') closed++;
});
setRfqSummary({ open, quoted, closed });
// Recent items
const { data: recent, error: recentErr } = await supabase
.from('rfqs')
.select('*')
.eq('buyer_id', user.id)
.order('created_at', { ascending: false })
.limit(5);
if (recentErr) throw recentErr;
setRecentItems(recent || []);
} else {
// Supplier
const { data: allRecipients, error: recErr } = await supabase
.from('rfq_recipients')
.select('id, rfqs!inner(id, status)')
.eq('supplier_id', user.id);
if (recErr) throw recErr;
let assignedOpen = 0;
allRecipients?.forEach((r: any) => {
if (r.rfqs && r.rfqs.status === 'open') assignedOpen++;
});
const { data: myQuotes, error: qErr } = await supabase
.from('quotations')
.select('id, status')
.eq('supplier_id', user.id);
if (qErr) throw qErr;
let accepted = 0;
myQuotes?.forEach((q) => {
if (q.status === 'accepted') accepted++;
});
setSupplierSummary({
assignedOpen,
myQuotes: myQuotes?.length || 0,
accepted,
});
const { data: recent, error: recentErr } = await supabase
.from('rfq_recipients')
.select('id, rfqs!inner(*)')
.eq('supplier_id', user.id)
.order('created_at', { ascending: false })
.limit(5);
if (recentErr) throw recentErr;
// Map joined data
const mapped = (recent || []).map((r: any) => r.rfqs);
setRecentItems(mapped);
}
} catch (err: any) {
console.error(err);
setError('Failed to load dashboard data.');
} finally {
setLoading(false);
}
};
const handlePrimaryAction = () => {
if (profile?.role === 'buyer') {
history.push('/rfq/new');
} else {
history.push('/requests');
}
};
const handleRecentItemTap = (item: RfqRow) => {
history.push(`/rfq/${item.id}`);
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
<div
style={{
fontSize: '13px',
fontWeight: '700',
letterSpacing: '0.08em',
textTransform: 'uppercase',
color: 'var(--color-brand)',
}}
>
QuoteLink
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>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-tertiary)',
}}
>
Procurement made simpler
</div>
</div>
<div
onClick={() => history.push('/profile')}
style={{
width: '40px',
height: '40px',
borderRadius: '999px',
background: 'var(--color-brand-medium)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
color: 'var(--color-brand)',
fontSize: '16px',
fontWeight: '700',
textTransform: 'uppercase',
flexShrink: 0,
}}
>
{profile.full_name.charAt(0)}
</div>
</div>
<div
style={{
margin: '0 20px 18px',
display: 'flex',
flexDirection: 'column',
gap: '5px',
}}
>
<div
style={{
fontSize: '26px',
fontWeight: '400',
color: 'var(--color-text-primary)',
lineHeight: '1.08',
}}
>
Good to see you,{' '}
<span style={{ fontWeight: '700' }}>
{profile.full_name.split(' ')[0]}
</span>
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
{profile.role === 'buyer'
? 'Track requests, review supplier pricing, and keep decisions moving.'
: 'Review assigned RFQs, send pricing fast, and stay on top of wins.'}
</div>
</div>
{error && (
<div
style={{
margin: '0 20px 12px',
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
<div
style={{
background: 'var(--color-brand-strong)',
borderRadius: '24px',
padding: '22px',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
gap: '14px',
cursor: 'pointer',
}}
onClick={handlePrimaryAction}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
}}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
>
<span
style={{
fontSize: '12px',
fontWeight: '600',
color: 'rgba(255,255,255,0.72)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{profile.role === 'buyer' ? 'Active Requests' : 'Assigned RFQs'}
</span>
<span
style={{
fontSize: '34px',
fontWeight: '400',
color: '#ffffff',
}}
>
{profile.role === 'buyer'
? rfqSummary.open + rfqSummary.quoted
: supplierSummary.assignedOpen}
</span>
</div>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '14px',
background: 'rgba(255,255,255,0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon
icon={profile.role === 'buyer' ? addOutline : searchOutline}
style={{ color: '#ffffff', fontSize: '24px' }}
/>
</div>
</div>
<div
style={{
fontSize: '14px',
fontWeight: '600',
color: 'var(--color-accent)',
}}
>
{profile.role === 'buyer'
? 'Create new request →'
: 'Browse requests →'}
</div>
</div>
<div style={{ display: 'flex', gap: '12px', margin: '0 20px 24px' }}>
{profile.role === 'buyer' ? (
<>
<DashboardMetricCard
label="Received Quotes"
value={rfqSummary.quoted.toString()}
hint="Awaiting decision"
icon={documentTextOutline}
/>
<DashboardMetricCard
label="Completed"
value={rfqSummary.closed.toString()}
hint="Past requests"
icon={documentTextOutline}
/>
</>
) : (
<>
<DashboardMetricCard
label="My Quotes"
value={supplierSummary.myQuotes.toString()}
hint="Submitted"
icon={documentTextOutline}
/>
<DashboardMetricCard
label="Accepted"
value={supplierSummary.accepted.toString()}
hint="Won bids"
icon={documentTextOutline}
/>
</>
)}
</div>
<div
style={{
margin: '16px 20px 8px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-end',
}}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Recent Activity
</div>
<div
onClick={() => history.push('/requests')}
style={{
fontSize: '13px',
fontWeight: '600',
color: 'var(--color-brand)',
cursor: 'pointer',
}}
>
See all
</div>
</div>
{loading ? (
<div
style={{
margin: '0 20px',
display: 'flex',
justifyContent: 'center',
padding: '20px',
}}
>
<IonSpinner
name="crescent"
style={{ color: 'var(--color-brand)' }}
/>
</div>
) : recentItems.length > 0 ? (
recentItems.map((item) => (
<RecentActivityCard
key={item.id}
title={item.title}
subtitle={new Date(item.created_at).toLocaleDateString()}
meta={item.status}
onClick={() => handleRecentItemTap(item)}
/>
))
) : (
<div
style={{
margin: '0 20px',
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '28px',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
textAlign: 'center',
gap: '12px',
}}
>
<IonIcon
icon={documentTextOutline}
style={{ fontSize: '48px', color: 'var(--color-text-tertiary)' }}
/>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
No recent activity yet.
</div>
{profile.role === 'buyer' && (
<button
onClick={handlePrimaryAction}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '10px 20px',
fontSize: '14px',
fontWeight: '600',
border: 'none',
cursor: 'pointer',
marginTop: '8px',
}}
>
Create Request
</button>
)}
</div>
)}
</IonContent>
</IonPage>
);
};
export default Home;
+900
View File
@@ -0,0 +1,900 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
IonContent,
IonIcon,
IonPage,
useIonViewWillEnter,
} from '@ionic/react';
import { useHistory } from 'react-router-dom';
import {
chevronForwardOutline,
ellipsisVertical,
flashOutline,
heart,
notificationsOutline,
phonePortraitOutline,
checkmarkCircleOutline,
timeOutline,
wifiOutline,
medkitOutline,
attach,
attachOutline,
trashOutline,
pinOutline,
} from 'ionicons/icons';
import momImage from '../assets/mom.jpg';
import dadImage from '../assets/dad.jpg';
import basketIcon from '../assets/basket.png';
import { setStatusBarStyle, Style } from '../utils/statusBar';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import DashboardSkeleton from '../components/DashboardSkeleton';
import { formatMoney } from '../utils/formatMoney';
import {
buildCacheKey,
readCache,
removeCache,
writeCache,
} from '../utils/localCache';
import {
fetchHomeSnapshot,
buildSnapshotHash,
getWarmedHomeSnapshot,
HomeAlert,
SupportCategoryTone,
} from '../utils/homeSnapshot';
import { hydrateHomeSnapshotImages } from '../utils/imageCache';
import '../styles/home.css';
type ActivityStatusTone = 'success' | 'warning' | 'info' | 'partial';
type HomeRenderableIcon = {
iconType: 'ion' | 'image';
icon?: any;
iconSrc?: string;
iconAlt?: string;
};
const quickActions: Array<
HomeRenderableIcon & {
label: string;
helper: string;
tone: SupportCategoryTone;
}
> = [
{
label: 'Grocery',
helper: 'Voucher for partner stores',
iconType: 'image',
iconSrc: basketIcon,
iconAlt: 'Groceries',
tone: 'grocery',
},
{
label: 'Medication',
helper: 'Voucher for trusted pharmacies',
iconType: 'ion',
icon: medkitOutline,
tone: 'medication',
},
{
label: 'Airtime & Data',
helper: 'Top up mobile credit quickly',
iconType: 'ion',
icon: wifiOutline,
tone: 'airtime',
},
{
label: 'Electricity',
helper: 'Send ZESA meter support',
iconType: 'ion',
icon: flashOutline,
tone: 'electricity',
},
];
const renderHomeIcon = (item: HomeRenderableIcon) => {
if (item.iconType === 'image' && item.iconSrc) {
const isPill = item.iconSrc.includes('pill');
const isBasket = item.iconSrc.includes('basket');
return (
<img
src={item.iconSrc}
alt={item.iconAlt ?? ''}
className={`home-custom-icon ${isPill ? 'is-pill' : ''} ${isBasket ? 'is-basket' : ''}`}
/>
);
}
return item.icon ? <IonIcon icon={item.icon} /> : null;
};
const HomePage: React.FC = () => {
const history = useHistory();
const { user, profile, profileStatus } = useAuth();
const [alerts, setAlerts] = useState<HomeAlert[]>([]);
const [alertsLoading, setAlertsLoading] = useState(true);
const [alertsError, setAlertsError] = useState<string | null>(null);
const [lovedOnes, setLovedOnes] = useState<any[]>([]);
const [lovedOnesLoading, setLovedOnesLoading] = useState(true);
const [lovedOnesError, setLovedOnesError] = useState<string | null>(null);
const [activities, setActivities] = useState<any[]>([]);
const [activitiesLoading, setActivitiesLoading] = useState(true);
const [activitiesError, setActivitiesError] = useState<string | null>(null);
const [monthlySentTotal, setMonthlySentTotal] = useState(0);
const [selectedLovedOne, setSelectedLovedOne] = useState<any | null>(null);
const [lovedOneActionLoading, setLovedOneActionLoading] = useState(false);
const [homeDataUserId, setHomeDataUserId] = useState<string | null>(null);
const [profileAvatarUrl, setProfileAvatarUrl] = useState<string | null>(null);
const lastSnapshotHashRef = useRef<string | null>(null);
const getProfileAvatarUrl = (avatarPath?: string | null) => {
if (!avatarPath) return null;
const { data } = supabase.storage.from('avatars').getPublicUrl(avatarPath);
return data.publicUrl || null;
};
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 getRecipientAvatarUrl = async (
photoPath?: string | null,
firstName?: string | null
) => {
const seededImage = getSeededRecipientImage(firstName, photoPath);
if (seededImage) return seededImage;
if (photoPath) {
const { data } = supabase.storage
.from('recipient-photos')
.getPublicUrl(photoPath);
if (data?.publicUrl) return data.publicUrl;
}
return null;
};
useIonViewWillEnter(() => {
setStatusBarStyle(Style.Light);
if (user?.id) {
void loadHomePageData(user.id);
}
});
useEffect(() => {
if (user?.id && profileStatus === 'loaded' && homeDataUserId !== user.id) {
void loadHomePageData(user.id);
}
}, [homeDataUserId, profileStatus, user?.id]);
useEffect(() => {
if (!user?.id) {
setProfileAvatarUrl(null);
return;
}
const avatarCacheKey = buildCacheKey(user.id, 'profileAvatarUrl');
let cancelled = false;
const loadAvatar = async () => {
const cachedAvatarUrl = await readCache<string>(avatarCacheKey);
if (!cancelled && cachedAvatarUrl) {
setProfileAvatarUrl(cachedAvatarUrl);
}
const nextAvatarUrl = getProfileAvatarUrl(profile?.avatar_path);
if (!cancelled) {
setProfileAvatarUrl(nextAvatarUrl);
}
if (nextAvatarUrl) {
void writeCache(avatarCacheKey, nextAvatarUrl);
}
};
void loadAvatar();
return () => {
cancelled = true;
};
}, [profile?.avatar_path, user?.id]);
const loadHomePageData = async (activeUserId: string) => {
setHomeDataUserId(activeUserId);
const cacheKey = buildCacheKey(activeUserId, 'homeSnapshot');
let hasCache = false;
try {
const warmedSnapshot = getWarmedHomeSnapshot(activeUserId);
const cached = warmedSnapshot ?? (await readCache<any>(cacheKey));
const isCurrentUserCache = cached?.userId === activeUserId;
if (
cached &&
isCurrentUserCache &&
typeof cached === 'object' &&
Array.isArray(cached.alerts) &&
Array.isArray(cached.lovedOnes) &&
Array.isArray(cached.activities) &&
typeof cached.monthlySentTotal === 'number'
) {
setAlerts(cached.alerts);
setLovedOnes(cached.lovedOnes);
setActivities(cached.activities);
setMonthlySentTotal(cached.monthlySentTotal);
setAlertsLoading(false);
setLovedOnesLoading(false);
setActivitiesLoading(false);
lastSnapshotHashRef.current = buildSnapshotHash({
monthlySentTotal: cached.monthlySentTotal,
alerts: cached.alerts,
lovedOnes: cached.lovedOnes,
activities: cached.activities,
imageUrls: cached.imageUrls ?? [],
});
hasCache = true;
}
} catch (err) {
console.error('[home cache] error reading', err);
}
if (!hasCache) {
setAlertsLoading(true);
setLovedOnesLoading(true);
setActivitiesLoading(true);
}
setAlertsError(null);
setLovedOnesError(null);
setActivitiesError(null);
try {
const nextSnapshot = await fetchHomeSnapshot(
activeUserId,
getRecipientAvatarUrl
);
const hydratedSnapshot = await hydrateHomeSnapshotImages(
activeUserId,
nextSnapshot
);
const nextSnapshotHash = buildSnapshotHash(hydratedSnapshot);
if (lastSnapshotHashRef.current !== nextSnapshotHash) {
setMonthlySentTotal(hydratedSnapshot.monthlySentTotal);
setAlerts(hydratedSnapshot.alerts);
setLovedOnes(hydratedSnapshot.lovedOnes);
setActivities(hydratedSnapshot.activities);
lastSnapshotHashRef.current = nextSnapshotHash;
}
setAlertsLoading(false);
setLovedOnesLoading(false);
setActivitiesLoading(false);
void writeCache(cacheKey, {
userId: activeUserId,
monthlySentTotal: hydratedSnapshot.monthlySentTotal,
alerts: hydratedSnapshot.alerts,
lovedOnes: hydratedSnapshot.lovedOnes,
activities: hydratedSnapshot.activities,
imageUrls: hydratedSnapshot.imageUrls,
cachedAt: new Date().toISOString(),
});
} catch (err) {
console.error('[home data fetch]', err);
setAlertsError('Could not load care alerts');
setLovedOnesError('Could not load loved ones');
setActivitiesError('Could not load activity');
setAlertsLoading(false);
setLovedOnesLoading(false);
setActivitiesLoading(false);
}
};
const handleAlertTap = (alert: HomeAlert) => {
history.push('/support/new', {
recipientId: alert.recipientId,
serviceType: alert.serviceType,
parentRoot: '/home',
});
};
const handleSupportClick = (serviceType?: SupportCategoryTone) => {
history.push(
'/support/new',
serviceType
? { serviceType, parentRoot: '/home' }
: { parentRoot: '/home' }
);
};
const handleRecipientsClick = () => {
history.push('/recipients');
};
const handleTogglePinLovedOne = async () => {
if (!selectedLovedOne?.id || !user?.id || lovedOneActionLoading) {
return;
}
const isPinned = Boolean(selectedLovedOne.pinnedAt);
setLovedOneActionLoading(true);
const nextLovedOnes = lovedOnes.map((person) => {
if (person.id !== selectedLovedOne.id) return person;
return {
...person,
pinnedAt: isPinned ? null : new Date().toISOString(),
};
});
const sortedLovedOnes = [...nextLovedOnes].sort((a, b) => {
if (a.pinnedAt && !b.pinnedAt) return -1;
if (!a.pinnedAt && b.pinnedAt) return 1;
return 0;
});
setLovedOnes(sortedLovedOnes);
setSelectedLovedOne(null);
const { error } = await supabase
.from('recipients')
.update({ pinned_at: isPinned ? null : new Date().toISOString() })
.eq('id', selectedLovedOne.id)
.eq('user_id', user.id);
if (error) {
await loadHomePageData(user.id);
}
setLovedOneActionLoading(false);
};
const handleDeleteLovedOne = async () => {
if (!selectedLovedOne?.id || !user?.id || lovedOneActionLoading) {
return;
}
setLovedOneActionLoading(true);
const recipientId = selectedLovedOne.id;
const previousLovedOnes = lovedOnes;
setLovedOnes((current) =>
current.filter((person) => person.id !== recipientId)
);
setSelectedLovedOne(null);
const { error } = await supabase
.from('recipients')
.update({ archived_at: new Date().toISOString(), is_active: false })
.eq('id', recipientId)
.eq('user_id', user.id);
if (error) {
setLovedOnes(previousLovedOnes);
}
setLovedOneActionLoading(false);
};
const displayName = useMemo(() => {
const firstName = profile?.first_name?.trim();
if (firstName) return firstName;
const emailName = user?.email?.split('@')[0]?.trim();
return emailName || 'there';
}, [profile?.first_name, user?.email]);
const displayInitial = displayName.charAt(0).toUpperCase();
const activeLovedOnesCount = lovedOnes.length;
const isPreviewMode = !user;
const currentMonthLabel = useMemo(
() =>
new Intl.DateTimeFormat(undefined, {
month: 'long',
}).format(new Date()),
[]
);
const monthlySentLabel = useMemo(
() => formatMoney(monthlySentTotal, 'USD'),
[monthlySentTotal]
);
const showInitialDashboardSkeleton =
!isPreviewMode &&
profileStatus === 'loading' &&
lovedOnesLoading &&
activitiesLoading &&
alertsLoading &&
lovedOnes.length === 0 &&
activities.length === 0 &&
alerts.length === 0;
return (
<IonPage>
<IonContent
fullscreen
style={{ '--background': 'var(--color-bg)' } as React.CSSProperties}
>
{showInitialDashboardSkeleton ? (
<DashboardSkeleton />
) : (
<div className="home-shell">
<div className="home-topline">
<div className="home-topline-left">
<button
type="button"
className="home-main-avatar-wrap"
aria-label="Open profile"
onClick={() => history.push('/profile')}
>
{profileAvatarUrl ? (
<img
src={profileAvatarUrl}
alt={profile?.full_name || displayName}
className="home-main-avatar"
/>
) : (
<span className="home-main-avatar-fallback">
{displayInitial}
</span>
)}
</button>
<div className="home-greeting-block">
<h1 className="home-greeting">Hi {displayName} 👋</h1>
</div>
</div>
<button
type="button"
className="home-notification-card"
aria-label="Notifications"
onClick={() =>
history.push('/notifications', { parentRoot: '/home' })
}
>
<IonIcon icon={notificationsOutline} />
<span className="home-dot" />
</button>
</div>
<div className="home-header-actions-row">
<div className="home-tagline-wrap">
<p className="home-subcopy">
Supporting {activeLovedOnesCount}{' '}
{activeLovedOnesCount === 1 ? 'loved one' : 'loved ones'}
</p>
</div>
<div className="home-month-pill">
<div className="home-month-icon">
<IonIcon icon={heart} />
</div>
<div className="home-month-copy">
<p className="home-month-label">{currentMonthLabel}</p>
<p className="home-month-value">{monthlySentLabel}</p>
</div>
</div>
</div>
{(alertsLoading || alertsError || alerts.length > 0) && (
<>
<div className="home-section-row">
<h2 className="home-section-heading">Care Alerts</h2>
</div>
<div className="home-alert-marquee">
{alertsLoading && alerts.length === 0 ? (
<div className="home-alert-overlay-state">
<div
className="home-alert-card home-alert-skeleton"
aria-label="Loading care alerts"
>
<div className="home-alert-icon" />
<div className="home-alert-content">
<span className="home-alert-skeleton-title" />
<span className="home-alert-skeleton-subtitle" />
<span className="home-alert-skeleton-cta" />
</div>
</div>
</div>
) : alertsError ? (
<div className="home-alert-overlay-state">
<p className="home-alert-error">{alertsError}</p>
</div>
) : alerts.length > 0 ? (
<div className="home-alert-marquee-track">
{[...alerts, ...alerts].map((alert, index) => (
<button
key={`${alert.id}-${index}`}
type="button"
className="home-alert-card"
onClick={() => handleAlertTap(alert)}
>
<div
className={`home-alert-icon home-tone-${alert.tone}`}
>
{alert.iconType === 'image' ? (
<img
src={alert.icon as string}
alt=""
className="home-custom-icon is-basket"
/>
) : (
<IonIcon icon={alert.icon as any} />
)}
</div>
<div className="home-alert-content">
<span className="home-alert-title">
{alert.title}
</span>
<span className="home-alert-subtitle">
{alert.subtitle}
</span>
</div>
<div
className={`home-alert-chevron-chip home-tone-${alert.tone}`}
>
<IonIcon icon={chevronForwardOutline} />
</div>
</button>
))}
</div>
) : null}
</div>
</>
)}
<div className="home-section-row home-section-row-spaced">
<h2 className="home-section-heading">Your Loved Ones</h2>
<button
type="button"
className="home-section-link"
onClick={handleRecipientsClick}
>
View all
</button>
</div>
<div className="home-loved-ones-scroll">
{lovedOnesLoading && lovedOnes.length === 0 ? (
<div
className="home-person-card home-person-card-lavender"
style={{ opacity: 0.5 }}
>
<div className="home-person-header">
<div className="home-person-meta">
<div className="home-person-avatar-shell"></div>
<div>
<p className="home-person-name">Loading...</p>
</div>
</div>
</div>
</div>
) : lovedOnesError ? (
<p className="home-alert-error">{lovedOnesError}</p>
) : lovedOnes.length === 0 ? (
<div
className="home-empty-alerts"
style={{ margin: '0 20px', width: 'auto' }}
>
<div className="home-empty-alerts-icon">
<IonIcon icon={heart} />
</div>
<h3 className="home-empty-alerts-msg">No loved ones yet</h3>
<p className="home-empty-alerts-helper">
Add family members to start supporting them.
</p>
<button
className="home-empty-alerts-cta"
onClick={handleRecipientsClick}
>
Add loved one
</button>
</div>
) : (
lovedOnes.map((person) => (
<div
key={person.id}
className={`home-person-card home-person-card-${person.cardTone}`}
>
<div className="home-person-header">
<div className="home-person-meta">
<div className="home-person-avatar-shell">
{person.avatar ? (
<img
src={person.avatar}
alt={person.name}
className="home-person-avatar"
loading="eager"
decoding="sync"
/>
) : (
<span className="home-person-initial">
{person.fallbackInitial}
</span>
)}
<span className="home-person-online" />
</div>
<div>
<p className="home-person-name">
{person.name} <span>{person.emoji}</span>
</p>
<p className="home-person-location">
{person.lastSupportLabel}
</p>
</div>
</div>
<div className="home-card-menu-wrap">
<button
type="button"
className={`home-card-menu ${selectedLovedOne?.id === person.id ? 'is-active' : ''}`}
aria-label={`More options for ${person.name}`}
aria-expanded={selectedLovedOne?.id === person.id}
onClick={() =>
setSelectedLovedOne((current) =>
current?.id === person.id ? null : person
)
}
>
<IonIcon icon={ellipsisVertical} />
</button>
{selectedLovedOne?.id === person.id && (
<div className="home-loved-one-panel">
<button
type="button"
className="home-loved-one-panel-action"
onClick={() => {
void handleTogglePinLovedOne();
}}
disabled={lovedOneActionLoading}
>
<IonIcon
icon={person.pinnedAt ? attachOutline : attach}
/>
<span>{person.pinnedAt ? 'Unpin' : 'Pin'}</span>
</button>
<button
type="button"
className="home-loved-one-panel-action is-danger"
onClick={() => {
void handleDeleteLovedOne();
}}
disabled={lovedOneActionLoading}
>
<IonIcon icon={trashOutline} />
<span>Remove</span>
</button>
</div>
)}
</div>
</div>
<div className="home-status-stack">
{person.statuses.length > 0 ? (
person.statuses.slice(0, 3).map((item: any) => {
const isSuccess = item.status === 'success';
return (
<div
key={`${person.id}-${item.id ?? item.createdAt ?? item.label}`}
className="home-status-row"
>
<div
className={`home-status-icon home-tone-${item.iconTone}`}
>
{renderHomeIcon(item)}
</div>
<div className="home-status-copy">
<p className="home-status-label">
{item.label}
</p>
<p
className={`home-status-detail ${isSuccess ? 'is-success' : 'is-warning'}`}
>
{item.detail}
</p>
</div>
<IonIcon
icon={
isSuccess
? checkmarkCircleOutline
: timeOutline
}
className={`home-status-trailing ${isSuccess ? 'is-success' : 'is-warning'}`}
/>
</div>
);
})
) : (
<div className="home-status-empty-row">
<IonIcon icon={heart} />
<span>No support sent yet</span>
</div>
)}
</div>
<button
type="button"
className={`home-send-button home-tone-${person.repeatAction.tone}`}
onClick={() =>
history.push('/support/new', {
recipientId: person.id,
serviceType: person.primaryServiceType,
parentRoot: '/home',
})
}
>
<span className="home-send-button-icon">
{renderHomeIcon(person.repeatAction)}
</span>
<span>{person.repeatCta}</span>
</button>
</div>
))
)}
</div>
<div className="home-carousel-indicator">
<span className="home-dot-active" />
<span className="home-dot-inactive" />
<span className="home-dot-inactive" />
</div>
<div className="home-section-row home-section-row-spaced">
<h2 className="home-section-heading">Send Support</h2>
</div>
<div className="home-action-grid">
{quickActions.map((action) => (
<button
key={action.label}
type="button"
className="home-action-card"
onClick={() => handleSupportClick(action.tone)}
>
<div className={`home-action-icon home-tone-${action.tone}`}>
{renderHomeIcon(action)}
</div>
<div className="home-action-text-block">
<span className="home-action-label">{action.label}</span>
<span className="home-action-helper">{action.helper}</span>
</div>
</button>
))}
</div>
<div className="home-section-row">
<h2 className="home-section-heading">Family Updates</h2>
<button
type="button"
className="home-section-link"
onClick={() => history.push('/activity')}
>
View all
</button>
</div>
<div className="home-activity-card">
{activitiesLoading && activities.length === 0 ? (
<div
style={{
padding: '20px',
textAlign: 'center',
color: 'var(--ion-color-medium)',
}}
>
Loading activity...
</div>
) : activitiesError ? (
<div style={{ padding: '20px', textAlign: 'center' }}>
<p className="home-alert-error">{activitiesError}</p>
</div>
) : activities.length === 0 ? (
<div
className="home-empty-alerts"
style={{ boxShadow: 'none' }}
>
<div
className="home-empty-alerts-icon"
style={{
background: 'rgba(23, 24, 39, 0.04)',
color: 'var(--ion-color-medium)',
}}
>
<IonIcon icon={timeOutline} />
</div>
<h3 className="home-empty-alerts-msg">No recent activity</h3>
<p className="home-empty-alerts-helper">
Support history will appear here once you send support.
</p>
<button
className="home-empty-alerts-cta"
onClick={() => handleSupportClick()}
>
Send first support
</button>
</div>
) : (
activities.map((activity, index) => (
<button
key={activity.id}
type="button"
className={`home-activity-row home-activity-row-button ${
index === activities.length - 1 ? 'is-last' : ''
}`}
onClick={() =>
history.push(`/recipients/${activity.recipientId}`)
}
>
<div className="home-activity-avatar-shell">
{activity.avatar ? (
<img
src={activity.avatar}
alt=""
className="home-activity-avatar"
loading="eager"
decoding="sync"
/>
) : (
<div className="home-activity-avatar home-activity-avatar-fallback">
<span>{activity.fallbackInitial}</span>
</div>
)}
<div
className={`home-activity-avatar-badge home-tone-${activity.iconTone}`}
>
{renderHomeIcon(activity.icon)}
</div>
</div>
<div className="home-activity-copy">
<div className="home-activity-head-row">
<div className="home-activity-text-block">
<p className="home-activity-title">
{activity.title}
</p>
<p className="home-activity-subtitle">
{activity.subtitle}
</p>
</div>
<div className="home-activity-right">
<p className="home-activity-amount">
{formatMoney(Number(activity.amount), 'USD')}
</p>
<div
className={`home-activity-badge home-badge-${activity.tone}`}
>
<span>{activity.status}</span>
</div>
</div>
</div>
</div>
</button>
))
)}
</div>
</div>
)}
</IonContent>
</IonPage>
);
};
export default HomePage;
-491
View File
@@ -1,491 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline, cameraOutline, closeCircle } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import SupplierPickerRow, {
SupplierOption,
} from '../components/SupplierPickerRow';
const NewRfq: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const [title, setTitle] = useState('');
const [requestText, setRequestText] = useState('');
const [supplierOptions, setSupplierOptions] = useState<SupplierOption[]>([]);
const [selectedSupplierIds, setSelectedSupplierIds] = useState<string[]>([]);
const [loadingSuppliers, setLoadingSuppliers] = useState(true);
const [imageFile, setImageFile] = useState<File | null>(null);
const [imagePreviewUrl, setImagePreviewUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
loadSuppliers();
return () => {
cleanupPreview();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const loadSuppliers = async () => {
setLoadingSuppliers(true);
const { data, error: err } = await supabase
.from('profiles')
.select('id, full_name, company_name, city')
.eq('role', 'supplier')
.order('company_name', { ascending: true })
.order('full_name', { ascending: true });
if (!err && data) {
setSupplierOptions(data);
}
setLoadingSuppliers(false);
};
const cleanupPreview = () => {
if (imagePreviewUrl) {
URL.revokeObjectURL(imagePreviewUrl);
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const file = e.target.files[0];
setImageFile(file);
cleanupPreview();
setImagePreviewUrl(URL.createObjectURL(file));
}
};
const toggleSupplier = (id: string) => {
if (selectedSupplierIds.includes(id)) {
setSelectedSupplierIds(selectedSupplierIds.filter((s) => s !== id));
} else {
if (selectedSupplierIds.length >= 5) {
showError('Select up to 5 suppliers');
} else {
setSelectedSupplierIds([...selectedSupplierIds, id]);
}
}
};
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleCreateRfq = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
if (!requestText.trim()) {
showError('Please describe your request.');
return;
}
if (selectedSupplierIds.length === 0) {
showError('Please select at least 1 supplier.');
return;
}
setLoading(true);
setError('');
try {
// 1. Get Reference Number
const { data: refData, error: refError } =
await supabase.functions.invoke('create-rfq-reference', {
body: {},
});
if (refError || !refData?.referenceNumber) {
throw new Error('Failed to generate reference number.');
}
const referenceNumber = refData.referenceNumber;
const derivedTitle =
title.trim() || requestText.trim().substring(0, 30) + '...';
// 2. Insert RFQ
const { data: rfq, error: rfqError } = await supabase
.from('rfqs')
.insert({
buyer_id: user.id,
reference_number: referenceNumber,
title: derivedTitle,
request_text: requestText.trim(),
status: 'open',
})
.select('id')
.single();
if (rfqError) throw rfqError;
// 3. Upload Image if present
if (imageFile) {
const filePath = `${user.id}/${rfq.id}/${Date.now()}-${imageFile.name}`;
const { error: uploadError } = await supabase.storage
.from('rfq-images')
.upload(filePath, imageFile);
if (uploadError) throw uploadError;
const { error: imgMetaError } = await supabase
.from('rfq_images')
.insert({
rfq_id: rfq.id,
owner_id: user.id,
storage_path: filePath,
});
if (imgMetaError) throw imgMetaError;
}
// 4. Insert Recipients
const recipientsToInsert = selectedSupplierIds.map((sid) => ({
rfq_id: rfq.id,
supplier_id: sid,
}));
const { error: recError } = await supabase
.from('rfq_recipients')
.insert(recipientsToInsert);
if (recError) throw recError;
// 5. Navigate
history.replace(`/rfq/${rfq.id}`);
} catch (err: any) {
console.error(err);
showError(err.message || 'Failed to create RFQ.');
} finally {
setLoading(false);
}
};
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
New Request
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div style={{ margin: '0 0 16px', background: 'transparent' }}>
<h1
style={{
fontSize: '26px',
fontWeight: '700',
color: '#0f1720',
margin: '0 0 4px 0',
}}
>
Request Quote
</h1>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
Describe what you need and select suppliers.
</p>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
marginBottom: '16px',
}}
>
{error}
</div>
)}
<form
onSubmit={handleCreateRfq}
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<input
type="text"
placeholder="Title (e.g. 100 Bricks + Cement)"
value={title}
onChange={(e) => setTitle(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
<textarea
placeholder="Describe your request..."
value={requestText}
onChange={(e) => setRequestText(e.target.value)}
rows={4}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '14px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
resize: 'vertical',
}}
required
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<label
style={{ fontSize: '13px', fontWeight: '600', color: '#0f1720' }}
>
Site Photo or Reference (Optional)
</label>
{imagePreviewUrl ? (
<div style={{ position: 'relative', width: 'max-content' }}>
<img
src={imagePreviewUrl}
alt="Preview"
style={{
width: '88px',
height: '88px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
<IonIcon
icon={closeCircle}
onClick={() => {
setImageFile(null);
setImagePreviewUrl(null);
}}
style={{
position: 'absolute',
top: '-8px',
right: '-8px',
fontSize: '24px',
color: '#b91c1c',
cursor: 'pointer',
background: '#fff',
borderRadius: '50%',
}}
/>
</div>
) : (
<label
style={{
background: '#edf4ee',
borderRadius: '24px',
padding: '18px',
display: 'flex',
alignItems: 'center',
gap: '16px',
cursor: 'pointer',
}}
>
<div
style={{
width: '48px',
height: '48px',
borderRadius: '12px',
background: 'rgba(22,101,52,0.12)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon
icon={cameraOutline}
style={{ color: '#166534', fontSize: '24px' }}
/>
</div>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<span
style={{
fontSize: '14px',
fontWeight: '600',
color: '#166534',
}}
>
Add a photo
</span>
<span
style={{
fontSize: '12px',
fontWeight: '400',
color: '#6c7a71',
}}
>
Tap to browse
</span>
</div>
<input
type="file"
accept="image/*"
onChange={handleFileChange}
style={{ display: 'none' }}
/>
</label>
)}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-end',
}}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Select Suppliers (Up to 5)
</label>
<span
style={{
fontSize: '12px',
fontWeight: '400',
color: '#6c7a71',
}}
>
{selectedSupplierIds.length}/5 selected
</span>
</div>
<div
style={{
background: '#f9fbf9',
borderRadius: '12px',
padding: '14px',
maxHeight: '200px',
overflowY: 'auto',
}}
>
{loadingSuppliers ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '10px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : supplierOptions.length > 0 ? (
supplierOptions.map((supplier) => (
<SupplierPickerRow
key={supplier.id}
supplier={supplier}
selected={selectedSupplierIds.includes(supplier.id)}
onToggle={() => toggleSupplier(supplier.id)}
/>
))
) : (
<div
style={{
fontSize: '13px',
color: '#6c7a71',
textAlign: 'center',
padding: '10px',
}}
>
No suppliers found.
</div>
)}
</div>
</div>
<button
type="submit"
disabled={loading || selectedSupplierIds.length === 0}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || selectedSupplierIds.length === 0 ? 0.7 : 1,
marginTop: '8px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Send Request'
)}
</button>
</form>
</IonContent>
</IonPage>
);
};
export default NewRfq;

Some files were not shown because too many files have changed in this diff Show More