Compare commits

..

1 Commits

Author SHA1 Message Date
AppCakes c8ec54c22d build: da8aa2fb-9871-4e3e-a583-70eda77c4d68 2026-06-12 11:55:41 +00:00
102 changed files with 4408 additions and 6425 deletions
Binary file not shown.
+2 -2
View File
@@ -4,10 +4,10 @@ android {
namespace = "io.ionic.starter" namespace = "io.ionic.starter"
compileSdk = rootProject.ext.compileSdkVersion compileSdk = rootProject.ext.compileSdkVersion
defaultConfig { defaultConfig {
applicationId "com.qoutelink.app" applicationId "io.shopkeep.app"
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 3 versionCode 1
versionName "1.0" versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [googleMapsApiKey: System.getenv("VITE_GOOGLE_MAPS_KEY") ?: ""] manifestPlaceholders = [googleMapsApiKey: System.getenv("VITE_GOOGLE_MAPS_KEY") ?: ""]
+1 -1
View File
@@ -25,7 +25,7 @@
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="com.qoutelink.app" /> <data android:scheme="io.shopkeep.app" />
</intent-filter> </intent-filter>
</activity> </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 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="ic_launcher_background">#FFFFFF</color> <color name="ic_launcher_background">#FFFFFF</color>
</resources> </resources>
@@ -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'?> <?xml version='1.0' encoding='utf-8'?>
<resources> <resources>
<string name="app_name">Qoutelink</string> <string name="app_name">ShopKeep</string>
<string name="title_activity_main">Qoutelink</string> <string name="title_activity_main">ShopKeep</string>
<string name="package_name">io.ionic.starter</string> <string name="package_name">io.ionic.starter</string>
<string name="custom_url_scheme">io.ionic.starter</string> <string name="custom_url_scheme">io.ionic.starter</string>
</resources> </resources>
+2 -4
View File
@@ -16,9 +16,7 @@
</style> </style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"> <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/splashBackground</item> <item name="android:background">@drawable/splash</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/splash_logo</item>
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
</style> </style>
</resources> </resources>
+2 -2
View File
@@ -1,8 +1,8 @@
import type { CapacitorConfig } from '@capacitor/cli'; import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = { const config: CapacitorConfig = {
appId: 'com.qoutelink.app', appId: 'io.shopkeep.app',
appName: 'Qoutelink', appName: 'ShopKeep',
webDir: 'dist', webDir: 'dist',
plugins: { plugins: {
FirebaseAuthentication: { FirebaseAuthentication: {
+4 -4
View File
@@ -299,7 +299,7 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements; CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3; CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = App/Info.plist; INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0; IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = ( LD_RUNPATH_SEARCH_PATHS = (
@@ -308,7 +308,7 @@
); );
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0;
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\""; OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
PRODUCT_BUNDLE_IDENTIFIER = com.qoutelink.app; PRODUCT_BUNDLE_IDENTIFIER = io.shopkeep.app;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
@@ -322,7 +322,7 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements; CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3; CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = App/Info.plist; INFOPLIST_FILE = App/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0; IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = ( LD_RUNPATH_SEARCH_PATHS = (
@@ -330,7 +330,7 @@
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.qoutelink.app; PRODUCT_BUNDLE_IDENTIFIER = io.shopkeep.app;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = ""; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
@@ -1,122 +1,14 @@
{ {
"images": [ "images" : [
{ {
"idiom": "iphone", "filename" : "AppIcon-512@2x.png",
"scale": "1x", "idiom" : "universal",
"size": "20x20", "platform" : "ios",
"filename": "icon-20.png" "size" : "1024x1024"
},
{
"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"
} }
], ],
"info": { "info" : {
"author": "appsuite", "author" : "xcode",
"version": 1 "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

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

Before

Width:  |  Height:  |  Size: 480 KiB

+3 -7
View File
@@ -7,7 +7,7 @@
<key>CFBundleDevelopmentRegion</key> <key>CFBundleDevelopmentRegion</key>
<string>en</string> <string>en</string>
<key>CFBundleDisplayName</key> <key>CFBundleDisplayName</key>
<string>Qoutelink</string> <string>ShopKeep</string>
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string> <string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>
@@ -47,18 +47,14 @@
</array> </array>
<key>UIViewControllerBasedStatusBarAppearance</key> <key>UIViewControllerBasedStatusBarAppearance</key>
<true/> <true/>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library so you can attach site photos and references to your requests.</string>
<key>NSCameraUsageDescription</key>
<string>We need access to your camera so you can take site photos for your requests.</string>
<key>CFBundleURLTypes</key> <key>CFBundleURLTypes</key>
<array> <array>
<dict> <dict>
<key>CFBundleURLName</key> <key>CFBundleURLName</key>
<string>com.qoutelink.app</string> <string>io.shopkeep.app</string>
<key>CFBundleURLSchemes</key> <key>CFBundleURLSchemes</key>
<array> <array>
<string>com.qoutelink.app</string> <string>io.shopkeep.app</string>
</array> </array>
</dict> </dict>
</array> </array>
+1 -2
View File
@@ -18,14 +18,13 @@
"@capacitor/haptics": "8.0.2", "@capacitor/haptics": "8.0.2",
"@capacitor/ios": "8.3.4", "@capacitor/ios": "8.3.4",
"@capacitor/keyboard": "8.0.3", "@capacitor/keyboard": "8.0.3",
"@capacitor/preferences": "^8.0.1",
"@capacitor/push-notifications": "^8.1.1", "@capacitor/push-notifications": "^8.1.1",
"@capacitor/status-bar": "8.0.2", "@capacitor/status-bar": "8.0.2",
"@hookform/resolvers": "^3.9.0", "@hookform/resolvers": "^3.9.0",
"@ionic/pwa-elements": "^3.0.0", "@ionic/pwa-elements": "^3.0.0",
"@ionic/react": "8.8.7", "@ionic/react": "8.8.7",
"@ionic/react-router": "8.8.7", "@ionic/react-router": "8.8.7",
"@supabase/supabase-js": "^2.108.1", "@supabase/supabase-js": "^2.0.0",
"firebase": "^11.0.0", "firebase": "^11.0.0",
"ionicons": "^7.4.0", "ionicons": "^7.4.0",
"katex": "^0.16.0", "katex": "^0.16.0",
+119 -20
View File
@@ -1,10 +1,39 @@
import React, { useEffect } from 'react'; import React, { useEffect } from 'react';
import { IonApp } from '@ionic/react'; import { Redirect, Route } from 'react-router-dom';
import {
IonApp,
IonRouterOutlet,
IonTabs,
IonTabBar,
IonTabButton,
IonIcon,
IonLabel,
setupIonicReact,
} from '@ionic/react';
import { IonReactRouter } from '@ionic/react-router'; import { IonReactRouter } from '@ionic/react-router';
import {
homeOutline,
peopleOutline,
receiptOutline,
home,
people,
receipt,
} from 'ionicons/icons';
import Home from './pages/Home';
import CustomersPage from './pages/CustomersPage';
import CustomerDetailPage from './pages/CustomerDetailPage';
import HistoryPage from './pages/HistoryPage';
import SaleFormPage from './pages/SaleFormPage';
import CreditFormPage from './pages/CreditFormPage';
import RepaymentFormPage from './pages/RepaymentFormPage';
import AuthPage from './pages/AuthPage';
import VerifyEmailPage from './pages/VerifyEmailPage';
import ForgotPasswordPage from './pages/ForgotPasswordPage';
import NewPasswordPage from './pages/NewPasswordPage';
import { AuthProvider } from './contexts/AuthContext'; import { AuthProvider } from './contexts/AuthContext';
import { ProfileProvider, useProfile } from './contexts/ProfileContext'; import ProtectedRoute from './components/ProtectedRoute';
import AppRoutes from './AppRoutes';
import { setStatusBarStyle, Style } from './utils/statusBar'; import { setStatusBarStyle, Style } from './utils/statusBar';
/* Core CSS required for Ionic components to work properly */ /* Core CSS required for Ionic components to work properly */
@@ -23,31 +52,101 @@ import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css'; import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css'; import '@ionic/react/css/display.css';
/**
* Ionic Dark Mode
* -----------------------------------------------------
* For more info, please see:
* https://ionicframework.com/docs/theming/dark-mode
*/
/* import '@ionic/react/css/palettes/dark.always.css'; */
/* import '@ionic/react/css/palettes/dark.class.css'; */
import '@ionic/react/css/palettes/dark.system.css';
/* Theme variables */ /* Theme variables */
import './theme/variables.css'; import './theme/variables.css';
const AppShell: React.FC = () => { setupIonicReact();
const { themeMode } = useProfile();
useEffect(() => {
document.body.classList.toggle('dark', themeMode === 'dark');
setStatusBarStyle(themeMode === 'dark' ? Style.Dark : Style.Light);
}, [themeMode]);
return (
<IonReactRouter>
<AppRoutes />
</IonReactRouter>
);
};
const App: React.FC = () => { const App: React.FC = () => {
useEffect(() => {
// Set status bar to light icons on our dark-ish backgrounds
setStatusBarStyle(Style.Dark);
}, []);
return ( return (
<IonApp> <IonApp>
<AuthProvider> <AuthProvider>
<ProfileProvider> <IonReactRouter>
<AppShell /> <IonRouterOutlet>
</ProfileProvider> {/* Auth Routes */}
<Route path="/auth" component={AuthPage} exact />
<Route path="/verify-email" component={VerifyEmailPage} exact />
<Route
path="/forgot-password"
component={ForgotPasswordPage}
exact
/>
<Route path="/new-password" component={NewPasswordPage} exact />
{/* Protected Form & Detail Routes (Outer Outlet for push/pop animation) */}
<ProtectedRoute path="/sale/new" component={SaleFormPage} exact />
<ProtectedRoute
path="/credit/new"
component={CreditFormPage}
exact
/>
<ProtectedRoute
path="/repayment/new"
component={RepaymentFormPage}
exact
/>
<ProtectedRoute
path="/customers/:id([0-9a-fA-F-]{36})"
component={CustomerDetailPage}
exact
/>
{/* Tab Shell */}
<Route
path={['/home', '/customers', '/history']}
render={() => (
<IonTabs>
<IonRouterOutlet>
<ProtectedRoute path="/home" component={Home} exact />
<ProtectedRoute
path="/customers"
component={CustomersPage}
exact
/>
<ProtectedRoute
path="/history"
component={HistoryPage}
exact
/>
</IonRouterOutlet>
<IonTabBar slot="bottom">
<IonTabButton tab="home" href="/home">
<IonIcon icon={homeOutline} />
<IonLabel>Home</IonLabel>
</IonTabButton>
<IonTabButton tab="customers" href="/customers">
<IonIcon icon={peopleOutline} />
<IonLabel>Customers</IonLabel>
</IonTabButton>
<IonTabButton tab="history" href="/history">
<IonIcon icon={receiptOutline} />
<IonLabel>History</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
)}
/>
{/* Root Redirect */}
<Route exact path="/" render={() => <Redirect to="/home" />} />
</IonRouterOutlet>
</IonReactRouter>
</AuthProvider> </AuthProvider>
</IonApp> </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;
+130
View File
@@ -0,0 +1,130 @@
import React from 'react';
import { IonIcon, IonItem, IonLabel, IonNote } from '@ionic/react';
import {
receiptOutline,
personAddOutline,
cashOutline,
chevronForwardOutline,
} from 'ionicons/icons';
import { formatMoney } from '../utils/money';
import { useAuth } from '../contexts/AuthContext';
import { formatDisplayDate } from '../utils/dates';
export type ActivityType = 'sale' | 'credit' | 'repayment';
export interface ActivityItem {
id: string;
type: ActivityType;
amount: number;
date: string;
customerName?: string;
note?: string;
customerId?: string;
}
interface ActivityRowProps {
item: ActivityItem;
onClick?: () => void;
showDate?: boolean;
}
const ActivityRow: React.FC<ActivityRowProps> = ({
item,
onClick,
showDate = false,
}) => {
const { profile } = useAuth();
const currency = profile?.currency || 'USD';
const getIcon = () => {
switch (item.type) {
case 'sale':
return receiptOutline;
case 'credit':
return personAddOutline;
case 'repayment':
return cashOutline;
}
};
const getTitle = () => {
switch (item.type) {
case 'sale':
return 'Cash Sale';
case 'credit':
return `Credit: ${item.customerName || 'Customer'}`;
case 'repayment':
return `Repayment: ${item.customerName || 'Customer'}`;
}
};
const getAmountColor = () => {
switch (item.type) {
case 'sale':
return 'var(--color-text-primary)';
case 'credit':
return 'var(--ion-color-primary)';
case 'repayment':
return 'var(--ion-color-success)';
}
};
return (
<IonItem
lines="none"
onClick={onClick}
detail={false}
style={{
'--background': 'transparent',
'--padding-start': '0',
'--padding-end': '0',
'--inner-padding-end': '0',
cursor: onClick ? 'pointer' : 'default',
}}
>
<div
className="icon-container"
slot="start"
style={{ marginRight: '12px' }}
>
<IonIcon icon={getIcon()} />
</div>
<IonLabel>
<h3 className="semibold" style={{ margin: '0', fontSize: '15px' }}>
{getTitle()}
</h3>
<p className="secondary-text" style={{ margin: '2px 0 0 0' }}>
{showDate ? formatDisplayDate(item.date) : item.note || 'No notes'}
</p>
</IonLabel>
<div
slot="end"
style={{ textAlign: 'right', display: 'flex', alignItems: 'center' }}
>
<IonNote
className="tabular"
style={{
fontSize: '15px',
color: getAmountColor(),
fontWeight: '400',
}}
>
{item.type === 'credit' ? '-' : '+'}
{formatMoney(item.amount, currency)}
</IonNote>
{onClick && (
<IonIcon
icon={chevronForwardOutline}
style={{
fontSize: '14px',
marginLeft: '8px',
color: 'var(--color-text-tertiary)',
}}
/>
)}
</div>
</IonItem>
);
};
export default ActivityRow;
+115
View File
@@ -0,0 +1,115 @@
import React from 'react';
import { IonIcon, IonItem, IonLabel, IonNote } from '@ionic/react';
import { chevronForwardOutline } from 'ionicons/icons';
import { formatMoney } from '../utils/money';
import { useAuth } from '../contexts/AuthContext';
interface CustomerRowProps {
id: string;
name: string;
balance: number;
phone?: string;
onClick: () => void;
}
const CustomerRow: React.FC<CustomerRowProps> = ({
id,
name,
balance,
phone,
onClick,
}) => {
const { profile } = useAuth();
const currency = profile?.currency || 'USD';
const getInitials = (name: string) => {
return name
.split(' ')
.map((n) => n[0])
.join('')
.toUpperCase()
.slice(0, 2);
};
return (
<IonItem
lines="none"
onClick={onClick}
detail={false}
style={{
'--background': 'transparent',
'--padding-start': '0',
'--padding-end': '0',
'--inner-padding-end': '0',
cursor: 'pointer',
marginBottom: '8px',
}}
>
<div
className="icon-container bold"
slot="start"
style={{
marginRight: '16px',
width: '44px',
height: '44px',
fontSize: '14px',
color: 'var(--ion-color-primary)',
}}
>
{getInitials(name)}
</div>
<IonLabel>
<h3 className="semibold" style={{ margin: '0', fontSize: '16px' }}>
{name}
</h3>
{phone && (
<p className="secondary-text" style={{ margin: '2px 0 0 0' }}>
{phone}
</p>
)}
</IonLabel>
<div
slot="end"
style={{ textAlign: 'right', display: 'flex', alignItems: 'center' }}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-end',
}}
>
<IonNote
className="tabular"
style={{
fontSize: '16px',
color:
balance > 0
? 'var(--ion-color-danger)'
: 'var(--ion-color-success)',
fontWeight: '400',
}}
>
{formatMoney(balance, currency)}
</IonNote>
<span
className="tertiary-text"
style={{ fontSize: '10px', marginTop: '2px' }}
>
{balance > 0 ? 'OUTSTANDING' : 'CLEARED'}
</span>
</div>
<IonIcon
icon={chevronForwardOutline}
style={{
fontSize: '16px',
marginLeft: '12px',
color: 'var(--color-text-tertiary)',
}}
/>
</div>
</IonItem>
);
};
export default CustomerRow;
-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;
+79
View File
@@ -0,0 +1,79 @@
import React from 'react';
import { IonIcon, IonButton } from '@ionic/react';
interface EmptyStateProps {
icon: string;
title: string;
description?: string;
actionText?: string;
onAction?: () => void;
}
const EmptyState: React.FC<EmptyStateProps> = ({
icon,
title,
description,
actionText,
onAction,
}) => {
return (
<div
className="widget-card"
style={{
padding: '40px 20px',
alignItems: 'center',
textAlign: 'center',
justifyContent: 'center',
}}
>
<div
className="icon-container"
style={{
width: '64px',
height: '64px',
borderRadius: '20px',
marginBottom: '20px',
background: 'var(--color-surface-secondary)',
color: 'var(--color-text-tertiary)',
}}
>
<IonIcon icon={icon} style={{ fontSize: '32px' }} />
</div>
<h3
style={{
margin: '0 0 8px 0',
fontSize: '18px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{title}
</h3>
{description && (
<p
className="secondary-text"
style={{ margin: '0 0 24px 0', maxWidth: '240px' }}
>
{description}
</p>
)}
{actionText && onAction && (
<IonButton
onClick={onAction}
shape="round"
fill="solid"
style={{
height: '44px',
'--border-radius': '999px',
fontSize: '14px',
fontWeight: '700',
}}
>
{actionText}
</IonButton>
)}
</div>
);
};
export default EmptyState;
+99
View File
@@ -0,0 +1,99 @@
import React from 'react';
import { IonIcon } from '@ionic/react';
import { formatMoney } from '../utils/money';
import { useAuth } from '../contexts/AuthContext';
interface MetricCardProps {
label: string;
value: number;
icon?: string;
subtitle?: string;
fullWidth?: boolean;
loading?: boolean;
}
const MetricCard: React.FC<MetricCardProps> = ({
label,
value,
icon,
subtitle,
fullWidth = false,
loading = false,
}) => {
const { profile } = useAuth();
const currency = profile?.currency || 'USD';
if (loading) {
return (
<div
className="widget-card"
style={{
width: fullWidth ? '100%' : 'auto',
minHeight: fullWidth ? '160px' : '100px',
}}
>
<div
className="skeleton-text"
style={{
width: '40%',
height: '12px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
marginBottom: '12px',
}}
/>
<div
className="skeleton-text"
style={{
width: '70%',
height: '32px',
background: 'var(--color-surface-secondary)',
borderRadius: '8px',
}}
/>
</div>
);
}
return (
<div
className="widget-card"
style={{
width: fullWidth ? '100%' : 'auto',
minHeight: fullWidth ? '160px' : '100px',
justifyContent: 'center',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
}}
>
<div>
<span className="tertiary-text">{label}</span>
<div
className="tabular"
style={{
fontSize: fullWidth ? '34px' : '24px',
fontWeight: '400',
color: 'var(--color-text-primary)',
marginTop: '4px',
}}
>
{formatMoney(value, currency)}
</div>
{subtitle && <div className="secondary-text">{subtitle}</div>}
</div>
{icon && (
<div className="icon-container">
<IonIcon icon={icon} />
</div>
)}
</div>
</div>
);
};
export default MetricCard;
+88
View File
@@ -0,0 +1,88 @@
import React from 'react';
import { IonInput, IonLabel } from '@ionic/react';
import { sanitizeMoneyInput, getCurrencySymbol } from '../utils/money';
import { useAuth } from '../contexts/AuthContext';
interface MoneyInputProps {
value: string;
onValueChange: (value: string) => void;
label?: string;
placeholder?: string;
error?: string;
}
const MoneyInput: React.FC<MoneyInputProps> = ({
value,
onValueChange,
label,
placeholder = '0.00',
error,
}) => {
const { profile } = useAuth();
const symbol = getCurrencySymbol(profile?.currency || 'USD');
const handleChange = (e: CustomEvent) => {
const rawValue = e.detail.value || '';
const sanitized = sanitizeMoneyInput(rawValue);
onValueChange(sanitized);
};
return (
<div className="money-input-container">
{label && (
<IonLabel
position="stacked"
className="semibold"
style={{ marginBottom: '8px', display: 'block', fontSize: '13px' }}
>
{label}
</IonLabel>
)}
<div
className="input-wrapper"
style={{
border: error ? '1px solid var(--ion-color-danger)' : 'none',
}}
>
<span
className="bold"
style={{
marginRight: '8px',
color: 'var(--color-text-primary)',
fontSize: '18px',
}}
>
{symbol}
</span>
<IonInput
type="text"
inputMode="decimal"
value={value}
placeholder={placeholder}
onIonChange={handleChange}
style={{
fontSize: '20px',
fontWeight: '700',
'--padding-top': '0',
'--padding-bottom': '0',
}}
className="tabular"
/>
</div>
{error && (
<IonLabel
color="danger"
style={{
fontSize: '12px',
marginTop: '4px',
display: 'block',
}}
>
{error}
</IonLabel>
)}
</div>
);
};
export default MoneyInput;
-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;
-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;
+5 -35
View File
@@ -1,9 +1,6 @@
import React, { useEffect } from 'react'; import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom'; import { Route, Redirect, RouteProps } from 'react-router-dom';
import { IonSpinner } from '@ionic/react';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { useProfileLoader } from '../hooks/useProfileLoader';
interface ProtectedRouteProps extends RouteProps { interface ProtectedRouteProps extends RouteProps {
component: React.ComponentType<any>; component: React.ComponentType<any>;
@@ -13,42 +10,15 @@ const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
component: Component, component: Component,
...rest ...rest
}) => { }) => {
const { user } = useAuth(); const { user, loading } = useAuth();
const { status } = useProfile();
const { loadProfileAndNavigate } = useProfileLoader();
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]);
return ( return (
<Route <Route
{...rest} {...rest}
render={(props) => { render={(props) => {
if (!user) { if (loading) return null; // AuthProvider already handles spinner, but double safety
return <Redirect to="/auth" />;
} return user ? <Component {...props} /> : <Redirect to="/auth" />;
if (status === 'loading') {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
}}
>
<IonSpinner name="crescent" />
</div>
);
}
if (status === 'missing') {
return <Redirect to="/setup-profile" />;
}
return <Component {...props} />;
}} }}
/> />
); );
-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;
-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;
-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;
+141 -23
View File
@@ -1,51 +1,169 @@
import React, { createContext, useContext, useEffect, useState } from 'react'; import React, {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import { User } from '@supabase/supabase-js'; import { User } from '@supabase/supabase-js';
import { supabase } from '../supabase'; import { supabase } from '../supabase';
import { Database } from '../database.types';
import { IonSpinner } from '@ionic/react';
type Profile = Database['public']['Tables']['profiles']['Row'];
interface AuthContextType { interface AuthContextType {
user: User | null; user: User | null;
signOut: () => Promise<void>; profile: Profile | null;
loading: boolean;
refreshProfile: () => Promise<void>;
} }
const AuthContext = createContext<AuthContextType>({ const AuthContext = createContext<AuthContextType | undefined>(undefined);
user: null,
signOut: async () => {},
});
export const useAuth = () => useContext(AuthContext);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children, children,
}) => { }) => {
const [user, setUser] = useState<User | null>(null); const [user, setUser] = useState<User | null>(null);
const [initializing, setInitializing] = useState(true); const [profile, setProfile] = useState<Profile | null>(null);
const [loading, setLoading] = useState(true);
const fetchProfile = useCallback(async (currentUser: User) => {
try {
const fallbackProfile = {
id: currentUser.id,
full_name:
typeof currentUser.user_metadata?.full_name === 'string'
? currentUser.user_metadata.full_name
: '',
shop_name: 'My Shop',
currency: 'USD',
};
const { data, error } = await supabase
.from('profiles')
.upsert(fallbackProfile, { onConflict: 'id', ignoreDuplicates: true })
.select('*')
.single();
if (error) {
console.error('Error fetching profile:', error);
setProfile({
...fallbackProfile,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
});
return;
}
setProfile(data);
} catch (err) {
console.error('Error fetching profile:', err);
setProfile(null);
}
}, []);
const refreshProfile = async () => {
if (user) {
await fetchProfile(user);
}
};
useEffect(() => { useEffect(() => {
supabase.auth.getSession().then(({ data }) => { let mounted = true;
setUser(data.session?.user ?? null);
setInitializing(false); const initialiseSession = async () => {
}); const timeout = window.setTimeout(() => {
if (mounted) {
console.warn('Auth initialisation timed out; showing app shell.');
setLoading(false);
}
}, 8000);
try {
const {
data: { session },
error,
} = await supabase.auth.getSession();
if (!mounted) return;
if (error) {
console.error('Error restoring auth session:', error);
}
const currentUser = session?.user ?? null;
setUser(currentUser);
if (currentUser) {
await fetchProfile(currentUser);
} else {
setProfile(null);
}
} catch (err) {
console.error('Error restoring auth session:', err);
if (mounted) {
setUser(null);
setProfile(null);
}
} finally {
window.clearTimeout(timeout);
if (mounted) {
setLoading(false);
}
}
};
void initialiseSession();
const { const {
data: { subscription }, data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => { } = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user ?? null); const currentUser = session?.user ?? null;
setUser(currentUser);
if (currentUser) {
void fetchProfile(currentUser);
} else {
setProfile(null);
}
setLoading(false);
}); });
return () => subscription.unsubscribe(); return () => {
}, []); mounted = false;
subscription.unsubscribe();
};
}, [fetchProfile]);
const signOut = async () => { if (loading) {
await supabase.auth.signOut(); return (
}; <div
style={{
if (initializing) { display: 'flex',
return null; // Or a simple spinner if preferred, but usually handled nicely alignItems: 'center',
justifyContent: 'center',
height: '100vh',
background: 'var(--color-bg, #f0f4ff)',
}}
>
<IonSpinner name="crescent" color="primary" />
</div>
);
} }
return ( return (
<AuthContext.Provider value={{ user, signOut }}> <AuthContext.Provider value={{ user, profile, loading, refreshProfile }}>
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>
); );
}; };
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
-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>
);
};
+110 -140
View File
@@ -14,204 +14,174 @@ export type Database = {
} }
public: { public: {
Tables: { Tables: {
credit_customers: {
Row: {
created_at: string
id: string
name: string
notes: string | null
phone: string | null
updated_at: string
user_id: string
}
Insert: {
created_at?: string
id?: string
name: string
notes?: string | null
phone?: string | null
updated_at?: string
user_id: string
}
Update: {
created_at?: string
id?: string
name?: string
notes?: string | null
phone?: string | null
updated_at?: string
user_id?: string
}
Relationships: []
}
credits: {
Row: {
amount: number
created_at: string
credit_date: string
customer_id: string
description: string | null
id: string
updated_at: string
user_id: string
}
Insert: {
amount: number
created_at?: string
credit_date?: string
customer_id: string
description?: string | null
id?: string
updated_at?: string
user_id: string
}
Update: {
amount?: number
created_at?: string
credit_date?: string
customer_id?: string
description?: string | null
id?: string
updated_at?: string
user_id?: string
}
Relationships: [
{
foreignKeyName: "credits_customer_id_fkey"
columns: ["customer_id"]
isOneToOne: false
referencedRelation: "credit_customers"
referencedColumns: ["id"]
},
]
}
profiles: { profiles: {
Row: { Row: {
avatar_url: string | null
city: string | null
company_name: string | null
created_at: string created_at: string
full_name: string currency: string
full_name: string | null
id: string id: string
phone: string | null shop_name: string | null
role: string
updated_at: string updated_at: string
} }
Insert: { Insert: {
avatar_url?: string | null
city?: string | null
company_name?: string | null
created_at?: string created_at?: string
full_name: string currency?: string
full_name?: string | null
id: string id: string
phone?: string | null shop_name?: string | null
role: string
updated_at?: string updated_at?: string
} }
Update: { Update: {
avatar_url?: string | null
city?: string | null
company_name?: string | null
created_at?: string created_at?: string
full_name?: string currency?: string
full_name?: string | null
id?: string id?: string
phone?: string | null shop_name?: string | null
role?: string
updated_at?: string updated_at?: string
} }
Relationships: [] Relationships: []
} }
quotations: { repayments: {
Row: { Row: {
amount: number
created_at: string created_at: string
currency_code: string customer_id: string
delivery_option: string
id: string id: string
note: string | null note: string | null
price_amount: number repayment_date: string
rfq_id: string
status: string
supplier_id: string
updated_at: string updated_at: string
user_id: string
} }
Insert: { Insert: {
amount: number
created_at?: string created_at?: string
currency_code?: string customer_id: string
delivery_option: string
id?: string id?: string
note?: string | null note?: string | null
price_amount: number repayment_date?: string
rfq_id: string
status?: string
supplier_id: string
updated_at?: string updated_at?: string
user_id: string
} }
Update: { Update: {
amount?: number
created_at?: string created_at?: string
currency_code?: string customer_id?: string
delivery_option?: string
id?: string id?: string
note?: string | null note?: string | null
price_amount?: number repayment_date?: string
rfq_id?: string
status?: string
supplier_id?: string
updated_at?: string updated_at?: string
user_id?: string
} }
Relationships: [ Relationships: [
{ {
foreignKeyName: "quotations_rfq_id_fkey" foreignKeyName: "repayments_customer_id_fkey"
columns: ["rfq_id"] columns: ["customer_id"]
isOneToOne: false isOneToOne: false
referencedRelation: "rfqs" referencedRelation: "credit_customers"
referencedColumns: ["id"]
},
{
foreignKeyName: "quotations_supplier_id_fkey"
columns: ["supplier_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"] referencedColumns: ["id"]
}, },
] ]
} }
rfq_images: { sales: {
Row: { Row: {
amount: number
created_at: string created_at: string
id: string id: string
owner_id: string note: string | null
rfq_id: string sale_date: 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
status: string
title: string
updated_at: string updated_at: string
user_id: string
} }
Insert: { Insert: {
buyer_id: string amount: number
created_at?: string created_at?: string
id?: string id?: string
reference_number: string note?: string | null
request_text: string sale_date?: string
status?: string
title: string
updated_at?: string updated_at?: string
user_id: string
} }
Update: { Update: {
buyer_id?: string amount?: number
created_at?: string created_at?: string
id?: string id?: string
reference_number?: string note?: string | null
request_text?: string sale_date?: string
status?: string
title?: string
updated_at?: string updated_at?: string
user_id?: string
} }
Relationships: [ Relationships: []
{
foreignKeyName: "rfqs_buyer_id_fkey"
columns: ["buyer_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
]
} }
} }
Views: { Views: {
-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 };
};
-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;
+233
View File
@@ -0,0 +1,233 @@
import React, { useState } from 'react';
import {
IonContent,
IonPage,
IonInput,
IonButton,
IonSpinner,
IonIcon,
IonText,
} from '@ionic/react';
import { storefrontOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
const AuthPage: React.FC = () => {
const [mode, setMode] = useState<'signin' | 'signup'>('signin');
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [messageType, setMessageType] = useState<'error' | 'success'>('error');
const history = useHistory();
const showMessage = (msg: string, type: 'error' | 'success' = 'error') => {
setMessage(msg);
setMessageType(type);
setTimeout(() => setMessage(null), 4000);
};
const handleAuth = async (e: React.FormEvent) => {
e.preventDefault();
if (!email || !password || (mode === 'signup' && !name)) {
showMessage('Please fill in all fields');
return;
}
setSubmitting(true);
setMessage(null);
try {
if (mode === 'signup') {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
full_name: name,
},
},
});
if (error) throw error;
if (data.session) {
history.push('/home');
} else {
history.push('/verify-email', { email });
}
} else {
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
if (error.message.toLowerCase().includes('email not confirmed')) {
await supabase.auth.resend({ type: 'signup', email });
history.push('/verify-email', { email, resent: true });
return;
}
throw error;
}
if (data.session) {
history.push('/home');
}
}
} catch (err: any) {
showMessage(err.message || 'An authentication error occurred');
} finally {
setSubmitting(false);
}
};
return (
<IonPage>
<IonContent
fullscreen
style={{
'--background':
'linear-gradient(160deg, rgba(199,210,254,0.52) 0%, #f0f4ff 58%, #f8fafc 100%)',
}}
>
<div className="auth-shell">
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
marginTop: '20px',
}}
>
<div
className="icon-container"
style={{ width: '44px', height: '44px' }}
>
<IonIcon icon={storefrontOutline} style={{ fontSize: '22px' }} />
</div>
<div>
<h1 className="bold" style={{ margin: '0', fontSize: '22px' }}>
ShopKeep
</h1>
<p className="secondary-text" style={{ margin: '0' }}>
Simple bookkeeping for you
</p>
</div>
</div>
<div className="auth-card">
<div className="pill-toggle">
<button
className={`pill-toggle-btn ${mode === 'signin' ? 'active' : ''}`}
onClick={() => setMode('signin')}
>
Sign in
</button>
<button
className={`pill-toggle-btn ${mode === 'signup' ? 'active' : ''}`}
onClick={() => setMode('signup')}
>
Create account
</button>
</div>
<form
onSubmit={handleAuth}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
{mode === 'signup' && (
<div className="input-wrapper">
<IonInput
label="Full Name"
labelPlacement="floating"
placeholder="Enter your name"
value={name}
onIonChange={(e) => setName(e.detail.value!)}
/>
</div>
)}
<div className="input-wrapper">
<IonInput
label="Email"
labelPlacement="floating"
type="email"
placeholder="name@example.com"
value={email}
onIonChange={(e) => setEmail(e.detail.value!)}
/>
</div>
<div className="input-wrapper">
<IonInput
label="Password"
labelPlacement="floating"
type="password"
placeholder="Min. 6 characters"
value={password}
onIonChange={(e) => setPassword(e.detail.value!)}
/>
</div>
{message && (
<div
style={{
background:
messageType === 'error'
? 'var(--color-danger-soft)'
: 'var(--color-success-soft)',
color:
messageType === 'error'
? 'var(--ion-color-danger-shade)'
: 'var(--ion-color-success-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
}}
>
{message}
</div>
)}
<IonButton
type="submit"
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '8px',
}}
disabled={submitting}
>
{submitting ? (
<IonSpinner name="crescent" />
) : mode === 'signin' ? (
'Sign in'
) : (
'Create account'
)}
</IonButton>
</form>
<div style={{ textAlign: 'center', marginTop: '8px' }}>
<IonText
color="primary"
className="semibold"
style={{ fontSize: '13px', cursor: 'pointer' }}
onClick={() => history.push('/forgot-password')}
>
Forgot password?
</IonText>
</div>
</div>
</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;
+359
View File
@@ -0,0 +1,359 @@
import React, { useState, useEffect } from 'react';
import {
IonContent,
IonPage,
IonHeader,
IonToolbar,
IonTitle,
IonButtons,
IonButton,
IonIcon,
IonInput,
IonTextarea,
IonSpinner,
IonLabel,
IonSelect,
IonSelectOption,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory, useLocation } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { getTodayISO } from '../utils/dates';
import MoneyInput from '../components/MoneyInput';
import { parseMoney } from '../utils/money';
interface Customer {
id: string;
name: string;
}
const CreditFormPage: React.FC = () => {
const history = useHistory();
const location = useLocation<{ customerId?: string }>();
const { user } = useAuth();
const [mode, setMode] = useState<'existing' | 'new'>('existing');
const [customers, setCustomers] = useState<Customer[]>([]);
const [selectedCustomerId, setSelectedCustomerId] = useState<string>(
location.state?.customerId || ''
);
const [newName, setNewName] = useState('');
const [phone, setPhone] = useState('');
const [amount, setAmount] = useState('');
const [creditDate, setCreditDate] = useState(getTodayISO());
const [description, setDescription] = useState('');
const [submitting, setSubmitting] = useState(false);
const [loadingCustomers, setLoadingCustomers] = useState(true);
const [errors, setErrors] = useState<Record<string, string>>({});
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
const fetchCustomers = async () => {
if (!user) return;
try {
const { data, error } = await supabase
.from('credit_customers')
.select('id, name')
.eq('user_id', user.id)
.order('name');
if (error) throw error;
setCustomers(data || []);
if (!data || data.length === 0) {
setMode('new');
}
} catch (err) {
console.error('Error fetching customers:', err);
} finally {
setLoadingCustomers(false);
}
};
fetchCustomers();
}, [user]);
const validate = () => {
const newErrors: Record<string, string> = {};
const parsedAmount = parseMoney(amount);
if (mode === 'existing' && !selectedCustomerId) {
newErrors.customer = 'Please select a customer';
}
if (mode === 'new' && !newName.trim()) {
newErrors.name = 'Customer name is required';
}
if (parsedAmount <= 0) {
newErrors.amount = 'Amount must be greater than 0';
}
if (!creditDate) {
newErrors.date = 'Date is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSave = async () => {
if (!validate() || !user) return;
setSubmitting(true);
setMessage(null);
try {
let customerId = selectedCustomerId;
if (mode === 'new') {
const { data: newCustomer, error: customerError } = await supabase
.from('credit_customers')
.insert([
{
user_id: user.id,
name: newName.trim(),
phone: phone.trim() || null,
},
])
.select()
.single();
if (customerError) throw customerError;
customerId = newCustomer.id;
}
const { error: creditError } = await supabase.from('credits').insert([
{
user_id: user.id,
customer_id: customerId,
amount: parseMoney(amount),
credit_date: creditDate,
description: description.trim() || null,
},
]);
if (creditError) throw creditError;
history.goBack();
} catch (err: any) {
console.error('Error saving credit:', err);
setMessage(err.message || 'Could not save credit');
setTimeout(() => setMessage(null), 4000);
} finally {
setSubmitting(false);
}
};
return (
<IonPage>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f0f4ff' }}>
<IonButtons slot="start">
<IonButton color="dark" onClick={() => history.goBack()}>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle className="bold">Add credit</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding" style={{ '--background': '#f0f4ff' }}>
<div className="form-card">
<div className="pill-toggle" style={{ marginBottom: '8px' }}>
<button
className={`pill-toggle-btn ${mode === 'existing' ? 'active' : ''}`}
onClick={() => setMode('existing')}
disabled={customers.length === 0}
>
Existing Customer
</button>
<button
className={`pill-toggle-btn ${mode === 'new' ? 'active' : ''}`}
onClick={() => setMode('new')}
>
New Customer
</button>
</div>
{mode === 'existing' ? (
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Select Customer
</IonLabel>
<div className="input-wrapper">
<IonSelect
interface="action-sheet"
placeholder="Choose a customer"
value={selectedCustomerId}
onIonChange={(e) => setSelectedCustomerId(e.detail.value)}
style={{ width: '100%' }}
>
{customers.map((c) => (
<IonSelectOption key={c.id} value={c.id}>
{c.name}
</IonSelectOption>
))}
</IonSelect>
</div>
{errors.customer && (
<IonLabel
color="danger"
style={{ fontSize: '12px', marginTop: '4px' }}
>
{errors.customer}
</IonLabel>
)}
</div>
) : (
<>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Customer Name
</IonLabel>
<div className="input-wrapper">
<IonInput
placeholder="e.g. John Doe"
value={newName}
onIonChange={(e) => setNewName(e.detail.value!)}
/>
</div>
{errors.name && (
<IonLabel
color="danger"
style={{ fontSize: '12px', marginTop: '4px' }}
>
{errors.name}
</IonLabel>
)}
</div>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Phone (optional)
</IonLabel>
<div className="input-wrapper">
<IonInput
type="tel"
placeholder="e.g. +1 234 567 890"
value={phone}
onIonChange={(e) => setPhone(e.detail.value!)}
/>
</div>
</div>
</>
)}
<MoneyInput
label="Credit amount"
value={amount}
onValueChange={(val) => {
setAmount(val);
if (errors.amount) setErrors({ ...errors, amount: '' });
}}
error={errors.amount}
/>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Credit date
</IonLabel>
<div className="input-wrapper">
<IonInput
type="date"
value={creditDate}
onIonChange={(e) => setCreditDate(e.detail.value!)}
/>
</div>
{errors.date && (
<IonLabel
color="danger"
style={{ fontSize: '12px', marginTop: '4px' }}
>
{errors.date}
</IonLabel>
)}
</div>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Description (optional)
</IonLabel>
<div
className="input-wrapper"
style={{ minHeight: '96px', padding: '8px 16px' }}
>
<IonTextarea
placeholder="e.g. 2 bags of rice, sugar"
value={description}
onIonChange={(e) => setDescription(e.detail.value!)}
rows={4}
/>
</div>
</div>
{message && (
<div
style={{
background: 'var(--color-danger-soft)',
color: 'var(--ion-color-danger-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
}}
>
{message}
</div>
)}
<IonButton
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '16px',
}}
disabled={submitting || (loadingCustomers && mode === 'existing')}
onClick={handleSave}
>
{submitting ? <IonSpinner name="crescent" /> : 'Save credit'}
</IonButton>
</div>
</IonContent>
</IonPage>
);
};
export default CreditFormPage;
+361
View File
@@ -0,0 +1,361 @@
import React, { useState, useCallback, useMemo } from 'react';
import {
IonContent,
IonPage,
IonHeader,
IonToolbar,
IonTitle,
IonButtons,
IonButton,
IonIcon,
IonRefresher,
IonRefresherContent,
IonAlert,
useIonViewWillEnter,
} from '@ionic/react';
import {
chevronBackOutline,
trashOutline,
receiptOutline,
personAddOutline,
cashOutline,
} from 'ionicons/icons';
import { useHistory, useParams } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../supabase';
import ActivityRow, { ActivityItem } from '../components/ActivityRow';
import EmptyState from '../components/EmptyState';
import { formatMoney } from '../utils/money';
const CustomerDetailPage: React.FC = () => {
const { id } = useParams<{ id: string }>();
const { user, profile } = useAuth();
const history = useHistory();
const currency = profile?.currency || 'USD';
const [loading, setLoading] = useState(true);
const [customer, setCustomer] = useState<any>(null);
const [activity, setActivity] = useState<ActivityItem[]>([]);
const [balance, setBalance] = useState(0);
const [showDeleteAlert, setShowDeleteAlert] = useState(false);
const fetchData = useCallback(async () => {
if (!user || !id) return;
setLoading(true);
try {
const [
{ data: customerData },
{ data: creditsData },
{ data: repaymentsData },
] = await Promise.all([
supabase.from('credit_customers').select('*').eq('id', id).single(),
supabase
.from('credits')
.select('*')
.eq('customer_id', id)
.order('credit_date', { ascending: false }),
supabase
.from('repayments')
.select('*')
.eq('customer_id', id)
.order('repayment_date', { ascending: false }),
]);
if (customerData) {
setCustomer(customerData);
const totalCredits = (creditsData || []).reduce(
(sum, c) => sum + Number(c.amount),
0
);
const totalRepayments = (repaymentsData || []).reduce(
(sum, r) => sum + Number(r.amount),
0
);
setBalance(Math.max(0, totalCredits - totalRepayments));
const combinedActivity: ActivityItem[] = [
...(creditsData || []).map((c) => ({
id: c.id,
type: 'credit' as const,
amount: Number(c.amount),
date: c.credit_date,
note: c.description,
})),
...(repaymentsData || []).map((r) => ({
id: r.id,
type: 'repayment' as const,
amount: Number(r.amount),
date: r.repayment_date,
note: r.note,
})),
].sort((a, b) => b.date.localeCompare(a.date));
setActivity(combinedActivity);
}
} catch (err) {
console.error('Error fetching customer detail:', err);
} finally {
setLoading(false);
}
}, [user, id]);
useIonViewWillEnter(() => {
fetchData();
}, [fetchData]);
const handleRefresh = async (e: CustomEvent) => {
await fetchData();
e.detail.complete();
};
const handleDelete = async () => {
try {
const { error } = await supabase
.from('credit_customers')
.delete()
.eq('id', id);
if (error) throw error;
history.push('/customers');
} catch (err) {
console.error('Error deleting customer:', err);
}
};
const getInitials = (name: string) => {
return name
.split(' ')
.map((n) => n[0])
.join('')
.toUpperCase()
.slice(0, 2);
};
if (!loading && !customer) {
return (
<IonPage>
<IonContent
className="ion-padding"
style={{ '--background': '#f0f4ff' }}
>
<EmptyState
icon="alert-circle-outline"
title="Customer not found"
actionText="Go Back"
onAction={() => history.push('/customers')}
/>
</IonContent>
</IonPage>
);
}
return (
<IonPage>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f0f4ff' }}>
<IonButtons slot="start">
<IonButton color="dark" onClick={() => history.push('/customers')}>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle className="bold">Customer</IonTitle>
<IonButtons slot="end">
<IonButton color="danger" onClick={() => setShowDeleteAlert(true)}>
<IonIcon icon={trashOutline} slot="icon-only" />
</IonButton>
</IonButtons>
</IonToolbar>
</IonHeader>
<IonContent fullscreen style={{ '--background': '#f0f4ff' }}>
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
<IonRefresherContent />
</IonRefresher>
<div className="page-padding" style={{ paddingTop: '16px' }}>
<div className="widget-card" style={{ padding: '24px 20px' }}>
<div
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '20px',
}}
>
<div
className="icon-container bold"
style={{
width: '56px',
height: '56px',
fontSize: '18px',
marginRight: '16px',
borderRadius: '16px',
}}
>
{customer ? getInitials(customer.name) : ''}
</div>
<div>
<h2 className="bold" style={{ margin: '0', fontSize: '20px' }}>
{customer?.name}
</h2>
{customer?.phone && (
<p className="secondary-text" style={{ margin: '2px 0 0 0' }}>
{customer.phone}
</p>
)}
</div>
</div>
<div style={{ marginBottom: '24px' }}>
<span className="tertiary-text">OUTSTANDING BALANCE</span>
<div
className="tabular"
style={{
fontSize: '34px',
fontWeight: '400',
color:
balance > 0
? 'var(--ion-color-danger)'
: 'var(--ion-color-success)',
marginTop: '4px',
}}
>
{formatMoney(balance, currency)}
</div>
<div
style={{
display: 'inline-block',
padding: '4px 12px',
borderRadius: '999px',
fontSize: '12px',
fontWeight: '600',
marginTop: '8px',
background:
balance > 0
? 'var(--color-danger-soft)'
: 'var(--color-success-soft)',
color:
balance > 0
? 'var(--ion-color-danger)'
: 'var(--ion-color-success)',
}}
>
{balance > 0 ? 'OWING' : 'CLEARED'}
</div>
</div>
<div style={{ display: 'flex', gap: '12px' }}>
<IonButton
fill="clear"
className="bold"
style={{
flex: 1,
fontSize: '14px',
background: 'var(--color-surface-secondary)',
color: 'var(--color-text-primary)',
'--border-radius': 'var(--radius-inner)',
height: '44px',
}}
onClick={() => history.push('/credit/new', { customerId: id })}
>
<IonIcon icon={personAddOutline} slot="start" />
Credit
</IonButton>
<IonButton
fill="solid"
className="bold"
style={{
flex: 1,
fontSize: '14px',
'--border-radius': 'var(--radius-inner)',
height: '44px',
}}
onClick={() =>
history.push('/repayment/new', { customerId: id })
}
disabled={balance === 0}
>
<IonIcon icon={cashOutline} slot="start" />
Repay
</IonButton>
</div>
</div>
</div>
<div className="section-header">
<h2>Activity</h2>
</div>
<div className="page-padding" style={{ paddingBottom: '40px' }}>
{loading ? (
<div className="widget-card" style={{ gap: '16px' }}>
{[1, 2, 3].map((i) => (
<div
key={i}
style={{ display: 'flex', gap: '12px', alignItems: 'center' }}
>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-surface-secondary)',
}}
/>
<div style={{ flex: 1 }}>
<div
style={{
width: '60%',
height: '12px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
marginBottom: '6px',
}}
/>
<div
style={{
width: '40%',
height: '10px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
}}
/>
</div>
</div>
))}
</div>
) : activity.length > 0 ? (
<div className="widget-card" style={{ padding: '8px 16px' }}>
{activity.map((item) => (
<ActivityRow
key={`${item.type}-${item.id}`}
item={item}
showDate
/>
))}
</div>
) : (
<EmptyState
icon={receiptOutline}
title="No activity yet"
description="Record the first credit or repayment for this customer."
/>
)}
</div>
<IonAlert
isOpen={showDeleteAlert}
onDidDismiss={() => setShowDeleteAlert(false)}
header="Delete Customer"
message="Are you sure you want to delete this customer? All their credit and repayment history will be lost."
buttons={[
{ text: 'Cancel', role: 'cancel' },
{ text: 'Delete', role: 'destructive', handler: handleDelete },
]}
/>
</IonContent>
</IonPage>
);
};
export default CustomerDetailPage;
+268
View File
@@ -0,0 +1,268 @@
import React, { useState, useCallback, useMemo } from 'react';
import {
IonContent,
IonPage,
IonIcon,
IonSegmentButton,
IonSearchbar,
IonRefresher,
IonRefresherContent,
useIonViewWillEnter,
} from '@ionic/react';
import { personAddOutline, peopleOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../supabase';
import MetricCard from '../components/MetricCard';
import CustomerRow from '../components/CustomerRow';
import EmptyState from '../components/EmptyState';
interface CustomerWithBalance {
id: string;
name: string;
phone: string | null;
balance: number;
}
const CustomersPage: React.FC = () => {
const { user } = useAuth();
const history = useHistory();
const [loading, setLoading] = useState(true);
const [customers, setCustomers] = useState<CustomerWithBalance[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const fetchData = useCallback(async () => {
if (!user) return;
setLoading(true);
try {
const [
{ data: customersData },
{ data: creditsData },
{ data: repaymentsData },
] = await Promise.all([
supabase
.from('credit_customers')
.select('*')
.eq('user_id', user.id)
.order('name'),
supabase
.from('credits')
.select('customer_id, amount')
.eq('user_id', user.id),
supabase
.from('repayments')
.select('customer_id, amount')
.eq('user_id', user.id),
]);
const customerBalances: CustomerWithBalance[] = (customersData || []).map(
(c) => {
const totalCredits = (creditsData || [])
.filter((cr) => cr.customer_id === c.id)
.reduce((sum, cr) => sum + Number(cr.amount), 0);
const totalRepayments = (repaymentsData || [])
.filter((r) => r.customer_id === c.id)
.reduce((sum, r) => sum + Number(r.amount), 0);
return {
id: c.id,
name: c.name,
phone: c.phone,
balance: Math.max(0, totalCredits - totalRepayments),
};
},
);
// Sort: outstanding balances first, then by name
setCustomers(
customerBalances.sort((a, b) => {
if (a.balance > 0 && b.balance === 0) return -1;
if (a.balance === 0 && b.balance > 0) return 1;
return a.name.localeCompare(b.name);
}),
);
} catch (err) {
console.error('Error fetching customers:', err);
} finally {
setLoading(false);
}
}, [user]);
useIonViewWillEnter(() => {
fetchData();
}, [fetchData]);
const handleRefresh = async (e: CustomEvent) => {
await fetchData();
e.detail.complete();
};
const filteredCustomers = useMemo(() => {
const query = searchQuery.toLowerCase().trim();
if (!query) return customers;
return customers.filter(
(c) =>
c.name.toLowerCase().includes(query) ||
(c.phone && c.phone.toLowerCase().includes(query)),
);
}, [customers, searchQuery]);
const totalOutstanding = useMemo(() => {
return customers.reduce((sum, c) => sum + c.balance, 0);
}, [customers]);
return (
<IonPage>
<IonContent
fullscreen
style={{
'--background':
'linear-gradient(160deg, rgba(199,210,254,0.35) 0%, #f0f4ff 58%, #f8fafc 100%)',
}}
>
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
<IonRefresherContent />
</IonRefresher>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top)) 20px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div>
<h1 className="bold" style={{ margin: '0', fontSize: '20px' }}>
Credit customers
</h1>
<p className="secondary-text" style={{ margin: '0' }}>
Track who owes your shop
</p>
</div>
<div
className="icon-container"
style={{
borderRadius: '12px',
background: '#ffffff',
color: 'var(--ion-color-primary)',
}}
onClick={() => history.push('/credit/new')}
>
<IonIcon icon={personAddOutline} style={{ fontSize: '22px' }} />
</div>
</div>
<div className="page-padding">
<IonSearchbar
value={searchQuery}
onIonInput={(e) => setSearchQuery(e.detail.value!)}
placeholder="Search customers"
className="custom-searchbar"
style={{
'--background': 'var(--color-surface-secondary)',
'--border-radius': '24px',
'--box-shadow': 'none',
padding: '0',
height: '44px',
marginBottom: '16px',
}}
/>
<MetricCard
label="Total Outstanding"
value={totalOutstanding}
fullWidth
loading={loading}
/>
</div>
<div className="section-header">
<h2>
Customers{' '}
{!loading && (
<span className="tertiary-text" style={{ marginLeft: '4px' }}>
({customers.length})
</span>
)}
</h2>
</div>
<div className="page-padding" style={{ paddingBottom: '120px' }}>
{loading ? (
<div className="widget-card" style={{ gap: '16px' }}>
{[1, 2, 3].map((i) => (
<div
key={i}
style={{ display: 'flex', gap: '12px', alignItems: 'center' }}
>
<div
style={{
width: '44px',
height: '44px',
borderRadius: '12px',
background: 'var(--color-surface-secondary)',
}}
/>
<div style={{ flex: 1 }}>
<div
style={{
width: '50%',
height: '14px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
marginBottom: '6px',
}}
/>
<div
style={{
width: '30%',
height: '10px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
}}
/>
</div>
</div>
))}
</div>
) : customers.length > 0 ? (
<>
{filteredCustomers.length > 0 ? (
<div className="widget-card" style={{ padding: '8px 16px' }}>
{filteredCustomers.map((c) => (
<CustomerRow
key={c.id}
id={c.id}
name={c.name}
phone={c.phone || undefined}
balance={c.balance}
onClick={() => history.push(`/customers/${c.id}`)}
/>
))}
</div>
) : (
<div style={{ textAlign: 'center', padding: '40px 20px' }}>
<p className="secondary-text">
No customers matching "{searchQuery}"
</p>
</div>
)}
</>
) : (
<EmptyState
icon={peopleOutline}
title="No credit customers yet"
description="Add a credit sale to start tracking balances."
actionText="Add Credit"
onAction={() => history.push('/credit/new')}
/>
)}
</div>
</IonContent>
</IonPage>
);
};
export default CustomersPage;
-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;
-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;
+162
View File
@@ -0,0 +1,162 @@
import React, { useState } from 'react';
import {
IonContent,
IonPage,
IonInput,
IonButton,
IonSpinner,
IonIcon,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
const ForgotPasswordPage: React.FC = () => {
const [email, setEmail] = useState('');
const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [messageType, setMessageType] = useState<'error' | 'success'>('error');
const history = useHistory();
const showMessage = (msg: string, type: 'error' | 'success' = 'error') => {
setMessage(msg);
setMessageType(type);
setTimeout(() => setMessage(null), 4000);
};
const handleReset = async (e: React.FormEvent) => {
e.preventDefault();
if (!email) {
showMessage('Please enter your email');
return;
}
setSubmitting(true);
setMessage(null);
try {
const { error } = await supabase.auth.resetPasswordForEmail(email);
if (error) throw error;
history.push('/verify-email', { email, type: 'recovery' });
} catch (err: any) {
showMessage(err.message || 'An error occurred');
} finally {
setSubmitting(false);
}
};
return (
<IonPage>
<IonContent
fullscreen
style={{
'--background':
'linear-gradient(160deg, rgba(199,210,254,0.52) 0%, #f0f4ff 58%, #f8fafc 100%)',
}}
>
<div className="auth-shell">
<IonButton
fill="clear"
color="dark"
onClick={() => history.push('/auth')}
style={{
position: 'absolute',
top: 'calc(var(--ion-safe-area-top, 0px) + 8px)',
left: '8px',
'--padding-start': '8px',
'--padding-end': '8px',
zIndex: 10,
}}
>
<div
style={{
background: '#ffffff',
width: '44px',
height: '44px',
borderRadius: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon icon={chevronBackOutline} />
</div>
</IonButton>
<div style={{ marginTop: '80px' }}>
<h1
className="bold"
style={{ fontSize: '24px', margin: '0 0 8px 0' }}
>
Reset password
</h1>
<p
className="secondary-text"
style={{ margin: '0', fontSize: '14px' }}
>
Enter your email and we'll send a 6-digit recovery code.
</p>
</div>
<div className="auth-card">
<form
onSubmit={handleReset}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<div className="input-wrapper">
<IonInput
label="Email"
labelPlacement="floating"
type="email"
placeholder="name@example.com"
value={email}
onIonChange={(e) => setEmail(e.detail.value!)}
/>
</div>
{message && (
<div
style={{
background:
messageType === 'error'
? 'var(--color-danger-soft)'
: 'var(--color-success-soft)',
color:
messageType === 'error'
? 'var(--ion-color-danger-shade)'
: 'var(--ion-color-success-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
textAlign: 'center',
}}
>
{message}
</div>
)}
<IonButton
type="submit"
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '8px',
}}
disabled={submitting}
>
{submitting ? <IonSpinner name="crescent" /> : 'Send code'}
</IonButton>
</form>
</div>
</div>
</IonContent>
</IonPage>
);
};
export default ForgotPasswordPage;
+339
View File
@@ -0,0 +1,339 @@
import React, { useState, useCallback, useMemo } from 'react';
import {
IonContent,
IonPage,
IonIcon,
IonRefresher,
IonRefresherContent,
IonSegment,
IonSegmentButton,
IonLabel,
IonActionSheet,
useIonViewWillEnter,
} from '@ionic/react';
import {
addOutline,
receiptOutline,
personAddOutline,
cashOutline,
} from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../supabase';
import ActivityRow, { ActivityItem } from '../components/ActivityRow';
import EmptyState from '../components/EmptyState';
import MetricCard from '../components/MetricCard';
import { groupItemsByDate, formatRelativeDate } from '../utils/dates';
const HistoryPage: React.FC = () => {
const { user } = useAuth();
const history = useHistory();
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState<
'all' | 'sales' | 'credit' | 'repayments'
>('all');
const [items, setItems] = useState<ActivityItem[]>([]);
const [showQuickAdd, setShowQuickAdd] = useState(false);
const fetchData = useCallback(async () => {
if (!user) return;
setLoading(true);
try {
const [
{ data: salesData },
{ data: creditsData },
{ data: repaymentsData },
] = await Promise.all([
supabase
.from('sales')
.select('*')
.eq('user_id', user.id)
.order('sale_date', { ascending: false }),
supabase
.from('credits')
.select('*, credit_customers(name)')
.eq('user_id', user.id)
.order('credit_date', { ascending: false }),
supabase
.from('repayments')
.select('*, credit_customers(name)')
.eq('user_id', user.id)
.order('repayment_date', { ascending: false }),
]);
const combined: ActivityItem[] = [
...(salesData || []).map((s) => ({
id: s.id,
type: 'sale' as const,
amount: Number(s.amount),
date: s.sale_date,
note: s.note,
})),
...(creditsData || []).map((c) => ({
id: c.id,
type: 'credit' as const,
amount: Number(c.amount),
date: c.credit_date,
customerName: (c.credit_customers as any)?.name,
note: c.description,
customerId: c.customer_id,
})),
...(repaymentsData || []).map((r) => ({
id: r.id,
type: 'repayment' as const,
amount: Number(r.amount),
date: r.repayment_date,
customerName: (r.credit_customers as any)?.name,
note: r.note,
customerId: r.customer_id,
})),
].sort((a, b) => b.date.localeCompare(a.date));
setItems(combined);
} catch (err) {
console.error('Error fetching history:', err);
} finally {
setLoading(false);
}
}, [user]);
useIonViewWillEnter(() => {
fetchData();
}, [fetchData]);
const handleRefresh = async (e: CustomEvent) => {
await fetchData();
e.detail.complete();
};
const filteredItems = useMemo(() => {
if (filter === 'all') return items;
if (filter === 'sales') return items.filter((i) => i.type === 'sale');
if (filter === 'credit') return items.filter((i) => i.type === 'credit');
if (filter === 'repayments')
return items.filter((i) => i.type === 'repayment');
return items;
}, [items, filter]);
const groupedItems = useMemo(() => {
return groupItemsByDate(filteredItems);
}, [filteredItems]);
const totals = useMemo(() => {
const salesTotal = items
.filter((i) => i.type === 'sale')
.reduce((sum, i) => sum + i.amount, 0);
const repaymentsTotal = items
.filter((i) => i.type === 'repayment')
.reduce((sum, i) => sum + i.amount, 0);
return { salesTotal, repaymentsTotal };
}, [items]);
return (
<IonPage>
<IonContent
fullscreen
style={{
'--background':
'linear-gradient(160deg, rgba(199,210,254,0.35) 0%, #f0f4ff 58%, #f8fafc 100%)',
}}
>
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
<IonRefresherContent />
</IonRefresher>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top)) 20px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div>
<h1 className="bold" style={{ margin: '0', fontSize: '20px' }}>
History
</h1>
<p className="secondary-text" style={{ margin: '0' }}>
All your transactions
</p>
</div>
<div
className="icon-container"
style={{
borderRadius: '12px',
background: '#ffffff',
color: 'var(--ion-color-primary)',
}}
onClick={() => setShowQuickAdd(true)}
>
<IonIcon icon={addOutline} style={{ fontSize: '22px' }} />
</div>
</div>
<div className="page-padding">
<IonSegment
value={filter}
onIonChange={(e) => setFilter(e.detail.value as any)}
style={{
'--background': 'var(--color-surface-secondary)',
borderRadius: '12px',
padding: '4px',
marginBottom: '16px',
}}
>
<IonSegmentButton
value="all"
style={{
'--indicator-color': 'var(--ion-color-primary)',
color: 'var(--color-text-primary)',
}}
>
<IonLabel className="semibold">All</IonLabel>
</IonSegmentButton>
<IonSegmentButton value="sales">
<IonLabel className="semibold">Sales</IonLabel>
</IonSegmentButton>
<IonSegmentButton value="credit">
<IonLabel className="semibold">Credit</IonLabel>
</IonSegmentButton>
<IonSegmentButton value="repayments">
<IonLabel className="semibold">Paid</IonLabel>
</IonSegmentButton>
</IonSegment>
<div className="metric-pair-row">
<MetricCard
label="Total Sales"
value={totals.salesTotal}
loading={loading}
/>
<MetricCard
label="Total Repaid"
value={totals.repaymentsTotal}
loading={loading}
/>
</div>
</div>
<div
className="page-padding"
style={{ paddingBottom: '120px', marginTop: '8px' }}
>
{loading ? (
<div className="widget-card" style={{ gap: '16px' }}>
{[1, 2, 3].map((i) => (
<div
key={i}
style={{ display: 'flex', gap: '12px', alignItems: 'center' }}
>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-surface-secondary)',
}}
/>
<div style={{ flex: 1 }}>
<div
style={{
width: '60%',
height: '12px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
marginBottom: '6px',
}}
/>
<div
style={{
width: '40%',
height: '10px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
}}
/>
</div>
</div>
))}
</div>
) : groupedItems.length > 0 ? (
groupedItems.map((group) => (
<div key={group.date} style={{ marginBottom: '20px' }}>
<div className="tertiary-text" style={{ marginBottom: '12px' }}>
{formatRelativeDate(group.date)}
</div>
<div className="widget-card" style={{ padding: '8px 16px' }}>
{group.items.map((item) => (
<ActivityRow
key={`${item.type}-${item.id}`}
item={item}
onClick={
item.customerId
? () => history.push(`/customers/${item.customerId}`)
: undefined
}
/>
))}
</div>
</div>
))
) : (
<EmptyState
icon={receiptOutline}
title={
filter === 'all' ? 'No activity yet' : `No ${filter} found`
}
description={
filter === 'all'
? 'Start recording sales and credits to see your history.'
: `You haven't recorded any ${filter} yet.`
}
actionText={
filter === 'all' || filter === 'sales'
? 'Add Sale'
: filter === 'credit'
? 'Add Credit'
: 'Record Repayment'
}
onAction={() => {
if (filter === 'sales' || filter === 'all')
history.push('/sale/new');
else if (filter === 'credit') history.push('/credit/new');
else history.push('/repayment/new');
}}
/>
)}
</div>
<IonActionSheet
isOpen={showQuickAdd}
onDidDismiss={() => setShowQuickAdd(false)}
header="Quick Actions"
buttons={[
{
text: 'Add Sale',
icon: receiptOutline,
handler: () => history.push('/sale/new'),
},
{
text: 'Add Credit',
icon: personAddOutline,
handler: () => history.push('/credit/new'),
},
{
text: 'Record Repayment',
icon: cashOutline,
handler: () => history.push('/repayment/new'),
},
{ text: 'Cancel', role: 'cancel' },
]}
/>
</IonContent>
</IonPage>
);
};
export default HistoryPage;
+290 -400
View File
@@ -1,467 +1,357 @@
import React, { useState } from 'react'; import React, { useState, useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { import {
IonPage,
IonContent, IonContent,
IonSpinner, IonPage,
useIonViewWillEnter,
IonIcon, IonIcon,
IonButton,
IonActionSheet,
IonRefresher,
IonRefresherContent,
useIonViewWillEnter,
} from '@ionic/react'; } from '@ionic/react';
import { documentTextOutline, addOutline, searchOutline } from 'ionicons/icons'; import {
import { supabase } from '../supabase'; addCircleOutline,
import { useProfile } from '../contexts/ProfileContext'; personAddOutline,
cashOutline,
receiptOutline,
walletOutline,
checkmarkCircleOutline,
personCircleOutline,
} from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import DashboardMetricCard from '../components/DashboardMetricCard'; import { supabase } from '../supabase';
import RecentActivityCard from '../components/RecentActivityCard'; import MetricCard from '../components/MetricCard';
import { Database } from '../database.types'; import ActivityRow, { ActivityItem } from '../components/ActivityRow';
import EmptyState from '../components/EmptyState';
type RfqRow = Database['public']['Tables']['rfqs']['Row']; import { getTodayISO } from '../utils/dates';
const Home: React.FC = () => { const Home: React.FC = () => {
const { user, profile } = useAuth();
const history = useHistory(); const history = useHistory();
const { user } = useAuth();
const { profile } = useProfile();
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(''); const [error, setError] = useState<string | null>(null);
const [showQuickActions, setShowQuickActions] = useState(false);
const [rfqSummary, setRfqSummary] = useState({ const [summary, setSummary] = useState({
open: 0, todaySales: 0,
quoted: 0, outstandingCredit: 0,
closed: 0, monthRepayments: 0,
}); recentActivity: [] as ActivityItem[],
const [supplierSummary, setSupplierSummary] = useState({
assignedOpen: 0,
myQuotes: 0,
accepted: 0,
});
const [recentItems, setRecentItems] = useState<any[]>([]);
useIonViewWillEnter(() => {
loadDashboardData();
}); });
const loadDashboardData = async () => { const fetchData = useCallback(async () => {
if (!user || !profile) return; if (!user) return;
setLoading(true); setLoading(true);
setError(''); setError(null);
try { try {
if (profile.role === 'buyer') { const today = getTodayISO();
// Aggregate counts const firstOfMonth = new Date();
const { data: allRfqs, error: countErr } = await supabase firstOfMonth.setDate(1);
.from('rfqs') const firstOfMonthISO = firstOfMonth.toISOString().split('T')[0];
.select('id, status')
.eq('buyer_id', user.id);
if (countErr) throw countErr; // Parallel queries for efficiency
const [
let open = 0, { data: salesToday },
quoted = 0, { data: creditsData },
closed = 0; { data: repaymentsData },
allRfqs?.forEach((r) => { { data: recentSales },
if (r.status === 'open') open++; { data: recentCredits },
else if (r.status === 'quoted') quoted++; { data: recentRepayments },
else if (r.status === 'closed') closed++; ] = await Promise.all([
}); supabase.from('sales').select('amount').eq('sale_date', today),
setRfqSummary({ open, quoted, closed }); supabase.from('credits').select('amount'),
supabase.from('repayments').select('amount, repayment_date'),
// Recent items supabase
const { data: recent, error: recentErr } = await supabase .from('sales')
.from('rfqs')
.select('*') .select('*')
.eq('buyer_id', user.id)
.order('created_at', { ascending: false }) .order('created_at', { ascending: false })
.limit(5); .limit(5),
if (recentErr) throw recentErr; supabase
setRecentItems(recent || []); .from('credits')
} else { .select('*, credit_customers(name)')
// 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 }) .order('created_at', { ascending: false })
.limit(5); .limit(5),
if (recentErr) throw recentErr; supabase
.from('repayments')
.select('*, credit_customers(name)')
.order('created_at', { ascending: false })
.limit(5),
]);
// Map joined data // Calculate totals
const mapped = (recent || []).map((r: any) => r.rfqs); const todaySalesTotal = (salesToday || []).reduce(
setRecentItems(mapped); (sum, s) => sum + Number(s.amount),
} 0
);
const totalCredits = (creditsData || []).reduce(
(sum, c) => sum + Number(c.amount),
0
);
const totalRepayments = (repaymentsData || []).reduce(
(sum, r) => sum + Number(r.amount),
0
);
const monthRepaymentsTotal = (repaymentsData || [])
.filter((r) => r.repayment_date >= firstOfMonthISO)
.reduce((sum, r) => sum + Number(r.amount), 0);
// Combine activity
const activity: ActivityItem[] = [
...(recentSales || []).map((s) => ({
id: s.id,
type: 'sale' as const,
amount: Number(s.amount),
date: s.sale_date,
note: s.note,
})),
...(recentCredits || []).map((c) => ({
id: c.id,
type: 'credit' as const,
amount: Number(c.amount),
date: c.credit_date,
customerName: (c.credit_customers as any)?.name,
note: c.description,
customerId: c.customer_id,
})),
...(recentRepayments || []).map((r) => ({
id: r.id,
type: 'repayment' as const,
amount: Number(r.amount),
date: r.repayment_date,
customerName: (r.credit_customers as any)?.name,
note: r.note,
customerId: r.customer_id,
})),
].sort((a, b) => b.id.localeCompare(a.id)); // Simplified sort for MVP, ideally use created_at
setSummary({
todaySales: todaySalesTotal,
outstandingCredit: Math.max(0, totalCredits - totalRepayments),
monthRepayments: monthRepaymentsTotal,
recentActivity: activity.slice(0, 10),
});
} catch (err: any) { } catch (err: any) {
console.error(err); console.error('Error fetching dashboard data:', err);
setError('Failed to load dashboard data.'); setError('Could not load dashboard data');
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [user]);
useIonViewWillEnter(() => {
fetchData();
}, [fetchData]);
const handleRefresh = async (e: CustomEvent) => {
await fetchData();
e.detail.complete();
}; };
const handlePrimaryAction = () => { const getGreeting = () => {
if (profile?.role === 'buyer') { const hour = new Date().getHours();
history.push('/rfq/new'); if (hour < 12) return 'Good morning';
} else { if (hour < 17) return 'Good afternoon';
history.push('/requests'); return 'Good evening';
}
}; };
const handleRecentItemTap = (item: RfqRow) => {
history.push(`/rfq/${item.id}`);
};
if (!profile) return null;
return ( return (
<IonPage style={{ background: 'var(--color-bg)' }}> <IonPage>
<IonContent <IonContent
fullscreen
style={{ style={{
'--background': 'var(--color-bg-gradient)', '--background':
'--padding-start': '0px', 'linear-gradient(160deg, rgba(199,210,254,0.45) 0%, #f0f4ff 58%, #f8fafc 100%)',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}} }}
> >
<IonRefresher slot="fixed" onIonRefresh={handleRefresh}>
<IonRefresherContent />
</IonRefresher>
<div <div
style={{ style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 16px', padding: 'calc(16px + var(--ion-safe-area-top)) 20px 16px',
display: 'flex', display: 'flex',
justifyContent: 'space-between', justifyContent: 'space-between',
alignItems: 'center', alignItems: 'center',
}} }}
> >
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}> <div>
<div <div className="secondary-text">{getGreeting()}</div>
style={{ <h1 className="bold" style={{ margin: '0', fontSize: '20px' }}>
fontSize: '13px', {profile?.shop_name || profile?.full_name || 'My Shop'}
fontWeight: '700', </h1>
letterSpacing: '0.08em',
textTransform: 'uppercase',
color: 'var(--color-brand)',
}}
>
QuoteLink
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-tertiary)',
}}
>
Procurement made simpler
</div>
</div> </div>
<div <div
onClick={() => history.push('/profile')} className="icon-container"
style={{ style={{
width: '40px',
height: '40px',
borderRadius: '999px', borderRadius: '999px',
background: 'var(--color-brand-medium)', background: 'var(--color-accent-soft)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
color: 'var(--color-brand)',
fontSize: '16px',
fontWeight: '700',
textTransform: 'uppercase',
flexShrink: 0,
}} }}
onClick={() => setShowQuickActions(true)}
> >
{profile.full_name.charAt(0)} <IonIcon icon={personCircleOutline} style={{ fontSize: '24px' }} />
</div> </div>
</div> </div>
<div <div className="page-padding">
style={{ <MetricCard
margin: '0 20px 18px', label="Today's Sales"
display: 'flex', value={summary.todaySales}
flexDirection: 'column', fullWidth
gap: '5px', loading={loading}
}} />
>
<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 className="metric-pair-row" style={{ marginTop: '12px' }}>
<div <MetricCard
style={{ label="Outstanding"
margin: '0 20px 12px', value={summary.outstandingCredit}
background: 'var(--color-danger-soft)', icon={walletOutline}
borderRadius: '12px', loading={loading}
padding: '12px 14px', />
fontSize: '13px', <MetricCard
fontWeight: '500', label="Repaid (Month)"
color: 'var(--color-danger-text)', value={summary.monthRepayments}
}} icon={checkmarkCircleOutline}
> loading={loading}
{error} />
</div> </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 <div
style={{ className="pill-toggle"
display: 'flex', style={{ marginTop: '12px', background: '#ffffff', padding: '8px' }}
justifyContent: 'space-between',
alignItems: 'flex-start',
}}
> >
<div <IonButton
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }} fill="clear"
> className="bold"
<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={{ style={{
width: '40px', flex: 1,
height: '40px', fontSize: '13px',
borderRadius: '14px', color: 'var(--color-text-primary)',
background: 'rgba(255,255,255,0.15)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}} }}
onClick={() => history.push('/sale/new')}
> >
<IonIcon <IonIcon icon={addCircleOutline} slot="start" />
icon={profile.role === 'buyer' ? addOutline : searchOutline} Add Sale
style={{ color: '#ffffff', fontSize: '24px' }} </IonButton>
/> <IonButton
</div> fill="clear"
</div> className="bold"
<div style={{
style={{ flex: 1,
fontSize: '14px', fontSize: '13px',
fontWeight: '600', color: 'var(--color-text-primary)',
color: 'var(--color-accent)', }}
}} onClick={() => history.push('/credit/new')}
> >
{profile.role === 'buyer' <IonIcon icon={personAddOutline} slot="start" />
? 'Create new request →' Credit
: 'Browse requests →'} </IonButton>
<IonButton
fill="clear"
className="bold"
style={{
flex: 1,
fontSize: '13px',
color: 'var(--color-text-primary)',
}}
onClick={() => history.push('/repayment/new')}
>
<IonIcon icon={cashOutline} slot="start" />
Repay
</IonButton>
</div> </div>
</div> </div>
<div style={{ display: 'flex', gap: '12px', margin: '0 20px 24px' }}> <div className="section-header">
{profile.role === 'buyer' ? ( <h2>Recent activity</h2>
<> <span className="see-all" onClick={() => history.push('/history')}>
<DashboardMetricCard See all
label="Received Quotes" </span>
value={rfqSummary.quoted.toString()} </div>
hint="Awaiting decision"
icon={documentTextOutline} <div className="page-padding" style={{ paddingBottom: '120px' }}>
/> {loading ? (
<DashboardMetricCard <div className="widget-card" style={{ gap: '16px' }}>
label="Completed" {[1, 2, 3].map((i) => (
value={rfqSummary.closed.toString()} <div
hint="Past requests" key={i}
icon={documentTextOutline} style={{ display: 'flex', gap: '12px', alignItems: 'center' }}
/> >
</> <div
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-surface-secondary)',
}}
/>
<div style={{ flex: 1 }}>
<div
style={{
width: '60%',
height: '12px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
marginBottom: '6px',
}}
/>
<div
style={{
width: '40%',
height: '10px',
background: 'var(--color-surface-secondary)',
borderRadius: '4px',
}}
/>
</div>
</div>
))}
</div>
) : summary.recentActivity.length > 0 ? (
<div className="widget-card" style={{ padding: '8px 16px' }}>
{summary.recentActivity.map((item) => (
<ActivityRow
key={`${item.type}-${item.id}`}
item={item}
onClick={
item.customerId
? () => history.push(`/customers/${item.customerId}`)
: undefined
}
/>
))}
</div>
) : ( ) : (
<> <EmptyState
<DashboardMetricCard icon={receiptOutline}
label="My Quotes" title="No activity yet"
value={supplierSummary.myQuotes.toString()} description="Record your first sale or credit to see it here."
hint="Submitted" actionText="Add Sale"
icon={documentTextOutline} onAction={() => history.push('/sale/new')}
/> />
<DashboardMetricCard
label="Accepted"
value={supplierSummary.accepted.toString()}
hint="Won bids"
icon={documentTextOutline}
/>
</>
)} )}
</div> </div>
<div <IonActionSheet
style={{ isOpen={showQuickActions}
margin: '16px 20px 8px', onDidDismiss={() => setShowQuickActions(false)}
display: 'flex', header="Settings"
justifyContent: 'space-between', buttons={[
alignItems: 'flex-end', {
}} text: 'Sign Out',
> role: 'destructive',
<div handler: () => {
style={{ supabase.auth.signOut();
fontSize: '15px', },
fontWeight: '700', },
color: 'var(--color-text-primary)', {
}} text: 'Cancel',
> role: 'cancel',
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> </IonContent>
</IonPage> </IonPage>
); );
+180
View File
@@ -0,0 +1,180 @@
import React, { useState } from 'react';
import {
IonContent,
IonPage,
IonInput,
IonButton,
IonSpinner,
IonIcon,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
const NewPasswordPage: React.FC = () => {
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [submitting, setSubmitting] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const history = useHistory();
const showMessage = (msg: string) => {
setMessage(msg);
setTimeout(() => setMessage(null), 4000);
};
const handleUpdate = async (e: React.FormEvent) => {
e.preventDefault();
if (!password || !confirmPassword) {
showMessage('Please fill in all fields');
return;
}
if (password.length < 6) {
showMessage('Password must be at least 6 characters');
return;
}
if (password !== confirmPassword) {
showMessage('Passwords do not match');
return;
}
setSubmitting(true);
setMessage(null);
try {
const { error } = await supabase.auth.updateUser({ password });
if (error) throw error;
history.push('/home');
} catch (err: any) {
showMessage(err.message || 'An error occurred');
} finally {
setSubmitting(false);
}
};
return (
<IonPage>
<IonContent
fullscreen
style={{
'--background':
'linear-gradient(160deg, rgba(199,210,254,0.52) 0%, #f0f4ff 58%, #f8fafc 100%)',
}}
>
<div className="auth-shell">
<IonButton
fill="clear"
color="dark"
onClick={() => history.push('/auth')}
style={{
position: 'absolute',
top: 'calc(var(--ion-safe-area-top, 0px) + 8px)',
left: '8px',
'--padding-start': '8px',
'--padding-end': '8px',
zIndex: 10,
}}
>
<div
style={{
background: '#ffffff',
width: '44px',
height: '44px',
borderRadius: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon icon={chevronBackOutline} />
</div>
</IonButton>
<div style={{ marginTop: '80px' }}>
<h1
className="bold"
style={{ fontSize: '24px', margin: '0 0 8px 0' }}
>
Create new password
</h1>
<p
className="secondary-text"
style={{ margin: '0', fontSize: '14px' }}
>
Set a strong password to protect your account.
</p>
</div>
<div className="auth-card">
<form
onSubmit={handleUpdate}
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<div className="input-wrapper">
<IonInput
label="New Password"
labelPlacement="floating"
type="password"
placeholder="Min. 6 characters"
value={password}
onIonChange={(e) => setPassword(e.detail.value!)}
/>
</div>
<div className="input-wrapper">
<IonInput
label="Confirm Password"
labelPlacement="floating"
type="password"
placeholder="Repeat your password"
value={confirmPassword}
onIonChange={(e) => setConfirmPassword(e.detail.value!)}
/>
</div>
{message && (
<div
style={{
background: 'var(--color-danger-soft)',
color: 'var(--ion-color-danger-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
textAlign: 'center',
}}
>
{message}
</div>
)}
<IonButton
type="submit"
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '8px',
}}
disabled={submitting}
>
{submitting ? (
<IonSpinner name="crescent" />
) : (
'Update password'
)}
</IonButton>
</form>
</div>
</div>
</IonContent>
</IonPage>
);
};
export default NewPasswordPage;
-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;
-390
View File
@@ -1,390 +0,0 @@
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { IonPage, IonContent, IonSpinner, IonIcon } from '@ionic/react';
import {
createOutline,
personOutline,
businessOutline,
locationOutline,
callOutline,
moonOutline,
sunnyOutline,
} from 'ionicons/icons';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { Preferences } from '@capacitor/preferences';
import ProfileInfoRow from '../components/ProfileInfoRow';
const Profile: React.FC = () => {
const history = useHistory();
const { signOut } = useAuth();
const { profile, clearProfile, themeMode, setThemeMode } = useProfile();
const [signingOut, setSigningOut] = useState(false);
const [error, setError] = useState('');
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSignOut = async () => {
setSigningOut(true);
try {
if (profile) {
await Preferences.remove({ key: `profile_${profile.id}` });
}
await signOut();
clearProfile();
history.replace('/auth');
} catch (err: any) {
console.error(err);
showError('Failed to sign out.');
} finally {
setSigningOut(false);
}
};
const handleEditProfile = () => {
history.push('/profile/edit');
};
const handleThemeToggle = async () => {
await setThemeMode(themeMode === 'dark' ? 'light' : 'dark');
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': 'calc(96px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
padding: 'calc(16px + var(--ion-safe-area-top, 0px)) 20px 16px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
<div
style={{
fontSize: '24px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Profile
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-tertiary)',
}}
>
Professional account details
</div>
</div>
<button
onClick={handleEditProfile}
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'transparent',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
border: 'none',
}}
>
<IonIcon
icon={createOutline}
style={{ color: 'var(--color-brand)', fontSize: '24px' }}
/>
</button>
</div>
{error && (
<div
style={{
margin: '0 20px 12px',
background: 'var(--color-danger-soft)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: 'var(--color-danger-text)',
}}
>
{error}
</div>
)}
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '24px',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
<div
style={{
width: '72px',
height: '72px',
borderRadius: '999px',
background: 'var(--color-brand-medium)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
fontSize: '32px',
fontWeight: '700',
color: 'var(--color-brand)',
textTransform: 'uppercase',
}}
>
{profile.full_name.charAt(0)}
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
>
<div
style={{
fontSize: '22px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{profile.full_name}
</div>
<div
style={{
background: 'var(--color-accent-soft)',
color: 'var(--color-accent-strong)',
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
width: 'max-content',
textTransform: 'capitalize',
}}
>
{profile.role}
</div>
</div>
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
Member since {new Date(profile.created_at).toLocaleDateString()}
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
gap: '16px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Appearance
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
Switch between light and dark mode
</div>
</div>
<button
onClick={handleThemeToggle}
style={{
background: 'var(--color-surface-raised)',
borderRadius: '999px',
border: 'none',
padding: '6px',
width: '120px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
cursor: 'pointer',
}}
>
<div
style={{
width: '48px',
height: '36px',
borderRadius: '999px',
background:
themeMode === 'light'
? 'var(--color-brand)'
: 'transparent',
color:
themeMode === 'light'
? '#ffffff'
: 'var(--color-text-secondary)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '6px',
fontSize: '12px',
fontWeight: '700',
transition: 'all 0.2s ease',
}}
>
<IonIcon icon={sunnyOutline} style={{ fontSize: '16px' }} />
</div>
<div
style={{
width: '48px',
height: '36px',
borderRadius: '999px',
background:
themeMode === 'dark' ? 'var(--color-brand)' : 'transparent',
color:
themeMode === 'dark'
? '#ffffff'
: 'var(--color-text-secondary)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '6px',
fontSize: '12px',
fontWeight: '700',
transition: 'all 0.2s ease',
}}
>
<IonIcon icon={moonOutline} style={{ fontSize: '16px' }} />
</div>
</button>
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '8px 0',
margin: '0 20px 12px',
display: 'flex',
flexDirection: 'column',
}}
>
<ProfileInfoRow
icon={personOutline}
label="Name"
value={profile.full_name}
onClick={handleEditProfile}
/>
{profile.company_name && (
<ProfileInfoRow
icon={businessOutline}
label="Company"
value={profile.company_name}
onClick={handleEditProfile}
/>
)}
{profile.city && (
<ProfileInfoRow
icon={locationOutline}
label="Location"
value={profile.city}
onClick={handleEditProfile}
/>
)}
{profile.phone && (
<ProfileInfoRow
icon={callOutline}
label="Phone"
value={profile.phone}
onClick={handleEditProfile}
/>
)}
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 20px',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
<button
onClick={handleSignOut}
disabled={signingOut}
style={{
background: 'var(--color-brand-strong)',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: signingOut ? 0.7 : 1,
}}
>
{signingOut ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Sign Out'
)}
</button>
</div>
</IonContent>
</IonPage>
);
};
export default Profile;
+353
View File
@@ -0,0 +1,353 @@
import React, { useState, useEffect, useMemo } from 'react';
import {
IonContent,
IonPage,
IonHeader,
IonToolbar,
IonTitle,
IonButtons,
IonButton,
IonIcon,
IonInput,
IonTextarea,
IonSpinner,
IonLabel,
IonSelect,
IonSelectOption,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory, useLocation } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { getTodayISO } from '../utils/dates';
import MoneyInput from '../components/MoneyInput';
import { parseMoney, formatMoney } from '../utils/money';
import EmptyState from '../components/EmptyState';
interface CustomerWithBalance {
id: string;
name: string;
balance: number;
}
const RepaymentFormPage: React.FC = () => {
const history = useHistory();
const location = useLocation<{ customerId?: string }>();
const { user, profile } = useAuth();
const currency = profile?.currency || 'USD';
const [customers, setCustomers] = useState<CustomerWithBalance[]>([]);
const [selectedCustomerId, setSelectedCustomerId] = useState<string>(
location.state?.customerId || ''
);
const [amount, setAmount] = useState('');
const [repaymentDate, setRepaymentDate] = useState(getTodayISO());
const [note, setNote] = useState('');
const [submitting, setSubmitting] = useState(false);
const [loadingCustomers, setLoadingCustomers] = useState(true);
const [errors, setErrors] = useState<Record<string, string>>({});
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
const fetchCustomersAndBalances = async () => {
if (!user) return;
try {
const [
{ data: customersData },
{ data: creditsData },
{ data: repaymentsData },
] = await Promise.all([
supabase
.from('credit_customers')
.select('id, name')
.eq('user_id', user.id),
supabase
.from('credits')
.select('customer_id, amount')
.eq('user_id', user.id),
supabase
.from('repayments')
.select('customer_id, amount')
.eq('user_id', user.id),
]);
const customerBalances: CustomerWithBalance[] = (
customersData || []
).map((c) => {
const totalCredits = (creditsData || [])
.filter((cr) => cr.customer_id === c.id)
.reduce((sum, cr) => sum + Number(cr.amount), 0);
const totalRepayments = (repaymentsData || [])
.filter((r) => r.customer_id === c.id)
.reduce((sum, r) => sum + Number(r.amount), 0);
return {
id: c.id,
name: c.name,
balance: Math.max(0, totalCredits - totalRepayments),
};
});
// Filter for customers with an outstanding balance
const activeCustomers = customerBalances.filter((c) => c.balance > 0);
setCustomers(activeCustomers);
// If a customer was passed in but has no balance, we should handle it
if (
selectedCustomerId &&
!activeCustomers.find((c) => c.id === selectedCustomerId)
) {
setSelectedCustomerId('');
}
} catch (err) {
console.error('Error fetching customers for repayment:', err);
} finally {
setLoadingCustomers(false);
}
};
fetchCustomersAndBalances();
}, [user, selectedCustomerId]);
const selectedCustomer = useMemo(
() => customers.find((c) => c.id === selectedCustomerId),
[customers, selectedCustomerId]
);
const validate = () => {
const newErrors: Record<string, string> = {};
const parsedAmount = parseMoney(amount);
if (!selectedCustomerId) {
newErrors.customer = 'Please select a customer';
} else if (selectedCustomer && parsedAmount > selectedCustomer.balance) {
newErrors.amount = `Amount cannot exceed outstanding balance of ${formatMoney(
selectedCustomer.balance,
currency
)}`;
}
if (parsedAmount <= 0) {
newErrors.amount = 'Amount must be greater than 0';
}
if (!repaymentDate) {
newErrors.date = 'Date is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSave = async () => {
if (!validate() || !user) return;
setSubmitting(true);
setMessage(null);
try {
const { error } = await supabase.from('repayments').insert([
{
user_id: user.id,
customer_id: selectedCustomerId,
amount: parseMoney(amount),
repayment_date: repaymentDate,
note: note.trim() || null,
},
]);
if (error) throw error;
history.goBack();
} catch (err: any) {
console.error('Error saving repayment:', err);
setMessage(err.message || 'Could not save repayment');
setTimeout(() => setMessage(null), 4000);
} finally {
setSubmitting(false);
}
};
return (
<IonPage>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f0f4ff' }}>
<IonButtons slot="start">
<IonButton color="dark" onClick={() => history.goBack()}>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle className="bold">Record repayment</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding" style={{ '--background': '#f0f4ff' }}>
{!loadingCustomers && customers.length === 0 ? (
<EmptyState
icon="wallet-outline"
title="No outstanding credit"
description="You don't have any customers with an outstanding balance right now."
actionText="Add Credit"
onAction={() => history.push('/credit/new')}
/>
) : (
<div className="form-card">
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Select Customer
</IonLabel>
<div className="input-wrapper">
<IonSelect
interface="action-sheet"
placeholder="Choose a customer"
value={selectedCustomerId}
onIonChange={(e) => setSelectedCustomerId(e.detail.value)}
style={{ width: '100%' }}
disabled={loadingCustomers}
>
{customers.map((c) => (
<IonSelectOption key={c.id} value={c.id}>
{c.name} ({formatMoney(c.balance, currency)})
</IonSelectOption>
))}
</IonSelect>
</div>
{errors.customer && (
<IonLabel
color="danger"
style={{ fontSize: '12px', marginTop: '4px' }}
>
{errors.customer}
</IonLabel>
)}
</div>
{selectedCustomer && (
<div
style={{
background: 'rgba(99,102,241,0.10)',
borderRadius: '12px',
padding: '16px',
display: 'flex',
flexDirection: 'column',
gap: '4px',
}}
>
<span className="tertiary-text" style={{ fontSize: '10px' }}>
OUTSTANDING BALANCE
</span>
<span
className="bold tabular"
style={{
fontSize: '22px',
color: 'var(--ion-color-primary)',
}}
>
{formatMoney(selectedCustomer.balance, currency)}
</span>
</div>
)}
<MoneyInput
label="Repayment amount"
value={amount}
onValueChange={(val) => {
setAmount(val);
if (errors.amount) setErrors({ ...errors, amount: '' });
}}
error={errors.amount}
/>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Repayment date
</IonLabel>
<div className="input-wrapper">
<IonInput
type="date"
value={repaymentDate}
onIonChange={(e) => setRepaymentDate(e.detail.value!)}
/>
</div>
{errors.date && (
<IonLabel
color="danger"
style={{ fontSize: '12px', marginTop: '4px' }}
>
{errors.date}
</IonLabel>
)}
</div>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Note (optional)
</IonLabel>
<div
className="input-wrapper"
style={{ minHeight: '96px', padding: '8px 16px' }}
>
<IonTextarea
placeholder="e.g. Paid in full"
value={note}
onIonChange={(e) => setNote(e.detail.value!)}
rows={4}
/>
</div>
</div>
{message && (
<div
style={{
background: 'var(--color-danger-soft)',
color: 'var(--ion-color-danger-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
}}
>
{message}
</div>
)}
<IonButton
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '16px',
}}
disabled={submitting || loadingCustomers}
onClick={handleSave}
>
{submitting ? <IonSpinner name="crescent" /> : 'Save repayment'}
</IonButton>
</div>
)}
</IonContent>
</IonPage>
);
};
export default RepaymentFormPage;
-456
View File
@@ -1,456 +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, pricetagOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import QuoteSummaryRow from '../components/QuoteSummaryRow';
const RfqDetail: React.FC = () => {
const history = useHistory();
const { id } = useParams<{ id: string }>();
const { user } = useAuth();
const { profile } = useProfile();
const [rfq, setRfq] = useState<any>(null);
const [images, setImages] = useState<string[]>([]);
const [quotes, setQuotes] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [supplierInvited, setSupplierInvited] = useState(false);
useIonViewWillEnter(() => {
loadRfqDetail();
});
const loadRfqDetail = async () => {
if (!user || !profile) return;
setLoading(true);
setError('');
try {
// Check supplier visibility first if supplier
if (profile.role === 'supplier') {
const { data: rec, error: recErr } = await supabase
.from('rfq_recipients')
.select('id')
.eq('rfq_id', id)
.eq('supplier_id', user.id)
.single();
if (recErr || !rec) {
throw new Error('Not invited to this RFQ');
}
setSupplierInvited(true);
}
// Load RFQ
const { data: rfqData, error: rfqErr } = await supabase
.from('rfqs')
.select('*')
.eq('id', id)
.single();
if (rfqErr) throw rfqErr;
setRfq(rfqData);
// Load Images
const { data: imgData } = await supabase
.from('rfq_images')
.select('storage_path')
.eq('rfq_id', id);
if (imgData && imgData.length > 0) {
const urls = imgData.map((img) => {
const { data } = supabase.storage
.from('rfq-images')
.getPublicUrl(img.storage_path);
return data.publicUrl;
});
setImages(urls);
}
// Load Quotes
if (profile.role === 'buyer') {
const { data: qData, error: qErr } = await supabase
.from('quotations')
.select(
'id, price_amount, delivery_option, status, profiles(full_name, company_name)'
)
.eq('rfq_id', id);
if (qErr) throw qErr;
setQuotes(qData || []);
} else {
const { data: qData, error: qErr } = await supabase
.from('quotations')
.select('id, price_amount, delivery_option, status')
.eq('rfq_id', id)
.eq('supplier_id', user.id);
if (qErr) throw qErr;
setQuotes(qData || []);
}
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to load RFQ details');
} finally {
setLoading(false);
}
};
const handlePrimaryAction = () => {
if (profile?.role === 'buyer') {
history.push(`/quote-list/${id}`);
} else {
if (quotes.length > 0) {
history.push(`/quote/${quotes[0].id}`, { mode: 'edit' });
} else {
history.push(`/quote/${id}`, { mode: 'create' });
}
}
};
const getStatusColor = (status: string) => {
if (status === 'open') {
return {
bg: 'var(--color-success-soft)',
text: 'var(--color-success-text)',
};
}
if (status === 'quoted') {
return {
bg: 'var(--color-warning-soft)',
text: 'var(--color-warning-text)',
};
}
return {
bg: 'var(--color-surface-raised)',
text: 'var(--color-text-secondary)',
};
};
if (!profile) return null;
return (
<IonPage style={{ background: 'var(--color-bg)' }}>
<IonHeader className="ion-no-border">
<IonToolbar
style={{ '--background': 'var(--color-bg)' } as React.CSSProperties}
>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={
{
'--color': 'var(--color-brand-strong)',
} as React.CSSProperties
}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{
fontSize: '18px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Request Details
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': 'var(--color-bg-gradient)',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(120px + var(--ion-safe-area-bottom))',
}}
>
{loading ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '40px',
}}
>
<IonSpinner
name="crescent"
style={{ color: 'var(--color-brand)' }}
/>
</div>
) : error ? (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
) : (
rfq && (
<>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px 0',
display: 'flex',
flexDirection: 'column',
gap: '10px',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div
style={{
background: 'var(--color-accent-soft)',
color: 'var(--color-warning-text)',
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
}}
>
{rfq.reference_number}
</div>
<div
style={{
background: getStatusColor(rfq.status).bg,
color: getStatusColor(rfq.status).text,
borderRadius: '999px',
padding: '6px 12px',
fontSize: '12px',
fontWeight: '700',
textTransform: 'capitalize',
}}
>
{rfq.status}
</div>
</div>
<div
style={{
fontSize: '22px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
{rfq.title}
</div>
<div
style={{
fontSize: '13px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
}}
>
Posted {new Date(rfq.created_at).toLocaleDateString()}
</div>
</div>
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px 0',
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
}}
>
Request Details
</div>
<div
style={{
fontSize: '15px',
fontWeight: '400',
color: 'var(--color-text-secondary)',
lineHeight: '1.6',
whiteSpace: 'pre-wrap',
}}
>
{rfq.request_text}
</div>
</div>
{images.length > 0 && (
<div
style={{
margin: '0 0 12px 0',
display: 'flex',
gap: '10px',
overflowX: 'auto',
}}
>
{images.map((url, i) => (
<img
key={i}
src={url}
alt="Reference"
style={{
width: '120px',
height: '120px',
borderRadius: '12px',
objectFit: 'cover',
}}
/>
))}
</div>
)}
<div
style={{
background: 'var(--color-surface)',
borderRadius: '24px',
padding: '20px',
marginBottom: '20px',
}}
>
<div
style={{
fontSize: '15px',
fontWeight: '700',
color: 'var(--color-text-primary)',
marginBottom: '16px',
}}
>
{profile.role === 'buyer' ? 'Quotations' : 'Your Quote'}
</div>
{quotes.length > 0 ? (
<div style={{ display: 'flex', flexDirection: 'column' }}>
{quotes.map((q) => (
<QuoteSummaryRow
key={q.id}
supplierName={
profile.role === 'buyer'
? q.profiles?.company_name ||
q.profiles?.full_name ||
'Supplier'
: 'My Quote'
}
priceLabel={`$${q.price_amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
deliveryOption={q.delivery_option}
status={q.status}
/>
))}
</div>
) : (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '12px',
}}
>
<div
style={{
width: '40px',
height: '40px',
borderRadius: '12px',
background: 'var(--color-surface-raised)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<IonIcon
icon={pricetagOutline}
style={{
color: 'var(--color-brand)',
fontSize: '20px',
}}
/>
</div>
<div
style={{
fontSize: '14px',
color: 'var(--color-text-secondary)',
}}
>
{profile.role === 'buyer'
? 'No quotes received yet.'
: "You haven't submitted a quote yet."}
</div>
</div>
)}
</div>
</>
)
)}
</IonContent>
{!loading && !error && (
<div
style={{
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
padding: '16px 20px calc(16px + var(--ion-safe-area-bottom, 0px))',
background: 'var(--color-surface)',
borderTop: '1px solid var(--color-border)',
display: 'flex',
zIndex: 10,
}}
>
<button
onClick={handlePrimaryAction}
style={{
background: 'var(--color-brand)',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
width: '100%',
cursor: 'pointer',
}}
>
{profile.role === 'buyer'
? 'View Quotations'
: quotes.length > 0
? 'Update Quote'
: 'Submit Quote'}
</button>
</div>
)}
</IonPage>
);
};
export default RfqDetail;
+188
View File
@@ -0,0 +1,188 @@
import React, { useState } from 'react';
import {
IonContent,
IonPage,
IonHeader,
IonToolbar,
IonTitle,
IonButtons,
IonButton,
IonIcon,
IonInput,
IonTextarea,
IonSpinner,
IonLabel,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory } from 'react-router-dom';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
import { getTodayISO } from '../utils/dates';
import MoneyInput from '../components/MoneyInput';
import { parseMoney } from '../utils/money';
const SaleFormPage: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const [amount, setAmount] = useState('');
const [saleDate, setSaleDate] = useState(getTodayISO());
const [note, setNote] = useState('');
const [submitting, setSubmitting] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const [message, setMessage] = useState<string | null>(null);
const validate = () => {
const newErrors: Record<string, string> = {};
const parsedAmount = parseMoney(amount);
if (parsedAmount <= 0) {
newErrors.amount = 'Amount must be greater than 0';
}
if (!saleDate) {
newErrors.date = 'Date is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSave = async () => {
if (!validate() || !user) return;
setSubmitting(true);
setMessage(null);
try {
const { error } = await supabase.from('sales').insert([
{
user_id: user.id,
amount: parseMoney(amount),
sale_date: saleDate,
note: note.trim() || null,
},
]);
if (error) throw error;
history.goBack();
} catch (err: any) {
console.error('Error saving sale:', err);
setMessage(err.message || 'Could not save sale');
setTimeout(() => setMessage(null), 4000);
} finally {
setSubmitting(false);
}
};
return (
<IonPage>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f0f4ff' }}>
<IonButtons slot="start">
<IonButton color="dark" onClick={() => history.goBack()}>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle className="bold">Add sale</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding" style={{ '--background': '#f0f4ff' }}>
<div className="form-card">
<MoneyInput
label="Sale amount"
value={amount}
onValueChange={(val) => {
setAmount(val);
if (errors.amount) setErrors({ ...errors, amount: '' });
}}
error={errors.amount}
/>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Sale date
</IonLabel>
<div className="input-wrapper">
<IonInput
type="date"
value={saleDate}
onIonChange={(e) => setSaleDate(e.detail.value!)}
/>
</div>
{errors.date && (
<IonLabel
color="danger"
style={{ fontSize: '12px', marginTop: '4px' }}
>
{errors.date}
</IonLabel>
)}
</div>
<div className="form-field">
<IonLabel
className="semibold"
style={{
marginBottom: '8px',
display: 'block',
fontSize: '13px',
}}
>
Note (optional)
</IonLabel>
<div
className="input-wrapper"
style={{ minHeight: '96px', padding: '8px 16px' }}
>
<IonTextarea
placeholder="e.g. Morning rush items"
value={note}
onIonChange={(e) => setNote(e.detail.value!)}
rows={4}
/>
</div>
</div>
{message && (
<div
style={{
background: 'var(--color-danger-soft)',
color: 'var(--ion-color-danger-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
}}
>
{message}
</div>
)}
<IonButton
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '16px',
}}
disabled={submitting}
onClick={handleSave}
>
{submitting ? <IonSpinner name="crescent" /> : 'Save sale'}
</IonButton>
</div>
</IonContent>
</IonPage>
);
};
export default SaleFormPage;
-338
View File
@@ -1,338 +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';
import { useAuth } from '../contexts/AuthContext';
import { useProfile } from '../contexts/ProfileContext';
import { Preferences } from '@capacitor/preferences';
const SetupProfile: React.FC = () => {
const history = useHistory();
const { user } = useAuth();
const { setProfile, setStatus } = useProfile();
const [role, setRole] = useState<'buyer' | 'supplier' | ''>('');
const [fullName, setFullName] = useState('');
const [companyName, setCompanyName] = useState('');
const [phone, setPhone] = useState('');
const [city, setCity] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleProfileSetup = async (e: React.FormEvent) => {
e.preventDefault();
if (!user) return;
if (!role) {
showError('Please select a role');
return;
}
if (!fullName) {
showError('Please enter your full name');
return;
}
setLoading(true);
setError('');
const newProfile = {
id: user.id,
role: role as 'buyer' | 'supplier',
full_name: fullName,
company_name: companyName || null,
phone: phone || null,
city: city || null,
avatar_url: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
const { error: insertError } = await supabase
.from('profiles')
.insert(newProfile);
if (insertError) {
showError(insertError.message);
setLoading(false);
return;
}
await Preferences.set({
key: `profile_${user.id}`,
value: JSON.stringify(newProfile),
});
setProfile(newProfile);
setStatus('loaded');
setLoading(false);
history.replace('/home');
};
return (
<IonPage style={{ background: '#eef4ef' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': 'transparent' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Setup Profile
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': 'linear-gradient(180deg, #eef4ef 0%, #f8fbf8 100%)',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
background: 'transparent',
margin: '0 0 16px 0',
display: 'flex',
flexDirection: 'column',
gap: '4px',
}}
>
<h1
style={{
fontSize: '26px',
fontWeight: '700',
color: '#0f1720',
margin: '0',
}}
>
Welcome!
</h1>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
Complete your profile to get started.
</p>
</div>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleProfileSetup}
style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}
>
<label
style={{
fontSize: '14px',
fontWeight: '600',
color: '#0f1720',
}}
>
I want to...
</label>
<div
style={{
display: 'flex',
background: '#edf4ee',
borderRadius: '999px',
padding: '4px',
}}
>
<button
type="button"
onClick={() => setRole('buyer')}
style={{
flex: 1,
background: role === 'buyer' ? '#166534' : 'transparent',
color: role === 'buyer' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
}}
>
Buy Materials
</button>
<button
type="button"
onClick={() => setRole('supplier')}
style={{
flex: 1,
background: role === 'supplier' ? '#166534' : 'transparent',
color: role === 'supplier' ? '#ffffff' : '#14532d',
borderRadius: '999px',
padding: '12px 18px',
fontSize: '14px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
}}
>
Sell Materials
</button>
</div>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}
>
<input
type="text"
placeholder="Full Name"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
/>
<input
type="text"
placeholder="Company Name (Optional)"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
<input
type="text"
placeholder="City (Optional)"
value={city}
onChange={(e) => setCity(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
<input
type="tel"
placeholder="Phone (Optional)"
value={phone}
onChange={(e) => setPhone(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
/>
</div>
<button
type="submit"
disabled={loading || !role || !fullName}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || !role || !fullName ? 0.7 : 1,
marginTop: '4px',
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Complete Setup'
)}
</button>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default SetupProfile;
-434
View File
@@ -1,434 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useHistory, useParams, useLocation } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useAuth } from '../contexts/AuthContext';
interface LocationState {
mode?: 'create' | 'edit';
}
const SupplierQuoteForm: React.FC = () => {
const history = useHistory();
const { id } = useParams<{ id: string }>(); // in create mode: id is rfq_id; in edit mode: id is quotation_id
const location = useLocation<LocationState>();
const mode = location.state?.mode || 'create';
const { user } = useAuth();
const [rfqSummary, setRfqSummary] = useState<{
id: string;
referenceNumber: string;
title: string;
} | null>(null);
const [priceDisplay, setPriceDisplay] = useState('');
const [deliveryOption, setDeliveryOption] = useState('');
const [note, setNote] = useState('');
const [existingQuotationId, setExistingQuotationId] = useState<string | null>(
null
);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
loadQuoteFormData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, mode]);
const loadQuoteFormData = async () => {
if (!user) return;
setLoading(true);
setError('');
try {
if (mode === 'edit') {
// id is quotation_id
const { data: quote, error: qErr } = await supabase
.from('quotations')
.select('*, rfqs(id, reference_number, title)')
.eq('id', id)
.single();
if (qErr) throw qErr;
setExistingQuotationId(quote.id);
setPriceDisplay(quote.price_amount.toString());
setDeliveryOption(quote.delivery_option);
setNote(quote.note || '');
setRfqSummary({
id: quote.rfqs.id,
referenceNumber: quote.rfqs.reference_number,
title: quote.rfqs.title,
});
} else {
// id is rfq_id
const { data: rfq, error: rfqErr } = await supabase
.from('rfqs')
.select('id, reference_number, title')
.eq('id', id)
.single();
if (rfqErr) throw rfqErr;
setRfqSummary({
id: rfq.id,
referenceNumber: rfq.reference_number,
title: rfq.title,
});
// Check if there is already a quote (just in case they navigated strangely)
const { data: quote } = await supabase
.from('quotations')
.select('*')
.eq('rfq_id', id)
.eq('supplier_id', user.id)
.maybeSingle();
if (quote) {
setExistingQuotationId(quote.id);
setPriceDisplay(quote.price_amount.toString());
setDeliveryOption(quote.delivery_option);
setNote(quote.note || '');
}
}
} catch (err: any) {
console.error(err);
setError('Failed to load form data.');
} finally {
setLoading(false);
}
};
const sanitizePriceInput = (val: string) => {
let sanitized = val.replace(/[^0-9.]/g, '');
const parts = sanitized.split('.');
if (parts.length > 2) {
sanitized = parts[0] + '.' + parts.slice(1).join('');
}
if (parts.length === 2 && parts[1].length > 2) {
sanitized = parts[0] + '.' + parts[1].substring(0, 2);
}
setPriceDisplay(sanitized);
};
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleSaveQuote = async (e: React.FormEvent) => {
e.preventDefault();
if (!user || !rfqSummary) return;
const amount = parseFloat(priceDisplay);
if (isNaN(amount) || amount < 0) {
showError('Please enter a valid amount.');
return;
}
if (!deliveryOption.trim()) {
showError('Please enter a delivery option.');
return;
}
setSaving(true);
setError('');
try {
if (existingQuotationId) {
const { error: updErr } = await supabase
.from('quotations')
.update({
price_amount: amount,
delivery_option: deliveryOption.trim(),
note: note.trim() || null,
updated_at: new Date().toISOString(),
})
.eq('id', existingQuotationId);
if (updErr) throw updErr;
} else {
const { error: insErr } = await supabase.from('quotations').insert({
rfq_id: rfqSummary.id,
supplier_id: user.id,
price_amount: amount,
currency_code: 'USD',
delivery_option: deliveryOption.trim(),
note: note.trim() || null,
status: 'submitted',
});
if (insErr) throw insErr;
}
history.replace(`/rfq/${rfqSummary.id}`);
} catch (err: any) {
console.error(err);
showError(err.message || 'Failed to save quotation.');
setSaving(false);
}
};
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
{existingQuotationId ? 'Update Quote' : 'Submit Quote'}
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
{loading ? (
<div
style={{
display: 'flex',
justifyContent: 'center',
padding: '40px',
}}
>
<IonSpinner name="crescent" style={{ color: '#166534' }} />
</div>
) : (
<>
{rfqSummary && (
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '20px',
margin: '0 0 12px',
display: 'flex',
flexDirection: 'column',
gap: '8px',
}}
>
<div
style={{
fontSize: '12px',
fontWeight: '700',
color: '#b45309',
background: 'rgba(245,158,11,0.14)',
borderRadius: '999px',
padding: '4px 10px',
width: 'max-content',
}}
>
{rfqSummary.referenceNumber}
</div>
<div
style={{
fontSize: '16px',
fontWeight: '600',
color: '#0f1720',
}}
>
{rfqSummary.title}
</div>
</div>
)}
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
marginBottom: '12px',
}}
>
{error}
</div>
)}
<form
onSubmit={handleSaveQuote}
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Total Price (USD)
</label>
<div
style={{
position: 'relative',
display: 'flex',
alignItems: 'center',
}}
>
<span
style={{
position: 'absolute',
left: '14px',
fontSize: '15px',
color: '#0f1720',
fontWeight: '600',
}}
>
$
</span>
<input
type="text"
inputMode="decimal"
placeholder="0.00"
value={priceDisplay}
onChange={(e) => sanitizePriceInput(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px 0 32px',
height: '48px',
fontSize: '15px',
fontWeight: '600',
color: '#0f1720',
width: '100%',
}}
required
/>
</div>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Delivery Option
</label>
<input
type="text"
placeholder="e.g. Free delivery in 2 days"
value={deliveryOption}
onChange={(e) => setDeliveryOption(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
/>
</div>
<div
style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}
>
<label
style={{
fontSize: '13px',
fontWeight: '600',
color: '#0f1720',
}}
>
Note for Buyer (Optional)
</label>
<textarea
placeholder="Add any conditions or details..."
value={note}
onChange={(e) => setNote(e.target.value)}
rows={4}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '14px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
resize: 'vertical',
}}
/>
</div>
<button
type="submit"
disabled={saving || !priceDisplay || !deliveryOption}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: saving || !priceDisplay || !deliveryOption ? 0.7 : 1,
marginTop: '8px',
}}
>
{saving ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : existingQuotationId ? (
'Update Quote'
) : (
'Submit Quote'
)}
</button>
</form>
</>
)}
</IonContent>
</IonPage>
);
};
export default SupplierQuoteForm;
-306
View File
@@ -1,306 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { IonPage, IonContent, IonSpinner, IonIcon } from '@ionic/react';
import { arrowBackOutline, checkmarkCircle } from 'ionicons/icons';
import { supabase } from '../supabase';
import OtpInput from '../components/OtpInput';
interface LocationState {
email?: string;
resent?: boolean;
}
const VerifyEmail: React.FC = () => {
const history = useHistory();
const location = useLocation<LocationState>();
const email = location.state?.email || '';
const resent = location.state?.resent || false;
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [cooldown, setCooldown] = useState(resent ? 60 : 0);
const [verified, setVerified] = useState(false);
useEffect(() => {
if (!email) {
history.replace('/auth');
}
}, [email, history]);
useEffect(() => {
if (cooldown > 0) {
const timer = setTimeout(() => setCooldown(cooldown - 1), 1000);
return () => clearTimeout(timer);
}
}, [cooldown]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleVerifyOtp = async (e: React.FormEvent) => {
e.preventDefault();
if (code.length !== 6) {
showError('Please enter the 6-digit code');
return;
}
setLoading(true);
setError('');
const { error } = await supabase.auth.verifyOtp({
email,
token: code,
type: 'email',
});
if (error) {
showError(error.message);
setLoading(false);
return;
}
setVerified(true);
setLoading(false);
};
const handleResend = async () => {
if (cooldown > 0) return;
const { error } = await supabase.auth.resend({
type: 'signup',
email,
});
if (error) {
showError(error.message);
} else {
setCooldown(60);
}
};
const handleBackToSignIn = () => {
history.replace('/auth');
};
if (!email) return null;
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '0px',
'--padding-end': '0px',
'--padding-top': '0px',
'--padding-bottom': '0px',
}}
>
<div
style={{
padding:
'calc(var(--ion-safe-area-top, 0px) + 18px) 20px calc(var(--ion-safe-area-bottom, 0px) + 28px)',
minHeight: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
<div
style={{
background: 'transparent',
padding: '0',
margin: '0 0 20px 0',
display: 'flex',
}}
>
<button
onClick={() => history.goBack()}
style={{
background: 'transparent',
border: 'none',
padding: '0',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
color: '#14532d',
}}
>
<IonIcon icon={arrowBackOutline} style={{ fontSize: '24px' }} />
</button>
</div>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
{verified ? (
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '20px',
alignItems: 'center',
textAlign: 'center',
padding: '20px 0',
}}
>
<IonIcon
icon={checkmarkCircle}
style={{ fontSize: '64px', color: '#166534' }}
/>
<div
style={{
background: 'rgba(22,101,52,0.10)',
borderRadius: '12px',
padding: '14px',
width: '100%',
}}
>
<span
style={{
color: '#14532d',
fontSize: '14px',
fontWeight: '600',
}}
>
Email confirmed. You can now sign in.
</span>
</div>
<button
onClick={handleBackToSignIn}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
width: '100%',
cursor: 'pointer',
}}
>
Back to Sign In
</button>
</div>
) : (
<>
<div>
<div
style={{
fontSize: '24px',
fontWeight: '700',
color: '#0f1720',
lineHeight: '1.15',
}}
>
Verify your email
</div>
<div
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
lineHeight: '1.55',
marginTop: '8px',
}}
>
We sent a 6-digit code to <strong>{email}</strong>. Enter it
below to confirm your account.
</div>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleVerifyOtp}
style={{
display: 'flex',
flexDirection: 'column',
gap: '20px',
}}
>
<OtpInput
value={code}
onChange={setCode}
disabled={loading}
/>
<button
type="submit"
disabled={loading || code.length !== 6}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || code.length !== 6 ? 0.7 : 1,
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Verify'
)}
</button>
</form>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<button
type="button"
onClick={handleResend}
disabled={cooldown > 0}
style={{
background: 'transparent',
border: 'none',
padding: '0',
fontSize: '14px',
fontWeight: '600',
color: cooldown > 0 ? '#8a978f' : '#f59e0b',
cursor: cooldown > 0 ? 'default' : 'pointer',
}}
>
{cooldown > 0
? `Resend code in ${cooldown}s`
: 'Resend code'}
</button>
</div>
</>
)}
</div>
</div>
</IonContent>
</IonPage>
);
};
export default VerifyEmail;
+275
View File
@@ -0,0 +1,275 @@
import React, { useState, useRef, useEffect } from 'react';
import {
IonContent,
IonPage,
IonInput,
IonButton,
IonSpinner,
IonIcon,
IonText,
} from '@ionic/react';
import { chevronBackOutline } from 'ionicons/icons';
import { useHistory, useLocation } from 'react-router-dom';
import { supabase } from '../supabase';
interface LocationState {
email: string;
type?: 'signup' | 'recovery';
resent?: boolean;
}
const VerifyEmailPage: React.FC = () => {
const history = useHistory();
const location = useLocation<LocationState>();
const email = location.state?.email || '';
const type = location.state?.type || 'signup';
const [digits, setDigits] = useState<string[]>(['', '', '', '', '', '']);
const [submitting, setSubmitting] = useState(false);
const [resending, setResending] = useState(false);
const [cooldown, setCooldown] = useState(location.state?.resent ? 60 : 0);
const [message, setMessage] = useState<string | null>(null);
const [messageType, setMessageType] = useState<'error' | 'success'>('error');
const inputRefs = useRef<HTMLIonInputElement[]>([]);
useEffect(() => {
if (cooldown > 0) {
const timer = setInterval(() => {
setCooldown((c) => c - 1);
}, 1000);
return () => clearInterval(timer);
}
}, [cooldown]);
const showMessage = (msg: string, type: 'error' | 'success' = 'error') => {
setMessage(msg);
setMessageType(type);
setTimeout(() => setMessage(null), 4000);
};
const handleDigitChange = (index: number, value: string) => {
const newDigits = [...digits];
// Only take the last character (for overwriting)
const val = value.slice(-1);
if (val && !/^\d+$/.test(val)) return;
newDigits[index] = val;
setDigits(newDigits);
if (val && index < 5) {
inputRefs.current[index + 1]?.setFocus();
}
};
const handleKeyDown = (index: number, e: any) => {
if (e.key === 'Backspace' && !digits[index] && index > 0) {
inputRefs.current[index - 1]?.setFocus();
}
};
const handleVerify = async () => {
const code = digits.join('');
if (code.length < 6) {
showMessage('Please enter the 6-digit code');
return;
}
setSubmitting(true);
setMessage(null);
try {
const { data, error } = await supabase.auth.verifyOtp({
email,
token: code,
type: (type === 'recovery' ? 'recovery' : 'signup') as any,
});
if (error) throw error;
if (type === 'recovery') {
history.push('/new-password');
} else {
history.push('/home');
}
} catch (err: any) {
showMessage(err.message || 'Invalid or expired code');
} finally {
setSubmitting(false);
}
};
const handleResend = async () => {
if (cooldown > 0) return;
setResending(true);
try {
const { error } = await supabase.auth.resend({
type: (type === 'recovery' ? 'recovery' : 'signup') as any,
email,
});
if (error) throw error;
showMessage('A new code has been sent', 'success');
setCooldown(60);
} catch (err: any) {
showMessage(err.message || 'Failed to resend code');
} finally {
setResending(false);
}
};
return (
<IonPage>
<IonContent
fullscreen
style={{
'--background':
'linear-gradient(160deg, rgba(199,210,254,0.52) 0%, #f0f4ff 58%, #f8fafc 100%)',
}}
>
<div className="auth-shell">
<IonButton
fill="clear"
color="dark"
onClick={() => history.push('/auth')}
style={{
position: 'absolute',
top: 'calc(var(--ion-safe-area-top, 0px) + 8px)',
left: '8px',
'--padding-start': '8px',
'--padding-end': '8px',
zIndex: 10,
}}
>
<div
style={{
background: '#ffffff',
width: '44px',
height: '44px',
borderRadius: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonIcon icon={chevronBackOutline} />
</div>
</IonButton>
<div style={{ marginTop: '80px' }}>
<h1
className="bold"
style={{ fontSize: '24px', margin: '0 0 8px 0' }}
>
Verify your email
</h1>
<p
className="secondary-text"
style={{ margin: '0', fontSize: '14px' }}
>
We've sent a 6-digit code to <span className="bold">{email}</span>
</p>
</div>
<div className="auth-card">
<div
style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}
>
{digits.map((digit, i) => (
<div
key={i}
style={{
width: '44px',
height: '52px',
background: '#e8edf8',
borderRadius: '12px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<IonInput
ref={(el) => {
inputRefs.current[i] = el!;
}}
value={digit}
onIonInput={(e) => handleDigitChange(i, e.detail.value!)}
onKeyDown={(e) => handleKeyDown(i, e)}
type="text"
inputMode="numeric"
style={{
textAlign: 'center',
fontSize: '22px',
fontWeight: '700',
color: '#111827',
}}
/>
</div>
))}
</div>
{message && (
<div
style={{
background:
messageType === 'error'
? 'var(--color-danger-soft)'
: 'var(--color-success-soft)',
color:
messageType === 'error'
? 'var(--ion-color-danger-shade)'
: 'var(--ion-color-success-shade)',
padding: '12px',
borderRadius: '12px',
fontSize: '13px',
textAlign: 'center',
}}
>
{message}
</div>
)}
<IonButton
expand="block"
className="bold"
style={{
height: '52px',
'--border-radius': 'var(--radius-pill)',
marginTop: '16px',
}}
disabled={submitting}
onClick={handleVerify}
>
{submitting ? <IonSpinner name="crescent" /> : 'Verify code'}
</IonButton>
<div style={{ textAlign: 'center', marginTop: '8px' }}>
<IonText
color={cooldown > 0 ? 'medium' : 'primary'}
className="semibold"
style={{
fontSize: '13px',
cursor: cooldown > 0 ? 'default' : 'pointer',
}}
onClick={handleResend}
>
{resending ? (
<IonSpinner name="dots" />
) : cooldown > 0 ? (
`Resend in ${cooldown}s`
) : (
'Resend code'
)}
</IonText>
</div>
</div>
</div>
</IonContent>
</IonPage>
);
};
export default VerifyEmailPage;
-311
View File
@@ -1,311 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import {
IonPage,
IonHeader,
IonToolbar,
IonButtons,
IonButton,
IonIcon,
IonTitle,
IonContent,
IonSpinner,
} from '@ionic/react';
import { chevronBackOutline, eyeOutline, eyeOffOutline } from 'ionicons/icons';
import { supabase } from '../supabase';
import { useProfileLoader } from '../hooks/useProfileLoader';
import OtpInput from '../components/OtpInput';
interface LocationState {
email?: string;
}
const VerifyReset: React.FC = () => {
const history = useHistory();
const location = useLocation<LocationState>();
const email = location.state?.email || '';
const { loadProfileAndNavigate } = useProfileLoader();
const [code, setCode] = useState('');
const [newPassword, setNewPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [cooldown, setCooldown] = useState(60);
const [overlayVisible, setOverlayVisible] = useState(false);
const [overlayError, setOverlayError] = useState(false);
useEffect(() => {
if (!email) {
history.replace('/forgot-password');
}
}, [email, history]);
useEffect(() => {
if (cooldown > 0) {
const timer = setTimeout(() => setCooldown(cooldown - 1), 1000);
return () => clearTimeout(timer);
}
}, [cooldown]);
const showError = (msg: string) => {
setError(msg);
setTimeout(() => setError(''), 4000);
};
const handleVerifyReset = async (e: React.FormEvent) => {
e.preventDefault();
if (code.length !== 6) {
showError('Please enter the 6-digit code');
return;
}
if (newPassword.length < 6) {
showError('Password must be at least 6 characters');
return;
}
setLoading(true);
setError('');
const { error: verifyError } = await supabase.auth.verifyOtp({
email,
token: code,
type: 'recovery',
});
if (verifyError) {
showError(verifyError.message);
setLoading(false);
return;
}
const { error: updateError } = await supabase.auth.updateUser({
password: newPassword,
});
if (updateError) {
showError(updateError.message);
setLoading(false);
return;
}
// Success -> load profile and navigate
loadProfileAndNavigate(setOverlayVisible, setOverlayError);
};
const handleResend = async () => {
if (cooldown > 0) return;
const { error } = await supabase.auth.resetPasswordForEmail(email);
if (error) {
showError(error.message);
} else {
setCooldown(60);
}
};
if (!email) return null;
return (
<IonPage style={{ background: '#f7faf7' }}>
<IonHeader className="ion-no-border">
<IonToolbar style={{ '--background': '#f7faf7' }}>
<IonButtons slot="start">
<IonButton
onClick={() => history.goBack()}
style={{ color: '#14532d' }}
>
<IonIcon icon={chevronBackOutline} slot="icon-only" />
</IonButton>
</IonButtons>
<IonTitle
style={{ fontSize: '18px', fontWeight: '700', color: '#0f1720' }}
>
Set New Password
</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent
style={{
'--background': '#f7faf7',
'--padding-start': '20px',
'--padding-end': '20px',
'--padding-top': '20px',
'--padding-bottom': 'calc(28px + var(--ion-safe-area-bottom))',
}}
>
<div
style={{
background: '#ffffff',
borderRadius: '24px',
padding: '24px',
margin: '0',
display: 'flex',
flexDirection: 'column',
gap: '18px',
}}
>
<div>
<h2
style={{
fontSize: '22px',
fontWeight: '700',
color: '#0f1720',
margin: '0 0 8px 0',
}}
>
Enter code
</h2>
<p
style={{
fontSize: '14px',
fontWeight: '400',
color: '#5f6d63',
margin: '0',
}}
>
We sent a 6-digit code to <strong>{email}</strong>.
</p>
</div>
{error && (
<div
style={{
background: 'rgba(239, 68, 68, 0.10)',
borderRadius: '12px',
padding: '12px 14px',
fontSize: '13px',
fontWeight: '500',
color: '#b91c1c',
}}
>
{error}
</div>
)}
<form
onSubmit={handleVerifyReset}
style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}
>
<OtpInput value={code} onChange={setCode} disabled={loading} />
<div style={{ position: 'relative' }}>
<input
type={showPassword ? 'text' : 'password'}
placeholder="New password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
style={{
background: '#f4f7f4',
border: 'none',
borderRadius: '12px',
padding: '0 40px 0 14px',
height: '48px',
fontSize: '15px',
fontWeight: '400',
color: '#0f1720',
width: '100%',
}}
required
minLength={6}
/>
<IonIcon
icon={showPassword ? eyeOffOutline : eyeOutline}
onClick={() => setShowPassword(!showPassword)}
style={{
position: 'absolute',
right: '14px',
top: '14px',
fontSize: '20px',
color: '#8a978f',
cursor: 'pointer',
}}
/>
</div>
<button
type="submit"
disabled={loading || code.length !== 6 || !newPassword}
style={{
background: '#166534',
color: '#ffffff',
borderRadius: '999px',
padding: '16px 20px',
fontSize: '15px',
fontWeight: '700',
border: 'none',
cursor: 'pointer',
opacity: loading || code.length !== 6 || !newPassword ? 0.7 : 1,
}}
>
{loading ? (
<IonSpinner
name="crescent"
style={{ color: '#fff', width: '20px', height: '20px' }}
/>
) : (
'Reset Password'
)}
</button>
</form>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<button
type="button"
onClick={handleResend}
disabled={cooldown > 0}
style={{
background: 'transparent',
border: 'none',
padding: '0',
fontSize: '14px',
fontWeight: '600',
color: cooldown > 0 ? '#8a978f' : '#f59e0b',
cursor: cooldown > 0 ? 'default' : 'pointer',
}}
>
{cooldown > 0 ? `Resend code in ${cooldown}s` : 'Resend code'}
</button>
</div>
</div>
{overlayVisible && (
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
background: 'rgba(255,255,255,0.9)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
zIndex: 9999,
}}
>
{overlayError ? (
<div
style={{
color: '#b91c1c',
fontSize: '15px',
fontWeight: '600',
}}
>
Error updating profile.
</div>
) : (
<IonSpinner name="crescent" style={{ color: '#166534' }} />
)}
</div>
)}
</IonContent>
</IonPage>
);
};
export default VerifyReset;
+2 -2
View File
@@ -2,6 +2,6 @@ import { createClient } from '@supabase/supabase-js';
import type { Database } from './database.types'; import type { Database } from './database.types';
export const supabase = createClient<Database>( export const supabase = createClient<Database>(
'https://ilffyqxtkssvqmszsfyw.supabase.co', 'https://sxdbfylkgcfmsatqipli.supabase.co',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImlsZmZ5cXh0a3NzdnFtc3pzZnl3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODE5MDQ2NTIsImV4cCI6MjA5NzQ4MDY1Mn0.xvCQEtNrr74KX8uD7enFktfFJhuFrSm6kFih1SlLFgk', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InN4ZGJmeWxrZ2NmbXNhdHFpcGxpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODExMTI5NjcsImV4cCI6MjA5NjY4ODk2N30.8ZvpjRBskCIH3FFnOkWsxZCOwNMX5txinffgXMDinKI',
); );
+276 -99
View File
@@ -1,114 +1,291 @@
/* Ionic CSS Variables */ /* ShopKeep — Custom Palette & Shared Styles */
:root { :root {
/** primary (QuoteLink forest green) **/ /** ShopKeep Brand Palette **/
--ion-color-primary: #166534; --ion-color-primary: #6366f1;
--ion-color-primary-rgb: 22, 101, 52; --ion-color-primary-rgb: 99, 102, 241;
--ion-color-primary-contrast: #ffffff; --ion-color-primary-contrast: #ffffff;
--ion-color-primary-contrast-rgb: 255, 255, 255; --ion-color-primary-contrast-rgb: 255, 255, 255;
--ion-color-primary-shade: #14532d; --ion-color-primary-shade: #5759d4;
--ion-color-primary-tint: #2b7a45; --ion-color-primary-tint: #7375f2;
/** secondary (logo price-tag orange) **/ --ion-color-secondary: #818cf8;
--ion-color-secondary: #f7931a; --ion-color-secondary-rgb: 129, 140, 248;
--ion-color-secondary-rgb: 247, 147, 26;
--ion-color-secondary-contrast: #ffffff; --ion-color-secondary-contrast: #ffffff;
--ion-color-secondary-contrast-rgb: 255, 255, 255; --ion-color-secondary-contrast-rgb: 255, 255, 255;
--ion-color-secondary-shade: #d97d12; --ion-color-secondary-shade: #727bda;
--ion-color-secondary-tint: #f9a640; --ion-color-secondary-tint: #8e98f9;
--color-brand: #166534; --ion-color-tertiary: #c7d2fe;
--color-brand-strong: #14532d; --ion-color-tertiary-rgb: 199, 210, 254;
--color-brand-soft: rgba(22, 101, 52, 0.1); --ion-color-tertiary-contrast: #111827;
--color-brand-medium: rgba(22, 101, 52, 0.18); --ion-color-tertiary-contrast-rgb: 17, 24, 39;
--color-accent: #f7931a; --ion-color-tertiary-shade: #afb9e0;
--color-accent-strong: #ea8200; --ion-color-tertiary-tint: #cdd7fe;
--color-accent-soft: rgba(247, 147, 26, 0.14);
--color-bg: #f3f4f1; --ion-color-success: #3aa67a;
--color-bg-gradient: linear-gradient( --ion-color-success-rgb: 58, 166, 122;
180deg, --ion-color-success-contrast: #ffffff;
#eef1ee 0%, --ion-color-success-contrast-rgb: 255, 255, 255;
#f7f8f5 52%, --ion-color-success-shade: #33926b;
#fbfcfa 100% --ion-color-success-tint: #4eb088;
);
--ion-color-danger: #cf6679;
--ion-color-danger-rgb: 207, 102, 121;
--ion-color-danger-contrast: #ffffff;
--ion-color-danger-contrast-rgb: 255, 255, 255;
--ion-color-danger-shade: #b65a6a;
--ion-color-danger-tint: #d57587;
--ion-color-light: #f3f5fb;
--ion-color-light-rgb: 243, 245, 251;
--ion-color-light-contrast: #111827;
--ion-color-light-contrast-rgb: 17, 24, 39;
--ion-color-light-shade: #d6d8dd;
--ion-color-light-tint: #f4f6fb;
/** App Custom Tokens **/
--color-bg: #f0f4ff;
--color-surface: #ffffff; --color-surface: #ffffff;
--color-surface-raised: #eef2ee; --color-surface-secondary: #e8edf8;
--color-surface-soft: #f7f8f6; --color-text-primary: #111827;
--color-text-primary: #18212b; --color-text-secondary: rgba(17, 24, 39, 0.6);
--color-text-secondary: rgba(24, 33, 43, 0.64); --color-text-tertiary: rgba(17, 24, 39, 0.38);
--color-text-tertiary: rgba(24, 33, 43, 0.42); --color-accent-soft: rgba(99, 102, 241, 0.18);
--color-border: rgba(23, 33, 43, 0.08); --color-success-soft: rgba(58, 166, 122, 0.12);
--color-success-soft: rgba(22, 101, 52, 0.12); --color-danger-soft: rgba(207, 102, 121, 0.12);
--color-success-text: #166534;
--color-warning-soft: rgba(247, 147, 26, 0.14);
--color-warning-text: #c36a00;
--color-danger-soft: rgba(220, 38, 38, 0.1);
--color-danger-text: #b91c1c;
--color-shell: rgba(255, 255, 255, 0.58);
--color-shadow-lg:
0 24px 60px rgba(23, 33, 43, 0.08), 0 8px 20px rgba(23, 33, 43, 0.04);
--color-shadow-sm: 0 4px 16px rgba(23, 33, 43, 0.05);
/* Backwards-compatible aliases */ /** Radii **/
--color-surface-hover: var(--color-surface-soft); --radius-pill: 999px;
--color-text-main: var(--color-text-primary); --radius-card: 24px;
--color-text-muted: var(--color-text-secondary); --radius-inner: 12px;
/* Basic Ionic variables */ /** Typography **/
--ion-background-color: var(--color-bg); --font-tabular: 'SF Mono', 'Roboto Mono', Menlo, monospace;
--ion-text-color: var(--color-text-primary); }
--ion-font-family: body {
Inter, -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'Roboto', background: var(--color-bg);
color: var(--color-text-primary);
font-family:
-apple-system, BlinkMacSystemFont, 'Inter', Roboto, Helvetica, Arial,
sans-serif; sans-serif;
} }
body.dark { /** Shared Auth Styles **/
--ion-color-primary: #0f3d2e; .auth-shell {
--ion-color-primary-rgb: 15, 61, 46; display: flex;
--ion-color-primary-contrast: #ffffff; flex-direction: column;
--ion-color-primary-contrast-rgb: 255, 255, 255; gap: 24px;
--ion-color-primary-shade: #0c3125; padding: calc(var(--ion-safe-area-top, 0px) + 18px) 20px
--ion-color-primary-tint: #295746; calc(var(--ion-safe-area-bottom, 0px) + 28px);
min-height: 100%;
--ion-color-secondary: #f57c00; }
--ion-color-secondary-rgb: 245, 124, 0;
--ion-color-secondary-contrast: #ffffff; .auth-card {
--ion-color-secondary-contrast-rgb: 255, 255, 255; background: var(--color-surface);
--ion-color-secondary-shade: #d66d00; border-radius: var(--radius-card);
--ion-color-secondary-tint: #f78f26; padding: 24px;
display: flex;
--color-brand: #0f3d2e; flex-direction: column;
--color-brand-strong: #145340; gap: 20px;
--color-brand-soft: rgba(15, 61, 46, 0.28); }
--color-brand-medium: rgba(15, 61, 46, 0.42);
--color-accent: #f57c00; /** Shared Form Styles **/
--color-accent-strong: #ff9831; .form-card {
--color-accent-soft: rgba(245, 124, 0, 0.18); background: var(--color-surface);
--color-bg: #121212; border-radius: var(--radius-card);
--color-bg-gradient: linear-gradient( padding: 20px;
180deg, display: flex;
#151515 0%, flex-direction: column;
#121212 55%, gap: 16px;
#101010 100% }
);
--color-surface: #1b1b1b; .form-field {
--color-surface-raised: #242424; display: flex;
--color-surface-soft: #202020; flex-direction: column;
--color-text-primary: #f4f4f4; }
--color-text-secondary: rgba(244, 244, 244, 0.72);
--color-text-tertiary: rgba(244, 244, 244, 0.48); .input-wrapper {
--color-border: rgba(255, 255, 255, 0.08); background: var(--color-surface-secondary);
--color-success-soft: rgba(29, 185, 84, 0.16); border-radius: var(--radius-inner);
--color-success-text: #78d29a; padding: 0 16px;
--color-warning-soft: rgba(245, 124, 0, 0.2); min-height: 52px;
--color-warning-text: #ffb15c; display: flex;
--color-danger-soft: rgba(255, 99, 99, 0.16); align-items: center;
--color-danger-text: #ff8f8f; }
--color-shell: rgba(33, 33, 33, 0.76);
--color-shadow-lg: .input-wrapper ion-input,
0 24px 60px rgba(0, 0, 0, 0.34), 0 8px 20px rgba(0, 0, 0, 0.22); .input-wrapper ion-textarea,
--color-shadow-sm: 0 4px 16px rgba(0, 0, 0, 0.24); .input-wrapper ion-select {
--padding-start: 0;
--ion-background-color: var(--color-bg); --padding-end: 0;
--ion-text-color: var(--color-text-primary); --placeholder-color: var(--color-text-tertiary);
--placeholder-opacity: 1;
color: var(--color-text-primary);
}
.money-input-container {
display: flex;
flex-direction: column;
}
/** Widget Styles **/
.widget-card {
background: var(--color-surface);
border-radius: var(--radius-card);
padding: 20px;
display: flex;
flex-direction: column;
}
.metric-pair-row {
display: flex;
gap: 12px;
margin-bottom: 12px;
}
.metric-pair-row .widget-card {
flex: 1;
padding: 16px;
}
.skeleton-text {
animation: skeleton-loading 1s linear infinite alternate;
}
@keyframes skeleton-loading {
0% {
background-color: var(--color-surface-secondary);
opacity: 0.5;
}
100% {
background-color: var(--color-surface-secondary);
opacity: 1;
}
}
/** Icon Containers **/
.icon-container {
width: 40px;
height: 40px;
border-radius: var(--radius-inner);
background: var(--color-accent-soft);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: var(--ion-color-primary);
}
.icon-container ion-icon {
font-size: 20px;
}
/** Tab Bar Styling **/
ion-tab-bar {
--background: var(--color-surface);
--border-width: 0;
height: calc(64px + var(--ion-safe-area-bottom));
padding-bottom: var(--ion-safe-area-bottom);
border-top-left-radius: var(--radius-card);
border-top-right-radius: var(--radius-card);
box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.04);
}
ion-tab-button {
--color: var(--color-text-tertiary);
--color-selected: var(--ion-color-primary);
}
ion-tab-button ion-label {
font-size: 11px;
font-weight: 600;
margin-top: 4px;
}
ion-tab-button ion-icon {
font-size: 24px;
}
/** Generic Utilities **/
.tabular {
font-family: var(--font-tabular);
}
.semibold {
font-weight: 600;
}
.bold {
font-weight: 700;
}
.tertiary-text {
color: var(--color-text-tertiary);
text-transform: uppercase;
font-size: 11px;
letter-spacing: 0.05em;
font-weight: 700;
}
.secondary-text {
color: var(--color-text-secondary);
font-size: 13px;
}
.pill-toggle {
background: var(--color-surface-secondary);
border-radius: var(--radius-pill);
display: flex;
padding: 4px;
gap: 4px;
}
.pill-toggle-btn {
flex: 1;
border-radius: var(--radius-pill);
height: 36px;
border: none;
font-size: 13px;
font-weight: 600;
color: var(--color-text-secondary);
background: transparent;
transition: all 0.2s ease;
}
.pill-toggle-btn.active {
background: var(--ion-color-primary);
color: #ffffff;
}
/** Page Spacing **/
.page-padding {
padding: 0 20px;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin: 24px 20px 12px;
}
.section-header h2 {
margin: 0;
font-size: 16px;
font-weight: 700;
color: var(--color-text-primary);
}
.section-header .see-all {
color: var(--ion-color-primary);
font-size: 13px;
font-weight: 600;
text-decoration: none;
}
/** Custom Searchbar **/
.custom-searchbar {
--padding-start: 0;
--padding-end: 0;
} }
+73
View File
@@ -0,0 +1,73 @@
/**
* Date utilities for ShopKeep.
*/
/**
* Returns today's date in YYYY-MM-DD format (local time).
*/
export const getTodayISO = (): string => {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
/**
* Formats a date string (YYYY-MM-DD) or ISO string for display.
*/
export const formatDisplayDate = (
dateStr: string,
options: Intl.DateTimeFormatOptions = {
month: 'short',
day: 'numeric',
year: 'numeric',
}
): string => {
if (!dateStr) return '';
const date = new Date(dateStr);
if (isNaN(date.getTime())) return dateStr;
return new Intl.DateTimeFormat('en-US', options).format(date);
};
/**
* Returns a relative date string (Today, Yesterday, or formatted date).
*/
export const formatRelativeDate = (dateStr: string): string => {
const today = getTodayISO();
const date = new Date(dateStr);
const dateISO = date.toISOString().split('T')[0];
if (dateISO === today) return 'Today';
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayISO = yesterday.toISOString().split('T')[0];
if (dateISO === yesterdayISO) return 'Yesterday';
return formatDisplayDate(dateStr);
};
/**
* Group items by date.
*/
export const groupItemsByDate = <T extends { date: string }>(
items: T[]
): { date: string; items: T[] }[] => {
const groups: Record<string, T[]> = {};
items.forEach((item) => {
if (!groups[item.date]) {
groups[item.date] = [];
}
groups[item.date].push(item);
});
return Object.keys(groups)
.sort((a, b) => b.localeCompare(a)) // Sort by date descending
.map((date) => ({
date,
items: groups[date],
}));
};

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