Browse Source
feat: implement production shop SPA with Flutter WebView bridge and REST API integration
main
feat: implement production shop SPA with Flutter WebView bridge and REST API integration
main
60 changed files with 11669 additions and 2235 deletions
-
3.env
-
27BACKEND_SPEC.md
-
301index.html
-
37package-lock.json
-
1package.json
-
206src/App.tsx
-
9src/components/account/AccountMenuRow.tsx
-
42src/components/account/HabibCoinsBanner.tsx
-
15src/components/account/OrderCounterCard.tsx
-
93src/components/bridge/HabibBridgeProviders.tsx
-
72src/components/checkout/AddressCard.tsx
-
20src/components/checkout/OrderSummaryRows.tsx
-
27src/components/common/CategoryCard.tsx
-
39src/components/common/CompactProductCard.tsx
-
40src/components/common/GridProductCard.tsx
-
51src/components/common/SearchBar.tsx
-
714src/components/common/ShimmerSkeletons.tsx
-
58src/components/layout/BottomNavBar.tsx
-
21src/components/layout/TopHeader.tsx
-
301src/components/modals/AddressFormSheet.tsx
-
188src/components/modals/LoginRequiredModal.tsx
-
195src/components/modals/OrderSummarySheet.tsx
-
290src/components/modals/PaymentMethodsSheet.tsx
-
197src/components/modals/ShipmentTrackingSheet.tsx
-
27src/components/orders/OrderListCard.tsx
-
720src/context/ShopAppContext.tsx
-
23src/hooks/use-habib-web-ready.ts
-
76src/hooks/use-hardware-back-handler.ts
-
50src/hooks/useSmartBack.ts
-
114src/index.css
-
229src/lib/auth-bridge.ts
-
95src/lib/cookies.ts
-
166src/lib/http.ts
-
315src/lib/mappers.ts
-
45src/lib/routes.ts
-
660src/lib/shopApi.ts
-
366src/lib/shopQueries.ts
-
68src/lib/view-paddings.ts
-
222src/lib/webview-actions.ts
-
7src/main.tsx
-
548src/pages/account/LanguageSettingPage.tsx
-
416src/pages/account/ProviderRequestPage.tsx
-
373src/pages/account/ShopAccountPage.tsx
-
95src/pages/account/ShopAddressPage.tsx
-
806src/pages/catalog/ShopBoothPage.tsx
-
185src/pages/catalog/ShopCatItemsPage.tsx
-
83src/pages/catalog/ShopCategoryPage.tsx
-
958src/pages/catalog/ShopSinglePage.tsx
-
1182src/pages/chat/ShopChatPage.tsx
-
396src/pages/checkout/ShopBuy01Page.tsx
-
594src/pages/checkout/ShopCartPage.tsx
-
2src/pages/checkout/ShopOrderSummaryPage.tsx
-
128src/pages/checkout/ShopPayResultPage.tsx
-
373src/pages/checkout/ShopPaymentPage.tsx
-
370src/pages/home/ShopHomePage.tsx
-
630src/pages/orders/ShopOrderDetailPage.tsx
-
164src/pages/orders/ShopOrdersPage.tsx
-
397src/pages/orders/ShopSupportPage.tsx
-
37src/types/window.d.ts
-
37vite.config.ts
@ -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 |
|||
|
|||
@ -0,0 +1,93 @@ |
|||
import React, { useEffect, useRef } from 'react'; |
|||
import { useLocation, useNavigate } from 'react-router-dom'; |
|||
import { initFlutterViewPaddings } from '../../lib/view-paddings'; |
|||
import { closeService, isInFlutterWebView } from '../../lib/webview-actions'; |
|||
import { |
|||
ensureGlobalHardwareBackInstalled, |
|||
useHardwareBackHandler, |
|||
} from '../../hooks/use-hardware-back-handler'; |
|||
import { recordInAppNavigation, useSmartBack } from '../../hooks/useSmartBack'; |
|||
import { ROUTES } from '../../lib/routes'; |
|||
import { useShopApp } from '../../context/ShopAppContext'; |
|||
|
|||
export const HabibBridgeProviders: React.FC<{ children: React.ReactNode }> = ({ |
|||
children, |
|||
}) => { |
|||
const location = useLocation(); |
|||
const navigate = useNavigate(); |
|||
const smartBack = useSmartBack(ROUTES.home); |
|||
const { toastMessage } = useShopApp(); |
|||
const isFirstMountRef = useRef(true); |
|||
|
|||
useEffect(() => { |
|||
window.__habibNavigate = (to: string) => navigate(to); |
|||
return () => { |
|||
delete window.__habibNavigate; |
|||
}; |
|||
}, [navigate]); |
|||
|
|||
useEffect(() => { |
|||
ensureGlobalHardwareBackInstalled(); |
|||
const cleanupPaddings = initFlutterViewPaddings(); |
|||
return cleanupPaddings; |
|||
}, []); |
|||
|
|||
useEffect(() => { |
|||
if (isFirstMountRef.current) { |
|||
isFirstMountRef.current = false; |
|||
return; |
|||
} |
|||
recordInAppNavigation(); |
|||
if (typeof window !== 'undefined') { |
|||
window.scrollTo({ top: 0, behavior: 'auto' }); |
|||
} |
|||
}, [location.pathname, location.search]); |
|||
|
|||
// Base route-level hardware back handler (sits at bottom of LIFO stack below modal sheets)
|
|||
useHardwareBackHandler(() => { |
|||
const isRoot = |
|||
location.pathname === '/' || location.pathname === '/shop-home'; |
|||
if (isRoot) { |
|||
if (isInFlutterWebView()) { |
|||
closeService(); |
|||
return true; |
|||
} |
|||
return false; |
|||
} |
|||
smartBack(ROUTES.home); |
|||
return true; |
|||
}, true); |
|||
|
|||
return ( |
|||
<> |
|||
{children} |
|||
{toastMessage && ( |
|||
<div |
|||
role="status" |
|||
aria-live="polite" |
|||
style={{ |
|||
position: 'fixed', |
|||
bottom: 'calc(92px + var(--safe-bottom, 0px))', |
|||
left: '50%', |
|||
transform: 'translateX(-50%)', |
|||
padding: '9px 18px', |
|||
borderRadius: '14px', |
|||
backgroundColor: 'rgba(17, 17, 17, 0.92)', |
|||
color: '#ffffff', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontSize: '12px', |
|||
fontWeight: 600, |
|||
lineHeight: '16px', |
|||
boxShadow: '0 6px 20px rgba(0, 0, 0, 0.25)', |
|||
zIndex: 9999, |
|||
pointerEvents: 'none', |
|||
whiteSpace: 'nowrap', |
|||
}} |
|||
> |
|||
{toastMessage} |
|||
</div> |
|||
)} |
|||
</> |
|||
); |
|||
}; |
|||
|
|||
@ -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<ShimmerBoxProps> = ({ |
|||
width = '100%', |
|||
height = 14, |
|||
borderRadius = 8, |
|||
dark = false, |
|||
style, |
|||
}) => ( |
|||
<div |
|||
aria-hidden="true" |
|||
className={dark ? 'habib-shimmer-dark' : 'habib-shimmer'} |
|||
style={{ |
|||
width, |
|||
height, |
|||
borderRadius, |
|||
flexShrink: 0, |
|||
...style, |
|||
}} |
|||
/> |
|||
); |
|||
|
|||
export const InlineSpinner: React.FC<{ |
|||
size?: number; |
|||
gold?: boolean; |
|||
}> = ({ size = 16, gold = false }) => ( |
|||
<span |
|||
aria-hidden="true" |
|||
className={`habib-inline-spinner${gold ? ' is-gold' : ''}`} |
|||
style={{ width: size, height: size }} |
|||
/> |
|||
); |
|||
|
|||
export const RetryBanner: React.FC<{ |
|||
message?: string; |
|||
onRetry: () => void; |
|||
}> = ({ |
|||
message = 'Connection took longer than expected. Check your network and try again.', |
|||
onRetry, |
|||
}) => ( |
|||
<div |
|||
role="alert" |
|||
style={{ |
|||
width: '100%', |
|||
padding: '18px 16px', |
|||
borderRadius: 16, |
|||
background: 'linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%)', |
|||
border: '1px solid #e8e4df', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
alignItems: 'center', |
|||
textAlign: 'center', |
|||
gap: 10, |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize: 13, |
|||
lineHeight: '19px', |
|||
color: '#292a2e', |
|||
}} |
|||
> |
|||
{message} |
|||
</span> |
|||
<button |
|||
type="button" |
|||
onClick={onRetry} |
|||
className="habib-cta-btn" |
|||
style={{ |
|||
padding: '8px 18px', |
|||
borderRadius: 10, |
|||
color: '#ffffff', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 12, |
|||
cursor: 'pointer', |
|||
}} |
|||
> |
|||
Retry |
|||
</button> |
|||
</div> |
|||
); |
|||
|
|||
export const EmptyStateBox: React.FC<{ |
|||
message: string; |
|||
compact?: boolean; |
|||
}> = ({ message, compact = false }) => ( |
|||
<div |
|||
style={{ |
|||
width: '100%', |
|||
padding: compact ? '18px 14px' : '32px 16px', |
|||
borderRadius: 15, |
|||
backgroundColor: '#ffffff', |
|||
border: '1px solid #e8e4df', |
|||
boxSizing: 'border-box', |
|||
textAlign: 'center', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize: 13, |
|||
lineHeight: '19px', |
|||
color: '#747474', |
|||
}} |
|||
> |
|||
{message} |
|||
</div> |
|||
); |
|||
|
|||
export const CompactCarouselShimmer: React.FC<{ count?: number }> = ({ |
|||
count = 3, |
|||
}) => ( |
|||
<div |
|||
className="habib-carousel-scroller habib-scroll-container" |
|||
data-testid="shimmer-compact-carousel" |
|||
> |
|||
<div className="habib-carousel-track"> |
|||
{Array.from({ length: count }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
className="habib-compact-card" |
|||
style={{ |
|||
padding: 12, |
|||
borderRadius: 15, |
|||
backgroundColor: '#ffffff', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 8, |
|||
}} |
|||
> |
|||
<ShimmerBox height={112} borderRadius={10} /> |
|||
<ShimmerBox width="62%" height={10} borderRadius={5} /> |
|||
<ShimmerBox width="90%" height={13} borderRadius={6} /> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
marginTop: 2, |
|||
}} |
|||
> |
|||
<ShimmerBox width={54} height={15} borderRadius={6} /> |
|||
<ShimmerBox width={30} height={12} borderRadius={6} /> |
|||
</div> |
|||
</div> |
|||
))} |
|||
</div> |
|||
</div> |
|||
); |
|||
|
|||
export const HomeFeedShimmer: React.FC = () => ( |
|||
<div |
|||
data-testid="shimmer-home-feed" |
|||
style={{ display: 'flex', flexDirection: 'column', gap: 20 }} |
|||
> |
|||
{/* Hero Banner Shimmer */} |
|||
<div |
|||
className="habib-hero-banner" |
|||
style={{ |
|||
width: '100%', |
|||
borderRadius: 15, |
|||
backgroundColor: '#182c1f', |
|||
padding: '16px 18px', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> |
|||
<ShimmerBox width={68} height={10} borderRadius={5} dark /> |
|||
<ShimmerBox width="72%" height={18} borderRadius={6} dark /> |
|||
<ShimmerBox width="56%" height={18} borderRadius={6} dark /> |
|||
<ShimmerBox width="65%" height={10} borderRadius={5} dark /> |
|||
</div> |
|||
<ShimmerBox width={108} height={30} borderRadius={8} dark /> |
|||
</div> |
|||
|
|||
{/* 5 Quick Categories Circular Pills Shimmer */} |
|||
<div className="habib-quick-cats"> |
|||
{Array.from({ length: 5 }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
style={{ |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
alignItems: 'center', |
|||
gap: 6, |
|||
}} |
|||
> |
|||
<ShimmerBox width={43} height={43} borderRadius="50%" /> |
|||
<ShimmerBox width={36} height={9} borderRadius={4} /> |
|||
</div> |
|||
))} |
|||
</div> |
|||
|
|||
{/* Populars Section Shimmer */} |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
padding: '0 2px', |
|||
}} |
|||
> |
|||
<ShimmerBox width={74} height={16} borderRadius={6} /> |
|||
<ShimmerBox width={56} height={12} borderRadius={6} /> |
|||
</div> |
|||
<CompactCarouselShimmer count={3} /> |
|||
</div> |
|||
|
|||
{/* New Stores Section Shimmer */} |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
padding: '0 2px', |
|||
}} |
|||
> |
|||
<ShimmerBox width={86} height={16} borderRadius={6} /> |
|||
<ShimmerBox width={56} height={12} borderRadius={6} /> |
|||
</div> |
|||
<CompactCarouselShimmer count={3} /> |
|||
</div> |
|||
</div> |
|||
); |
|||
|
|||
export const CategoryGridShimmer: React.FC<{ count?: number }> = ({ |
|||
count = 6, |
|||
}) => ( |
|||
<div className="habib-category-grid" data-testid="shimmer-category-grid"> |
|||
{Array.from({ length: count }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
style={{ |
|||
minHeight: 118, |
|||
padding: '14px 12px', |
|||
borderRadius: 16, |
|||
backgroundColor: '#ffffff', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}> |
|||
<ShimmerBox width="68%" height={14} borderRadius={6} /> |
|||
<ShimmerBox width="42%" height={10} borderRadius={5} /> |
|||
</div> |
|||
<div style={{ display: 'flex', justifyContent: 'flex-end' }}> |
|||
<ShimmerBox width={48} height={48} borderRadius={14} /> |
|||
</div> |
|||
</div> |
|||
))} |
|||
</div> |
|||
); |
|||
|
|||
export const ProductGridShimmer: React.FC<{ count?: number }> = ({ |
|||
count = 6, |
|||
}) => ( |
|||
<div className="habib-product-grid" data-testid="shimmer-product-grid"> |
|||
{Array.from({ length: count }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
style={{ |
|||
padding: 12, |
|||
borderRadius: 15, |
|||
backgroundColor: '#ffffff', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 9, |
|||
}} |
|||
> |
|||
<ShimmerBox height={132} borderRadius={11} /> |
|||
<ShimmerBox width="58%" height={10} borderRadius={5} /> |
|||
<ShimmerBox width="92%" height={13} borderRadius={6} /> |
|||
<ShimmerBox width="64%" height={13} borderRadius={6} /> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
marginTop: 2, |
|||
}} |
|||
> |
|||
<ShimmerBox width={62} height={16} borderRadius={6} /> |
|||
<ShimmerBox width={34} height={13} borderRadius={6} /> |
|||
</div> |
|||
</div> |
|||
))} |
|||
</div> |
|||
); |
|||
|
|||
export const ProductDetailBodyShimmer: React.FC = () => ( |
|||
<div data-testid="shimmer-product-detail" style={{ display: 'contents' }}> |
|||
<div |
|||
style={{ |
|||
position: 'relative', |
|||
zIndex: 1, |
|||
marginTop: -38, |
|||
borderTopLeftRadius: 20, |
|||
borderTopRightRadius: 20, |
|||
backgroundColor: '#f3f1ef', |
|||
padding: '18px var(--page-px) 16px', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 15, |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<ShimmerBox width="54%" height={11} borderRadius={5} /> |
|||
<ShimmerBox width={56} height={24} borderRadius={8} /> |
|||
</div> |
|||
|
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}> |
|||
<ShimmerBox width="82%" height={22} borderRadius={7} /> |
|||
<ShimmerBox width="38%" height={14} borderRadius={6} /> |
|||
</div> |
|||
|
|||
<div className="habib-single-attrs-grid" style={{ marginTop: 4 }}> |
|||
<ShimmerBox height={48} borderRadius={8} /> |
|||
<ShimmerBox height={48} borderRadius={8} /> |
|||
<ShimmerBox height={48} borderRadius={8} /> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
paddingTop: 4, |
|||
}} |
|||
> |
|||
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}> |
|||
<ShimmerBox width={39} height={39} borderRadius="50%" /> |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}> |
|||
<ShimmerBox width={126} height={14} borderRadius={6} /> |
|||
<ShimmerBox width={74} height={10} borderRadius={5} /> |
|||
</div> |
|||
</div> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
alignItems: 'flex-end', |
|||
gap: 5, |
|||
}} |
|||
> |
|||
<ShimmerBox width={42} height={13} borderRadius={5} /> |
|||
<ShimmerBox width={54} height={10} borderRadius={5} /> |
|||
</div> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
display: 'grid', |
|||
gridTemplateColumns: '1fr 1fr', |
|||
gap: 16, |
|||
marginTop: 8, |
|||
paddingBottom: 6, |
|||
}} |
|||
> |
|||
<ShimmerBox height={20} borderRadius={6} /> |
|||
<ShimmerBox height={20} borderRadius={6} /> |
|||
</div> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
flex: 1, |
|||
backgroundColor: '#ebe8e5', |
|||
padding: '24px var(--page-px) 28px', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 12, |
|||
}} |
|||
> |
|||
<ShimmerBox width={90} height={14} borderRadius={6} /> |
|||
<ShimmerBox width="45%" height={13} borderRadius={6} /> |
|||
<ShimmerBox |
|||
width={104} |
|||
height={14} |
|||
borderRadius={6} |
|||
style={{ marginTop: 8 }} |
|||
/> |
|||
<ShimmerBox width="96%" height={13} borderRadius={6} /> |
|||
<ShimmerBox width="91%" height={13} borderRadius={6} /> |
|||
<ShimmerBox width="78%" height={13} borderRadius={6} /> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
position: 'sticky', |
|||
bottom: 0, |
|||
zIndex: 20, |
|||
width: '100%', |
|||
minHeight: 87, |
|||
padding: '16px var(--page-px) calc(16px + var(--safe-bottom, 0px))', |
|||
borderRadius: '17px 17px 0 0', |
|||
backgroundColor: '#ffffff', |
|||
boxShadow: '0px -7px 12px rgba(103, 110, 124, 0.15)', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
gap: 12, |
|||
}} |
|||
> |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}> |
|||
<ShimmerBox width={68} height={13} borderRadius={5} /> |
|||
<ShimmerBox width={88} height={24} borderRadius={7} /> |
|||
</div> |
|||
<ShimmerBox width={176} height={52} borderRadius={11} /> |
|||
</div> |
|||
</div> |
|||
); |
|||
|
|||
export const StoreBoothBodyShimmer: React.FC = () => ( |
|||
<div |
|||
data-testid="shimmer-store-booth" |
|||
style={{ |
|||
position: 'relative', |
|||
zIndex: 1, |
|||
marginTop: -97, |
|||
flex: 1, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
alignItems: 'center', |
|||
padding: '0 var(--page-px) 32px', |
|||
}} |
|||
> |
|||
<ShimmerBox |
|||
width={64} |
|||
height={64} |
|||
borderRadius={32} |
|||
style={{ border: '2px solid #ffffff' }} |
|||
/> |
|||
<ShimmerBox |
|||
width={186} |
|||
height={18} |
|||
borderRadius={6} |
|||
style={{ marginTop: 12 }} |
|||
/> |
|||
<ShimmerBox |
|||
width={104} |
|||
height={13} |
|||
borderRadius={6} |
|||
style={{ marginTop: 8 }} |
|||
/> |
|||
|
|||
<div |
|||
style={{ |
|||
marginTop: 14, |
|||
width: '100%', |
|||
maxWidth: 340, |
|||
display: 'flex', |
|||
justifyContent: 'space-around', |
|||
gap: 10, |
|||
}} |
|||
> |
|||
<ShimmerBox width={64} height={13} borderRadius={5} /> |
|||
<ShimmerBox width={92} height={13} borderRadius={5} /> |
|||
<ShimmerBox width={60} height={13} borderRadius={5} /> |
|||
</div> |
|||
|
|||
<div className="habib-booth-metrics-grid" style={{ marginTop: 21 }}> |
|||
<ShimmerBox height={58} borderRadius={8} /> |
|||
<ShimmerBox height={58} borderRadius={8} /> |
|||
<ShimmerBox height={58} borderRadius={8} /> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
marginTop: 26, |
|||
width: '100%', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 10, |
|||
}} |
|||
> |
|||
<ShimmerBox width={62} height={16} borderRadius={6} /> |
|||
<ShimmerBox width="96%" height={13} borderRadius={5} /> |
|||
<ShimmerBox width="88%" height={13} borderRadius={5} /> |
|||
<ShimmerBox width="70%" height={13} borderRadius={5} /> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
marginTop: 28, |
|||
width: '100%', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 12, |
|||
}} |
|||
> |
|||
<ShimmerBox width={78} height={16} borderRadius={6} /> |
|||
<ProductGridShimmer count={4} /> |
|||
</div> |
|||
</div> |
|||
); |
|||
|
|||
export const OrdersListShimmer: React.FC<{ count?: number }> = ({ |
|||
count = 2, |
|||
}) => ( |
|||
<div className="habib-orders-grid" data-testid="shimmer-orders-list"> |
|||
{Array.from({ length: count }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
style={{ |
|||
width: '100%', |
|||
padding: 14, |
|||
borderRadius: 20, |
|||
backgroundColor: '#ffffff', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 14, |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<ShimmerBox width={142} height={16} borderRadius={6} /> |
|||
<ShimmerBox width={86} height={14} borderRadius={6} /> |
|||
</div> |
|||
<div style={{ display: 'flex', gap: 10 }}> |
|||
<ShimmerBox width={64} height={64} borderRadius={12} /> |
|||
<ShimmerBox width={64} height={64} borderRadius={12} /> |
|||
<ShimmerBox width={64} height={64} borderRadius={12} /> |
|||
</div> |
|||
<ShimmerBox height={38} borderRadius={11} /> |
|||
<ShimmerBox height={42} borderRadius={11} /> |
|||
</div> |
|||
))} |
|||
</div> |
|||
); |
|||
|
|||
export const OrderDetailShimmer: React.FC = () => ( |
|||
<div |
|||
data-testid="shimmer-order-detail" |
|||
style={{ display: 'flex', flexDirection: 'column', gap: 20 }} |
|||
> |
|||
<div |
|||
style={{ |
|||
width: '100%', |
|||
padding: 14, |
|||
borderRadius: 20, |
|||
backgroundColor: '#ebe8e5', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 14, |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<ShimmerBox width={146} height={18} borderRadius={6} /> |
|||
<ShimmerBox width={94} height={14} borderRadius={6} /> |
|||
</div> |
|||
<ShimmerBox height={41} borderRadius={12} /> |
|||
</div> |
|||
|
|||
<div className="habib-orders-grid"> |
|||
{Array.from({ length: 2 }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
style={{ |
|||
width: '100%', |
|||
padding: 14, |
|||
borderRadius: 20, |
|||
backgroundColor: '#ffffff', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 14, |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<ShimmerBox width={132} height={16} borderRadius={6} /> |
|||
<ShimmerBox width={74} height={22} borderRadius={10} /> |
|||
</div> |
|||
<div style={{ display: 'flex', gap: 10 }}> |
|||
<ShimmerBox width={58} height={58} borderRadius={10} /> |
|||
<div |
|||
style={{ |
|||
flex: 1, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 8, |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<ShimmerBox width="80%" height={14} borderRadius={6} /> |
|||
<ShimmerBox width="45%" height={14} borderRadius={6} /> |
|||
</div> |
|||
</div> |
|||
<ShimmerBox height={28} borderRadius={10} /> |
|||
</div> |
|||
))} |
|||
</div> |
|||
</div> |
|||
); |
|||
|
|||
export const ChatThreadShimmer: React.FC = () => ( |
|||
<div |
|||
data-testid="shimmer-chat-thread" |
|||
style={{ |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'flex-end', |
|||
gap: 14, |
|||
width: '100%', |
|||
}} |
|||
> |
|||
<div style={{ alignSelf: 'center' }}> |
|||
<ShimmerBox width={68} height={14} borderRadius={7} /> |
|||
</div> |
|||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 9 }}> |
|||
<ShimmerBox width={35} height={35} borderRadius="50%" /> |
|||
<ShimmerBox |
|||
width="68%" |
|||
height={62} |
|||
borderRadius="0px 20px 20px 20px" |
|||
/> |
|||
</div> |
|||
<div style={{ alignSelf: 'flex-end', width: '58%', marginRight: 8 }}> |
|||
<ShimmerBox height={48} borderRadius="20px 0px 20px 20px" /> |
|||
</div> |
|||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 9 }}> |
|||
<ShimmerBox width={35} height={35} borderRadius="50%" /> |
|||
<ShimmerBox |
|||
width="74%" |
|||
height={54} |
|||
borderRadius="0px 20px 20px 20px" |
|||
/> |
|||
</div> |
|||
</div> |
|||
); |
|||
|
|||
export const CartItemsShimmer: React.FC<{ count?: number }> = ({ |
|||
count = 2, |
|||
}) => ( |
|||
<div |
|||
data-testid="shimmer-cart-items" |
|||
style={{ display: 'flex', flexDirection: 'column', gap: 10 }} |
|||
> |
|||
{Array.from({ length: count }).map((_, idx) => ( |
|||
<div |
|||
key={idx} |
|||
style={{ |
|||
width: '100%', |
|||
minHeight: 121, |
|||
padding: 12, |
|||
borderRadius: 15, |
|||
backgroundColor: '#ffffff', |
|||
display: 'flex', |
|||
gap: 12, |
|||
alignItems: 'center', |
|||
}} |
|||
> |
|||
<ShimmerBox width={86} height={92} borderRadius={11} /> |
|||
<div |
|||
style={{ |
|||
flex: 1, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 8, |
|||
}} |
|||
> |
|||
<ShimmerBox width="84%" height={14} borderRadius={6} /> |
|||
<ShimmerBox width="52%" height={11} borderRadius={5} /> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
marginTop: 6, |
|||
}} |
|||
> |
|||
<ShimmerBox width={64} height={18} borderRadius={6} /> |
|||
<ShimmerBox width={86} height={30} borderRadius={9} /> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
))} |
|||
</div> |
|||
); |
|||
|
|||
@ -0,0 +1,301 @@ |
|||
import React, { useEffect, useState } from 'react'; |
|||
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler'; |
|||
import type { ApiAddress } from '../../lib/shopApi'; |
|||
import type { SaveAddressInput } from '../../context/ShopAppContext'; |
|||
import { isInFlutterWebView, pickManualLocation } from '../../lib/webview-actions'; |
|||
|
|||
interface AddressFormSheetProps { |
|||
isOpen: boolean; |
|||
onClose: () => void; |
|||
initialAddress?: ApiAddress | null; |
|||
onSave: (input: SaveAddressInput) => Promise<ApiAddress | null>; |
|||
} |
|||
|
|||
export const AddressFormSheet: React.FC<AddressFormSheetProps> = ({ |
|||
isOpen, |
|||
onClose, |
|||
initialAddress, |
|||
onSave, |
|||
}) => { |
|||
const [recipientName, setRecipientName] = useState(''); |
|||
const [phone, setPhone] = useState(''); |
|||
const [country, setCountry] = useState('United States'); |
|||
const [city, setCity] = useState('New York'); |
|||
const [streetLine, setStreetLine] = useState(''); |
|||
const [postalCode, setPostalCode] = useState(''); |
|||
const [lat, setLat] = useState<number | null>(null); |
|||
const [lon, setLon] = useState<number | null>(null); |
|||
const [isDefault, setIsDefault] = useState(true); |
|||
const [saving, setSaving] = useState(false); |
|||
|
|||
useEffect(() => { |
|||
if (!isOpen) return; |
|||
if (initialAddress) { |
|||
setRecipientName(initialAddress.recipient_name || ''); |
|||
setPhone(initialAddress.phone || ''); |
|||
setCountry(initialAddress.country || 'United States'); |
|||
setCity(initialAddress.city || 'New York'); |
|||
setStreetLine(initialAddress.street_line || ''); |
|||
setPostalCode(initialAddress.postal_code || ''); |
|||
setLat(initialAddress.lat !== null ? Number(initialAddress.lat) : null); |
|||
setLon(initialAddress.lon !== null ? Number(initialAddress.lon) : null); |
|||
setIsDefault(Boolean(initialAddress.is_default)); |
|||
} else { |
|||
setRecipientName(''); |
|||
setPhone(''); |
|||
setCountry('United States'); |
|||
setCity('New York'); |
|||
setStreetLine(''); |
|||
setPostalCode(''); |
|||
setLat(null); |
|||
setLon(null); |
|||
setIsDefault(true); |
|||
} |
|||
}, [initialAddress, isOpen]); |
|||
|
|||
useHardwareBackHandler(() => { |
|||
if (!saving) onClose(); |
|||
return true; |
|||
}, isOpen); |
|||
|
|||
if (!isOpen) return null; |
|||
|
|||
const handlePickMap = async () => { |
|||
const picked = await pickManualLocation(); |
|||
if (picked) { |
|||
setLat(picked.lat); |
|||
setLon(picked.lon); |
|||
if (picked.city) setCity(picked.city); |
|||
if (picked.country) setCountry(picked.country); |
|||
if (picked.address) setStreetLine(picked.address); |
|||
} |
|||
}; |
|||
|
|||
const handleSubmit = async (e: React.FormEvent) => { |
|||
e.preventDefault(); |
|||
if (!recipientName.trim() || !streetLine.trim() || saving) return; |
|||
setSaving(true); |
|||
try { |
|||
const saved = await onSave({ |
|||
id: initialAddress?.id, |
|||
recipient_name: recipientName.trim(), |
|||
phone: phone.trim(), |
|||
country: country.trim() || 'United States', |
|||
city: city.trim() || 'New York', |
|||
street_line: streetLine.trim(), |
|||
postal_code: postalCode.trim(), |
|||
lat, |
|||
lon, |
|||
is_default: isDefault, |
|||
}); |
|||
if (saved) { |
|||
onClose(); |
|||
} |
|||
} finally { |
|||
setSaving(false); |
|||
} |
|||
}; |
|||
|
|||
const inputStyle: React.CSSProperties = { |
|||
width: '100%', |
|||
height: '44px', |
|||
borderRadius: '12px', |
|||
backgroundColor: '#ffffff', |
|||
border: '1px solid #d7dbe2', |
|||
padding: '0 12px', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontSize: '13px', |
|||
color: '#111111', |
|||
}; |
|||
|
|||
return ( |
|||
<div |
|||
onClick={() => { |
|||
if (!saving) onClose(); |
|||
}} |
|||
style={{ |
|||
position: 'fixed', |
|||
inset: 0, |
|||
backgroundColor: 'rgba(17, 17, 17, 0.9)', |
|||
zIndex: 60, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'flex-end', |
|||
}} |
|||
> |
|||
<form |
|||
className="habib-bottom-sheet" |
|||
onClick={(e) => e.stopPropagation()} |
|||
onSubmit={handleSubmit} |
|||
style={{ |
|||
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: '14px', |
|||
maxHeight: '88dvh', |
|||
overflowY: 'auto', |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '15px', |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
{initialAddress ? 'Edit Delivery Address' : 'Add Delivery Address'} |
|||
</span> |
|||
<button |
|||
type="button" |
|||
onClick={onClose} |
|||
aria-label="Close" |
|||
style={{ |
|||
width: '24px', |
|||
height: '24px', |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-modal-close-cross.svg" |
|||
alt="" |
|||
style={{ width: '11.67px', height: '11.67px' }} |
|||
/> |
|||
</button> |
|||
</div> |
|||
|
|||
{isInFlutterWebView() && ( |
|||
<button |
|||
type="button" |
|||
onClick={handlePickMap} |
|||
style={{ |
|||
width: '100%', |
|||
height: '40px', |
|||
borderRadius: '11px', |
|||
backgroundColor: 'rgba(215, 142, 6, 0.12)', |
|||
border: '1px solid #d78e06', |
|||
color: '#d78e06', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize: '12px', |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
gap: '6px', |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-location-pin-gold.svg" |
|||
alt="" |
|||
style={{ width: '16px', height: '16px' }} |
|||
/> |
|||
{lat !== null ? 'Location pinned on map' : 'Pick Location on Map'} |
|||
</button> |
|||
)} |
|||
|
|||
<input |
|||
type="text" |
|||
required |
|||
placeholder="Recipient full name *" |
|||
value={recipientName} |
|||
onChange={(e) => setRecipientName(e.target.value)} |
|||
style={inputStyle} |
|||
/> |
|||
|
|||
<input |
|||
type="tel" |
|||
placeholder="Phone number" |
|||
value={phone} |
|||
onChange={(e) => setPhone(e.target.value)} |
|||
style={inputStyle} |
|||
/> |
|||
|
|||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}> |
|||
<input |
|||
type="text" |
|||
placeholder="Country" |
|||
value={country} |
|||
onChange={(e) => setCountry(e.target.value)} |
|||
style={inputStyle} |
|||
/> |
|||
<input |
|||
type="text" |
|||
placeholder="City" |
|||
value={city} |
|||
onChange={(e) => setCity(e.target.value)} |
|||
style={inputStyle} |
|||
/> |
|||
</div> |
|||
|
|||
<input |
|||
type="text" |
|||
required |
|||
placeholder="Street address, apartment, suite *" |
|||
value={streetLine} |
|||
onChange={(e) => setStreetLine(e.target.value)} |
|||
style={inputStyle} |
|||
/> |
|||
|
|||
<input |
|||
type="text" |
|||
placeholder="Postal / ZIP code" |
|||
value={postalCode} |
|||
onChange={(e) => setPostalCode(e.target.value)} |
|||
style={inputStyle} |
|||
/> |
|||
|
|||
<label |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
gap: '8px', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontSize: '12px', |
|||
fontWeight: 600, |
|||
color: '#292a2e', |
|||
cursor: 'pointer', |
|||
}} |
|||
> |
|||
<input |
|||
type="checkbox" |
|||
checked={isDefault} |
|||
onChange={(e) => setIsDefault(e.target.checked)} |
|||
style={{ width: '16px', height: '16px', accentColor: '#d78e06' }} |
|||
/> |
|||
Set as default shipping address |
|||
</label> |
|||
|
|||
<button |
|||
type="submit" |
|||
disabled={saving || !recipientName.trim() || !streetLine.trim()} |
|||
className="habib-cta-btn" |
|||
style={{ |
|||
width: '100%', |
|||
height: '50px', |
|||
borderRadius: '11px', |
|||
color: '#fbfbfc', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '15px', |
|||
cursor: saving ? 'not-allowed' : 'pointer', |
|||
opacity: saving || !recipientName.trim() || !streetLine.trim() ? 0.65 : 1, |
|||
}} |
|||
> |
|||
{saving ? 'Saving...' : 'Save Address'} |
|||
</button> |
|||
</form> |
|||
</div> |
|||
); |
|||
}; |
|||
|
|||
@ -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<LoginRequiredModalProps> = ({ |
|||
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 ( |
|||
<div |
|||
role="dialog" |
|||
aria-modal="true" |
|||
aria-labelledby="habib-login-modal-title" |
|||
onClick={() => { |
|||
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', |
|||
}} |
|||
> |
|||
<div |
|||
onClick={(e) => 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 */} |
|||
<div |
|||
style={{ |
|||
width: 60, |
|||
height: 60, |
|||
borderRadius: 20, |
|||
backgroundColor: 'rgba(215, 142, 6, 0.14)', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-account-avatar-gold.svg" |
|||
alt="" |
|||
style={{ |
|||
width: 28, |
|||
height: 30, |
|||
}} |
|||
/> |
|||
</div> |
|||
|
|||
{/* Title */} |
|||
<h2 |
|||
id="habib-login-modal-title" |
|||
style={{ |
|||
margin: 0, |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 18, |
|||
lineHeight: '24px', |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
{title} |
|||
</h2> |
|||
|
|||
{/* Description */} |
|||
<p |
|||
style={{ |
|||
margin: 0, |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 400, |
|||
fontSize: 13, |
|||
lineHeight: '19px', |
|||
color: '#64748b', |
|||
}} |
|||
> |
|||
{description} |
|||
</p> |
|||
|
|||
{/* Actions */} |
|||
<div |
|||
style={{ |
|||
width: '100%', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: 10, |
|||
marginTop: 6, |
|||
}} |
|||
> |
|||
<button |
|||
type="button" |
|||
disabled={isLoggingIn} |
|||
onClick={onConfirmLogin} |
|||
className="habib-cta-btn" |
|||
style={{ |
|||
width: '100%', |
|||
height: 48, |
|||
borderRadius: 12, |
|||
backgroundColor: '#d78e06', |
|||
border: 'none', |
|||
color: '#ffffff', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 15, |
|||
lineHeight: '20px', |
|||
cursor: isLoggingIn ? 'wait' : 'pointer', |
|||
opacity: isLoggingIn ? 0.8 : 1, |
|||
display: 'inline-flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
gap: 8, |
|||
}} |
|||
> |
|||
{isLoggingIn && <InlineSpinner size={16} />} |
|||
<span>{isLoggingIn ? 'Opening Habib Login...' : 'Log In'}</span> |
|||
</button> |
|||
|
|||
<button |
|||
type="button" |
|||
disabled={isLoggingIn} |
|||
onClick={onClose} |
|||
style={{ |
|||
width: '100%', |
|||
height: 42, |
|||
borderRadius: 12, |
|||
backgroundColor: '#f3f1ef', |
|||
border: 'none', |
|||
color: '#3d3d3d', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize: 13, |
|||
lineHeight: '18px', |
|||
cursor: isLoggingIn ? 'not-allowed' : 'pointer', |
|||
}} |
|||
> |
|||
Cancel |
|||
</button> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
); |
|||
}; |
|||
|
|||
@ -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<boolean>; |
|||
ctaText?: string; |
|||
onCtaClick?: () => void; |
|||
} |
|||
|
|||
export const OrderSummarySheet: React.FC<OrderSummarySheetProps> = ({ |
|||
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 ( |
|||
<div |
|||
onClick={onClose} |
|||
style={{ |
|||
position: 'fixed', |
|||
inset: 0, |
|||
backgroundColor: 'rgba(17, 17, 17, 0.9)', |
|||
zIndex: 60, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'flex-end', |
|||
}} |
|||
> |
|||
<div |
|||
className="habib-bottom-sheet" |
|||
onClick={(e) => e.stopPropagation()} |
|||
style={{ |
|||
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: '20px', |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
gap: '12px', |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '14px', |
|||
lineHeight: '19px', |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
Order Summary |
|||
</span> |
|||
<button |
|||
type="button" |
|||
onClick={onClose} |
|||
aria-label="Close" |
|||
style={{ |
|||
width: '24px', |
|||
height: '24px', |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-modal-close-cross.svg" |
|||
alt="" |
|||
style={{ width: '11.67px', height: '11.67px', display: 'block' }} |
|||
/> |
|||
</button> |
|||
</div> |
|||
|
|||
<OrderSummaryRows rows={rows} totalText={totalText} /> |
|||
|
|||
{onApplyPromo && ( |
|||
<form |
|||
onSubmit={handlePromoSubmit} |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
gap: '8px', |
|||
width: '100%', |
|||
}} |
|||
> |
|||
<input |
|||
type="text" |
|||
value={promoInput} |
|||
onChange={(e) => 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', |
|||
}} |
|||
/> |
|||
<button |
|||
type="submit" |
|||
disabled={applying} |
|||
style={{ |
|||
height: '40px', |
|||
padding: '0 14px', |
|||
borderRadius: '11px', |
|||
backgroundColor: '#292a2e', |
|||
color: '#ffffff', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 600, |
|||
fontSize: '12px', |
|||
cursor: 'pointer', |
|||
opacity: applying ? 0.65 : 1, |
|||
display: 'inline-flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
gap: '6px', |
|||
}} |
|||
> |
|||
{applying ? <InlineSpinner size={13} /> : 'Apply'} |
|||
</button> |
|||
</form> |
|||
)} |
|||
|
|||
<button |
|||
type="button" |
|||
className="habib-cta-btn" |
|||
onClick={() => { |
|||
if (onCtaClick) { |
|||
onCtaClick(); |
|||
} else { |
|||
onClose(); |
|||
} |
|||
}} |
|||
style={{ |
|||
width: '100%', |
|||
height: '52px', |
|||
borderRadius: '11px', |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '16px', |
|||
color: '#fbfbfc', |
|||
}} |
|||
> |
|||
{ctaText} |
|||
</button> |
|||
</div> |
|||
</div> |
|||
); |
|||
}; |
|||
|
|||
@ -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<PaymentMethodsSheetProps> = ({ |
|||
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 ( |
|||
<div |
|||
onClick={() => { |
|||
if (!isSubmitting) onClose(); |
|||
}} |
|||
style={{ |
|||
position: 'fixed', |
|||
inset: 0, |
|||
backgroundColor: 'rgba(17, 17, 17, 0.9)', |
|||
zIndex: 60, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'flex-end', |
|||
}} |
|||
> |
|||
<div |
|||
className="habib-bottom-sheet" |
|||
onClick={(e) => e.stopPropagation()} |
|||
style={{ |
|||
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: '20px', |
|||
}} |
|||
> |
|||
{/* Header & Close X Button */} |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
gap: '12px', |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '14px', |
|||
lineHeight: '19px', |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
Payment Methods |
|||
</div> |
|||
|
|||
<button |
|||
type="button" |
|||
disabled={isSubmitting} |
|||
onClick={onClose} |
|||
aria-label="Close" |
|||
style={{ |
|||
width: '24px', |
|||
height: '24px', |
|||
background: 'transparent', |
|||
border: 'none', |
|||
padding: 0, |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-modal-close-cross.svg" |
|||
alt="" |
|||
style={{ |
|||
width: '11.67px', |
|||
height: '11.67px', |
|||
display: 'block', |
|||
}} |
|||
/> |
|||
</button> |
|||
</div> |
|||
|
|||
{/* Payment Method Cards */} |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: '12px', |
|||
}} |
|||
> |
|||
{methods.length > 0 ? ( |
|||
methods.map((method) => ( |
|||
<PaymentMethodCard |
|||
key={method.id} |
|||
item={method} |
|||
isSelected={method.id === selectedMethodId} |
|||
onSelect={() => onSelectMethod(method.id)} |
|||
/> |
|||
)) |
|||
) : ( |
|||
<EmptyStateBox message="No payment methods available." compact /> |
|||
)} |
|||
</div> |
|||
|
|||
{needsMoreCoins && ( |
|||
<div |
|||
style={{ |
|||
padding: '10px 12px', |
|||
borderRadius: '12px', |
|||
backgroundColor: 'rgba(212, 71, 71, 0.08)', |
|||
border: '1px solid rgba(212, 71, 71, 0.3)', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
gap: '10px', |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontSize: '12px', |
|||
fontWeight: 600, |
|||
color: '#d44747', |
|||
}} |
|||
> |
|||
Need {requiredCoins} Habib Coins ({habibCoinsBalance} available) |
|||
</span> |
|||
{isInFlutterWebView() && ( |
|||
<button |
|||
type="button" |
|||
onClick={handleTopUpCoins} |
|||
style={{ |
|||
padding: '6px 12px', |
|||
borderRadius: '9px', |
|||
backgroundColor: '#292a2e', |
|||
color: '#ffffff', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontSize: '11px', |
|||
fontWeight: 600, |
|||
cursor: 'pointer', |
|||
flexShrink: 0, |
|||
}} |
|||
> |
|||
Buy Coins |
|||
</button> |
|||
)} |
|||
</div> |
|||
)} |
|||
|
|||
{/* "Purchase" CTA Button */} |
|||
<button |
|||
type="button" |
|||
disabled={isSubmitting || needsMoreCoins || methods.length === 0} |
|||
onClick={onConfirmPurchase} |
|||
className="habib-cta-btn" |
|||
style={{ |
|||
position: 'relative', |
|||
width: '100%', |
|||
height: '52px', |
|||
padding: '0 14px', |
|||
borderRadius: '11px', |
|||
border: 'none', |
|||
cursor: |
|||
isSubmitting || needsMoreCoins || methods.length === 0 |
|||
? 'not-allowed' |
|||
: 'pointer', |
|||
opacity: |
|||
isSubmitting || needsMoreCoins || methods.length === 0 ? 0.65 : 1, |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'inline-flex', |
|||
alignItems: 'center', |
|||
gap: '6px', |
|||
}} |
|||
> |
|||
{isSubmitting ? ( |
|||
<InlineSpinner size={18} /> |
|||
) : ( |
|||
<img |
|||
src="/assets/images/icon-credit-card-white.svg" |
|||
alt="" |
|||
style={{ |
|||
width: '24px', |
|||
height: '24px', |
|||
flexShrink: 0, |
|||
}} |
|||
/> |
|||
)} |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '16px', |
|||
lineHeight: '24px', |
|||
color: '#fbfbfc', |
|||
}} |
|||
> |
|||
{isSubmitting ? 'Processing...' : 'Purchase'} |
|||
</span> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
position: 'absolute', |
|||
right: '14px', |
|||
top: '50%', |
|||
transform: 'translateY(-50%)', |
|||
minWidth: '56px', |
|||
height: '24px', |
|||
padding: '0 6px', |
|||
borderRadius: '5px', |
|||
backgroundColor: 'rgba(255, 255, 255, 0.2)', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '14px', |
|||
lineHeight: '19px', |
|||
color: 'rgba(255, 255, 255, 0.85)', |
|||
}} |
|||
> |
|||
{totalPriceText} |
|||
</span> |
|||
</div> |
|||
</button> |
|||
</div> |
|||
</div> |
|||
); |
|||
}; |
|||
|
|||
@ -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<ShipmentTrackingSheetProps> = ({ |
|||
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 ( |
|||
<div |
|||
onClick={onClose} |
|||
style={{ |
|||
position: 'fixed', |
|||
inset: 0, |
|||
backgroundColor: 'rgba(17, 17, 17, 0.9)', |
|||
zIndex: 60, |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
justifyContent: 'flex-end', |
|||
}} |
|||
> |
|||
<div |
|||
className="habib-bottom-sheet" |
|||
onClick={(e) => e.stopPropagation()} |
|||
style={{ |
|||
padding: '22px var(--page-px) calc(24px + var(--safe-bottom, 0px))', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: '16px', |
|||
maxHeight: '85dvh', |
|||
overflowY: 'auto', |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '15px', |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
Shipment Tracking • {shipment.booth_name} |
|||
</span> |
|||
<button |
|||
type="button" |
|||
onClick={onClose} |
|||
aria-label="Close" |
|||
style={{ |
|||
width: '24px', |
|||
height: '24px', |
|||
cursor: 'pointer', |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'center', |
|||
}} |
|||
> |
|||
<img |
|||
src="/assets/images/icon-modal-close-cross.svg" |
|||
alt="" |
|||
style={{ width: '11.67px', height: '11.67px' }} |
|||
/> |
|||
</button> |
|||
</div> |
|||
|
|||
<div |
|||
style={{ |
|||
padding: '12px', |
|||
borderRadius: '12px', |
|||
backgroundColor: '#f3f3f3', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
gap: '8px', |
|||
}} |
|||
> |
|||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px' }}> |
|||
<span style={{ color: '#747474', fontWeight: 600 }}>Carrier</span> |
|||
<span style={{ color: '#111111', fontWeight: 700 }}> |
|||
{shipment.carrier_name || 'Habib Global Post'} |
|||
</span> |
|||
</div> |
|||
{shipment.tracking_code && ( |
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'center', |
|||
justifyContent: 'space-between', |
|||
fontSize: '12px', |
|||
}} |
|||
> |
|||
<span style={{ color: '#747474', fontWeight: 600 }}>Tracking Code</span> |
|||
<button |
|||
type="button" |
|||
onClick={handleCopyTracking} |
|||
style={{ |
|||
color: '#d78e06', |
|||
fontWeight: 700, |
|||
fontSize: '12px', |
|||
cursor: 'pointer', |
|||
}} |
|||
> |
|||
{shipment.tracking_code} (Copy) |
|||
</button> |
|||
</div> |
|||
)} |
|||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px' }}> |
|||
<span style={{ color: '#747474', fontWeight: 600 }}>Estimated Delivery</span> |
|||
<span style={{ color: '#111111', fontWeight: 700 }}> |
|||
{shipment.estimated_delivery_label || '2–3 Business Days'} |
|||
</span> |
|||
</div> |
|||
</div> |
|||
|
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}> |
|||
{(shipment.events || []).map((ev, idx) => ( |
|||
<div |
|||
key={ev.id || idx} |
|||
style={{ |
|||
display: 'flex', |
|||
alignItems: 'flex-start', |
|||
gap: '10px', |
|||
}} |
|||
> |
|||
<div |
|||
style={{ |
|||
width: '12px', |
|||
height: '12px', |
|||
marginTop: '3px', |
|||
borderRadius: '50%', |
|||
backgroundColor: idx === 0 ? '#0eb13c' : '#d78e06', |
|||
flexShrink: 0, |
|||
}} |
|||
/> |
|||
<div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}> |
|||
<span style={{ fontSize: '13px', fontWeight: 700, color: '#111111' }}> |
|||
{ev.title} |
|||
</span> |
|||
<span style={{ fontSize: '11px', color: '#747474' }}> |
|||
{ev.location ? `${ev.location} • ` : ''} |
|||
{ev.formatted_time} |
|||
</span> |
|||
</div> |
|||
</div> |
|||
))} |
|||
</div> |
|||
|
|||
<button |
|||
type="button" |
|||
className="habib-cta-btn" |
|||
onClick={onClose} |
|||
style={{ |
|||
width: '100%', |
|||
height: '48px', |
|||
borderRadius: '11px', |
|||
color: '#fbfbfc', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: '15px', |
|||
cursor: 'pointer', |
|||
}} |
|||
> |
|||
Close |
|||
</button> |
|||
</div> |
|||
</div> |
|||
); |
|||
}; |
|||
|
|||
@ -0,0 +1,720 @@ |
|||
import React, { |
|||
createContext, |
|||
useCallback, |
|||
useContext, |
|||
useEffect, |
|||
useMemo, |
|||
useRef, |
|||
useState, |
|||
} from 'react'; |
|||
import { useQuery, useQueryClient } from '@tanstack/react-query'; |
|||
import { useLocation } from 'react-router-dom'; |
|||
import { LoginRequiredModal } from '../components/modals/LoginRequiredModal'; |
|||
import { ensureToken, getToken } from '../lib/auth-bridge'; |
|||
import { ensureGuestToken, getUserLanguage, setUserLanguage } from '../lib/cookies'; |
|||
import { USE_MOCK_DATA } from '../lib/routes'; |
|||
import { |
|||
type ApiAddress, |
|||
type ApiCart, |
|||
type ApiOrderCounters, |
|||
type ApiProductCard, |
|||
type ApiShippingMethod, |
|||
type ApiUserProfile, |
|||
shopApi, |
|||
} from '../lib/shopApi'; |
|||
import { clearUserScopedCache, shopKeys } from '../lib/shopQueries'; |
|||
import { useHabibWebReady } from '../hooks/use-habib-web-ready'; |
|||
|
|||
export interface SaveAddressInput { |
|||
id?: number; |
|||
label?: string; |
|||
recipient_name: string; |
|||
phone?: string; |
|||
country?: string; |
|||
city?: string; |
|||
street_line: string; |
|||
postal_code?: string; |
|||
lat?: number | null; |
|||
lon?: number | null; |
|||
is_default?: boolean; |
|||
} |
|||
|
|||
export interface LoginModalOptions { |
|||
title?: string; |
|||
description?: string; |
|||
featureName?: string; |
|||
onAuthenticated?: () => void; |
|||
} |
|||
|
|||
interface ShopAppContextValue { |
|||
hydrated: boolean; |
|||
isUserAuthenticated: boolean; |
|||
openLoginModal: (options?: LoginModalOptions) => void; |
|||
closeLoginModal: () => void; |
|||
requireAuth: (options?: LoginModalOptions) => Promise<boolean>; |
|||
cart: ApiCart | null; |
|||
cartItemsCount: number; |
|||
cartTotalQuantity: number; |
|||
isCartBusy: boolean; |
|||
addresses: ApiAddress[]; |
|||
selectedAddressId: number | null; |
|||
selectedAddress: ApiAddress | null; |
|||
shippingMethods: ApiShippingMethod[]; |
|||
selectedShippingMethod: ApiShippingMethod | null; |
|||
selectedPaymentMethod: string; |
|||
setSelectedPaymentMethod: (code: string) => void; |
|||
bookmarkedProducts: ApiProductCard[]; |
|||
isBookmarked: (productId?: number | null, slug?: string | null) => boolean; |
|||
toggleBookmark: ( |
|||
productRef: string | number, |
|||
numericId?: number, |
|||
slug?: string |
|||
) => Promise<boolean>; |
|||
profile: ApiUserProfile | null; |
|||
orderCounters: ApiOrderCounters | null; |
|||
habibCoinsBalance: number; |
|||
setHabibCoinsBalance: (coins: number) => void; |
|||
language: string; |
|||
changeLanguage: (lang: string) => void; |
|||
addToCart: ( |
|||
productRef: string | number, |
|||
quantity?: number, |
|||
variantId?: number | null |
|||
) => Promise<ApiCart | null>; |
|||
updateCartItemQuantity: (itemId: number, quantity: number) => Promise<void>; |
|||
removeCartItem: (itemId: number) => Promise<void>; |
|||
clearCart: () => Promise<void>; |
|||
applyPromoCode: (code: string) => Promise<boolean>; |
|||
selectAddress: (id: number) => void; |
|||
saveAddress: (input: SaveAddressInput) => Promise<ApiAddress | null>; |
|||
deleteAddress: (id: number) => Promise<void>; |
|||
selectShippingMethod: (codeOrId: string | number) => void; |
|||
refreshCart: () => Promise<void>; |
|||
refreshAccountData: () => Promise<void>; |
|||
toastMessage: string | null; |
|||
showToast: (message: string) => void; |
|||
} |
|||
|
|||
const ShopAppContext = createContext<ShopAppContextValue | null>(null); |
|||
|
|||
export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({ |
|||
children, |
|||
}) => { |
|||
const queryClient = useQueryClient(); |
|||
const location = useLocation(); |
|||
const isBare = |
|||
location.search.includes('bare=1') || location.search.includes('embed=1'); |
|||
|
|||
const [isCartBusy, setIsCartBusy] = useState(false); |
|||
const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null); |
|||
const [selectedShippingCode, setSelectedShippingCode] = useState<string>('standard'); |
|||
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('google_pay'); |
|||
const [habibCoinsBalance, setHabibCoinsBalance] = useState<number>(() => |
|||
typeof window !== 'undefined' && typeof window.HABIB_COINS === 'number' |
|||
? window.HABIB_COINS |
|||
: USE_MOCK_DATA |
|||
? 21 |
|||
: 0 |
|||
); |
|||
const [language, setLanguage] = useState<string>(() => getUserLanguage()); |
|||
const [authToken, setAuthToken] = useState<string>(() => getToken()); |
|||
const [loginModalState, setLoginModalState] = useState<{ |
|||
isOpen: boolean; |
|||
title: string; |
|||
description: string; |
|||
onAuthenticated?: () => void; |
|||
}>({ |
|||
isOpen: false, |
|||
title: 'Sign in Required', |
|||
description: 'Please log in with your Habib account to continue.', |
|||
}); |
|||
const [isLoggingIn, setIsLoggingIn] = useState(false); |
|||
const loginResolverRef = useRef<((authenticated: boolean) => void) | null>(null); |
|||
const [toastMessage, setToastMessage] = useState<string | null>(null); |
|||
const toastTimerRef = useRef<number | undefined>(undefined); |
|||
|
|||
useHabibWebReady(true); |
|||
|
|||
useEffect(() => { |
|||
ensureGuestToken(); |
|||
}, []); |
|||
|
|||
const cartQuery = useQuery({ |
|||
queryKey: shopKeys.cart(), |
|||
queryFn: () => shopApi.fetchCart(false), |
|||
enabled: !isBare, |
|||
}); |
|||
|
|||
const profileQuery = useQuery({ |
|||
queryKey: shopKeys.profile(), |
|||
queryFn: () => shopApi.fetchProfile(), |
|||
enabled: !isBare, |
|||
}); |
|||
|
|||
const addressesQuery = useQuery({ |
|||
queryKey: shopKeys.addresses(), |
|||
queryFn: () => shopApi.fetchAddresses(), |
|||
enabled: !isBare, |
|||
}); |
|||
|
|||
const shippingMethodsQuery = useQuery({ |
|||
queryKey: shopKeys.shippingMethods(), |
|||
queryFn: () => shopApi.fetchShippingMethods(), |
|||
enabled: !isBare, |
|||
staleTime: 5 * 60_000, |
|||
}); |
|||
|
|||
const bookmarksQuery = useQuery({ |
|||
queryKey: shopKeys.bookmarks(), |
|||
queryFn: () => shopApi.fetchBookmarks(), |
|||
enabled: !isBare, |
|||
}); |
|||
|
|||
const orderCountersQuery = useQuery({ |
|||
queryKey: shopKeys.orderCounters(), |
|||
queryFn: () => shopApi.fetchOrderCounters(), |
|||
enabled: !isBare, |
|||
}); |
|||
|
|||
const hydrated = |
|||
isBare || (!cartQuery.isPending && !bookmarksQuery.isPending); |
|||
const cart = cartQuery.data ?? null; |
|||
const profile = profileQuery.data ?? null; |
|||
const orderCounters = orderCountersQuery.data ?? null; |
|||
|
|||
const isUserAuthenticated = useMemo(() => { |
|||
if (isBare) return true; |
|||
if (profile !== null) { |
|||
return Boolean(profile.is_authenticated); |
|||
} |
|||
return Boolean(authToken || getToken()); |
|||
}, [authToken, isBare, profile]); |
|||
|
|||
const addresses = useMemo( |
|||
() => addressesQuery.data?.results ?? [], |
|||
[addressesQuery.data] |
|||
); |
|||
|
|||
const shippingMethods = useMemo( |
|||
() => shippingMethodsQuery.data?.results ?? [], |
|||
[shippingMethodsQuery.data] |
|||
); |
|||
|
|||
const bookmarkedProducts = useMemo( |
|||
() => |
|||
(bookmarksQuery.data?.results ?? []) |
|||
.map((entry) => entry.product_detail) |
|||
.filter((p): p is ApiProductCard => Boolean(p)), |
|||
[bookmarksQuery.data] |
|||
); |
|||
|
|||
const bookmarkedIdSet = useMemo( |
|||
() => new Set(bookmarkedProducts.map((p) => p.id)), |
|||
[bookmarkedProducts] |
|||
); |
|||
|
|||
const bookmarkedSlugSet = useMemo( |
|||
() => new Set(bookmarkedProducts.map((p) => p.slug)), |
|||
[bookmarkedProducts] |
|||
); |
|||
|
|||
useEffect(() => { |
|||
if (typeof profile?.habib_coins_balance === 'number') { |
|||
setHabibCoinsBalance(profile.habib_coins_balance); |
|||
} |
|||
}, [profile?.habib_coins_balance]); |
|||
|
|||
const showToast = useCallback((message: string) => { |
|||
setToastMessage(message); |
|||
if (typeof window !== 'undefined') { |
|||
if (toastTimerRef.current !== undefined) { |
|||
window.clearTimeout(toastTimerRef.current); |
|||
} |
|||
toastTimerRef.current = window.setTimeout(() => { |
|||
setToastMessage(null); |
|||
}, 2400); |
|||
} |
|||
}, []); |
|||
|
|||
const refreshCart = useCallback(async () => { |
|||
await queryClient.invalidateQueries({ queryKey: shopKeys.cart() }); |
|||
}, [queryClient]); |
|||
|
|||
const refreshAccountData = useCallback(async () => { |
|||
await Promise.allSettled([ |
|||
queryClient.invalidateQueries({ queryKey: shopKeys.profile() }), |
|||
queryClient.invalidateQueries({ queryKey: shopKeys.addresses() }), |
|||
queryClient.invalidateQueries({ queryKey: shopKeys.shippingMethods() }), |
|||
queryClient.invalidateQueries({ queryKey: shopKeys.bookmarks() }), |
|||
queryClient.invalidateQueries({ queryKey: shopKeys.orderCounters() }), |
|||
queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() }), |
|||
]); |
|||
}, [queryClient]); |
|||
|
|||
useEffect(() => { |
|||
if (typeof window === 'undefined') return; |
|||
|
|||
const handleTokenChange = async ( |
|||
event: WindowEventMap['habib:auth-token-changed'] |
|||
) => { |
|||
const nextToken = event.detail?.token ?? getToken(); |
|||
setAuthToken(nextToken || ''); |
|||
clearUserScopedCache(queryClient); |
|||
if (nextToken) { |
|||
try { |
|||
const merged = await shopApi.mergeGuestCart(ensureGuestToken()); |
|||
queryClient.setQueryData<ApiCart>(shopKeys.cart(), merged); |
|||
} catch { |
|||
// fallback to query invalidation below
|
|||
} |
|||
} |
|||
await queryClient.invalidateQueries({ queryKey: shopKeys.all }); |
|||
}; |
|||
|
|||
const handleCoinsChange = (event: WindowEventMap['habib:coins-changed']) => { |
|||
if (typeof event.detail?.coins === 'number') { |
|||
setHabibCoinsBalance(event.detail.coins); |
|||
} |
|||
}; |
|||
|
|||
window.addEventListener('habib:auth-token-changed', handleTokenChange); |
|||
window.addEventListener('habib:coins-changed', handleCoinsChange); |
|||
return () => { |
|||
window.removeEventListener('habib:auth-token-changed', handleTokenChange); |
|||
window.removeEventListener('habib:coins-changed', handleCoinsChange); |
|||
}; |
|||
}, [queryClient]); |
|||
|
|||
const closeLoginModal = useCallback(() => { |
|||
setIsLoggingIn(false); |
|||
setLoginModalState((prev) => ({ |
|||
...prev, |
|||
isOpen: false, |
|||
onAuthenticated: undefined, |
|||
})); |
|||
if (loginResolverRef.current) { |
|||
const resolve = loginResolverRef.current; |
|||
loginResolverRef.current = null; |
|||
resolve(false); |
|||
} |
|||
}, []); |
|||
|
|||
const openLoginModal = useCallback((options?: LoginModalOptions) => { |
|||
const title = options?.title || 'Sign in Required'; |
|||
const description = |
|||
options?.description || |
|||
(options?.featureName |
|||
? `Please log in with your Habib account to access ${options.featureName}.` |
|||
: 'Please log in with your Habib account to continue.'); |
|||
setLoginModalState({ |
|||
isOpen: true, |
|||
title, |
|||
description, |
|||
onAuthenticated: options?.onAuthenticated, |
|||
}); |
|||
}, []); |
|||
|
|||
const requireAuth = useCallback( |
|||
(options?: LoginModalOptions): Promise<boolean> => { |
|||
if (isBare || isUserAuthenticated) { |
|||
options?.onAuthenticated?.(); |
|||
return Promise.resolve(true); |
|||
} |
|||
openLoginModal(options); |
|||
return new Promise<boolean>((resolve) => { |
|||
if (loginResolverRef.current) { |
|||
loginResolverRef.current(false); |
|||
} |
|||
loginResolverRef.current = resolve; |
|||
}); |
|||
}, |
|||
[isBare, isUserAuthenticated, openLoginModal] |
|||
); |
|||
|
|||
const handleConfirmModalLogin = useCallback(async () => { |
|||
if (isLoggingIn) return; |
|||
setIsLoggingIn(true); |
|||
try { |
|||
const token = await ensureToken(60000, { forceLogin: true }); |
|||
if (token) { |
|||
setAuthToken(token); |
|||
await Promise.allSettled([refreshAccountData(), refreshCart()]); |
|||
const pendingCallback = loginModalState.onAuthenticated; |
|||
setIsLoggingIn(false); |
|||
setLoginModalState((prev) => ({ |
|||
...prev, |
|||
isOpen: false, |
|||
onAuthenticated: undefined, |
|||
})); |
|||
if (loginResolverRef.current) { |
|||
const resolve = loginResolverRef.current; |
|||
loginResolverRef.current = null; |
|||
resolve(true); |
|||
} |
|||
showToast('Signed in with Habib'); |
|||
pendingCallback?.(); |
|||
} else { |
|||
setIsLoggingIn(false); |
|||
showToast('Sign-in canceled'); |
|||
} |
|||
} catch { |
|||
setIsLoggingIn(false); |
|||
showToast('Could not complete sign-in'); |
|||
} |
|||
}, [ |
|||
isLoggingIn, |
|||
loginModalState.onAuthenticated, |
|||
refreshAccountData, |
|||
refreshCart, |
|||
showToast, |
|||
]); |
|||
|
|||
const addToCart = useCallback( |
|||
async ( |
|||
productRef: string | number, |
|||
quantity = 1, |
|||
variantId?: number | null |
|||
): Promise<ApiCart | null> => { |
|||
setIsCartBusy(true); |
|||
try { |
|||
const updated = await shopApi.addCartItem({ |
|||
product_id: productRef, |
|||
quantity, |
|||
variant_id: variantId, |
|||
}); |
|||
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
showToast('Added to cart'); |
|||
return updated; |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not add item'); |
|||
return null; |
|||
} finally { |
|||
setIsCartBusy(false); |
|||
} |
|||
}, |
|||
[queryClient, showToast] |
|||
); |
|||
|
|||
const updateCartItemQuantity = useCallback( |
|||
async (itemId: number, quantity: number) => { |
|||
setIsCartBusy(true); |
|||
try { |
|||
const updated = await shopApi.updateCartItem(itemId, quantity); |
|||
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not update cart'); |
|||
} finally { |
|||
setIsCartBusy(false); |
|||
} |
|||
}, |
|||
[queryClient, showToast] |
|||
); |
|||
|
|||
const removeCartItem = useCallback( |
|||
async (itemId: number) => { |
|||
setIsCartBusy(true); |
|||
try { |
|||
const updated = await shopApi.removeCartItem(itemId); |
|||
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not remove item'); |
|||
} finally { |
|||
setIsCartBusy(false); |
|||
} |
|||
}, |
|||
[queryClient, showToast] |
|||
); |
|||
|
|||
const clearCart = useCallback(async () => { |
|||
setIsCartBusy(true); |
|||
try { |
|||
const updated = await shopApi.clearCart(); |
|||
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not clear cart'); |
|||
} finally { |
|||
setIsCartBusy(false); |
|||
} |
|||
}, [queryClient, showToast]); |
|||
|
|||
const applyPromoCode = useCallback( |
|||
async (code: string): Promise<boolean> => { |
|||
setIsCartBusy(true); |
|||
try { |
|||
const updated = await shopApi.applyPromoCode(code); |
|||
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated); |
|||
showToast(code ? `Promo "${code.toUpperCase()}" applied` : 'Promo removed'); |
|||
return true; |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Invalid promo code'); |
|||
return false; |
|||
} finally { |
|||
setIsCartBusy(false); |
|||
} |
|||
}, |
|||
[queryClient, showToast] |
|||
); |
|||
|
|||
const isBookmarked = useCallback( |
|||
(productId?: number | null, slug?: string | null): boolean => { |
|||
if (productId && bookmarkedIdSet.has(productId)) return true; |
|||
if (slug && bookmarkedSlugSet.has(slug)) return true; |
|||
return false; |
|||
}, |
|||
[bookmarkedIdSet, bookmarkedSlugSet] |
|||
); |
|||
|
|||
const toggleBookmark = useCallback( |
|||
async ( |
|||
productRef: string | number, |
|||
numericId?: number, |
|||
slug?: string |
|||
): Promise<boolean> => { |
|||
const currentlySaved = isBookmarked(numericId, slug || String(productRef)); |
|||
if (!isBare && !isUserAuthenticated) { |
|||
const authed = await requireAuth({ |
|||
featureName: 'saved items', |
|||
}); |
|||
if (!authed) return currentlySaved; |
|||
} |
|||
try { |
|||
if (currentlySaved) { |
|||
await shopApi.removeBookmark(productRef); |
|||
await queryClient.invalidateQueries({ queryKey: shopKeys.bookmarks() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.productDetailsAll(), |
|||
}); |
|||
showToast('Removed from saved items'); |
|||
return false; |
|||
} |
|||
await shopApi.addBookmark(productRef); |
|||
await queryClient.invalidateQueries({ queryKey: shopKeys.bookmarks() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.productDetailsAll(), |
|||
}); |
|||
showToast('Saved to bookmarks'); |
|||
return true; |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not update bookmark'); |
|||
return currentlySaved; |
|||
} |
|||
}, |
|||
[isBare, isBookmarked, isUserAuthenticated, queryClient, requireAuth, showToast] |
|||
); |
|||
|
|||
const selectAddress = useCallback((id: number) => { |
|||
setSelectedAddressId(id); |
|||
}, []); |
|||
|
|||
const saveAddress = useCallback( |
|||
async (input: SaveAddressInput): Promise<ApiAddress | null> => { |
|||
if (!isBare && !isUserAuthenticated) { |
|||
const authed = await requireAuth({ |
|||
featureName: 'delivery addresses', |
|||
}); |
|||
if (!authed) return null; |
|||
} |
|||
try { |
|||
let saved: ApiAddress; |
|||
if (input.id) { |
|||
saved = await shopApi.updateAddress(input.id, input); |
|||
} else { |
|||
saved = await shopApi.createAddress(input); |
|||
} |
|||
await queryClient.invalidateQueries({ queryKey: shopKeys.addresses() }); |
|||
setSelectedAddressId(saved.id); |
|||
showToast(input.id ? 'Address updated' : 'Address added'); |
|||
return saved; |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not save address'); |
|||
return null; |
|||
} |
|||
}, |
|||
[isBare, isUserAuthenticated, queryClient, requireAuth, showToast] |
|||
); |
|||
|
|||
const deleteAddress = useCallback( |
|||
async (id: number) => { |
|||
if (!isBare && !isUserAuthenticated) { |
|||
const authed = await requireAuth({ |
|||
featureName: 'delivery addresses', |
|||
}); |
|||
if (!authed) return; |
|||
} |
|||
try { |
|||
await shopApi.deleteAddress(id); |
|||
await queryClient.invalidateQueries({ queryKey: shopKeys.addresses() }); |
|||
setSelectedAddressId((prev) => (prev === id ? null : prev)); |
|||
showToast('Address deleted'); |
|||
} catch (err) { |
|||
showToast(err instanceof Error ? err.message : 'Could not delete address'); |
|||
} |
|||
}, |
|||
[isBare, isUserAuthenticated, queryClient, requireAuth, showToast] |
|||
); |
|||
|
|||
const selectShippingMethod = useCallback( |
|||
(codeOrId: string | number) => { |
|||
const found = shippingMethods.find( |
|||
(m) => m.code === String(codeOrId) || m.id === Number(codeOrId) |
|||
); |
|||
if (found) { |
|||
setSelectedShippingCode(found.code); |
|||
} else { |
|||
setSelectedShippingCode(String(codeOrId)); |
|||
} |
|||
}, |
|||
[shippingMethods] |
|||
); |
|||
|
|||
const changeLanguage = useCallback( |
|||
(lang: string) => { |
|||
setUserLanguage(lang); |
|||
setLanguage(lang); |
|||
const label = |
|||
lang === 'fa' ? 'فارسی' : lang === 'ar' ? 'العربية' : 'English'; |
|||
showToast(`Language set to ${label}`); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.all }); |
|||
}, |
|||
[queryClient, showToast] |
|||
); |
|||
|
|||
const selectedAddress = useMemo( |
|||
() => |
|||
addresses.find((a) => a.id === selectedAddressId) || |
|||
addresses.find((a) => a.is_default) || |
|||
addresses[0] || |
|||
null, |
|||
[addresses, selectedAddressId] |
|||
); |
|||
|
|||
const resolvedSelectedAddressId = selectedAddress?.id ?? null; |
|||
|
|||
const selectedShippingMethod = useMemo( |
|||
() => |
|||
shippingMethods.find((m) => m.code === selectedShippingCode) || |
|||
shippingMethods.find((m) => m.is_default) || |
|||
shippingMethods[0] || |
|||
null, |
|||
[selectedShippingCode, shippingMethods] |
|||
); |
|||
|
|||
const cartItemsCount = cart?.items?.length ?? 0; |
|||
const cartTotalQuantity = |
|||
cart?.pricing?.total_quantity ?? |
|||
cart?.items?.reduce((acc, item) => acc + item.quantity, 0) ?? |
|||
0; |
|||
|
|||
const value = useMemo<ShopAppContextValue>( |
|||
() => ({ |
|||
hydrated, |
|||
isUserAuthenticated, |
|||
openLoginModal, |
|||
closeLoginModal, |
|||
requireAuth, |
|||
cart, |
|||
cartItemsCount, |
|||
cartTotalQuantity, |
|||
isCartBusy, |
|||
addresses, |
|||
selectedAddressId: resolvedSelectedAddressId, |
|||
selectedAddress, |
|||
shippingMethods, |
|||
selectedShippingMethod, |
|||
selectedPaymentMethod, |
|||
setSelectedPaymentMethod, |
|||
bookmarkedProducts, |
|||
isBookmarked, |
|||
toggleBookmark, |
|||
profile, |
|||
orderCounters, |
|||
habibCoinsBalance, |
|||
setHabibCoinsBalance, |
|||
language, |
|||
changeLanguage, |
|||
addToCart, |
|||
updateCartItemQuantity, |
|||
removeCartItem, |
|||
clearCart, |
|||
applyPromoCode, |
|||
selectAddress, |
|||
saveAddress, |
|||
deleteAddress, |
|||
selectShippingMethod, |
|||
refreshCart, |
|||
refreshAccountData, |
|||
toastMessage, |
|||
showToast, |
|||
}), |
|||
[ |
|||
hydrated, |
|||
isUserAuthenticated, |
|||
openLoginModal, |
|||
closeLoginModal, |
|||
requireAuth, |
|||
cart, |
|||
cartItemsCount, |
|||
cartTotalQuantity, |
|||
isCartBusy, |
|||
addresses, |
|||
resolvedSelectedAddressId, |
|||
selectedAddress, |
|||
shippingMethods, |
|||
selectedShippingMethod, |
|||
selectedPaymentMethod, |
|||
bookmarkedProducts, |
|||
isBookmarked, |
|||
toggleBookmark, |
|||
profile, |
|||
orderCounters, |
|||
habibCoinsBalance, |
|||
language, |
|||
changeLanguage, |
|||
addToCart, |
|||
updateCartItemQuantity, |
|||
removeCartItem, |
|||
clearCart, |
|||
applyPromoCode, |
|||
selectAddress, |
|||
saveAddress, |
|||
deleteAddress, |
|||
selectShippingMethod, |
|||
refreshCart, |
|||
refreshAccountData, |
|||
toastMessage, |
|||
showToast, |
|||
] |
|||
); |
|||
|
|||
return ( |
|||
<ShopAppContext.Provider value={value}> |
|||
{children} |
|||
<LoginRequiredModal |
|||
isOpen={loginModalState.isOpen} |
|||
title={loginModalState.title} |
|||
description={loginModalState.description} |
|||
isLoggingIn={isLoggingIn} |
|||
onConfirmLogin={() => { |
|||
void handleConfirmModalLogin(); |
|||
}} |
|||
onClose={closeLoginModal} |
|||
/> |
|||
</ShopAppContext.Provider> |
|||
); |
|||
}; |
|||
|
|||
export function useShopApp(): ShopAppContextValue { |
|||
const ctx = useContext(ShopAppContext); |
|||
if (!ctx) { |
|||
throw new Error('useShopApp must be used inside ShopAppProvider'); |
|||
} |
|||
return ctx; |
|||
} |
|||
@ -0,0 +1,23 @@ |
|||
import { useEffect, useRef } from 'react'; |
|||
|
|||
export function useHabibWebReady(ready = true): void { |
|||
const announcedRef = useRef(false); |
|||
|
|||
useEffect(() => { |
|||
if (!ready || announcedRef.current || typeof window === 'undefined') return; |
|||
announcedRef.current = true; |
|||
|
|||
let raf2 = 0; |
|||
const raf1 = window.requestAnimationFrame(() => { |
|||
raf2 = window.requestAnimationFrame(() => { |
|||
window.__announceHabibWebReady?.(); |
|||
}); |
|||
}); |
|||
|
|||
return () => { |
|||
window.cancelAnimationFrame(raf1); |
|||
if (raf2) window.cancelAnimationFrame(raf2); |
|||
}; |
|||
}, [ready]); |
|||
} |
|||
|
|||
@ -0,0 +1,76 @@ |
|||
import { useEffect, useRef } from 'react'; |
|||
|
|||
type HardwareBackCallback = () => boolean; |
|||
|
|||
interface StackEntry { |
|||
id: number; |
|||
handler: () => boolean; |
|||
} |
|||
|
|||
let nextHandlerId = 1; |
|||
const backHandlerStack: StackEntry[] = []; |
|||
let globalHandlersInstalled = false; |
|||
|
|||
function runHardwareBackSync(): boolean { |
|||
if (typeof document !== 'undefined') { |
|||
const active = document.activeElement as HTMLElement | null; |
|||
if ( |
|||
active && |
|||
(active.tagName === 'INPUT' || |
|||
active.tagName === 'TEXTAREA' || |
|||
active.isContentEditable) |
|||
) { |
|||
active.blur(); |
|||
return true; |
|||
} |
|||
} |
|||
|
|||
for (let i = backHandlerStack.length - 1; i >= 0; i -= 1) { |
|||
try { |
|||
const handled = backHandlerStack[i].handler(); |
|||
if (handled) { |
|||
return true; |
|||
} |
|||
} catch { |
|||
// ignore individual handler errors
|
|||
} |
|||
} |
|||
|
|||
return false; |
|||
} |
|||
|
|||
export function ensureGlobalHardwareBackInstalled(): void { |
|||
if (typeof window === 'undefined' || globalHandlersInstalled) return; |
|||
globalHandlersInstalled = true; |
|||
window.__habibHandleHardwareBackSync = () => runHardwareBackSync(); |
|||
window.__habibHandleHardwareBack = () => Promise.resolve(runHardwareBackSync()); |
|||
} |
|||
|
|||
export function useHardwareBackHandler( |
|||
callback: HardwareBackCallback, |
|||
enabled = true |
|||
): void { |
|||
const callbackRef = useRef<HardwareBackCallback>(callback); |
|||
callbackRef.current = callback; |
|||
|
|||
useEffect(() => { |
|||
ensureGlobalHardwareBackInstalled(); |
|||
if (!enabled) return; |
|||
|
|||
const id = nextHandlerId; |
|||
nextHandlerId += 1; |
|||
const entry: StackEntry = { |
|||
id, |
|||
handler: () => callbackRef.current(), |
|||
}; |
|||
backHandlerStack.push(entry); |
|||
|
|||
return () => { |
|||
const idx = backHandlerStack.findIndex((item) => item.id === id); |
|||
if (idx !== -1) { |
|||
backHandlerStack.splice(idx, 1); |
|||
} |
|||
}; |
|||
}, [enabled]); |
|||
} |
|||
|
|||
@ -0,0 +1,50 @@ |
|||
import { useCallback } from 'react'; |
|||
import { useLocation, useNavigate } from 'react-router-dom'; |
|||
import { ROUTES } from '../lib/routes'; |
|||
import { closeService, isInFlutterWebView } from '../lib/webview-actions'; |
|||
|
|||
let inAppNavigationCount = 0; |
|||
|
|||
export function recordInAppNavigation(): void { |
|||
inAppNavigationCount += 1; |
|||
} |
|||
|
|||
export function getInAppNavigationCount(): number { |
|||
return inAppNavigationCount; |
|||
} |
|||
|
|||
export function useSmartBack(defaultFallback: string = ROUTES.home) { |
|||
const navigate = useNavigate(); |
|||
const location = useLocation(); |
|||
|
|||
return useCallback( |
|||
(overrideFallback?: string) => { |
|||
const targetFallback = overrideFallback || defaultFallback; |
|||
const isRoot = |
|||
location.pathname === '/' || location.pathname === '/shop-home'; |
|||
|
|||
if (isRoot) { |
|||
if (isInFlutterWebView()) { |
|||
closeService(); |
|||
return; |
|||
} |
|||
navigate(ROUTES.test); |
|||
return; |
|||
} |
|||
|
|||
const historyIdx = |
|||
typeof window !== 'undefined' && |
|||
typeof window.history?.state?.idx === 'number' |
|||
? window.history.state.idx |
|||
: inAppNavigationCount; |
|||
|
|||
if (historyIdx > 0) { |
|||
navigate(-1); |
|||
} else { |
|||
navigate(targetFallback, { replace: true }); |
|||
} |
|||
}, |
|||
[defaultFallback, location.pathname, navigate] |
|||
); |
|||
} |
|||
|
|||
@ -0,0 +1,229 @@ |
|||
import { deleteCookie, getCookie, setCookie } from './cookies'; |
|||
|
|||
const TOKEN_COOKIE_NAME = 'HABIB_TOKEN'; |
|||
const REDIRECT_SESSION_KEY = 'redirect'; |
|||
|
|||
function cleanToken(raw: string | undefined | null): string { |
|||
if (!raw || typeof raw !== 'string') return ''; |
|||
const trimmed = raw.trim().replace(/^["']|["']$/g, ''); |
|||
if (!trimmed || trimmed === 'NO_TOKEN' || trimmed === 'null' || trimmed === 'undefined') { |
|||
return ''; |
|||
} |
|||
return trimmed; |
|||
} |
|||
|
|||
function readTokenFromBootstrap(): string { |
|||
if (typeof window === 'undefined') return ''; |
|||
const win = window as Window & { |
|||
__HABIB_BOOTSTRAP__?: Record<string, unknown>; |
|||
}; |
|||
const boot = win.__HABIB_BOOTSTRAP__; |
|||
if (!boot || typeof boot !== 'object') return ''; |
|||
const data = (boot.data as Record<string, unknown> | undefined) || {}; |
|||
const payload = (boot.payload as Record<string, unknown> | undefined) || {}; |
|||
const candidate = |
|||
boot.token || |
|||
boot.auth_token || |
|||
boot.authToken || |
|||
data.token || |
|||
data.auth_token || |
|||
data.authToken || |
|||
payload.token || |
|||
payload.auth_token || |
|||
payload.authToken; |
|||
return typeof candidate === 'string' ? cleanToken(candidate) : ''; |
|||
} |
|||
|
|||
function readTokenFromUrl(): string { |
|||
if (typeof window === 'undefined' || !window.location?.search) return ''; |
|||
try { |
|||
const sp = new URLSearchParams(window.location.search); |
|||
return cleanToken( |
|||
sp.get('token') || |
|||
sp.get('auth_token') || |
|||
sp.get('habib_token') || |
|||
sp.get(TOKEN_COOKIE_NAME) |
|||
); |
|||
} catch { |
|||
return ''; |
|||
} |
|||
} |
|||
|
|||
function readTokenFromSessionStorage(): string { |
|||
if (typeof window === 'undefined') return ''; |
|||
try { |
|||
return cleanToken(window.sessionStorage.getItem(TOKEN_COOKIE_NAME)); |
|||
} catch { |
|||
return ''; |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* Reads the authentication token provided by the Habib host app by default: |
|||
* 1. `window.HABIB_TOKEN` |
|||
* 2. URL query parameters (`token`, `auth_token`, `habib_token`, `HABIB_TOKEN`) |
|||
* 3. `window.__HABIB_BOOTSTRAP__` (`initial_config`) |
|||
* 4. `HABIB_TOKEN` / `habib_token` cookies set by Flutter `WebAppScreen._setCoockies()` |
|||
* 5. `sessionStorage.getItem('HABIB_TOKEN')` |
|||
*/ |
|||
export function getToken(): string { |
|||
if (typeof window === 'undefined') return ''; |
|||
const winToken = cleanToken(window.HABIB_TOKEN); |
|||
if (winToken) return winToken; |
|||
|
|||
const urlToken = readTokenFromUrl(); |
|||
if (urlToken) { |
|||
window.HABIB_TOKEN = urlToken; |
|||
return urlToken; |
|||
} |
|||
|
|||
const bootstrapToken = readTokenFromBootstrap(); |
|||
if (bootstrapToken) { |
|||
window.HABIB_TOKEN = bootstrapToken; |
|||
return bootstrapToken; |
|||
} |
|||
|
|||
const cookieToken = |
|||
cleanToken(getCookie(TOKEN_COOKIE_NAME)) || cleanToken(getCookie('habib_token')); |
|||
if (cookieToken) { |
|||
return cookieToken; |
|||
} |
|||
|
|||
return readTokenFromSessionStorage(); |
|||
} |
|||
|
|||
export function isAuthenticated(): boolean { |
|||
return Boolean(getToken()); |
|||
} |
|||
|
|||
function postFlutterLoginMessage(): boolean { |
|||
if (typeof window === 'undefined') return false; |
|||
const channel = window.HabibApp ?? window.FlutterChannel; |
|||
if (!channel || typeof channel.postMessage !== 'function') { |
|||
return false; |
|||
} |
|||
try { |
|||
channel.postMessage(JSON.stringify({ action: 'login' })); |
|||
return true; |
|||
} catch { |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
let inflightLoginPromise: Promise<string> | null = null; |
|||
|
|||
/** |
|||
* Ensures a valid Habib token exists, or triggers the native Flutter login screen |
|||
* via `window.HabibApp.postMessage(JSON.stringify({ action: 'login' }))` (matching Marriage's `authBridge.ensureToken()`). |
|||
*/ |
|||
export function ensureToken( |
|||
timeoutMs = 60000, |
|||
options?: { forceLogin?: boolean } |
|||
): Promise<string> { |
|||
if (!options?.forceLogin) { |
|||
const existing = getToken(); |
|||
if (existing) { |
|||
return Promise.resolve(existing); |
|||
} |
|||
} |
|||
|
|||
if (typeof window === 'undefined') { |
|||
return Promise.resolve(''); |
|||
} |
|||
|
|||
if (inflightLoginPromise) { |
|||
return inflightLoginPromise; |
|||
} |
|||
|
|||
try { |
|||
window.sessionStorage.setItem(REDIRECT_SESSION_KEY, 'true'); |
|||
} catch { |
|||
// ignore sessionStorage error
|
|||
} |
|||
|
|||
inflightLoginPromise = new Promise<string>((resolve) => { |
|||
let settled = false; |
|||
let timerId: number | undefined; |
|||
let removeFlutterListener: (() => void) | undefined; |
|||
|
|||
const finish = (token: string) => { |
|||
if (settled) return; |
|||
settled = true; |
|||
if (timerId !== undefined) window.clearTimeout(timerId); |
|||
window.removeEventListener('habib:auth-token-changed', onTokenEvent); |
|||
if (removeFlutterListener) removeFlutterListener(); |
|||
inflightLoginPromise = null; |
|||
resolve(token); |
|||
}; |
|||
|
|||
const syncAfterBridgeLogin = (explicitToken?: string): string => { |
|||
const candidate = |
|||
cleanToken(explicitToken) || |
|||
cleanToken(getCookie(TOKEN_COOKIE_NAME)) || |
|||
cleanToken(getCookie('habib_token')) || |
|||
getToken(); |
|||
if (candidate) { |
|||
setCookie(TOKEN_COOKIE_NAME, candidate); |
|||
window.HABIB_TOKEN = candidate; |
|||
} |
|||
return candidate; |
|||
}; |
|||
|
|||
const onTokenEvent = (event: WindowEventMap['habib:auth-token-changed']) => { |
|||
const next = cleanToken(event.detail?.token) || getToken(); |
|||
if (next) { |
|||
finish(next); |
|||
} |
|||
}; |
|||
|
|||
window.addEventListener('habib:auth-token-changed', onTokenEvent); |
|||
|
|||
if (typeof window.addFlutterResponseListener === 'function') { |
|||
removeFlutterListener = window.addFlutterResponseListener((payload) => { |
|||
const action = String( |
|||
payload?.action || (payload as Record<string, unknown>)?.type || '' |
|||
).toLowerCase(); |
|||
if (action === 'login') { |
|||
if (payload?.success === false) { |
|||
finish(''); |
|||
return; |
|||
} |
|||
const dataToken = |
|||
typeof payload?.data?.token === 'string' |
|||
? cleanToken(payload.data.token) |
|||
: ''; |
|||
const resolved = syncAfterBridgeLogin(dataToken); |
|||
finish(resolved); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
const sent = postFlutterLoginMessage(); |
|||
if (!sent) { |
|||
finish(getToken()); |
|||
return; |
|||
} |
|||
|
|||
timerId = window.setTimeout(() => { |
|||
finish(syncAfterBridgeLogin()); |
|||
}, timeoutMs); |
|||
}); |
|||
|
|||
return inflightLoginPromise; |
|||
} |
|||
|
|||
export function signOutLocal(): void { |
|||
deleteCookie(TOKEN_COOKIE_NAME); |
|||
deleteCookie('habib_token'); |
|||
if (typeof window !== 'undefined') { |
|||
try { |
|||
window.sessionStorage.removeItem(TOKEN_COOKIE_NAME); |
|||
} catch { |
|||
// ignore
|
|||
} |
|||
window.HABIB_TOKEN = ''; |
|||
window.dispatchEvent( |
|||
new CustomEvent('habib:auth-token-changed', { detail: { token: '' } }) |
|||
); |
|||
} |
|||
} |
|||
@ -0,0 +1,95 @@ |
|||
const GUEST_COOKIE_NAME = 'HABIB_GUEST_TOKEN'; |
|||
const SHOP_GUEST_STORAGE_KEY = 'habib_shop_guest_token'; |
|||
const FLUTTER_LANG_COOKIE_NAME = 'HABIB_LANGUAGE'; |
|||
const USER_LANG_COOKIE_NAME = 'HABIB_USER_LANGUAGE'; |
|||
const SHOP_LANG_STORAGE_KEY = 'habib_shop_language'; |
|||
|
|||
export function getCookie(name: string): string { |
|||
if (typeof document === 'undefined') return ''; |
|||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
|||
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${escaped}=([^;]*)`)); |
|||
return match ? decodeURIComponent(match[1]) : ''; |
|||
} |
|||
|
|||
export function setCookie(name: string, value: string, maxAgeDays = 365): void { |
|||
if (typeof document === 'undefined') return; |
|||
const maxAge = Math.floor(maxAgeDays * 86400); |
|||
document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; SameSite=Lax`; |
|||
} |
|||
|
|||
export function deleteCookie(name: string): void { |
|||
if (typeof document === 'undefined') return; |
|||
document.cookie = `${name}=; path=/; max-age=0; SameSite=Lax`; |
|||
} |
|||
|
|||
function generateRandomGuestToken(): string { |
|||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { |
|||
return `guest-${crypto.randomUUID()}`; |
|||
} |
|||
return `guest-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; |
|||
} |
|||
|
|||
export function ensureGuestToken(): string { |
|||
if (typeof window === 'undefined') return 'guest-ssr'; |
|||
const flutterGuest = getCookie(GUEST_COOKIE_NAME).trim(); |
|||
if (flutterGuest && flutterGuest !== 'null' && flutterGuest !== 'undefined') { |
|||
try { |
|||
window.localStorage.setItem(SHOP_GUEST_STORAGE_KEY, flutterGuest); |
|||
} catch { |
|||
// ignore storage quota errors
|
|||
} |
|||
return flutterGuest; |
|||
} |
|||
|
|||
let stored = ''; |
|||
try { |
|||
stored = (window.localStorage.getItem(SHOP_GUEST_STORAGE_KEY) || '').trim(); |
|||
} catch { |
|||
stored = ''; |
|||
} |
|||
if (!stored) { |
|||
stored = getCookie(SHOP_GUEST_STORAGE_KEY).trim(); |
|||
} |
|||
if (!stored) { |
|||
stored = generateRandomGuestToken(); |
|||
} |
|||
|
|||
try { |
|||
window.localStorage.setItem(SHOP_GUEST_STORAGE_KEY, stored); |
|||
} catch { |
|||
// ignore storage errors
|
|||
} |
|||
setCookie(SHOP_GUEST_STORAGE_KEY, stored, 365); |
|||
return stored; |
|||
} |
|||
|
|||
export function getUserLanguage(): string { |
|||
if (typeof window === 'undefined') return 'en'; |
|||
const fromCookie = ( |
|||
getCookie(FLUTTER_LANG_COOKIE_NAME) || |
|||
getCookie(USER_LANG_COOKIE_NAME) || |
|||
getCookie('USER_LANGUAGE') |
|||
).trim(); |
|||
if (fromCookie) return fromCookie; |
|||
try { |
|||
const stored = (window.localStorage.getItem(SHOP_LANG_STORAGE_KEY) || '').trim(); |
|||
if (stored) return stored; |
|||
} catch { |
|||
// ignore storage errors
|
|||
} |
|||
return 'en'; |
|||
} |
|||
|
|||
export function setUserLanguage(lang: string): void { |
|||
const normalized = (lang || 'en').trim().toLowerCase(); |
|||
setCookie(FLUTTER_LANG_COOKIE_NAME, normalized, 365); |
|||
setCookie(USER_LANG_COOKIE_NAME, normalized, 365); |
|||
if (typeof window !== 'undefined') { |
|||
try { |
|||
window.localStorage.setItem(SHOP_LANG_STORAGE_KEY, normalized); |
|||
} catch { |
|||
// ignore storage errors
|
|||
} |
|||
} |
|||
} |
|||
|
|||
@ -0,0 +1,166 @@ |
|||
import { getToken } from './auth-bridge'; |
|||
import { ensureGuestToken, getUserLanguage } from './cookies'; |
|||
|
|||
const API_BASE = (import.meta.env.VITE_API_BASE_URL as string | undefined) || '/api/shop'; |
|||
const THROTTLE_STORAGE_KEY = 'HABIB_SHOP_THROTTLE_MS'; |
|||
|
|||
export function resolveClientThrottleMs(): number { |
|||
if (typeof window === 'undefined') return 0; |
|||
try { |
|||
const params = new URLSearchParams(window.location.search); |
|||
const paramVal = params.get('throttle') ?? params.get('throttle_ms'); |
|||
if (paramVal !== null) { |
|||
const parsed = Number.parseInt(paramVal, 10); |
|||
if (!Number.isFinite(parsed) || parsed <= 0) { |
|||
window.sessionStorage.removeItem(THROTTLE_STORAGE_KEY); |
|||
return 0; |
|||
} |
|||
const clamped = Math.min(parsed, 5000); |
|||
window.sessionStorage.setItem(THROTTLE_STORAGE_KEY, String(clamped)); |
|||
return clamped; |
|||
} |
|||
const stored = window.sessionStorage.getItem(THROTTLE_STORAGE_KEY); |
|||
if (stored) { |
|||
const parsed = Number.parseInt(stored, 10); |
|||
if (Number.isFinite(parsed) && parsed > 0) { |
|||
return Math.min(parsed, 5000); |
|||
} |
|||
} |
|||
} catch { |
|||
// ignore storage access issues in restricted webviews
|
|||
} |
|||
return 0; |
|||
} |
|||
|
|||
export class ShopApiError extends Error { |
|||
status: number; |
|||
data: unknown; |
|||
|
|||
constructor(message: string, status: number, data?: unknown) { |
|||
super(message); |
|||
this.name = 'ShopApiError'; |
|||
this.status = status; |
|||
this.data = data; |
|||
} |
|||
} |
|||
|
|||
export function resolveMediaUrl(url: string | undefined | null, fallback = ''): string { |
|||
if (!url) return fallback; |
|||
if ( |
|||
url.startsWith('http://') || |
|||
url.startsWith('https://') || |
|||
url.startsWith('blob:') || |
|||
url.startsWith('data:') || |
|||
url.startsWith('/') |
|||
) { |
|||
return url; |
|||
} |
|||
return `/${url}`; |
|||
} |
|||
|
|||
interface RequestOptions { |
|||
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; |
|||
body?: unknown; |
|||
query?: Record<string, string | number | boolean | undefined | null>; |
|||
signal?: AbortSignal; |
|||
} |
|||
|
|||
function buildUrl( |
|||
endpoint: string, |
|||
query?: Record<string, string | number | boolean | undefined | null> |
|||
): string { |
|||
const cleanBase = API_BASE.replace(/\/+$/, ''); |
|||
const cleanPath = endpoint.startsWith('/') ? endpoint : `/${endpoint}`; |
|||
let full = `${cleanBase}${cleanPath}`; |
|||
|
|||
if (query) { |
|||
const params = new URLSearchParams(); |
|||
for (const [key, val] of Object.entries(query)) { |
|||
if (val !== undefined && val !== null && val !== '') { |
|||
params.set(key, String(val)); |
|||
} |
|||
} |
|||
const qs = params.toString(); |
|||
if (qs) { |
|||
full += (full.includes('?') ? '&' : '?') + qs; |
|||
} |
|||
} |
|||
return full; |
|||
} |
|||
|
|||
export async function shopRequest<T>( |
|||
endpoint: string, |
|||
options: RequestOptions = {} |
|||
): Promise<T> { |
|||
const { method = 'GET', body, query, signal } = options; |
|||
const headers: Record<string, string> = { |
|||
Accept: 'application/json', |
|||
}; |
|||
|
|||
const token = getToken(); |
|||
if (token) { |
|||
headers.Authorization = `Token ${token}`; |
|||
} |
|||
|
|||
const guestToken = ensureGuestToken(); |
|||
if (guestToken) { |
|||
headers['X-Guest-Token'] = guestToken; |
|||
} |
|||
|
|||
const lang = getUserLanguage(); |
|||
if (lang) { |
|||
headers['Accept-Language'] = lang; |
|||
headers['X-User-Language'] = lang; |
|||
} |
|||
|
|||
const throttleMs = resolveClientThrottleMs(); |
|||
if (throttleMs > 0) { |
|||
headers['X-Shop-Throttle-Ms'] = String(throttleMs); |
|||
} |
|||
|
|||
let fetchBody: BodyInit | undefined; |
|||
if (body !== undefined) { |
|||
if (body instanceof FormData) { |
|||
fetchBody = body; |
|||
} else { |
|||
headers['Content-Type'] = 'application/json'; |
|||
fetchBody = JSON.stringify(body); |
|||
} |
|||
} |
|||
|
|||
const response = await fetch(buildUrl(endpoint, query), { |
|||
method, |
|||
headers, |
|||
body: fetchBody, |
|||
signal, |
|||
}); |
|||
|
|||
if (response.status === 204) { |
|||
return undefined as T; |
|||
} |
|||
|
|||
let parsed: unknown = null; |
|||
const contentType = response.headers.get('content-type') || ''; |
|||
if (contentType.includes('application/json')) { |
|||
try { |
|||
parsed = await response.json(); |
|||
} catch { |
|||
parsed = null; |
|||
} |
|||
} else { |
|||
parsed = await response.text(); |
|||
} |
|||
|
|||
if (!response.ok) { |
|||
const errObj = (parsed && typeof parsed === 'object' ? parsed : {}) as Record<string, unknown>; |
|||
const message = |
|||
(typeof errObj.error === 'string' && errObj.error) || |
|||
(typeof errObj.detail === 'string' && errObj.detail) || |
|||
(typeof errObj.message === 'string' && errObj.message) || |
|||
`Request failed (${response.status})`; |
|||
throw new ShopApiError(message, response.status, parsed); |
|||
} |
|||
|
|||
return parsed as T; |
|||
} |
|||
|
|||
@ -0,0 +1,315 @@ |
|||
import type { |
|||
CategoryTileItem, |
|||
CompactProductItem, |
|||
GridProductItem, |
|||
} from '../data/catalogData'; |
|||
import type { |
|||
CartItemData, |
|||
PaymentReviewItem, |
|||
ShippingAddressOption, |
|||
} from '../data/checkoutData'; |
|||
import type { OrderCardData, ShipmentCardData } from '../data/ordersData'; |
|||
import { resolveMediaUrl } from './http'; |
|||
import type { |
|||
ApiAddress, |
|||
ApiCartItem, |
|||
ApiCategory, |
|||
ApiOrderSummary, |
|||
ApiProductCard, |
|||
ApiShipment, |
|||
} from './shopApi'; |
|||
|
|||
export function mapProductToCompactItem( |
|||
product: ApiProductCard, |
|||
bookmarkedOverride?: boolean |
|||
): CompactProductItem { |
|||
const ratingStr = |
|||
product.rating_avg !== undefined && product.rating_avg !== null |
|||
? String(Number(product.rating_avg).toFixed(1)).replace(/\.0$/, '') |
|||
: undefined; |
|||
|
|||
return { |
|||
id: `prod-${product.id}`, |
|||
relX: 0, |
|||
relY: 28, |
|||
imageSrc: |
|||
resolveMediaUrl(product.primary_image_url) || |
|||
'/assets/images/product-brown-leather-bag.png', |
|||
hasBookmark: |
|||
bookmarkedOverride !== undefined |
|||
? bookmarkedOverride |
|||
: Boolean(product.is_bookmarked), |
|||
rating: ratingStr, |
|||
ratingPillWidth: ratingStr && ratingStr.length > 1 ? 34 : 28, |
|||
title: product.title, |
|||
titleLines: product.title.length > 22 ? 2 : 1, |
|||
origin: product.origin_label || `${product.store_name || 'Habib Shop'}`, |
|||
originRelY: product.title.length > 22 ? 36 : 22, |
|||
oldPrice: product.formatted_old_price || undefined, |
|||
price: product.formatted_price || `$${product.price}`, |
|||
discountBadge: product.discount_badge || undefined, |
|||
}; |
|||
} |
|||
|
|||
export function mapProductToGridItem(product: ApiProductCard): GridProductItem { |
|||
const ratingStr = |
|||
product.rating_avg !== undefined && product.rating_avg !== null |
|||
? String(Number(product.rating_avg).toFixed(1)).replace(/\.0$/, '') |
|||
: '5'; |
|||
|
|||
return { |
|||
id: `grid-${product.id}`, |
|||
relX: 0, |
|||
relY: 0, |
|||
imageSrc: |
|||
resolveMediaUrl(product.primary_image_url) || |
|||
'/assets/images/product-brown-leather-bag.png', |
|||
imageRadius: 12, |
|||
rating: ratingStr, |
|||
ratingPillWidth: ratingStr.length > 1 ? 34 : 28, |
|||
ratingStarLeft: 4.5, |
|||
ratingTextLeft: 16.5, |
|||
ratingTextWidth: 15, |
|||
title: product.title, |
|||
titleLines: product.title.length > 22 ? 2 : 1, |
|||
origin: product.origin_label || `${product.store_name || 'Habib Shop'}`, |
|||
originRelY: product.title.length > 22 ? 36 : 22, |
|||
oldPrice: product.formatted_old_price || undefined, |
|||
price: product.formatted_price || `$${product.price}`, |
|||
discountBadge: product.discount_badge || undefined, |
|||
}; |
|||
} |
|||
|
|||
export function mapCategoryToTile( |
|||
category: ApiCategory, |
|||
index: number |
|||
): CategoryTileItem { |
|||
const isRightCol = index % 2 === 1; |
|||
return { |
|||
id: `cat-${category.id}`, |
|||
x: isRightCol ? 194 : 16, |
|||
y: 111 + Math.floor(index / 2) * 132, |
|||
width: isRightCol ? 165 : 166, |
|||
isRightCol, |
|||
countBadgeLeft: isRightCol ? 134 : 135, |
|||
innerLeft: isRightCol ? 18 : 16, |
|||
label: category.localized_title || category.title, |
|||
labelRelY: 47, |
|||
iconSrc: |
|||
resolveMediaUrl(category.icon_url) || |
|||
'/assets/images/icon-cat-bag-large.svg', |
|||
iconLeft: 46.5, |
|||
iconWidth: 40, |
|||
iconHeight: 40, |
|||
}; |
|||
} |
|||
|
|||
export function mapCartItemToCard(item: ApiCartItem, index: number): CartItemData { |
|||
return { |
|||
id: String(item.id), |
|||
y: 69 + index * 133, |
|||
imageSrc: |
|||
resolveMediaUrl(item.image_url) || |
|||
'/assets/images/product-brown-leather-bag.png', |
|||
title: item.variant_title |
|||
? `${item.title} (${item.variant_title})` |
|||
: item.title, |
|||
titleHeight: item.title.length > 24 ? 28 : 17, |
|||
titleLineHeight: item.title.length > 24 ? 14 : 17, |
|||
originRelY: item.title.length > 24 ? 34 : 19, |
|||
origin: item.origin_label || item.store_name || 'Habib Shop', |
|||
quantity: String(item.quantity), |
|||
price: item.formatted_unit_price || `$${item.unit_price}`, |
|||
}; |
|||
} |
|||
|
|||
export function mapCartItemToReview( |
|||
item: ApiCartItem, |
|||
index: number |
|||
): PaymentReviewItem { |
|||
return { |
|||
id: String(item.id), |
|||
relY: index * 91, |
|||
imageSrc: |
|||
resolveMediaUrl(item.image_url) || |
|||
'/assets/images/product-brown-leather-bag.png', |
|||
title: item.title, |
|||
price: item.formatted_unit_price || `$${item.unit_price}`, |
|||
quantity: String(item.quantity), |
|||
}; |
|||
} |
|||
|
|||
export function mapAddressToOption( |
|||
addr: ApiAddress, |
|||
selectedId: number | null, |
|||
index: number |
|||
): ShippingAddressOption { |
|||
return { |
|||
id: String(addr.id), |
|||
relY: index * 97, |
|||
name: addr.recipient_name || addr.label || 'Recipient', |
|||
nameWidth: 90, |
|||
address: |
|||
addr.full_address || |
|||
[addr.street_line, addr.city, addr.postal_code, addr.country] |
|||
.filter(Boolean) |
|||
.join(', '), |
|||
selected: selectedId !== null ? addr.id === selectedId : addr.is_default, |
|||
}; |
|||
} |
|||
|
|||
export function mapOrderToCardData( |
|||
order: ApiOrderSummary, |
|||
index: number |
|||
): OrderCardData { |
|||
const thumbs = (order.thumbnails || []).slice(0, 5).map((src, idx) => ({ |
|||
src: resolveMediaUrl(src) || '/assets/images/product-brown-leather-bag.png', |
|||
relX: idx * 53, |
|||
radius: idx === 0 ? 12 : 8, |
|||
})); |
|||
|
|||
if (thumbs.length === 0) { |
|||
thumbs.push({ |
|||
src: '/assets/images/product-brown-leather-bag.png', |
|||
relX: 0, |
|||
radius: 12, |
|||
}); |
|||
} |
|||
|
|||
const extraCount = (order.thumbnails?.length || 0) - 5; |
|||
|
|||
return { |
|||
id: `order-${order.id}`, |
|||
y: 154 + index * 253, |
|||
orderCode: order.order_number, |
|||
price: order.formatted_total || `$${order.total_amount}`, |
|||
date: order.formatted_date, |
|||
thumbnails: thumbs, |
|||
moreCountBadge: extraCount > 0 ? `+${extraCount}` : undefined, |
|||
itemsCountText: `${order.items_count} item`, |
|||
shopsCountText: `${order.shops_count} shop`, |
|||
deliveryProgressText: `${order.delivered_shipments_count} / ${Math.max( |
|||
1, |
|||
order.total_shipments_count |
|||
)} Delivery`,
|
|||
}; |
|||
} |
|||
|
|||
export function mapShipmentToCardData( |
|||
shipment: ApiShipment, |
|||
orderDate: string, |
|||
index: number |
|||
): ShipmentCardData { |
|||
const isDelivered = shipment.status === 'delivered'; |
|||
const isShipping = shipment.status === 'shipping'; |
|||
const statusType: 'packed' | 'delivered' | 'shipping' = isDelivered |
|||
? 'delivered' |
|||
: isShipping |
|||
? 'shipping' |
|||
: 'packed'; |
|||
|
|||
const statusLabel = isDelivered |
|||
? 'Delivered' |
|||
: isShipping |
|||
? 'Shiping' |
|||
: shipment.status === 'canceled' |
|||
? 'Canceled' |
|||
: shipment.status === 'ordered' |
|||
? 'Ordered' |
|||
: 'Packed'; |
|||
|
|||
const statusIconSrc = isDelivered |
|||
? '/assets/images/icon-status-delivered-green.svg' |
|||
: isShipping |
|||
? '/assets/images/icon-status-shipping-gold.svg' |
|||
: '/assets/images/icon-status-packed-gold.svg'; |
|||
|
|||
const statusColor = isDelivered |
|||
? '#0eb13c' |
|||
: shipment.status === 'canceled' |
|||
? '#d44747' |
|||
: '#d78e06'; |
|||
|
|||
const statusBg = isDelivered |
|||
? 'rgba(14, 177, 60, 0.2)' |
|||
: shipment.status === 'canceled' |
|||
? 'rgba(212, 71, 71, 0.14)' |
|||
: 'rgba(239, 196, 126, 0.2)'; |
|||
|
|||
const thumbs = (shipment.thumbnails || []).map((src, idx) => ({ |
|||
src: resolveMediaUrl(src) || '/assets/images/product-brown-leather-bag.png', |
|||
relX: idx * 53, |
|||
radius: idx === 0 ? 12 : 8, |
|||
})); |
|||
|
|||
if (thumbs.length === 0) { |
|||
thumbs.push({ |
|||
src: '/assets/images/product-brown-leather-bag.png', |
|||
relX: 0, |
|||
radius: 12, |
|||
}); |
|||
} |
|||
|
|||
const infoRows: ShipmentCardData['infoRows'] = isShipping |
|||
? [ |
|||
{ |
|||
iconSrc: '/assets/images/icon-date-time-grey-18.svg', |
|||
label: 'Order', |
|||
labelWidth: 32, |
|||
value: orderDate || shipment.estimated_delivery_label, |
|||
valueLeft: 64, |
|||
relY: 10, |
|||
}, |
|||
{ |
|||
iconSrc: '/assets/images/icon-delivery-truck-grey-18.svg', |
|||
label: 'Tracking code', |
|||
labelWidth: 76, |
|||
value: shipment.tracking_code || 'HBB-TRK-102', |
|||
valueLeft: 108, |
|||
relY: 38, |
|||
}, |
|||
] |
|||
: [ |
|||
{ |
|||
iconSrc: isDelivered |
|||
? '/assets/images/icon-delivered-box-check-grey-18.svg' |
|||
: '/assets/images/icon-delivery-truck-grey-18.svg', |
|||
label: 'Delivery', |
|||
labelWidth: 45, |
|||
value: shipment.estimated_delivery_label || orderDate || '2-4 Days', |
|||
valueLeft: 77, |
|||
relY: 10, |
|||
}, |
|||
]; |
|||
|
|||
return { |
|||
id: `shipment-${shipment.id}`, |
|||
y: 213 + index * 241, |
|||
height: isShipping ? 249 : 221, |
|||
innerHeight: isShipping ? 173 : 145, |
|||
boothName: shipment.booth_name || 'Al-Hujjah Books', |
|||
boothAvatar: |
|||
resolveMediaUrl(shipment.booth_avatar) || |
|||
'/assets/images/avatar-al-hujjah-books.png', |
|||
statusType, |
|||
statusLabel, |
|||
statusBadgeLeft: isDelivered ? 233 : 244, |
|||
statusBadgeWidth: isDelivered ? 85 : 74, |
|||
statusIconSrc, |
|||
statusIconLeft: 6.5, |
|||
statusIconTop: 5.5, |
|||
statusIconSize: isDelivered || isShipping ? 16 : 15, |
|||
statusTextLeft: 26.5, |
|||
statusTextWidth: 48, |
|||
statusColor, |
|||
statusBg, |
|||
thumbnails: thumbs, |
|||
infoBoxHeight: infoRows.length > 1 ? 66 : 38, |
|||
infoRows, |
|||
stepperRelY: isShipping ? 200 : 172, |
|||
greenLineWidth: isDelivered ? 264 : isShipping ? 186 : 84, |
|||
completedSteps: shipment.completed_steps || (isDelivered ? 4 : isShipping ? 3 : 2), |
|||
deliveryLabelColor: isDelivered ? '#111111' : isShipping ? '#747474' : '#8b8b8b', |
|||
}; |
|||
} |
|||
|
|||
@ -0,0 +1,45 @@ |
|||
export const ROUTES = { |
|||
home: '/', |
|||
categories: '/categories', |
|||
category: (slug: string = 'home-living') => `/categories/${encodeURIComponent(slug)}`, |
|||
search: (query?: string) => |
|||
query && query.trim() |
|||
? `/search?q=${encodeURIComponent(query.trim())}` |
|||
: '/search', |
|||
product: (idOrSlug: string | number = 'islam-in-the-bible-book') => |
|||
`/products/${encodeURIComponent(String(idOrSlug))}`, |
|||
stores: '/stores', |
|||
store: (idOrSlug: string | number = 'tashakol-farzandan-rohhallah') => |
|||
`/stores/${encodeURIComponent(String(idOrSlug))}`, |
|||
chat: '/chat', |
|||
chatThread: (idOrSlug: string | number = 'al-hujjah-books') => |
|||
`/chat/${encodeURIComponent(String(idOrSlug))}`, |
|||
cart: '/cart', |
|||
checkoutShipping: '/checkout/shipping', |
|||
checkoutReview: '/checkout/review', |
|||
checkoutResult: (orderNumber: string = 'ORD-28465') => |
|||
`/checkout/result/${encodeURIComponent(orderNumber)}`, |
|||
orders: (tab?: 'current' | 'delivered' | 'canceled') => |
|||
tab ? `/orders?tab=${tab}` : '/orders', |
|||
orderDetail: (orderNumber: string = 'ORD-28465') => |
|||
`/orders/${encodeURIComponent(orderNumber)}`, |
|||
orderSupport: (orderNumber: string = 'ORD-28465') => |
|||
`/orders/${encodeURIComponent(orderNumber)}/support`, |
|||
support: '/support', |
|||
account: '/account', |
|||
bookmarks: '/account/bookmarks', |
|||
addresses: '/account/addresses', |
|||
profile: '/account/profile', |
|||
settings: '/account/settings', |
|||
test: '/test', |
|||
} as const; |
|||
|
|||
export const USE_MOCK_DATA = |
|||
String(import.meta.env.VITE_USE_MOCK_DATA ?? '').trim().toLowerCase() === 'true'; |
|||
|
|||
export function isBareMode(search: string): boolean { |
|||
if (!search) return false; |
|||
const params = new URLSearchParams(search); |
|||
return params.get('bare') === '1' || params.get('embed') === '1'; |
|||
} |
|||
|
|||
@ -0,0 +1,660 @@ |
|||
import { shopRequest } from './http'; |
|||
|
|||
export interface ApiBanner { |
|||
id: number; |
|||
slug: string; |
|||
title: string; |
|||
title_i18n?: Record<string, string>; |
|||
subtitle: string; |
|||
cta_label: string; |
|||
image_url: string; |
|||
target_route: string; |
|||
display_order: number; |
|||
} |
|||
|
|||
export interface ApiCategory { |
|||
id: number; |
|||
parent: number | null; |
|||
slug: string; |
|||
title: string; |
|||
localized_title: string; |
|||
title_i18n?: Record<string, string>; |
|||
icon_url: string; |
|||
small_icon_url: string; |
|||
accent_color: string; |
|||
display_order: number; |
|||
is_quick: boolean; |
|||
products_count: number; |
|||
} |
|||
|
|||
export interface ApiStoreSummary { |
|||
id: number; |
|||
slug: string; |
|||
name: string; |
|||
tagline: string; |
|||
country: string; |
|||
city: string; |
|||
origin_label: string; |
|||
logo_url: string; |
|||
banner_url: string; |
|||
badge: string; |
|||
membership_label: string; |
|||
sales_label: string; |
|||
since_label: string; |
|||
avg_response_time: string; |
|||
on_time_delivery_rate: number; |
|||
satisfaction_rate: number; |
|||
rating_avg: string | number; |
|||
reviews_count: number; |
|||
products_count: number; |
|||
is_verified: boolean; |
|||
} |
|||
|
|||
export interface ApiProductCard { |
|||
id: number; |
|||
slug: string; |
|||
sku: string; |
|||
title: string; |
|||
primary_image_url: string; |
|||
hero_image_url: string; |
|||
price: string; |
|||
formatted_price: string; |
|||
compare_at_price: string | null; |
|||
formatted_old_price: string | null; |
|||
discount_badge: string; |
|||
coin_price: number; |
|||
currency: string; |
|||
stock_qty: number; |
|||
origin_label: string; |
|||
rating_avg: string | number; |
|||
reviews_count: number; |
|||
store: number; |
|||
store_slug: string; |
|||
store_name: string; |
|||
category: number; |
|||
category_slug: string; |
|||
category_title: string; |
|||
is_popular: boolean; |
|||
is_new_store_pick: boolean; |
|||
is_bookmarked: boolean; |
|||
} |
|||
|
|||
export interface ApiProductMedia { |
|||
id: number; |
|||
image_url: string; |
|||
alt_text: string; |
|||
sort_order: number; |
|||
} |
|||
|
|||
export interface ApiProductVariant { |
|||
id: number; |
|||
sku: string; |
|||
title: string; |
|||
attributes_json: Record<string, string>; |
|||
price_override: string | null; |
|||
coin_price_override: number | null; |
|||
stock_qty: number; |
|||
is_active: boolean; |
|||
} |
|||
|
|||
export interface ApiReview { |
|||
id: number; |
|||
product: number; |
|||
author_name: string; |
|||
rating: number; |
|||
comment: string; |
|||
image_url: string; |
|||
formatted_date: string; |
|||
created_at: string; |
|||
} |
|||
|
|||
export interface ApiProductDetail extends ApiProductCard { |
|||
breadcrumb: string; |
|||
description: string; |
|||
condition_label: string; |
|||
processing_time_label: string; |
|||
product_type_label: string; |
|||
specs_json: Record<string, string>; |
|||
shipping_info_json: Record<string, string>; |
|||
store_detail: ApiStoreSummary; |
|||
media: ApiProductMedia[]; |
|||
variants: ApiProductVariant[]; |
|||
reviews: ApiReview[]; |
|||
related_products: ApiProductCard[]; |
|||
} |
|||
|
|||
export interface ApiStoreDetail extends ApiStoreSummary { |
|||
description: string; |
|||
created_at: string; |
|||
products: ApiProductCard[]; |
|||
} |
|||
|
|||
export interface ApiCartItem { |
|||
id: number; |
|||
product_id: number; |
|||
product_slug: string; |
|||
title: string; |
|||
image_url: string; |
|||
origin_label: string; |
|||
store_id: number; |
|||
store_slug: string; |
|||
store_name: string; |
|||
variant: number | null; |
|||
variant_title: string; |
|||
quantity: number; |
|||
unit_price: string; |
|||
formatted_unit_price: string; |
|||
line_total: string; |
|||
formatted_line_total: string; |
|||
coin_unit_price: number; |
|||
} |
|||
|
|||
export interface ApiCartPricing { |
|||
items_count: number; |
|||
total_quantity: number; |
|||
total_units?: number; |
|||
shops_count: number; |
|||
subtotal: string; |
|||
formatted_subtotal: string; |
|||
shipping_fee: string; |
|||
formatted_shipping_fee: string; |
|||
discount_amount: string; |
|||
formatted_discount: string; |
|||
formatted_discount_amount?: string; |
|||
promo_code: string; |
|||
total: string; |
|||
total_amount?: string; |
|||
formatted_total: string; |
|||
coin_total: number; |
|||
coins_total?: number; |
|||
} |
|||
|
|||
export interface ApiCart { |
|||
id: number; |
|||
currency: string; |
|||
promo_code: string; |
|||
items: ApiCartItem[]; |
|||
pricing: ApiCartPricing; |
|||
updated_at: string; |
|||
} |
|||
|
|||
export interface ApiAddress { |
|||
id: number; |
|||
label: string; |
|||
recipient_name: string; |
|||
phone: string; |
|||
country: string; |
|||
city: string; |
|||
street_line: string; |
|||
postal_code: string; |
|||
lat: string | number | null; |
|||
lon: string | number | null; |
|||
is_default: boolean; |
|||
full_address: string; |
|||
created_at: string; |
|||
} |
|||
|
|||
export interface ApiShippingMethod { |
|||
id: number; |
|||
code: string; |
|||
title: string; |
|||
title_i18n?: Record<string, string>; |
|||
subtitle: string; |
|||
price: string; |
|||
formatted_price: string; |
|||
coin_price: number; |
|||
estimated_days_min: number; |
|||
estimated_days_max: number; |
|||
is_default: boolean; |
|||
} |
|||
|
|||
export interface ApiPaymentMethod { |
|||
id: string; |
|||
code: string; |
|||
label: string; |
|||
icon_url: string; |
|||
is_default: boolean; |
|||
balance?: number; |
|||
} |
|||
|
|||
export interface ApiShipmentEvent { |
|||
id: number; |
|||
status: string; |
|||
title: string; |
|||
location: string; |
|||
formatted_time: string; |
|||
occurred_at: string; |
|||
} |
|||
|
|||
export interface ApiShipment { |
|||
id: number; |
|||
store: number; |
|||
booth_name: string; |
|||
booth_slug: string; |
|||
booth_avatar: string; |
|||
status: 'ordered' | 'packed' | 'shipping' | 'delivered' | 'canceled'; |
|||
carrier_name: string; |
|||
tracking_code: string; |
|||
estimated_delivery_label: string; |
|||
completed_steps: number; |
|||
thumbnails: string[]; |
|||
events: ApiShipmentEvent[]; |
|||
} |
|||
|
|||
export interface ApiOrderItem { |
|||
id: number; |
|||
product: number | null; |
|||
product_slug: string; |
|||
store: number; |
|||
store_name: string; |
|||
store_slug: string; |
|||
title_snapshot: string; |
|||
image_snapshot: string; |
|||
origin_snapshot: string; |
|||
unit_price: string; |
|||
formatted_unit_price: string; |
|||
coin_unit_price: number; |
|||
quantity: number; |
|||
line_total: string; |
|||
formatted_line_total: string; |
|||
} |
|||
|
|||
export interface ApiOrderSummary { |
|||
id: number; |
|||
order_number: string; |
|||
status: string; |
|||
payment_method: string; |
|||
payment_method_label: string; |
|||
payment_status: string; |
|||
currency: string; |
|||
total_amount: string; |
|||
formatted_total: string; |
|||
coins_charged: number; |
|||
formatted_date: string; |
|||
formatted_datetime: string; |
|||
thumbnails: string[]; |
|||
items_count: number; |
|||
shops_count: number; |
|||
delivered_shipments_count: number; |
|||
total_shipments_count: number; |
|||
placed_at: string; |
|||
} |
|||
|
|||
export interface ApiOrderDetail extends ApiOrderSummary { |
|||
subtotal: string; |
|||
formatted_subtotal: string; |
|||
shipping_fee: string; |
|||
formatted_shipping_fee: string; |
|||
discount_amount: string; |
|||
formatted_discount: string; |
|||
promo_code: string; |
|||
shipping_method_title: string; |
|||
shipping_address_snapshot: { |
|||
recipient_name?: string; |
|||
phone?: string; |
|||
full_address?: string; |
|||
city?: string; |
|||
country?: string; |
|||
street_line?: string; |
|||
}; |
|||
notes: string; |
|||
items: ApiOrderItem[]; |
|||
shipments: ApiShipment[]; |
|||
} |
|||
|
|||
export interface ApiOrderCounters { |
|||
current: number; |
|||
in_progress: number; |
|||
delivered: number; |
|||
canceled: number; |
|||
returned: number; |
|||
} |
|||
|
|||
export interface ApiUserProfile { |
|||
is_authenticated: boolean; |
|||
id?: number; |
|||
guest_token?: string; |
|||
full_name: string; |
|||
email: string; |
|||
phone_number: string; |
|||
avatar_url: string; |
|||
habib_coins_balance: number; |
|||
shop_provider: Record<string, unknown> | null; |
|||
provider_requests: { |
|||
id: number; |
|||
service: string; |
|||
status: string; |
|||
public_name: string; |
|||
created_at: string; |
|||
}[]; |
|||
} |
|||
|
|||
export interface ApiSupportSubject { |
|||
id: number; |
|||
slug: string; |
|||
label: string; |
|||
title_i18n?: Record<string, string>; |
|||
icon_url: string; |
|||
display_order: number; |
|||
} |
|||
|
|||
export interface ApiSupportTicket { |
|||
id: number; |
|||
ticket_number: string; |
|||
order: number | null; |
|||
order_number: string; |
|||
subject: number | null; |
|||
subject_label: string; |
|||
description: string; |
|||
attachment_url: string; |
|||
status: string; |
|||
admin_reply: string; |
|||
formatted_date: string; |
|||
created_at: string; |
|||
} |
|||
|
|||
export interface ApiConversation { |
|||
id: number; |
|||
store: number; |
|||
store_detail: ApiStoreSummary; |
|||
last_message_preview: string; |
|||
last_message_at: string | null; |
|||
formatted_last_time: string; |
|||
unread_user_count: number; |
|||
created_at: string; |
|||
} |
|||
|
|||
export interface ApiChatMessage { |
|||
id: number; |
|||
conversation: number; |
|||
sender_type: 'customer' | 'store' | 'system'; |
|||
text: string; |
|||
attachment_url: string; |
|||
product_ref: number | null; |
|||
order_ref: number | null; |
|||
is_read: boolean; |
|||
formatted_time: string; |
|||
date_group: string; |
|||
created_at: string; |
|||
} |
|||
|
|||
export interface HomeFeedResponse { |
|||
banners: ApiBanner[]; |
|||
quick_categories: ApiCategory[]; |
|||
categories: ApiCategory[]; |
|||
popular_products: ApiProductCard[]; |
|||
new_store_products: ApiProductCard[]; |
|||
featured_stores: ApiStoreSummary[]; |
|||
cart_items_count: number; |
|||
habib_coins_balance: number; |
|||
} |
|||
|
|||
export const shopApi = { |
|||
// Home & Catalog
|
|||
fetchHomeFeed: () => shopRequest<HomeFeedResponse>('/home/'), |
|||
|
|||
fetchCategories: (q?: string) => |
|||
shopRequest<{ results: ApiCategory[] }>('/categories/', { query: { q } }), |
|||
|
|||
fetchCategoryDetail: (slug: string, q?: string) => |
|||
shopRequest<{ category: ApiCategory; products: ApiProductCard[] }>( |
|||
`/categories/${encodeURIComponent(slug)}/`, |
|||
{ query: { q } } |
|||
), |
|||
|
|||
fetchProducts: (params?: { |
|||
q?: string; |
|||
category?: string; |
|||
store?: string; |
|||
popular?: boolean; |
|||
new_store?: boolean; |
|||
sort?: 'price_asc' | 'price_desc' | 'rating' | 'newest'; |
|||
}) => |
|||
shopRequest<{ count: number; results: ApiProductCard[] }>('/products/', { |
|||
query: params, |
|||
}), |
|||
|
|||
fetchProductDetail: (idOrSlug: string | number) => |
|||
shopRequest<ApiProductDetail>(`/products/${encodeURIComponent(String(idOrSlug))}/`), |
|||
|
|||
fetchProductReviews: (idOrSlug: string | number) => |
|||
shopRequest<{ count: number; results: ApiReview[] }>( |
|||
`/products/${encodeURIComponent(String(idOrSlug))}/reviews/` |
|||
), |
|||
|
|||
createProductReview: ( |
|||
idOrSlug: string | number, |
|||
payload: { rating: number; comment: string; author_name?: string; image_url?: string } |
|||
) => |
|||
shopRequest<ApiReview>( |
|||
`/products/${encodeURIComponent(String(idOrSlug))}/reviews/`, |
|||
{ method: 'POST', body: payload } |
|||
), |
|||
|
|||
fetchStores: (q?: string) => |
|||
shopRequest<{ count: number; results: ApiStoreSummary[] }>('/stores/', { |
|||
query: { q }, |
|||
}), |
|||
|
|||
fetchStoreDetail: (idOrSlug: string | number) => |
|||
shopRequest<ApiStoreDetail>(`/stores/${encodeURIComponent(String(idOrSlug))}/`), |
|||
|
|||
// Cart & Checkout
|
|||
fetchCart: (includeShipping = false) => |
|||
shopRequest<ApiCart>('/cart/', { |
|||
query: { include_shipping: includeShipping ? '1' : undefined }, |
|||
}), |
|||
|
|||
clearCart: () => shopRequest<ApiCart>('/cart/', { method: 'DELETE' }), |
|||
|
|||
addCartItem: (payload: { |
|||
product_id: string | number; |
|||
variant_id?: number | null; |
|||
quantity?: number; |
|||
}) => shopRequest<ApiCart>('/cart/items/', { method: 'POST', body: payload }), |
|||
|
|||
updateCartItem: (itemId: number, quantity: number) => |
|||
shopRequest<ApiCart>(`/cart/items/${itemId}/`, { |
|||
method: 'PATCH', |
|||
body: { quantity }, |
|||
}), |
|||
|
|||
removeCartItem: (itemId: number) => |
|||
shopRequest<ApiCart>(`/cart/items/${itemId}/`, { method: 'DELETE' }), |
|||
|
|||
mergeGuestCart: (guestToken?: string) => |
|||
shopRequest<ApiCart>('/cart/merge/', { |
|||
method: 'POST', |
|||
body: guestToken ? { guest_token: guestToken } : {}, |
|||
}), |
|||
|
|||
applyPromoCode: (promoCode: string) => |
|||
shopRequest<ApiCart>('/cart/promo/', { |
|||
method: 'POST', |
|||
body: { promo_code: promoCode }, |
|||
}), |
|||
|
|||
fetchShippingMethods: () => |
|||
shopRequest<{ results: ApiShippingMethod[] }>('/checkout/shipping-methods/'), |
|||
|
|||
fetchCheckoutSummary: (shippingMethodCodeOrId?: string | number) => |
|||
shopRequest<{ |
|||
cart: ApiCart; |
|||
shipping_method: ApiShippingMethod; |
|||
pricing: ApiCartPricing; |
|||
habib_coins_balance: number; |
|||
}>('/checkout/summary/', { |
|||
query: { shipping_method: shippingMethodCodeOrId }, |
|||
}), |
|||
|
|||
fetchPaymentMethods: () => |
|||
shopRequest<{ habib_coins_balance: number; results: ApiPaymentMethod[] }>( |
|||
'/payment/methods/' |
|||
), |
|||
|
|||
// Orders & Shipments
|
|||
fetchOrders: (status?: 'current' | 'delivered' | 'canceled') => |
|||
shopRequest<{ count: number; results: ApiOrderSummary[] }>('/orders/', { |
|||
query: { status }, |
|||
}), |
|||
|
|||
fetchOrderCounters: () => shopRequest<ApiOrderCounters>('/orders/counters/'), |
|||
|
|||
placeOrder: (payload: { |
|||
address_id?: number | null; |
|||
shipping_address?: Record<string, unknown>; |
|||
shipping_method?: string | number; |
|||
payment_method: string; |
|||
promo_code?: string; |
|||
notes?: string; |
|||
}) => shopRequest<ApiOrderDetail>('/orders/', { method: 'POST', body: payload }), |
|||
|
|||
fetchOrderDetail: (orderNumber: string) => |
|||
shopRequest<ApiOrderDetail>(`/orders/${encodeURIComponent(orderNumber)}/`), |
|||
|
|||
fetchOrderReceipt: (orderNumber: string) => |
|||
shopRequest<{ |
|||
order_number: string; |
|||
status: string; |
|||
payment_status: string; |
|||
payment_method: string; |
|||
payment_method_label: string; |
|||
total_paid: string; |
|||
coins_charged: number; |
|||
order_date: string; |
|||
shipping_address: Record<string, unknown>; |
|||
}>(`/orders/${encodeURIComponent(orderNumber)}/receipt/`), |
|||
|
|||
cancelOrder: (orderNumber: string) => |
|||
shopRequest<ApiOrderDetail>(`/orders/${encodeURIComponent(orderNumber)}/cancel/`, { |
|||
method: 'POST', |
|||
}), |
|||
|
|||
fetchShipmentTracking: (orderNumber: string, shipmentId: number) => |
|||
shopRequest<ApiShipment>( |
|||
`/orders/${encodeURIComponent(orderNumber)}/shipments/${shipmentId}/` |
|||
), |
|||
|
|||
// Profile, Addresses, Bookmarks & Provider
|
|||
fetchProfile: () => shopRequest<ApiUserProfile>('/me/profile/'), |
|||
|
|||
updateProfile: (payload: { |
|||
full_name?: string; |
|||
email?: string; |
|||
phone_number?: string; |
|||
}) => shopRequest<ApiUserProfile>('/me/profile/', { method: 'PUT', body: payload }), |
|||
|
|||
fetchAddresses: () => shopRequest<{ results: ApiAddress[] }>('/me/addresses/'), |
|||
|
|||
createAddress: (payload: { |
|||
label?: string; |
|||
recipient_name: string; |
|||
phone?: string; |
|||
country?: string; |
|||
city?: string; |
|||
street_line: string; |
|||
postal_code?: string; |
|||
lat?: number | null; |
|||
lon?: number | null; |
|||
is_default?: boolean; |
|||
}) => shopRequest<ApiAddress>('/me/addresses/', { method: 'POST', body: payload }), |
|||
|
|||
updateAddress: ( |
|||
id: number, |
|||
payload: Partial<{ |
|||
label: string; |
|||
recipient_name: string; |
|||
phone: string; |
|||
country: string; |
|||
city: string; |
|||
street_line: string; |
|||
postal_code: string; |
|||
lat: number | null; |
|||
lon: number | null; |
|||
is_default: boolean; |
|||
}> |
|||
) => |
|||
shopRequest<ApiAddress>(`/me/addresses/${id}/`, { |
|||
method: 'PATCH', |
|||
body: payload, |
|||
}), |
|||
|
|||
deleteAddress: (id: number) => |
|||
shopRequest<void>(`/me/addresses/${id}/`, { method: 'DELETE' }), |
|||
|
|||
fetchBookmarks: () => |
|||
shopRequest<{ |
|||
count: number; |
|||
results: { id: number; product: number; product_detail: ApiProductCard }[]; |
|||
}>('/me/bookmarks/'), |
|||
|
|||
addBookmark: (productIdOrSlug: string | number) => |
|||
shopRequest<{ id: number; product: number; product_detail: ApiProductCard }>( |
|||
'/me/bookmarks/', |
|||
{ method: 'POST', body: { product_id: productIdOrSlug } } |
|||
), |
|||
|
|||
removeBookmark: (productIdOrSlug: string | number) => |
|||
shopRequest<void>( |
|||
`/me/bookmarks/${encodeURIComponent(String(productIdOrSlug))}/`, |
|||
{ method: 'DELETE' } |
|||
), |
|||
|
|||
applyAsProvider: (payload: { store_name: string; description?: string }) => |
|||
shopRequest<{ |
|||
id?: number; |
|||
service: string; |
|||
status: string; |
|||
public_name: string; |
|||
message: string; |
|||
}>('/providers/apply/', { method: 'POST', body: payload }), |
|||
|
|||
// Support & Chat
|
|||
fetchSupportSubjects: () => |
|||
shopRequest<{ results: ApiSupportSubject[] }>('/support/subjects/'), |
|||
|
|||
fetchSupportTickets: () => |
|||
shopRequest<{ count: number; results: ApiSupportTicket[] }>('/support/tickets/'), |
|||
|
|||
createSupportTicket: (payload: { |
|||
order_number?: string; |
|||
product_id?: string | number; |
|||
subject?: string | number; |
|||
subject_label?: string; |
|||
description: string; |
|||
attachment_url?: string; |
|||
}) => |
|||
shopRequest<ApiSupportTicket>('/support/tickets/', { |
|||
method: 'POST', |
|||
body: payload, |
|||
}), |
|||
|
|||
fetchChatConversations: () => |
|||
shopRequest<{ count: number; results: ApiConversation[] }>('/chat/conversations/'), |
|||
|
|||
createChatConversation: (storeIdOrSlug: string | number) => |
|||
shopRequest<ApiConversation>('/chat/conversations/', { |
|||
method: 'POST', |
|||
body: { store_id: storeIdOrSlug }, |
|||
}), |
|||
|
|||
fetchChatMessages: (pkOrSlug: string | number, afterId?: number) => |
|||
shopRequest<{ conversation: ApiConversation; results: ApiChatMessage[] }>( |
|||
`/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`, |
|||
{ query: { after_id: afterId } } |
|||
), |
|||
|
|||
sendChatMessage: ( |
|||
pkOrSlug: string | number, |
|||
payload: { text?: string; attachment_url?: string } |
|||
) => |
|||
shopRequest<{ |
|||
conversation: ApiConversation; |
|||
message: ApiChatMessage; |
|||
new_messages: ApiChatMessage[]; |
|||
}>( |
|||
`/chat/conversations/${encodeURIComponent(String(pkOrSlug))}/messages/`, |
|||
{ method: 'POST', body: payload } |
|||
), |
|||
}; |
|||
|
|||
@ -0,0 +1,366 @@ |
|||
import { |
|||
QueryClient, |
|||
useMutation, |
|||
useQuery, |
|||
useQueryClient, |
|||
} from '@tanstack/react-query'; |
|||
import { |
|||
type ApiChatMessage, |
|||
type ApiConversation, |
|||
type ApiOrderDetail, |
|||
type ApiProductDetail, |
|||
type ApiUserProfile, |
|||
shopApi, |
|||
} from './shopApi'; |
|||
|
|||
export type ProductsQueryParams = NonNullable< |
|||
Parameters<typeof shopApi.fetchProducts>[0] |
|||
>; |
|||
|
|||
export const shopQueryClient = new QueryClient({ |
|||
defaultOptions: { |
|||
queries: { |
|||
staleTime: 60_000, |
|||
gcTime: 15 * 60_000, |
|||
retry: 1, |
|||
refetchOnWindowFocus: false, |
|||
}, |
|||
}, |
|||
}); |
|||
|
|||
export const shopKeys = { |
|||
all: ['shop'] as const, |
|||
home: () => ['shop', 'home'] as const, |
|||
categoriesAll: () => ['shop', 'categories'] as const, |
|||
categories: (q?: string) => ['shop', 'categories', q ?? ''] as const, |
|||
categoryDetailsAll: () => ['shop', 'category'] as const, |
|||
categoryDetail: (slug: string, q?: string) => |
|||
['shop', 'category', slug, q ?? ''] as const, |
|||
productsAll: () => ['shop', 'products'] as const, |
|||
products: (params?: ProductsQueryParams) => |
|||
['shop', 'products', params ?? {}] as const, |
|||
productDetailsAll: () => ['shop', 'product'] as const, |
|||
productDetail: (idOrSlug: string | number) => |
|||
['shop', 'product', String(idOrSlug)] as const, |
|||
storeDetailsAll: () => ['shop', 'store'] as const, |
|||
storeDetail: (idOrSlug: string | number) => |
|||
['shop', 'store', String(idOrSlug)] as const, |
|||
cart: () => ['shop', 'cart'] as const, |
|||
shippingMethods: () => ['shop', 'shipping-methods'] as const, |
|||
paymentMethods: () => ['shop', 'payment-methods'] as const, |
|||
ordersAll: () => ['shop', 'orders'] as const, |
|||
orders: (status: 'current' | 'delivered' | 'canceled') => |
|||
['shop', 'orders', status] as const, |
|||
orderCounters: () => ['shop', 'order-counters'] as const, |
|||
orderDetailsAll: () => ['shop', 'order-detail'] as const, |
|||
orderDetail: (orderNumber: string) => |
|||
['shop', 'order-detail', orderNumber] as const, |
|||
orderReceiptsAll: () => ['shop', 'order-receipt'] as const, |
|||
orderReceipt: (orderNumber: string) => |
|||
['shop', 'order-receipt', orderNumber] as const, |
|||
profile: () => ['shop', 'profile'] as const, |
|||
addresses: () => ['shop', 'addresses'] as const, |
|||
bookmarks: () => ['shop', 'bookmarks'] as const, |
|||
supportSubjects: () => ['shop', 'support-subjects'] as const, |
|||
supportTickets: () => ['shop', 'support-tickets'] as const, |
|||
chatConversations: () => ['shop', 'chat-conversations'] as const, |
|||
chatMessagesAll: () => ['shop', 'chat-messages'] as const, |
|||
chatMessages: (pkOrSlug: string | number) => |
|||
['shop', 'chat-messages', String(pkOrSlug)] as const, |
|||
}; |
|||
|
|||
export function clearUserScopedCache(queryClient: QueryClient): void { |
|||
queryClient.removeQueries({ queryKey: shopKeys.ordersAll() }); |
|||
queryClient.removeQueries({ queryKey: shopKeys.orderDetailsAll() }); |
|||
queryClient.removeQueries({ queryKey: shopKeys.orderReceiptsAll() }); |
|||
queryClient.removeQueries({ queryKey: shopKeys.chatMessagesAll() }); |
|||
queryClient.removeQueries({ queryKey: shopKeys.chatConversations() }); |
|||
queryClient.removeQueries({ queryKey: shopKeys.supportTickets() }); |
|||
} |
|||
|
|||
export function useHomeFeedQuery(enabled = true) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.home(), |
|||
queryFn: () => shopApi.fetchHomeFeed(), |
|||
enabled, |
|||
}); |
|||
} |
|||
|
|||
export function useCategoriesQuery(enabled = true, q?: string) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.categories(q), |
|||
queryFn: () => shopApi.fetchCategories(q), |
|||
enabled, |
|||
}); |
|||
} |
|||
|
|||
export function useCategoryDetailQuery( |
|||
slug: string, |
|||
enabled = true, |
|||
q?: string |
|||
) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.categoryDetail(slug, q), |
|||
queryFn: () => shopApi.fetchCategoryDetail(slug, q), |
|||
enabled: enabled && Boolean(slug), |
|||
}); |
|||
} |
|||
|
|||
export function useProductsQuery(params?: ProductsQueryParams, enabled = true) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.products(params), |
|||
queryFn: () => shopApi.fetchProducts(params), |
|||
enabled, |
|||
}); |
|||
} |
|||
|
|||
export function useProductDetailQuery( |
|||
idOrSlug: string | number, |
|||
enabled = true |
|||
) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.productDetail(idOrSlug), |
|||
queryFn: () => shopApi.fetchProductDetail(idOrSlug), |
|||
enabled: enabled && Boolean(idOrSlug), |
|||
}); |
|||
} |
|||
|
|||
export function useStoreDetailQuery( |
|||
idOrSlug: string | number, |
|||
enabled = true |
|||
) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.storeDetail(idOrSlug), |
|||
queryFn: () => shopApi.fetchStoreDetail(idOrSlug), |
|||
enabled: enabled && Boolean(idOrSlug), |
|||
}); |
|||
} |
|||
|
|||
export function useOrdersQuery( |
|||
status: 'current' | 'delivered' | 'canceled', |
|||
enabled = true |
|||
) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.orders(status), |
|||
queryFn: () => shopApi.fetchOrders(status), |
|||
enabled, |
|||
}); |
|||
} |
|||
|
|||
export function useOrderDetailQuery(orderNumber: string, enabled = true) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.orderDetail(orderNumber), |
|||
queryFn: () => shopApi.fetchOrderDetail(orderNumber), |
|||
enabled: enabled && Boolean(orderNumber), |
|||
}); |
|||
} |
|||
|
|||
export function useOrderReceiptQuery(orderNumber: string, enabled = true) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.orderReceipt(orderNumber), |
|||
queryFn: () => shopApi.fetchOrderReceipt(orderNumber), |
|||
enabled: enabled && Boolean(orderNumber), |
|||
}); |
|||
} |
|||
|
|||
export function usePaymentMethodsQuery(enabled = true) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.paymentMethods(), |
|||
queryFn: () => shopApi.fetchPaymentMethods(), |
|||
enabled, |
|||
}); |
|||
} |
|||
|
|||
export function useSupportSubjectsQuery(enabled = true) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.supportSubjects(), |
|||
queryFn: () => shopApi.fetchSupportSubjects(), |
|||
enabled, |
|||
staleTime: 5 * 60_000, |
|||
}); |
|||
} |
|||
|
|||
export function useChatMessagesQuery( |
|||
pkOrSlug: string | number, |
|||
enabled = true |
|||
) { |
|||
return useQuery({ |
|||
queryKey: shopKeys.chatMessages(pkOrSlug), |
|||
queryFn: () => shopApi.fetchChatMessages(pkOrSlug), |
|||
enabled: enabled && Boolean(pkOrSlug), |
|||
staleTime: 30_000, |
|||
}); |
|||
} |
|||
|
|||
export function useCreateReviewMutation() { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: ({ |
|||
productRef, |
|||
payload, |
|||
}: { |
|||
productRef: string | number; |
|||
routeRef?: string | number; |
|||
payload: { |
|||
rating: number; |
|||
comment: string; |
|||
author_name?: string; |
|||
image_url?: string; |
|||
}; |
|||
}) => shopApi.createProductReview(productRef, payload), |
|||
onSuccess: (created, variables) => { |
|||
const refs = new Set( |
|||
[variables.productRef, variables.routeRef] |
|||
.filter((v): v is string | number => Boolean(v)) |
|||
.map(String) |
|||
); |
|||
for (const ref of refs) { |
|||
queryClient.setQueryData<ApiProductDetail>( |
|||
shopKeys.productDetail(ref), |
|||
(old) => |
|||
old |
|||
? { |
|||
...old, |
|||
reviews: [created, ...(old.reviews || [])], |
|||
reviews_count: (old.reviews_count || 0) + 1, |
|||
} |
|||
: old |
|||
); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.productDetail(ref), |
|||
}); |
|||
} |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.storeDetailsAll(), |
|||
}); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
export function usePlaceOrderMutation() { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: (payload: Parameters<typeof shopApi.placeOrder>[0]) => |
|||
shopApi.placeOrder(payload), |
|||
onSuccess: (order) => { |
|||
queryClient.setQueryData<ApiOrderDetail>( |
|||
shopKeys.orderDetail(order.order_number), |
|||
order |
|||
); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.cart() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.orderCounters(), |
|||
}); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.paymentMethods(), |
|||
}); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.home() }); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.productsAll() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.productDetailsAll(), |
|||
}); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
export function useCancelOrderMutation() { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: (orderNumber: string) => shopApi.cancelOrder(orderNumber), |
|||
onSuccess: (updated, requestedOrderNumber) => { |
|||
queryClient.setQueryData<ApiOrderDetail>( |
|||
shopKeys.orderDetail(updated.order_number), |
|||
updated |
|||
); |
|||
if (requestedOrderNumber !== updated.order_number) { |
|||
queryClient.setQueryData<ApiOrderDetail>( |
|||
shopKeys.orderDetail(requestedOrderNumber), |
|||
updated |
|||
); |
|||
} |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.orderCounters(), |
|||
}); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.orderReceipt(updated.order_number), |
|||
}); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() }); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.paymentMethods(), |
|||
}); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
export function useCreateSupportTicketMutation() { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: (payload: Parameters<typeof shopApi.createSupportTicket>[0]) => |
|||
shopApi.createSupportTicket(payload), |
|||
onSuccess: () => { |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.supportTickets(), |
|||
}); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
export function useUpdateProfileMutation() { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: (payload: Parameters<typeof shopApi.updateProfile>[0]) => |
|||
shopApi.updateProfile(payload), |
|||
onSuccess: (updated) => { |
|||
queryClient.setQueryData<ApiUserProfile>(shopKeys.profile(), updated); |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() }); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
export function useApplyProviderMutation() { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: (payload: Parameters<typeof shopApi.applyAsProvider>[0]) => |
|||
shopApi.applyAsProvider(payload), |
|||
onSuccess: () => { |
|||
void queryClient.invalidateQueries({ queryKey: shopKeys.profile() }); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
export function useSendChatMessageMutation(resolvedConvRef: string | number) { |
|||
const queryClient = useQueryClient(); |
|||
return useMutation({ |
|||
mutationFn: (payload: { text?: string; attachment_url?: string }) => |
|||
shopApi.sendChatMessage(resolvedConvRef, payload), |
|||
onSuccess: (res) => { |
|||
const incomingBatch = |
|||
res.new_messages && res.new_messages.length > 0 |
|||
? res.new_messages |
|||
: [res.message]; |
|||
queryClient.setQueryData<{ |
|||
conversation: ApiConversation; |
|||
results: ApiChatMessage[]; |
|||
}>(shopKeys.chatMessages(resolvedConvRef), (old) => { |
|||
const prevList = old?.results || []; |
|||
const seen = new Set(prevList.map((m) => m.id)); |
|||
const fresh = incomingBatch.filter((m) => m && !seen.has(m.id)); |
|||
const nextConv = res.conversation || old?.conversation; |
|||
if (!nextConv) return old; |
|||
return { |
|||
conversation: nextConv, |
|||
results: [...prevList, ...fresh], |
|||
}; |
|||
}); |
|||
void queryClient.invalidateQueries({ |
|||
queryKey: shopKeys.chatConversations(), |
|||
}); |
|||
}, |
|||
}); |
|||
} |
|||
|
|||
@ -0,0 +1,68 @@ |
|||
import type { FlutterResponsePayload } from '../types/window'; |
|||
import { postActionToFlutter, isInFlutterWebView } from './webview-actions'; |
|||
|
|||
function toLogicalPx(rawPx: unknown, devicePixelRatio: number): number { |
|||
const num = Number(rawPx); |
|||
if (!Number.isFinite(num) || num <= 0) return 0; |
|||
// Flutter MediaQuery padding values may already be logical or physical depending on bridge payload
|
|||
if (num > 120 && devicePixelRatio > 1) { |
|||
return Math.round(num / devicePixelRatio); |
|||
} |
|||
return Math.round(num); |
|||
} |
|||
|
|||
function applySafeCssVars(data: Record<string, unknown>): void { |
|||
if (typeof document === 'undefined') return; |
|||
const root = document.documentElement; |
|||
const dpr = Number(data.devicePixelRatio || window.devicePixelRatio || 1) || 1; |
|||
|
|||
const paddings = (data.viewPadding || data.padding || data) as Record<string, unknown>; |
|||
if (paddings.top !== undefined) { |
|||
root.style.setProperty('--safe-top', `${toLogicalPx(paddings.top, dpr)}px`); |
|||
} |
|||
if (paddings.bottom !== undefined) { |
|||
root.style.setProperty('--safe-bottom', `${toLogicalPx(paddings.bottom, dpr)}px`); |
|||
} |
|||
if (paddings.left !== undefined) { |
|||
root.style.setProperty('--safe-left', `${toLogicalPx(paddings.left, dpr)}px`); |
|||
} |
|||
if (paddings.right !== undefined) { |
|||
root.style.setProperty('--safe-right', `${toLogicalPx(paddings.right, dpr)}px`); |
|||
} |
|||
if (data.keyboardHeight !== undefined || paddings.bottomInset !== undefined) { |
|||
const rawKb = data.keyboardHeight ?? paddings.bottomInset ?? 0; |
|||
root.style.setProperty('--kb-height', `${toLogicalPx(rawKb, dpr)}px`); |
|||
} |
|||
} |
|||
|
|||
export function initFlutterViewPaddings(): () => void { |
|||
if (typeof window === 'undefined') { |
|||
return () => {}; |
|||
} |
|||
|
|||
const handlePayload = (payload: FlutterResponsePayload) => { |
|||
if (!payload || typeof payload !== 'object') return; |
|||
const action = payload.action; |
|||
const data = (payload.data || payload) as Record<string, unknown>; |
|||
if ( |
|||
action === 'initial_config' || |
|||
action === 'get_view_paddings' || |
|||
action === 'view_paddings_changed' || |
|||
action === 'keyboard_changed' |
|||
) { |
|||
applySafeCssVars(data); |
|||
} |
|||
}; |
|||
|
|||
const unsubscribe = |
|||
typeof window.addFlutterResponseListener === 'function' |
|||
? window.addFlutterResponseListener(handlePayload) |
|||
: () => {}; |
|||
|
|||
if (isInFlutterWebView()) { |
|||
postActionToFlutter('get_view_paddings'); |
|||
} |
|||
|
|||
return unsubscribe; |
|||
} |
|||
|
|||
@ -0,0 +1,222 @@ |
|||
import type { FlutterResponsePayload } from '../types/window'; |
|||
import { getToken } from './auth-bridge'; |
|||
|
|||
function getFlutterChannel() { |
|||
if (typeof window === 'undefined') return undefined; |
|||
const ch = window.HabibApp ?? window.FlutterChannel; |
|||
return ch && typeof ch.postMessage === 'function' ? ch : undefined; |
|||
} |
|||
|
|||
export function isInFlutterWebView(): boolean { |
|||
return Boolean(getFlutterChannel()); |
|||
} |
|||
|
|||
export function postActionToFlutter( |
|||
action: string, |
|||
extraPayload: Record<string, unknown> = {} |
|||
): boolean { |
|||
const channel = getFlutterChannel(); |
|||
if (!channel) return false; |
|||
try { |
|||
channel.postMessage( |
|||
JSON.stringify({ |
|||
action, |
|||
...extraPayload, |
|||
}) |
|||
); |
|||
return true; |
|||
} catch { |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
export function requestFlutterAction( |
|||
action: string, |
|||
extraPayload: Record<string, unknown> = {}, |
|||
timeoutMs = 45000 |
|||
): Promise<FlutterResponsePayload | null> { |
|||
if (!isInFlutterWebView()) { |
|||
return Promise.resolve(null); |
|||
} |
|||
|
|||
return new Promise((resolve) => { |
|||
let settled = false; |
|||
let unsubscribe: (() => void) | undefined; |
|||
|
|||
const finish = (res: FlutterResponsePayload | null) => { |
|||
if (settled) return; |
|||
settled = true; |
|||
window.clearTimeout(timer); |
|||
if (unsubscribe) unsubscribe(); |
|||
resolve(res); |
|||
}; |
|||
|
|||
if (typeof window.addFlutterResponseListener === 'function') { |
|||
unsubscribe = window.addFlutterResponseListener((payload) => { |
|||
if (payload?.action === action) { |
|||
finish(payload); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
const timer = window.setTimeout(() => { |
|||
finish(null); |
|||
}, timeoutMs); |
|||
|
|||
const posted = postActionToFlutter(action, extraPayload); |
|||
if (!posted) { |
|||
finish(null); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
export function closeService(): boolean { |
|||
return postActionToFlutter('close_service'); |
|||
} |
|||
|
|||
export function openAiAssistant(): boolean { |
|||
return postActionToFlutter('open_ai_assistant'); |
|||
} |
|||
|
|||
export function openExternalUrl(url: string): void { |
|||
if (!url) return; |
|||
if (postActionToFlutter('open_external_url', { url, data: { url } })) { |
|||
return; |
|||
} |
|||
if (typeof window !== 'undefined') { |
|||
window.open(url, '_blank', 'noopener,noreferrer'); |
|||
} |
|||
} |
|||
|
|||
export async function copyToClipboard(text: string): Promise<boolean> { |
|||
if (!text) return false; |
|||
if (isInFlutterWebView()) { |
|||
postActionToFlutter('copy_to_clipboard', { text, data: { text } }); |
|||
return true; |
|||
} |
|||
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { |
|||
try { |
|||
await navigator.clipboard.writeText(text); |
|||
return true; |
|||
} catch { |
|||
return false; |
|||
} |
|||
} |
|||
return false; |
|||
} |
|||
|
|||
export function downloadFile(url: string, filename?: string): void { |
|||
if (!url) return; |
|||
if (postActionToFlutter('download_file', { url, filename, data: { url, filename } })) { |
|||
return; |
|||
} |
|||
if (typeof document !== 'undefined') { |
|||
const a = document.createElement('a'); |
|||
a.href = url; |
|||
if (filename) a.download = filename; |
|||
a.target = '_blank'; |
|||
a.rel = 'noopener noreferrer'; |
|||
document.body.appendChild(a); |
|||
a.click(); |
|||
document.body.removeChild(a); |
|||
} |
|||
} |
|||
|
|||
export async function buyHabibCoinPackages(): Promise<number | null> { |
|||
if (!isInFlutterWebView()) { |
|||
return null; |
|||
} |
|||
const response = await requestFlutterAction('buy_coin', {}, 120000); |
|||
if (!response) return null; |
|||
const data = (response.data || response) as Record<string, unknown>; |
|||
const rawBalance = data.coinsBalance ?? data.coin_balance; |
|||
if (rawBalance !== undefined) { |
|||
const parsed = Number(rawBalance); |
|||
if (Number.isFinite(parsed) && parsed >= 0) { |
|||
window.HABIB_COINS = parsed; |
|||
return parsed; |
|||
} |
|||
} |
|||
return typeof window.HABIB_COINS === 'number' ? window.HABIB_COINS : null; |
|||
} |
|||
|
|||
export interface PickedLocationResult { |
|||
lat: number; |
|||
lon: number; |
|||
address?: string; |
|||
city?: string; |
|||
country?: string; |
|||
} |
|||
|
|||
export async function pickManualLocation(): Promise<PickedLocationResult | null> { |
|||
const response = await requestFlutterAction('pick_manual_location', {}, 90000); |
|||
if (!response || response.success === false) return null; |
|||
const data = (response.data || response) as Record<string, unknown>; |
|||
const lat = Number(data.lat ?? data.latitude); |
|||
const lon = Number(data.lon ?? data.lng ?? data.longitude); |
|||
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null; |
|||
return { |
|||
lat, |
|||
lon, |
|||
address: typeof data.address === 'string' ? data.address : undefined, |
|||
city: typeof data.city === 'string' ? data.city : undefined, |
|||
country: typeof data.country === 'string' ? data.country : undefined, |
|||
}; |
|||
} |
|||
|
|||
export async function uploadFileViaFlutterBridge(): Promise<string | null> { |
|||
if (!isInFlutterWebView()) return null; |
|||
const uploadPayload = { |
|||
uploadUrl: '/upload-tmp-media/', |
|||
fieldName: 'file', |
|||
allowedTypes: ['image', 'video'], |
|||
}; |
|||
const response = await requestFlutterAction( |
|||
'upload_file', |
|||
{ |
|||
...uploadPayload, |
|||
data: uploadPayload, |
|||
}, |
|||
90000 |
|||
); |
|||
if (!response || response.success === false) return null; |
|||
const data = (response.data || response) as Record<string, unknown>; |
|||
const url = |
|||
(typeof data.url === 'string' && data.url) || |
|||
(typeof data.file_url === 'string' && data.file_url) || |
|||
(typeof data.path === 'string' && data.path) || |
|||
''; |
|||
return url || null; |
|||
} |
|||
|
|||
export async function uploadBrowserFileToTmpMedia(file: File): Promise<string> { |
|||
const formData = new FormData(); |
|||
formData.append('file', file); |
|||
const headers: Record<string, string> = {}; |
|||
const token = getToken(); |
|||
if (token) { |
|||
headers.Authorization = `Token ${token}`; |
|||
} |
|||
|
|||
try { |
|||
const resp = await fetch('/upload-tmp-media/', { |
|||
method: 'POST', |
|||
headers, |
|||
body: formData, |
|||
}); |
|||
if (resp.ok) { |
|||
const json = (await resp.json()) as Record<string, unknown>; |
|||
const resolved = |
|||
(typeof json.url === 'string' && json.url) || |
|||
(typeof json.file === 'string' && json.file) || |
|||
(typeof json.path === 'string' && json.path) || |
|||
''; |
|||
if (resolved) return resolved; |
|||
} |
|||
} catch { |
|||
// fallback to local object URL for standalone preview
|
|||
} |
|||
|
|||
return URL.createObjectURL(file); |
|||
} |
|||
|
|||
958
src/pages/catalog/ShopSinglePage.tsx
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
1182
src/pages/chat/ShopChatPage.tsx
File diff suppressed because it is too large
View File
File diff suppressed because it is too large
View File
@ -1,48 +1,186 @@ |
|||
import React, { useState } from 'react'; |
|||
import React, { useEffect, useMemo, useState } from 'react'; |
|||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'; |
|||
import { MobileShell } from '../../components/layout/MobileShell'; |
|||
import { StandardPageHeader } from '../../components/layout/TopHeader'; |
|||
import { |
|||
EmptyStateBox, |
|||
OrdersListShimmer, |
|||
RetryBanner, |
|||
} from '../../components/common/ShimmerSkeletons'; |
|||
import { OrderFilterTabs } from '../../components/orders/OrderFilterTabs'; |
|||
import { OrderListCard } from '../../components/orders/OrderListCard'; |
|||
import { useShopApp } from '../../context/ShopAppContext'; |
|||
import { |
|||
ORDER_FILTER_TABS, |
|||
ORDERS_LIST_CARDS, |
|||
type OrderFilterTabItem, |
|||
} from '../../data/ordersData'; |
|||
import { mapOrderToCardData } from '../../lib/mappers'; |
|||
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes'; |
|||
import { useOrdersQuery } from '../../lib/shopQueries'; |
|||
|
|||
/** |
|||
* Node 4175:9811 — `shop-orders` (Orders List, 375×814) |
|||
*/ |
|||
export const ShopOrdersPage: React.FC = () => { |
|||
const navigate = useNavigate(); |
|||
const location = useLocation(); |
|||
const isBare = isBareMode(location.search); |
|||
const useMockFallback = isBare || USE_MOCK_DATA; |
|||
const [searchParams, setSearchParams] = useSearchParams(); |
|||
const { orderCounters } = useShopApp(); |
|||
|
|||
const paramTab = searchParams.get('tab'); |
|||
const initialTab: OrderFilterTabItem['id'] = |
|||
paramTab === 'delivered' || paramTab === 'canceled' ? paramTab : 'current'; |
|||
|
|||
const [activeTabId, setActiveTabId] = |
|||
useState<OrderFilterTabItem['id']>('current'); |
|||
useState<OrderFilterTabItem['id']>(initialTab); |
|||
|
|||
useEffect(() => { |
|||
if ( |
|||
paramTab === 'current' || |
|||
paramTab === 'delivered' || |
|||
paramTab === 'canceled' |
|||
) { |
|||
setActiveTabId(paramTab); |
|||
} |
|||
}, [paramTab]); |
|||
|
|||
const ordersQuery = useOrdersQuery(activeTabId, !isBare); |
|||
const orders = ordersQuery.data?.results ?? null; |
|||
const loading = |
|||
!isBare && (ordersQuery.isPending || (!orders && ordersQuery.isFetching)); |
|||
const loadError = !isBare && ordersQuery.isError; |
|||
|
|||
const tabs = useMemo<OrderFilterTabItem[]>(() => { |
|||
if (isBare) return ORDER_FILTER_TABS; |
|||
if (!orderCounters) { |
|||
return useMockFallback |
|||
? ORDER_FILTER_TABS |
|||
: ORDER_FILTER_TABS.map((tab) => ({ ...tab, count: '0' })); |
|||
} |
|||
return ORDER_FILTER_TABS.map((tab) => ({ |
|||
...tab, |
|||
count: |
|||
tab.id === 'current' |
|||
? String(orderCounters.current) |
|||
: tab.id === 'delivered' |
|||
? String(orderCounters.delivered) |
|||
: String(orderCounters.canceled), |
|||
})); |
|||
}, [isBare, orderCounters, useMockFallback]); |
|||
|
|||
const handleSelectTab = (id: OrderFilterTabItem['id']) => { |
|||
setActiveTabId(id); |
|||
if (!isBare) { |
|||
setSearchParams({ tab: id }, { replace: true }); |
|||
} |
|||
}; |
|||
|
|||
return ( |
|||
<MobileShell width={375} height={814} backgroundColor="#f3f1ef"> |
|||
{/* Top Header: Back button + "Orders" */} |
|||
<StandardPageHeader title="Orders" titleTop={29} backTo="/shop-account" /> |
|||
<StandardPageHeader |
|||
title="Orders" |
|||
titleTop={29} |
|||
backTo={ROUTES.account} |
|||
/> |
|||
|
|||
<div |
|||
style={{ |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
flex: 1, |
|||
padding: '26px var(--page-px) 28px', |
|||
padding: '26px var(--page-px) calc(28px + var(--safe-bottom, 0px))', |
|||
gap: 22, |
|||
}} |
|||
> |
|||
{/* Segmented Filter Tabs (4175:9880 + 4175:9892) */} |
|||
{/* Segmented Filter Tabs */} |
|||
<OrderFilterTabs |
|||
tabs={ORDER_FILTER_TABS} |
|||
tabs={tabs} |
|||
activeTabId={activeTabId} |
|||
onSelectTab={(id) => setActiveTabId(id)} |
|||
onSelectTab={handleSelectTab} |
|||
/> |
|||
|
|||
{/* Order Cards (4175:10954 & 4175:10644) */} |
|||
<div className="habib-orders-grid"> |
|||
{ORDERS_LIST_CARDS.map((order) => ( |
|||
<OrderListCard key={order.id} order={order} /> |
|||
))} |
|||
</div> |
|||
{/* Order Cards */} |
|||
{!isBare && loading ? ( |
|||
<OrdersListShimmer count={2} /> |
|||
) : !isBare && orders ? ( |
|||
orders.length > 0 ? ( |
|||
<div className="habib-orders-grid"> |
|||
{orders.map((order, idx) => ( |
|||
<OrderListCard |
|||
key={order.id} |
|||
order={mapOrderToCardData(order, idx)} |
|||
onViewDetails={() => |
|||
navigate(ROUTES.orderDetail(order.order_number)) |
|||
} |
|||
/> |
|||
))} |
|||
</div> |
|||
) : ( |
|||
<div |
|||
style={{ |
|||
padding: '42px 20px', |
|||
borderRadius: 20, |
|||
background: 'linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%)', |
|||
border: '1px solid #ffffff', |
|||
textAlign: 'center', |
|||
display: 'flex', |
|||
flexDirection: 'column', |
|||
alignItems: 'center', |
|||
gap: 10, |
|||
}} |
|||
> |
|||
<span |
|||
style={{ |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 15, |
|||
color: '#111111', |
|||
}} |
|||
> |
|||
{`No ${activeTabId} orders`} |
|||
</span> |
|||
<button |
|||
type="button" |
|||
onClick={() => navigate(ROUTES.home)} |
|||
style={{ |
|||
marginTop: 4, |
|||
padding: '9px 18px', |
|||
borderRadius: 11, |
|||
backgroundColor: '#d78e06', |
|||
color: '#ffffff', |
|||
fontFamily: 'var(--font-sans)', |
|||
fontWeight: 700, |
|||
fontSize: 12, |
|||
cursor: 'pointer', |
|||
}} |
|||
> |
|||
Browse Shop |
|||
</button> |
|||
</div> |
|||
) |
|||
) : ( |
|||
<> |
|||
{!isBare && loadError && ( |
|||
<RetryBanner |
|||
message="Could not load orders. Tap Retry to refresh." |
|||
onRetry={() => void ordersQuery.refetch()} |
|||
/> |
|||
)} |
|||
{useMockFallback ? ( |
|||
<div className="habib-orders-grid"> |
|||
{ORDERS_LIST_CARDS.map((order) => ( |
|||
<OrderListCard key={order.id} order={order} /> |
|||
))} |
|||
</div> |
|||
) : ( |
|||
<EmptyStateBox message={`No ${activeTabId} orders`} /> |
|||
)} |
|||
</> |
|||
)} |
|||
</div> |
|||
</MobileShell> |
|||
); |
|||
|
|||
@ -0,0 +1,37 @@ |
|||
export interface FlutterResponsePayload { |
|||
action?: string; |
|||
success?: boolean; |
|||
error?: string; |
|||
data?: Record<string, unknown>; |
|||
[key: string]: unknown; |
|||
} |
|||
|
|||
export type FlutterResponseListener = (payload: FlutterResponsePayload) => void; |
|||
|
|||
declare global { |
|||
interface Window { |
|||
HabibApp?: { |
|||
postMessage: (message: string) => void; |
|||
}; |
|||
FlutterChannel?: { |
|||
postMessage: (message: string) => void; |
|||
}; |
|||
HABIB_TOKEN?: string; |
|||
HABIB_COINS?: number; |
|||
HABIB_WEB_READY_SENT?: boolean; |
|||
__announceHabibWebReady?: () => void; |
|||
onFlutterResponse?: (payload: FlutterResponsePayload | string) => void; |
|||
addFlutterResponseListener?: (listener: FlutterResponseListener) => () => void; |
|||
__habibHandleHardwareBack?: () => Promise<boolean> | boolean; |
|||
__habibHandleHardwareBackSync?: () => boolean; |
|||
__habibNavigate?: (to: string) => void; |
|||
} |
|||
|
|||
interface WindowEventMap { |
|||
'habib:auth-token-changed': CustomEvent<{ token: string; previousToken: string }>; |
|||
'habib:coins-changed': CustomEvent<{ coins: number }>; |
|||
} |
|||
} |
|||
|
|||
export {}; |
|||
|
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue