diff --git a/.env b/.env new file mode 100644 index 0000000..e803925 --- /dev/null +++ b/.env @@ -0,0 +1,3 @@ +# Set to true to fall back to mock data when backend responses are empty or offline +VITE_USE_MOCK_DATA=false + diff --git a/BACKEND_SPEC.md b/BACKEND_SPEC.md index 6722985..2f3fb31 100644 --- a/BACKEND_SPEC.md +++ b/BACKEND_SPEC.md @@ -4680,3 +4680,30 @@ node scripts/verify-backend-spec.mjs 3. **20 Canonical Data Entities:** All 20 canonical relational models defined with complete field definitions and PostgreSQL DDL. 4. **Exhaustive REST Endpoints:** At least 62 RESTful endpoint contracts documented across all 13 functional domains with full JSON schemas and examples. 5. **Real Concrete Fixtures:** Every endpoint example and mock schema reflects authentic data from the frontend design tokens and mock catalogs. + + +### 7.3 Production Integration & Flutter WebView Bridge Module Citations + +The production SPA integration inside `src/` adds parameterized routing, live Habib Django REST API bindings (`/api/shop/*`), global shopping cart and account state hydration, interactive overlay bottom sheets, and full `window.FlutterChannel` host bridge parity (`web_ready`, `HABIB_TOKEN`, `HABIB_COINS`, `HABIB_VIEW_PADDINGS`, `handleBackButton`, `buy_coin`, `pick_manual_location`, `upload_file`, and `open_external_url`). Every production source module in `src/` is mapped below: + +| Source File Path | Architectural Role & Backend / Host Integration Responsibility | +|---|---| +| `src/types/window.d.ts` | Global TypeScript declarations for `window.FlutterChannel`, `window.HABIB_TOKEN`, `window.HABIB_COINS`, `window.HABIB_VIEW_PADDINGS`, `window.onFlutterResponse`, and `window.handleBackButton`. | +| `src/lib/cookies.ts` | Cookie persistence utilities managing `HABIB_TOKEN`, `USER_LANGUAGE`, and guest cart session token `HABIB_SHOP_GUEST`. | +| `src/lib/auth-bridge.ts` | Habib host authentication token resolver (`getToken`), asynchronous Flutter login handshake (`ensureToken`), and local session sign-out helper (`signOutLocal`). | +| `src/lib/view-paddings.ts` | Safe-area inset listener binding `window.HABIB_VIEW_PADDINGS` and `habib:view-paddings-changed` events to CSS custom properties `--safe-top` through `--safe-left`. | +| `src/lib/webview-actions.ts` | Typed Flutter WebView bridge actions for `close`, `open_external_url`, `copy_to_clipboard`, `download_file`, `buy_coin`, `pick_manual_location`, and `upload_file`. | +| `src/lib/routes.ts` | Parameterized production URL builders (`ROUTES`) and `?bare=1` / `?embed=1` Figma snapshot detection (`isBareMode`). | +| `src/lib/http.ts` | Fetch client (`shopRequest`) injecting `Authorization: Token `, `X-Shop-Session: `, and `Accept-Language: ` headers plus media URL resolution (`resolveMediaUrl`). | +| `src/lib/shopApi.ts` | Strongly typed TypeScript API client covering home feed, categories, products, reviews, store booths, cart, promo codes, shipping/payment methods, orders, shipment tracking, profile, addresses, bookmarks, provider requests, support tickets, and store chat. | +| `src/lib/mappers.ts` | Pure data adapters transforming backend REST DTOs into the UI presentation props consumed by `CompactProductCard`, `GridProductCard`, `CategoryCard`, `AddressCard`, `OrderListCard`, and `ShipmentOrderCard`. | +| `src/hooks/use-hardware-back-handler.ts` | LIFO Android hardware back-button handler stack invoked by `window.handleBackButton()` so open bottom sheets close before route history pops. | +| `src/hooks/use-habib-web-ready.ts` | Lifecycle hook posting `{ action: "web_ready" }` to `window.FlutterChannel` after initial hydration and double `requestAnimationFrame` paint. | +| `src/hooks/useSmartBack.ts` | Safe in-app back navigation hook tracking internal SPA transitions and falling back to deterministic parent routes on deep-linked entry. | +| `src/context/ShopAppContext.tsx` | Application-wide React context hydrating guest/authenticated cart, saved addresses, shipping/payment selections, bookmarks, shopper profile, order counters, Habib Coin balance, language preference, and toast notifications. | +| `src/components/bridge/HabibBridgeProviders.tsx` | Root router-level bridge provider installing global hardware back handling, safe-area padding synchronization, scroll restoration, and status toasts. | +| `src/components/modals/OrderSummarySheet.tsx` | True overlay bottom sheet for `/cart` order pricing breakdown and promo code application, registered on the LIFO hardware back stack. | +| `src/components/modals/PaymentMethodsSheet.tsx` | True overlay bottom sheet for `/checkout/review` payment method selection including live Habib Coins balance validation. | +| `src/components/modals/AddressFormSheet.tsx` | True overlay bottom sheet for `/checkout/shipping` and `/account/addresses` address creation/editing with optional Flutter `pick_manual_location` pin selection. | +| `src/components/modals/ShipmentTrackingSheet.tsx` | True overlay bottom sheet for `/orders/:orderId` carrier tracking code copy and chronological shipment milestone timeline. | +| `src/components/common/ShimmerSkeletons.tsx` | Geometry-matched shimmer skeleton loaders (`HomeFeedShimmer`, `CategoryGridShimmer`, `ProductGridShimmer`, `ProductDetailBodyShimmer`, `StoreBoothBodyShimmer`, `OrdersListShimmer`, `OrderDetailShimmer`, `ChatThreadShimmer`, `CartItemsShimmer`), tactile `InlineSpinner`, and network `RetryBanner`. | diff --git a/index.html b/index.html index 00c76a0..6f21d73 100644 --- a/index.html +++ b/index.html @@ -3,14 +3,301 @@ - - Habib Shop - - - + Habib Shop +
diff --git a/package-lock.json b/package-lock.json index 79d1342..30d4832 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "habib-shop", "version": "0.0.0", "dependencies": { + "@tanstack/react-query": "^5.105.1", "react": "^19.3.1", "react-dom": "^19.3.1", "react-router-dom": "^7.18.5" @@ -984,6 +985,38 @@ "dev": true, "license": "MIT" }, + "node_modules/@tanstack/query-core": { + "version": "5.105.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.105.1.tgz", + "integrity": "sha512-B/rNlZoZ54w1dlddiUt9oEe1SLM+37c00SKLJEg9YH+7as3Y54P81o9Fh+2ujZ36tXPnQJ5oVe7AcyEWkyFhPg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.105.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.105.1.tgz", + "integrity": "sha512-qcu+/+PtBOjW8qU4/0l47QVmNG7hPOWsCLzP0bTRhE1X7HYa757C4732wXTUH0QhCjTV1yedX8onsCiEwlNYrA==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.105.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1043,7 +1076,7 @@ "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "csstype": "^3.2.2" @@ -1531,7 +1564,7 @@ "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, + "devOptional": true, "license": "MIT" }, "node_modules/debug": { diff --git a/package.json b/package.json index b61579e..7a58cbe 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "preview": "vite preview" }, "dependencies": { + "@tanstack/react-query": "^5.105.1", "react": "^19.3.1", "react-dom": "^19.3.1", "react-router-dom": "^7.18.5" diff --git a/src/App.tsx b/src/App.tsx index d8a072c..255f1b4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,11 @@ import React from 'react'; +import { QueryClientProvider } from '@tanstack/react-query'; import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; +import { ShopAppProvider } from './context/ShopAppContext'; +import { HabibBridgeProviders } from './components/bridge/HabibBridgeProviders'; +import { shopQueryClient } from './lib/shopQueries'; + // Home & Discovery import { ShopHomePage } from './pages/home/ShopHomePage'; import { ShopCategoryPage } from './pages/catalog/ShopCategoryPage'; @@ -38,73 +43,140 @@ import { TestDirectoryPage } from './pages/test/TestDirectoryPage'; export const App: React.FC = () => { return ( - - - {/* Test & QA Hub */} - } /> - - {/* 1. Home & Discovery */} - } /> - } /> - } /> - } /> - - {/* 2. Product & Store */} - } /> - } /> - } /> - - {/* 3. Cart & Checkout */} - } /> - } /> - } /> - } /> - } /> - } /> - - {/* 4. Orders & Support */} - } /> - } /> - } /> - - {/* 5. Account & Settings */} - } /> - } /> - } /> - } /> - } /> - - {/* 6. Standalone Nodes */} - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - } /> - - {/* Fallback */} - } /> - - + + + + + + {/* Test & QA Hub */} + } /> + + {/* ===================================================== */} + {/* Production Parameterized Routes */} + {/* ===================================================== */} + } /> + } /> + } + /> + } + /> + } /> + } /> + } /> + } /> + } /> + + {/* Cart & Checkout */} + } /> + } /> + } /> + } + /> + + {/* Orders & Support */} + } /> + } /> + } + /> + } /> + + {/* Account & Settings */} + } /> + } + /> + } /> + } /> + } /> + + {/* ===================================================== */} + {/* Legacy / Figma Design Showcase Routes (?bare=1 QA) */} + {/* ===================================================== */} + {/* 1. Home & Discovery */} + } /> + } /> + } /> + + {/* 2. Product & Store */} + } /> + } /> + } /> + + {/* 3. Cart & Checkout */} + } /> + } + /> + } /> + } /> + } + /> + } /> + + {/* 4. Orders & Support */} + } /> + } + /> + } /> + + {/* 5. Account & Settings */} + } /> + } + /> + } /> + } /> + } /> + + {/* 6. Standalone Nodes */} + } + /> + } + /> + } + /> + } + /> + } + /> + } + /> + } /> + + {/* Fallback */} + } /> + + + + + ); }; diff --git a/src/components/account/AccountMenuRow.tsx b/src/components/account/AccountMenuRow.tsx index 9c48bc7..3392e26 100644 --- a/src/components/account/AccountMenuRow.tsx +++ b/src/components/account/AccountMenuRow.tsx @@ -4,19 +4,22 @@ import type { AccountMenuRowItem } from '../../data/accountData'; interface AccountMenuRowProps { row: AccountMenuRowItem; + onClick?: () => void; } /** * Reusable menu row on `shop-category` Account Overview (4214:345) and `provider requst` (4214:10531). * - Dimensions: 317×34 at (29, row.y) */ -export const AccountMenuRow: React.FC = ({ row }) => { +export const AccountMenuRow: React.FC = ({ row, onClick }) => { const navigate = useNavigate(); return (
{ - if (row.targetRoute) { + if (onClick) { + onClick(); + } else if (row.targetRoute) { navigate(row.targetRoute); } }} @@ -26,7 +29,7 @@ export const AccountMenuRow: React.FC = ({ row }) => { display: 'flex', alignItems: 'center', gap: 9, - cursor: row.targetRoute ? 'pointer' : 'default', + cursor: onClick || row.targetRoute ? 'pointer' : 'default', minWidth: 0, }} > diff --git a/src/components/account/HabibCoinsBanner.tsx b/src/components/account/HabibCoinsBanner.tsx index 2e60a99..7521ef4 100644 --- a/src/components/account/HabibCoinsBanner.tsx +++ b/src/components/account/HabibCoinsBanner.tsx @@ -1,10 +1,45 @@ import React from 'react'; +import { useLocation } from 'react-router-dom'; +import { useShopApp } from '../../context/ShopAppContext'; +import { isBareMode } from '../../lib/routes'; +import { buyHabibCoinPackages, isInFlutterWebView } from '../../lib/webview-actions'; + +interface HabibCoinsBannerProps { + coinsCount?: number; + onBuyCoins?: () => void; +} /** * Habib Coins inventory banner on `provider requst` (4214:10558). * - Dimensions: 343×55 at (16, 692), radius 16.5, fill #fbfbfc, shadow 0px 2px 13px rgba(71, 85, 105, 0.1) */ -export const HabibCoinsBanner: React.FC = () => { +export const HabibCoinsBanner: React.FC = ({ + coinsCount, + onBuyCoins, +}) => { + const location = useLocation(); + const isBare = isBareMode(location.search); + const { habibCoinsBalance, setHabibCoinsBalance, showToast } = useShopApp(); + + const resolvedCoins = + coinsCount !== undefined ? coinsCount : isBare ? 21 : habibCoinsBalance; + + const handleBuyCoins = async () => { + if (onBuyCoins) { + onBuyCoins(); + return; + } + if (isInFlutterWebView()) { + const updated = await buyHabibCoinPackages(); + if (typeof updated === 'number') { + setHabibCoinsBalance(updated); + showToast(`Balance updated: ${updated} Habib Coins`); + } + return; + } + showToast('Open Habib mobile app to purchase coin packages'); + }; + return (
{ color: '#111111', }} > - 21 Habib Coins + {resolvedCoins} Habib Coins
@@ -62,6 +97,9 @@ export const HabibCoinsBanner: React.FC = () => { {/* "Buy Coins" button */} )} - + ); }; diff --git a/src/components/common/ShimmerSkeletons.tsx b/src/components/common/ShimmerSkeletons.tsx new file mode 100644 index 0000000..664750d --- /dev/null +++ b/src/components/common/ShimmerSkeletons.tsx @@ -0,0 +1,714 @@ +import React from 'react'; + +interface ShimmerBoxProps { + width?: number | string; + height?: number | string; + borderRadius?: number | string; + dark?: boolean; + style?: React.CSSProperties; +} + +export const ShimmerBox: React.FC = ({ + width = '100%', + height = 14, + borderRadius = 8, + dark = false, + style, +}) => ( + + ); +}; + diff --git a/src/components/modals/LoginRequiredModal.tsx b/src/components/modals/LoginRequiredModal.tsx new file mode 100644 index 0000000..ead71ac --- /dev/null +++ b/src/components/modals/LoginRequiredModal.tsx @@ -0,0 +1,188 @@ +import React from 'react'; +import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; +import { InlineSpinner } from '../common/ShimmerSkeletons'; + +export interface LoginRequiredModalProps { + isOpen: boolean; + title?: string; + description?: string; + isLoggingIn?: boolean; + onConfirmLogin: () => void; + onClose: () => void; +} + +/** + * Modal shown when an unauthenticated user triggers a feature that requires + * Habib authentication. Clicking "Log In" invokes the native Flutter login bridge + * (`window.HabibApp.postMessage(JSON.stringify({ action: 'login' }))`). + */ +export const LoginRequiredModal: React.FC = ({ + isOpen, + title = 'Sign in Required', + description = 'Please log in with your Habib account to continue.', + isLoggingIn = false, + onConfirmLogin, + onClose, +}) => { + useHardwareBackHandler(() => { + if (!isLoggingIn) { + onClose(); + } + return true; + }, isOpen); + + if (!isOpen) return null; + + return ( +
{ + if (!isLoggingIn) onClose(); + }} + style={{ + position: 'fixed', + inset: 0, + zIndex: 120, + backgroundColor: 'rgba(21, 28, 49, 0.52)', + backdropFilter: 'blur(3px)', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + padding: '24px 20px', + }} + > +
e.stopPropagation()} + style={{ + width: '100%', + maxWidth: 335, + borderRadius: 20, + backgroundColor: '#ffffff', + boxShadow: '0px 14px 36px rgba(17, 17, 17, 0.24)', + padding: '24px 20px 20px', + display: 'flex', + flexDirection: 'column', + alignItems: 'center', + textAlign: 'center', + gap: 14, + boxSizing: 'border-box', + }} + > + {/* Icon Badge */} +
+ +
+ + {/* Title */} +

+ {title} +

+ + {/* Description */} +

+ {description} +

+ + {/* Actions */} +
+ + + +
+
+
+ ); +}; + diff --git a/src/components/modals/OrderSummarySheet.tsx b/src/components/modals/OrderSummarySheet.tsx new file mode 100644 index 0000000..be9419f --- /dev/null +++ b/src/components/modals/OrderSummarySheet.tsx @@ -0,0 +1,195 @@ +import React, { useState } from 'react'; +import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; +import { InlineSpinner } from '../common/ShimmerSkeletons'; +import { OrderSummaryRows, type SummaryLineRow } from '../checkout/OrderSummaryRows'; + +interface OrderSummarySheetProps { + isOpen: boolean; + onClose: () => void; + rows: SummaryLineRow[]; + totalText: string; + promoCode?: string; + onApplyPromo?: (code: string) => Promise; + ctaText?: string; + onCtaClick?: () => void; +} + +export const OrderSummarySheet: React.FC = ({ + isOpen, + onClose, + rows, + totalText, + promoCode = '', + onApplyPromo, + ctaText = 'Got it', + onCtaClick, +}) => { + const [promoInput, setPromoInput] = useState(promoCode); + const [applying, setApplying] = useState(false); + + useHardwareBackHandler(() => { + onClose(); + return true; + }, isOpen); + + if (!isOpen) return null; + + const handlePromoSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + if (!onApplyPromo || applying) return; + setApplying(true); + try { + await onApplyPromo(promoInput.trim()); + } finally { + setApplying(false); + } + }; + + return ( +
+
e.stopPropagation()} + style={{ + padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', + display: 'flex', + flexDirection: 'column', + gap: '20px', + }} + > +
+ + Order Summary + + +
+ + + + {onApplyPromo && ( +
+ setPromoInput(e.target.value)} + placeholder="Promo code (e.g. HABIB10)" + style={{ + flex: 1, + height: '40px', + borderRadius: '11px', + backgroundColor: '#ffffff', + border: '1px solid #d7dbe2', + padding: '0 12px', + fontFamily: 'var(--font-sans)', + fontSize: '12px', + color: '#111111', + }} + /> + +
+ )} + + +
+
+ ); +}; + diff --git a/src/components/modals/PaymentMethodsSheet.tsx b/src/components/modals/PaymentMethodsSheet.tsx new file mode 100644 index 0000000..9073de2 --- /dev/null +++ b/src/components/modals/PaymentMethodsSheet.tsx @@ -0,0 +1,290 @@ +import React from 'react'; +import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; +import { EmptyStateBox, InlineSpinner } from '../common/ShimmerSkeletons'; +import { PaymentMethodCard } from '../checkout/PaymentMethodCard'; +import type { PaymentMethodItem } from '../../data/checkoutData'; +import { buyHabibCoinPackages, isInFlutterWebView } from '../../lib/webview-actions'; + +interface PaymentMethodsSheetProps { + isOpen: boolean; + onClose: () => void; + methods: PaymentMethodItem[]; + selectedMethodId: string; + onSelectMethod: (id: string) => void; + totalPriceText: string; + onConfirmPurchase: () => void; + isSubmitting?: boolean; + habibCoinsBalance?: number; + requiredCoins?: number; + onCoinsUpdated?: (coins: number) => void; +} + +export const PaymentMethodsSheet: React.FC = ({ + isOpen, + onClose, + methods, + selectedMethodId, + onSelectMethod, + totalPriceText, + onConfirmPurchase, + isSubmitting = false, + habibCoinsBalance = 21, + requiredCoins = 0, + onCoinsUpdated, +}) => { + useHardwareBackHandler(() => { + if (!isSubmitting) { + onClose(); + } + return true; + }, isOpen); + + if (!isOpen) return null; + + const isHabCoinSelected = + selectedMethodId === 'habcoin' || selectedMethodId === 'pm-habcoin'; + const needsMoreCoins = + isHabCoinSelected && requiredCoins > 0 && habibCoinsBalance < requiredCoins; + + const handleTopUpCoins = async () => { + if (isInFlutterWebView()) { + const updated = await buyHabibCoinPackages(); + if (typeof updated === 'number' && onCoinsUpdated) { + onCoinsUpdated(updated); + } + } + }; + + return ( +
{ + if (!isSubmitting) onClose(); + }} + style={{ + position: 'fixed', + inset: 0, + backgroundColor: 'rgba(17, 17, 17, 0.9)', + zIndex: 60, + display: 'flex', + flexDirection: 'column', + justifyContent: 'flex-end', + }} + > +
e.stopPropagation()} + style={{ + padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', + display: 'flex', + flexDirection: 'column', + gap: '20px', + }} + > + {/* Header & Close X Button */} +
+
+ Payment Methods +
+ + +
+ + {/* Payment Method Cards */} +
+ {methods.length > 0 ? ( + methods.map((method) => ( + onSelectMethod(method.id)} + /> + )) + ) : ( + + )} +
+ + {needsMoreCoins && ( +
+ + Need {requiredCoins} Habib Coins ({habibCoinsBalance} available) + + {isInFlutterWebView() && ( + + )} +
+ )} + + {/* "Purchase" CTA Button */} + +
+
+ ); +}; + diff --git a/src/components/modals/ShipmentTrackingSheet.tsx b/src/components/modals/ShipmentTrackingSheet.tsx new file mode 100644 index 0000000..94c98da --- /dev/null +++ b/src/components/modals/ShipmentTrackingSheet.tsx @@ -0,0 +1,197 @@ +import React from 'react'; +import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; +import type { ApiShipment } from '../../lib/shopApi'; +import { copyToClipboard } from '../../lib/webview-actions'; + +interface ShipmentTrackingSheetProps { + shipment: ApiShipment | null; + onClose: () => void; + onCopied?: () => void; +} + +export const ShipmentTrackingSheet: React.FC = ({ + shipment, + onClose, + onCopied, +}) => { + const isOpen = Boolean(shipment); + + useHardwareBackHandler(() => { + onClose(); + return true; + }, isOpen); + + if (!shipment) return null; + + const handleCopyTracking = async () => { + if (!shipment.tracking_code) return; + const ok = await copyToClipboard(shipment.tracking_code); + if (ok && onCopied) onCopied(); + }; + + return ( +
+
e.stopPropagation()} + style={{ + padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', + display: 'flex', + flexDirection: 'column', + gap: '16px', + maxHeight: '85dvh', + overflowY: 'auto', + }} + > +
+ + Shipment Tracking • {shipment.booth_name} + + +
+ +
+
+ Carrier + + {shipment.carrier_name || 'Habib Global Post'} + +
+ {shipment.tracking_code && ( +
+ Tracking Code + +
+ )} +
+ Estimated Delivery + + {shipment.estimated_delivery_label || '2–3 Business Days'} + +
+
+ +
+ {(shipment.events || []).map((ev, idx) => ( +
+
+
+ + {ev.title} + + + {ev.location ? `${ev.location} • ` : ''} + {ev.formatted_time} + +
+
+ ))} +
+ + +
+
+ ); +}; + diff --git a/src/components/orders/OrderListCard.tsx b/src/components/orders/OrderListCard.tsx index 29644fe..ec69d9f 100644 --- a/src/components/orders/OrderListCard.tsx +++ b/src/components/orders/OrderListCard.tsx @@ -1,17 +1,17 @@ import React from 'react'; import { useNavigate } from 'react-router-dom'; import type { OrderCardData } from '../../data/ordersData'; +import { ROUTES } from '../../lib/routes'; interface OrderListCardProps { order: OrderCardData; + onViewDetails?: () => void; } -/** - * Order summary card on `shop-orders` (4175:10954 & 4175:10644). - * - Dimensions: 342×233 at (17, order.y), radius 20 - * - Gradient: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%), border 1px solid #ffffff - */ -export const OrderListCard: React.FC = ({ order }) => { +export const OrderListCard: React.FC = ({ + order, + onViewDetails, +}) => { const navigate = useNavigate(); return ( @@ -29,7 +29,6 @@ export const OrderListCard: React.FC = ({ order }) => { gap: 15, }} > - {/* Top section */}
= ({ order }) => { gap: 10, }} > - {/* Row 1: Order code, dot, price, and date */}
= ({ order }) => {
- {/* Date on right */}
= ({ order }) => {
- {/* Thumbnails row */}
= ({ order }) => {
- {/* Grey status bar */}
= ({ order }) => {
- {/* Right delivery count */}
= ({ order }) => {
- {/* View Details button */} + + + {LANGUAGE_OPTIONS.map((opt) => { + const active = language === opt.code; + return ( + + ); + })} + + + )} ); }; diff --git a/src/pages/account/ProviderRequestPage.tsx b/src/pages/account/ProviderRequestPage.tsx index e83fe3c..50a6579 100644 --- a/src/pages/account/ProviderRequestPage.tsx +++ b/src/pages/account/ProviderRequestPage.tsx @@ -1,23 +1,219 @@ -import React, { useState } from 'react'; -import { useNavigate } from 'react-router-dom'; +import React, { useEffect, useMemo, useState } from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; import { MobileShell } from '../../components/layout/MobileShell'; import { HabibCoinsBanner } from '../../components/account/HabibCoinsBanner'; import { ProviderBadgeCard } from '../../components/account/ProviderBadgeCard'; import { AccountMenuRow } from '../../components/account/AccountMenuRow'; +import { EmptyStateBox } from '../../components/common/ShimmerSkeletons'; import { + type AccountMenuRowItem, PROVIDER_BADGE_CARDS, - PROVIDER_SETTINGS_MENU_ROWS, + type ProviderBadgeCardItem, PROVIDER_INFO_MENU_ROWS, + PROVIDER_SETTINGS_MENU_ROWS, } from '../../data/accountData'; +import { useShopApp } from '../../context/ShopAppContext'; +import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; +import { useSmartBack } from '../../hooks/useSmartBack'; +import { resolveMediaUrl } from '../../lib/http'; +import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes'; +import { + useApplyProviderMutation, + useUpdateProfileMutation, +} from '../../lib/shopQueries'; +import { openExternalUrl } from '../../lib/webview-actions'; /** * Node 4214:10531 — `provider requst` (Provider Request & Profile Settings, 375×1768) */ export const ProviderRequestPage: React.FC = () => { const navigate = useNavigate(); + const location = useLocation(); + const bare = isBareMode(location.search); + const useMockFallback = bare || USE_MOCK_DATA; + const smartBack = useSmartBack(ROUTES.account); + + const { + isUserAuthenticated, + requireAuth, + profile, + language, + orderCounters, + selectedAddress, + showToast, + } = useShopApp(); + + const updateProfileMutation = useUpdateProfileMutation(); + const applyProviderMutation = useApplyProviderMutation(); + const [fullName, setFullName] = useState(''); const [email, setEmail] = useState(''); const [phoneNumber, setPhoneNumber] = useState(''); + const savingProfile = updateProfileMutation.isPending; + + const [applyOpen, setApplyOpen] = useState(false); + const [storeName, setStoreName] = useState(''); + const [storeDesc, setStoreDesc] = useState(''); + const submittingProvider = applyProviderMutation.isPending; + + useEffect(() => { + if (bare || !profile) return; + setFullName((prev) => prev || profile.full_name || ''); + setEmail((prev) => prev || profile.email || ''); + setPhoneNumber((prev) => prev || profile.phone_number || ''); + }, [bare, profile]); + + useHardwareBackHandler(() => { + if (!submittingProvider) setApplyOpen(false); + return true; + }, applyOpen); + + const providerBadges = useMemo(() => { + if (bare || !profile?.provider_requests?.length) { + return useMockFallback ? PROVIDER_BADGE_CARDS : []; + } + const mapped = profile.provider_requests.slice(0, 4).map((req, idx): ProviderBadgeCardItem => { + const normalized = (req.status || '').toLowerCase(); + const isApproved = normalized.includes('accept') || normalized.includes('approv'); + const isDenied = normalized.includes('reject') || normalized.includes('deni'); + const svcTitle = + req.service === 'shop' + ? req.public_name || 'Habib Shop' + : req.service + ? `Habib ${req.service.charAt(0).toUpperCase()}${req.service.slice(1)}` + : req.public_name || 'Habib Shop'; + + return { + id: `prov-live-${req.id}-${idx}`, + x: idx % 2 === 0 ? 28 : 194, + y: 532 + Math.floor(idx / 2) * 66, + width: 154, + innerLeft: 13, + innerWidth: 128, + statusText: isApproved ? 'Provider in' : isDenied ? 'Request Denied' : 'Under Review', + statusWidth: 96, + title: svcTitle, + titleWidth: 86, + gradientBg: isApproved + ? 'linear-gradient(180deg, #203bcc 0%, #9961e7 100%)' + : isDenied + ? 'linear-gradient(180deg, #cd4343 0%, #862222 100%)' + : 'linear-gradient(180deg, #eca533 0%, #ffd74b 100%)', + iconSrc: isApproved + ? '/assets/images/icon-provider-events-calendar.svg' + : isDenied + ? '/assets/images/icon-provider-maukibs-flag.svg' + : '/assets/images/icon-provider-requests-doc.svg', + iconLeft: 9, + iconTop: 12, + iconWidth: 16, + iconHeight: 16, + badgeType: isApproved ? 'approved' : isDenied ? 'denied' : 'review', + }; + }); + + return mapped.length > 0 ? mapped : useMockFallback ? PROVIDER_BADGE_CARDS : []; + }, [bare, profile, useMockFallback]); + + const settingsRows = useMemo(() => { + if (bare) return PROVIDER_SETTINGS_MENU_ROWS; + const langLabel = + language === 'fa' ? 'فارسی' : language === 'ar' ? 'العربية' : 'English'; + const activeOrders = orderCounters?.in_progress ?? 0; + + return PROVIDER_SETTINGS_MENU_ROWS.map((row) => { + if (row.id === 'prov-azan') { + return { + ...row, + subtitle: + selectedAddress?.city || (useMockFallback ? row.subtitle : 'Not set'), + targetRoute: ROUTES.addresses, + }; + } + if (row.id === 'prov-language') { + return { + ...row, + subtitle: langLabel, + rightIconType: 'arrow-right', + targetRoute: ROUTES.settings, + }; + } + if (row.id === 'prov-notifications') { + return { + ...row, + badgeCount: activeOrders > 0 ? String(activeOrders) : undefined, + targetRoute: ROUTES.orders('current'), + }; + } + return { + ...row, + targetRoute: ROUTES.settings, + }; + }); + }, [bare, language, orderCounters, selectedAddress, useMockFallback]); + + const infoRows = useMemo(() => { + if (bare) return PROVIDER_INFO_MENU_ROWS; + return PROVIDER_INFO_MENU_ROWS.map((row) => { + if (row.id === 'info-faqs') { + return { ...row, targetRoute: ROUTES.support }; + } + if (row.id === 'info-about') { + return { ...row, targetRoute: ROUTES.stores }; + } + return { ...row, targetRoute: '' }; + }); + }, [bare]); + + const handleSaveProfile = async () => { + if (savingProfile) return; + if (!bare && !isUserAuthenticated) { + const authed = await requireAuth({ + featureName: 'profile settings', + }); + if (!authed) return; + } + try { + await updateProfileMutation.mutateAsync({ + full_name: fullName.trim(), + email: email.trim(), + phone_number: phoneNumber.trim(), + }); + showToast('Profile saved'); + } catch (err) { + showToast(err instanceof Error ? err.message : 'Could not update profile'); + } + }; + + const handleApplyProvider = async (e: React.FormEvent) => { + e.preventDefault(); + if (!storeName.trim() || submittingProvider) return; + if (!bare && !isUserAuthenticated) { + const authed = await requireAuth({ + featureName: 'provider application', + }); + if (!authed) return; + } + try { + const res = await applyProviderMutation.mutateAsync({ + store_name: storeName.trim(), + description: storeDesc.trim(), + }); + showToast(res.message || 'Provider application submitted'); + setApplyOpen(false); + setStoreName(''); + setStoreDesc(''); + } catch (err) { + showToast(err instanceof Error ? err.message : 'Could not submit application'); + } + }; + + const avatarSrc = + !bare && profile?.avatar_url + ? resolveMediaUrl(profile.avatar_url) + : useMockFallback + ? '/assets/images/avatar-provider-ahd-art.png' + : '/assets/images/icon-account-avatar-gold.svg'; return ( @@ -30,7 +226,7 @@ export const ProviderRequestPage: React.FC = () => { gap: 23, }} > - {/* Top Bar: Back + Center Avatar + Edit/Camera */} + {/* Top Bar: Back + Center Avatar + Edit/Settings */}
{ > Profile {
+ + {!bare && ( + + )} {/* Provider Status Card (4214:10539) */} @@ -295,11 +513,15 @@ export const ProviderRequestPage: React.FC = () => { Your are a provider in: -
- {PROVIDER_BADGE_CARDS.map((badge) => ( - - ))} -
+ {providerBadges.length > 0 ? ( +
+ {providerBadges.map((badge) => ( + + ))} +
+ ) : ( + + )} {/* Habib Coins Banner (4214:10558) */} @@ -307,7 +529,13 @@ export const ProviderRequestPage: React.FC = () => { {/* "Become a provider on Habib" Card (4214:10599) */}
navigate('/language-setting')} + onClick={() => { + if (bare) { + navigate('/language-setting'); + } else { + setApplyOpen(true); + } + }} style={{ width: '100%', minHeight: 55, @@ -359,6 +587,11 @@ export const ProviderRequestPage: React.FC = () => { {/* "My Wallet ($24)" Card (4214:10615) */}
{ + if (!bare) { + navigate(ROUTES.settings); + } + }} style={{ width: '100%', minHeight: 55, @@ -410,7 +643,7 @@ export const ProviderRequestPage: React.FC = () => { color: '#111111', }} > - My Wallet ($24) + {useMockFallback ? 'My Wallet ($24)' : 'My Wallet ($0)'}
{ gap: 19, }} > - {PROVIDER_SETTINGS_MENU_ROWS.map((row) => ( + {settingsRows.map((row) => ( ))}
@@ -466,13 +699,27 @@ export const ProviderRequestPage: React.FC = () => { gap: 19, }} > - {PROVIDER_INFO_MENU_ROWS.map((row) => ( - + {infoRows.map((row) => ( + openExternalUrl('https://habibapp.com') + : undefined + } + /> ))}
{/* Delete Account Card (4214:10703) */}
{ + if (!bare) { + navigate(ROUTES.support); + showToast('Submit an account deletion request to Habib Support'); + } + }} style={{ width: '100%', minHeight: 55, @@ -575,6 +822,9 @@ export const ProviderRequestPage: React.FC = () => { Instagram { + if (!bare) openExternalUrl('https://habibapp.com'); + }} style={{ width: 32, height: 31, @@ -584,6 +834,9 @@ export const ProviderRequestPage: React.FC = () => { Telegram { + if (!bare) openExternalUrl('https://habibapp.com'); + }} style={{ width: 32, height: 31, @@ -593,6 +846,9 @@ export const ProviderRequestPage: React.FC = () => { WhatsApp { + if (!bare) openExternalUrl('https://habibapp.com'); + }} style={{ width: 30.25, height: 30.28, @@ -602,6 +858,130 @@ export const ProviderRequestPage: React.FC = () => {
+ + {/* Provider Application Bottom Sheet */} + {applyOpen && ( +
{ + if (!submittingProvider) setApplyOpen(false); + }} + style={{ + position: 'fixed', + inset: 0, + backgroundColor: 'rgba(17, 17, 17, 0.9)', + zIndex: 60, + display: 'flex', + flexDirection: 'column', + justifyContent: 'flex-end', + }} + > +
e.stopPropagation()} + onSubmit={handleApplyProvider} + style={{ + padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', + display: 'flex', + flexDirection: 'column', + gap: 14, + }} + > +
+ + Open a Habib Shop Booth + + +
+ + setStoreName(e.target.value)} + style={{ + width: '100%', + height: 46, + borderRadius: 12, + backgroundColor: '#ffffff', + border: '1px solid #d7dbe2', + padding: '0 12px', + fontFamily: 'var(--font-sans)', + fontSize: 13, + color: '#111111', + }} + /> + +