Browse Source

feat: implement core shop application context, API client, and pages

main
sina_sajjadi 4 days ago
parent
commit
775994ea5a
  1. 44
      scripts/verify-product-gallery.mjs
  2. 55
      scripts/verify-product-reviews.mjs
  3. 15
      src/context/ShopAppContext.tsx
  4. 10
      src/data/accountData.ts
  5. 20
      src/lib/cookies.ts
  6. 29
      src/lib/shopApi.ts
  7. 49
      src/lib/shopQueries.ts
  8. 31
      src/pages/catalog/ShopBoothPage.tsx
  9. 579
      src/pages/catalog/ShopSinglePage.tsx
  10. 101
      src/pages/checkout/ShopCartPage.tsx
  11. 77
      src/pages/checkout/ShopPaymentPage.tsx
  12. 171
      src/pages/home/ShopHomePage.tsx
  13. 374
      src/pages/orders/ShopSupportPage.tsx

44
scripts/verify-product-gallery.mjs

@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
const pagePath = path.join(process.cwd(), 'src/pages/catalog/ShopSinglePage.tsx');
const src = fs.readFileSync(pagePath, 'utf8');
assert.ok(!src.includes('indicator-carousel-dots.svg'), 'Static carousel dots SVG must be removed');
assert.ok(src.includes('liveProduct.media'), 'Gallery must bind to product.media');
const resolveMediaUrl = (u) => (!u ? '' : u.startsWith('http') || u.startsWith('/') ? u : `/${u}`);
function buildSlides(liveProduct, useMockFallback, title = 'Islam in the Bible Book') {
if (liveProduct) {
const slides = (Array.isArray(liveProduct.media) ? liveProduct.media : [])
.slice()
.sort((a, b) => a.sort_order - b.sort_order || a.id - b.id)
.map((m, i) => ({ id: `media-${m.id}-${i}`, src: resolveMediaUrl(m.image_url), alt: m.alt_text || title }))
.filter((s) => Boolean(s.src));
if (slides.length > 0) return slides;
return [{ id: 'hero-fallback', src: resolveMediaUrl(liveProduct.hero_image_url || liveProduct.primary_image_url) || '/assets/images/product-duffel-bag-hero.png', alt: title }];
}
return useMockFallback ? ['/assets/images/product-duffel-bag-hero.png', '/assets/images/product-brown-leather-bag.png', '/assets/images/product-boby-backpack.png'].map((s, i) => ({ id: `mock-${i + 1}`, src: s, alt: title })) : [];
}
// 1. Sorts media by sort_order then id, filters empty URLs, falls back alt_text to title
const sorted = buildSlides({
media: [
{ id: 9, image_url: 'media/b.jpg', alt_text: 'Side', sort_order: 2 },
{ id: 4, image_url: '', alt_text: 'Empty', sort_order: 0 },
{ id: 5, image_url: '/media/a.jpg', alt_text: '', sort_order: 1 },
],
}, false, 'Leather Bag');
assert.deepEqual(sorted.map((s) => [s.src, s.alt]), [['/media/a.jpg', 'Leather Bag'], ['/media/b.jpg', 'Side']]);
// 2. Falls back to hero/primary when media[] is empty
const fallback = buildSlides({ media: [], hero_image_url: '', primary_image_url: 'media/p.jpg' }, false, 'Book');
assert.equal(fallback.length, 1);
assert.equal(fallback[0].src, '/media/p.jpg');
// 3. Empty when no liveProduct and mock disabled; 3 slides when mock enabled
assert.equal(buildSlides(null, false).length, 0);
assert.equal(buildSlides(null, true).length, 3);
console.log('PASS: Product gallery assertions passed.');

55
scripts/verify-product-reviews.mjs

@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
const singlePage = fs.readFileSync(
path.join(process.cwd(), 'src/pages/catalog/ShopSinglePage.tsx'),
'utf8'
);
const shopApiSrc = fs.readFileSync(
path.join(process.cwd(), 'src/lib/shopApi.ts'),
'utf8'
);
// 1. ShopSinglePage uses reviewsCount backed by liveProduct.reviews_count instead of displayReviews.length
assert.ok(singlePage.includes('liveProduct.reviews_count'));
assert.ok(!singlePage.includes('Review(${displayReviews.length})'));
assert.ok(!singlePage.includes('Customer Reviews (${displayReviews.length})'));
assert.ok(singlePage.includes('resolveMediaUrl(r.image_url)'));
assert.ok(singlePage.includes('review.imageUrl &&'));
// 2. reviewsCount logic handles >20 cap, seeded count, and fallback
function computeReviewsCount(liveProduct, displayReviewsLen) {
return liveProduct
? Math.max(liveProduct.reviews_count ?? 0, displayReviewsLen)
: displayReviewsLen;
}
assert.equal(computeReviewsCount({ reviews_count: 47 }, 20), 47);
assert.equal(computeReviewsCount({ reviews_count: 12 }, 0), 12);
assert.equal(computeReviewsCount({ reviews_count: 0 }, 2), 2);
assert.equal(computeReviewsCount(null, 3), 3);
// 3. createProductReview builds FormData when File is provided and keeps JSON otherwise
assert.ok(shopApiSrc.includes("form.append('image', payload.image)"));
function buildReviewBody(payload) {
if (payload.image) {
const form = new FormData();
form.append('rating', String(payload.rating));
form.append('comment', payload.comment);
form.append('image', payload.image);
if (payload.author_name) form.append('author_name', payload.author_name);
return form;
}
return payload;
}
const jsonBody = buildReviewBody({ rating: 5, comment: 'Great!' });
assert.ok(!(jsonBody instanceof FormData));
const file = new File([new Uint8Array([137, 80, 78, 71])], 'photo.png', { type: 'image/png' });
const multipartBody = buildReviewBody({ rating: 4, comment: 'Nice!', image: file, author_name: 'Ali' });
assert.ok(multipartBody instanceof FormData);
assert.equal(multipartBody.get('rating'), '4');
assert.equal(multipartBody.get('comment'), 'Nice!');
assert.equal(multipartBody.get('author_name'), 'Ali');
assert.equal(multipartBody.get('image')?.name, 'photo.png');
console.log('PASS: Product review count & multipart image assertions passed.');

15
src/context/ShopAppContext.tsx

@ -412,6 +412,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
}, [queryClient]);
const refreshCart = useCallback(async () => {
void queryClient.invalidateQueries({
queryKey: shopKeys.checkoutSummariesAll(),
});
if (!getToken()) {
await queryClient.invalidateQueries({ queryKey: shopKeys.cart() });
return;
@ -628,6 +631,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
quantity,
});
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({
queryKey: shopKeys.checkoutSummariesAll(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
showToast('Added to cart');
return updated;
@ -647,6 +653,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
try {
const updated = await shopApi.updateCartItem(itemId, quantity);
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({
queryKey: shopKeys.checkoutSummariesAll(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not update cart');
@ -663,6 +672,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
try {
const updated = await shopApi.removeCartItem(itemId);
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({
queryKey: shopKeys.checkoutSummariesAll(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not remove item');
@ -678,6 +690,9 @@ export const ShopAppProvider: React.FC<{ children: React.ReactNode }> = ({
try {
const updated = await shopApi.clearCart();
queryClient.setQueryData<ApiCart>(shopKeys.cart(), updated);
void queryClient.invalidateQueries({
queryKey: shopKeys.checkoutSummariesAll(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.home() });
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not clear cart');

10
src/data/accountData.ts

@ -93,11 +93,11 @@ export const SHOP_ACCOUNT_MENU_ROWS: AccountMenuRowItem[] = [
subtitle: 'Name, contact number, email, etc.',
subtitleWidth: 155,
iconBoxBg: 'rgba(21, 28, 49, 0.1)',
iconSrc: '/assets/images/icon-menu-saved-bookmark.svg',
iconLeft: 9,
iconTop: 7,
iconWidth: 14,
iconHeight: 18,
iconSrc: '/assets/images/standalone-user-filled-icon.svg',
iconLeft: 5,
iconTop: 5,
iconWidth: 24,
iconHeight: 24,
rightIconType: 'none',
targetRoute: '/provider-requst',
},

20
src/lib/cookies.ts

@ -611,6 +611,16 @@ const FA_DICTIONARY: Record<string, string> = {
'ثبت تیکت پشتیبانی امکان‌پذیر نیست. لطفاً دوباره تلاش کنید.',
'Ticket Submitted!': 'تیکت ثبت شد!',
'Submit Ticket': 'ثبت تیکت',
'Submitted Tickets': 'تیکت‌های ثبت‌شده',
Open: 'باز',
Resolved: 'پاسخ داده شده',
'Support Reply': 'پاسخ پشتیبانی',
'View attachment': 'مشاهده پیوست',
'No support tickets submitted yet.': 'هنوز تیکت پشتیبانی ثبت نشده است.',
'Could not load support tickets. Tap Retry to refresh.':
'بارگذاری تیکت‌های پشتیبانی امکان‌پذیر نبود. برای تلاش مجدد ضربه بزنید.',
'Sign in to view your submitted tickets.':
'برای مشاهده تیکت‌های ثبت‌شده خود وارد حساب کاربری شوید.',
// Chat
Online: 'آنلاین',
@ -1172,6 +1182,16 @@ const AR_DICTIONARY: Record<string, string> = {
'تعذر إرسال تذكرة الدعم. يرجى المحاولة مرة أخرى.',
'Ticket Submitted!': 'تم إرسال التذكرة!',
'Submit Ticket': 'إرسال التذكرة',
'Submitted Tickets': 'التذاكر المرسلة',
Open: 'مفتوحة',
Resolved: 'تم الحل',
'Support Reply': 'رد الدعم',
'View attachment': 'عرض المرفق',
'No support tickets submitted yet.': 'لم يتم إرسال أي تذاكر دعم بعد.',
'Could not load support tickets. Tap Retry to refresh.':
'تعذر تحميل تذاكر الدعم. اضغط على إعادة المحاولة للتحديث.',
'Sign in to view your submitted tickets.':
'سجل الدخول لعرض تذاكر الدعم المرسلة.',
// Chat
Online: 'متصل',

29
src/lib/shopApi.ts

@ -138,12 +138,15 @@ export interface ApiCartItem {
}
export interface ApiCartPricing {
currency?: string;
items_count: number;
total_quantity: number;
total_units?: number;
shops_count: number;
subtotal: string;
formatted_subtotal: string;
compare_subtotal?: string;
formatted_compare_subtotal?: string | null;
shipping_fee: string;
formatted_shipping_fee: string;
total: string;
@ -437,12 +440,27 @@ export const shopApi = {
createProductReview: (
idOrSlug: string | number,
payload: { rating: number; comment: string; author_name?: string; image_url?: string }
) =>
shopRequest<ApiReview>(
payload: {
rating: number;
comment: string;
author_name?: string;
image?: File;
}
) => {
let body: BodyInit | Record<string, unknown> = payload;
if (payload.image) {
const form = new FormData();
form.append('rating', String(payload.rating));
form.append('comment', payload.comment);
form.append('image', payload.image);
if (payload.author_name) form.append('author_name', payload.author_name);
body = form;
}
return shopRequest<ApiReview>(
`/products/${encodeURIComponent(String(idOrSlug))}/reviews/`,
{ method: 'POST', body: payload }
),
{ method: 'POST', body }
);
},
fetchStores: (q?: string) =>
shopRequest<{ count: number; results: ApiStoreSummary[] }>('/stores/', {
@ -502,6 +520,7 @@ export const shopApi = {
shipping_address?: Record<string, unknown>;
shipping_method?: string | number;
payment_method: string;
confirm_payment?: boolean;
notes?: string;
}) => shopRequest<ApiOrderDetail>('/orders/', { method: 'POST', body: payload }),

49
src/lib/shopQueries.ts

@ -11,6 +11,7 @@ import {
type ApiOrderDetail,
type ApiProductCard,
type ApiProductDetail,
type ApiSupportTicket,
type ApiUserProfile,
shopApi,
} from './shopApi';
@ -53,6 +54,9 @@ export const shopKeys = {
storeDetail: (idOrSlug: string | number) =>
['shop', 'store', String(idOrSlug)] as const,
cart: () => ['shop', 'cart'] as const,
checkoutSummariesAll: () => ['shop', 'checkout-summary'] as const,
checkoutSummary: (shippingMethod?: string | number) =>
['shop', 'checkout-summary', String(shippingMethod ?? '')] as const,
shippingMethods: () => ['shop', 'shipping-methods'] as const,
paymentMethods: () => ['shop', 'payment-methods'] as const,
ordersAll: () => ['shop', 'orders'] as const,
@ -108,6 +112,7 @@ export function findCachedCategoryBySlug(
}
export function clearUserScopedCache(queryClient: QueryClient): void {
queryClient.removeQueries({ queryKey: shopKeys.checkoutSummariesAll() });
queryClient.removeQueries({ queryKey: shopKeys.ordersAll() });
queryClient.removeQueries({ queryKey: shopKeys.orderDetailsAll() });
queryClient.removeQueries({ queryKey: shopKeys.orderReceiptsAll() });
@ -221,6 +226,17 @@ export function useOrderReceiptQuery(orderNumber: string, enabled = true) {
});
}
export function useCheckoutSummaryQuery(
shippingMethod?: string | number,
enabled = true
) {
return useQuery({
queryKey: shopKeys.checkoutSummary(shippingMethod),
queryFn: () => shopApi.fetchCheckoutSummary(shippingMethod),
enabled,
});
}
export function usePaymentMethodsQuery(enabled = true) {
return useQuery({
queryKey: shopKeys.paymentMethods(),
@ -238,6 +254,14 @@ export function useSupportSubjectsQuery(enabled = true) {
});
}
export function useSupportTicketsQuery(enabled = true) {
return useQuery({
queryKey: shopKeys.supportTickets(),
queryFn: () => shopApi.fetchSupportTickets(),
enabled,
});
}
export function useChatMessagesQuery(
pkOrSlug: string | number,
enabled = true
@ -259,12 +283,7 @@ export function useCreateReviewMutation() {
}: {
productRef: string | number;
routeRef?: string | number;
payload: {
rating: number;
comment: string;
author_name?: string;
image_url?: string;
};
payload: Parameters<typeof shopApi.createProductReview>[1];
}) => shopApi.createProductReview(productRef, payload),
onSuccess: (created, variables) => {
const refs = new Set(
@ -308,6 +327,9 @@ export function usePlaceOrderMutation() {
order
);
void queryClient.invalidateQueries({ queryKey: shopKeys.cart() });
void queryClient.invalidateQueries({
queryKey: shopKeys.checkoutSummariesAll(),
});
void queryClient.invalidateQueries({ queryKey: shopKeys.ordersAll() });
void queryClient.invalidateQueries({
queryKey: shopKeys.orderCounters(),
@ -360,7 +382,20 @@ export function useCreateSupportTicketMutation() {
return useMutation({
mutationFn: (payload: Parameters<typeof shopApi.createSupportTicket>[0]) =>
shopApi.createSupportTicket(payload),
onSuccess: () => {
onSuccess: (created) => {
queryClient.setQueryData<{ count: number; results: ApiSupportTicket[] }>(
shopKeys.supportTickets(),
(old) => {
if (!old) return { count: 1, results: [created] };
const filtered = old.results.filter((t) => t.id !== created.id);
return {
...old,
count:
filtered.length === old.results.length ? old.count + 1 : old.count,
results: [created, ...filtered],
};
}
);
void queryClient.invalidateQueries({
queryKey: shopKeys.supportTickets(),
});

31
src/pages/catalog/ShopBoothPage.tsx

@ -72,7 +72,7 @@ export const ShopBoothPage: React.FC = () => {
return (
<MobileShell width={375} height={1233} backgroundColor="#f3f1ef">
{/* Top Store Logo Backdrop & Floating Actions */}
{/* Top Banner Calligraphy Image & Floating Actions */}
<div
style={{
position: 'relative',
@ -82,24 +82,17 @@ export const ShopBoothPage: React.FC = () => {
flexShrink: 0,
}}
>
{isStoreShimmer ? (
<ShimmerBox width="100%" height="100%" borderRadius={0} />
) : (
<img
src={
resolveMediaUrl(liveStore?.logo_url) ||
'/assets/images/avatar-tashakol-booth.png'
}
alt=""
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block',
pointerEvents: 'none',
}}
/>
)}
<img
src="/assets/images/bg-booth-calligraphy-header.png"
alt=""
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block',
pointerEvents: 'none',
}}
/>
<div
style={{

579
src/pages/catalog/ShopSinglePage.tsx

@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { CompactProductCard } from '../../components/common/CompactProductCard';
@ -20,7 +20,13 @@ import {
useCreateReviewMutation,
useProductDetailQuery,
} from '../../lib/shopQueries';
import { copyToClipboard } from '../../lib/webview-actions';
import {
copyToClipboard,
isInFlutterWebView,
pickFileViaFlutterBridge,
} from '../../lib/webview-actions';
const MAX_REVIEW_IMAGE_BYTES = 10 * 1024 * 1024;
const STATIC_PRODUCT_REVIEWS = [
{
@ -74,8 +80,39 @@ export const ShopSinglePage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'info' | 'review'>('info');
const [reviewRating, setReviewRating] = useState(5);
const [reviewComment, setReviewComment] = useState('');
const [reviewImage, setReviewImage] = useState<{
file: File;
previewUrl: string;
isObjectUrl: boolean;
} | null>(null);
const [pickingReviewImage, setPickingReviewImage] = useState(false);
const reviewFileInputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
return () => {
if (reviewImage?.isObjectUrl) {
URL.revokeObjectURL(reviewImage.previewUrl);
}
};
}, [reviewImage]);
const resolvedRef = productId || 'islam-in-the-bible-book';
const [slideState, setSlideState] = useState<{ ref: string; index: number }>({
ref: resolvedRef,
index: 0,
});
const [dragOffset, setDragOffset] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [heroEl, setHeroEl] = useState<HTMLDivElement | null>(null);
const dragStartRef = useRef<{
id: number;
x: number;
y: number;
lastX: number;
time: number;
locked: 'x' | null;
} | null>(null);
const wheelCooldownRef = useRef(0);
const productQuery = useProductDetailQuery(resolvedRef, !isBare);
const createReviewMutation = useCreateReviewMutation();
@ -133,6 +170,62 @@ export const ShopSinglePage: React.FC = () => {
}
};
const stageReviewFile = (
file: File,
previewUrl?: string,
isObjectUrl = false
) => {
if (file.type && !file.type.startsWith('image/')) {
if (isObjectUrl && previewUrl) URL.revokeObjectURL(previewUrl);
showToast(tr('Failed to upload image. Please try another file.'));
return;
}
if (file.size > MAX_REVIEW_IMAGE_BYTES) {
if (isObjectUrl && previewUrl) URL.revokeObjectURL(previewUrl);
showToast('Image exceeds the 10 MB size limit');
return;
}
setReviewImage({
file,
previewUrl: previewUrl || URL.createObjectURL(file),
isObjectUrl: previewUrl ? isObjectUrl : true,
});
};
const handlePickReviewImage = async () => {
if (isBare || submittingReview || pickingReviewImage) return;
if (isInFlutterWebView()) {
setPickingReviewImage(true);
try {
const picked = await pickFileViaFlutterBridge('image');
if (!picked) return;
if (picked.file) {
stageReviewFile(picked.file, picked.url, Boolean(picked.isObjectUrl));
return;
}
const resp = await fetch(resolveMediaUrl(picked.url));
const blob = await resp.blob();
stageReviewFile(
new File([blob], picked.name || `review-${Date.now()}.jpg`, {
type: blob.type || 'image/jpeg',
})
);
} catch {
showToast(tr('Failed to upload image. Please try another file.'));
} finally {
setPickingReviewImage(false);
}
return;
}
reviewFileInputRef.current?.click();
};
const handleReviewFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = '';
if (file) stageReviewFile(file);
};
const handleSubmitReview = async (e: React.FormEvent) => {
e.preventDefault();
if (!reviewComment.trim() || submittingReview) return;
@ -149,19 +242,198 @@ export const ShopSinglePage: React.FC = () => {
payload: {
rating: reviewRating,
comment: reviewComment.trim(),
image: reviewImage?.file,
},
});
setReviewComment('');
setReviewImage(null);
showToast('Review submitted');
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not post review');
}
};
const heroImageSrc = liveProduct
? resolveMediaUrl(liveProduct.hero_image_url || liveProduct.primary_image_url) ||
'/assets/images/product-duffel-bag-hero.png'
: '/assets/images/product-duffel-bag-hero.png';
const productTitle = liveProduct?.title || 'Islam in the Bible Book';
const gallerySlides = useMemo(() => {
if (liveProduct) {
const mediaSlides = (Array.isArray(liveProduct.media) ? liveProduct.media : [])
.slice()
.sort((a, b) => a.sort_order - b.sort_order || a.id - b.id)
.map((m, idx) => ({
id: `media-${m.id}-${idx}`,
src: resolveMediaUrl(m.image_url),
alt: m.alt_text || productTitle,
}))
.filter((s) => Boolean(s.src));
if (mediaSlides.length > 0) {
return mediaSlides;
}
return [
{
id: 'hero-fallback',
src:
resolveMediaUrl(
liveProduct.hero_image_url || liveProduct.primary_image_url
) || '/assets/images/product-duffel-bag-hero.png',
alt: productTitle,
},
];
}
if (!useMockFallback) {
return [];
}
return [
{
id: 'mock-1',
src: '/assets/images/product-duffel-bag-hero.png',
alt: productTitle,
},
{
id: 'mock-2',
src: '/assets/images/product-brown-leather-bag.png',
alt: productTitle,
},
{
id: 'mock-3',
src: '/assets/images/product-boby-backpack.png',
alt: productTitle,
},
];
}, [liveProduct, productTitle, useMockFallback]);
const maxSlideIndex = Math.max(0, gallerySlides.length - 1);
const activeSlide =
slideState.ref === resolvedRef
? Math.min(slideState.index, maxSlideIndex)
: 0;
const setActiveSlide = (next: number | ((prev: number) => number)) => {
setSlideState((prev) => {
const current =
prev.ref === resolvedRef ? Math.min(prev.index, maxSlideIndex) : 0;
const raw = typeof next === 'function' ? next(current) : next;
return {
ref: resolvedRef,
index: Math.max(0, Math.min(maxSlideIndex, raw)),
};
});
};
useEffect(() => {
if (!heroEl) return;
// Consume horizontal touchmove so Android WebView / Flutter does not cancel the swipe
const onTouchMove = (e: TouchEvent) => {
if (dragStartRef.current?.locked === 'x' && e.cancelable) {
e.preventDefault();
}
};
heroEl.addEventListener('touchmove', onTouchMove, { passive: false });
return () => {
heroEl.removeEventListener('touchmove', onTouchMove);
};
}, [heroEl]);
const handleGalleryPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (!e.isPrimary || gallerySlides.length <= 1) return;
if (e.pointerType === 'mouse' && e.button !== 0) return;
dragStartRef.current = {
id: e.pointerId,
x: e.clientX,
y: e.clientY,
lastX: e.clientX,
time: Date.now(),
locked: null,
};
};
const handleGalleryPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const start = dragStartRef.current;
if (!start || start.id !== e.pointerId) return;
start.lastX = e.clientX;
const dx = e.clientX - start.x;
const dy = e.clientY - start.y;
if (!start.locked) {
const absX = Math.abs(dx);
const absY = Math.abs(dy);
if (absX < 6 && absY < 8) return;
if (absY > absX) {
dragStartRef.current = null;
return;
}
start.locked = 'x';
if (e.pointerType === 'mouse') {
e.currentTarget.setPointerCapture(e.pointerId);
}
setIsDragging(true);
}
const atEdge =
(activeSlide === 0 && dx > 0) ||
(activeSlide === gallerySlides.length - 1 && dx < 0);
setDragOffset(atEdge ? dx * 0.3 : dx);
};
const finishGalleryDrag = (
e: React.PointerEvent<HTMLDivElement>,
cancelled = false
) => {
const start = dragStartRef.current;
if (!start || start.id !== e.pointerId) return;
dragStartRef.current = null;
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
e.currentTarget.releasePointerCapture(e.pointerId);
}
if (start.locked === 'x' && !cancelled) {
const endX = Number.isFinite(e.clientX) ? e.clientX : start.lastX;
const dx = endX - start.x;
const elapsed = Date.now() - start.time;
const threshold = Math.min(50, (e.currentTarget.clientWidth || 375) * 0.16);
const isQuickFlick = elapsed < 250 && Math.abs(dx) > 20;
if (dx <= -threshold || (isQuickFlick && dx < 0)) {
setActiveSlide((prev) => prev + 1);
} else if (dx >= threshold || (isQuickFlick && dx > 0)) {
setActiveSlide((prev) => prev - 1);
}
}
setIsDragging(false);
setDragOffset(0);
};
const handleGalleryWheel = (e: React.WheelEvent<HTMLDivElement>) => {
if (
gallerySlides.length <= 1 ||
Math.abs(e.deltaX) <= Math.abs(e.deltaY) ||
Math.abs(e.deltaX) < 20
) {
return;
}
const now = Date.now();
if (now - wheelCooldownRef.current < 450) return;
wheelCooldownRef.current = now;
setActiveSlide((prev) => (e.deltaX > 0 ? prev + 1 : prev - 1));
};
const handleGalleryKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (gallerySlides.length <= 1) return;
if (e.key === 'ArrowRight') {
e.preventDefault();
setActiveSlide((prev) => prev + 1);
} else if (e.key === 'ArrowLeft') {
e.preventDefault();
setActiveSlide((prev) => prev - 1);
}
};
const displayReviews =
!isBare && reviews
@ -171,10 +443,14 @@ export const ShopSinglePage: React.FC = () => {
date: r.formatted_date,
rating: r.rating,
comment: r.comment,
imageUrl: resolveMediaUrl(r.image_url),
}))
: useMockFallback
? STATIC_PRODUCT_REVIEWS
? STATIC_PRODUCT_REVIEWS.map((r) => ({ ...r, imageUrl: '' }))
: [];
const reviewsCount = liveProduct
? Math.max(liveProduct.reviews_count ?? 0, displayReviews.length)
: displayReviews.length;
const storeDetail = liveProduct?.store_detail;
const storeSlug = storeDetail?.slug || liveProduct?.store_slug || 'al-hujjah-books';
@ -183,18 +459,70 @@ export const ShopSinglePage: React.FC = () => {
return (
<MobileShell width={375} height={1233} backgroundColor="#f3f1ef">
{/* Hero Product Image & Floating Top Controls */}
<div className="habib-single-hero-wrap">
{/* Hero Product Image Gallery & Floating Top Controls */}
<div
ref={setHeroEl}
className="habib-single-hero-wrap"
role="region"
aria-roledescription="carousel"
aria-label={tr('Product images')}
onWheel={handleGalleryWheel}
onKeyDown={handleGalleryKeyDown}
style={{ touchAction: gallerySlides.length > 1 ? 'pan-y' : undefined }}
>
{isProductShimmer ? (
<ShimmerBox width="100%" height="100%" borderRadius={0} />
) : !liveProduct && !useMockFallback ? (
) : gallerySlides.length === 0 ? (
<div style={{ width: '100%', height: '100%', backgroundColor: '#e8e4df' }} />
) : (
<img
className="habib-single-hero-img"
src={heroImageSrc}
alt={liveProduct?.title || 'Islam in the Bible Book'}
/>
<div
onPointerDown={handleGalleryPointerDown}
onPointerMove={handleGalleryPointerMove}
onPointerUp={(e) => finishGalleryDrag(e)}
onPointerCancel={(e) => finishGalleryDrag(e, true)}
onLostPointerCapture={(e) => {
if (e.target === e.currentTarget) finishGalleryDrag(e, true);
}}
style={{
direction: 'ltr',
display: 'flex',
width: '100%',
height: '100%',
transform: `translateX(calc(-${activeSlide * 100}% + ${dragOffset}px))`,
transition: isDragging
? 'none'
: 'transform 380ms cubic-bezier(0.22, 1, 0.36, 1)',
willChange: gallerySlides.length > 1 ? 'transform' : undefined,
touchAction: gallerySlides.length > 1 ? 'pan-y' : undefined,
userSelect: 'none',
cursor:
gallerySlides.length > 1
? isDragging
? 'grabbing'
: 'grab'
: undefined,
}}
>
{gallerySlides.map((slide) => (
<div
key={slide.id}
style={{
flex: '0 0 100%',
width: '100%',
height: '100%',
overflow: 'hidden',
}}
>
<img
className="habib-single-hero-img"
src={slide.src}
alt={slide.alt}
draggable={false}
style={{ pointerEvents: 'none' }}
/>
</div>
))}
</div>
)}
{/* Floating Top Action Row */}
@ -207,6 +535,8 @@ export const ShopSinglePage: React.FC = () => {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
zIndex: 2,
pointerEvents: 'none',
}}
>
<button
@ -225,6 +555,7 @@ export const ShopSinglePage: React.FC = () => {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
pointerEvents: 'auto',
}}
>
<img
@ -244,6 +575,7 @@ export const ShopSinglePage: React.FC = () => {
position: 'relative',
width: 88,
height: 40,
pointerEvents: 'auto',
}}
>
<img
@ -289,19 +621,51 @@ export const ShopSinglePage: React.FC = () => {
</div>
{/* Image Carousel Dots */}
{!isProductShimmer && (
<img
src="/assets/images/indicator-carousel-dots.svg"
alt=""
{!isProductShimmer && gallerySlides.length > 1 && (
<div
style={{
direction: 'ltr',
position: 'absolute',
left: '50%',
bottom: 56,
bottom: 50,
transform: 'translateX(-50%)',
width: 38,
height: 7,
display: 'flex',
alignItems: 'center',
gap: 4,
zIndex: 1,
}}
/>
>
{gallerySlides.map((slide, idx) => {
const isActive = activeSlide === idx;
return (
<button
key={slide.id}
type="button"
aria-label={`Show product image ${idx + 1} of ${gallerySlides.length}`}
aria-current={isActive ? 'true' : undefined}
onClick={() => setActiveSlide(idx)}
style={{
padding: '6px 0',
border: 'none',
background: 'transparent',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
}}
>
<span
style={{
width: isActive ? 16 : 7,
height: 7,
borderRadius: 3.5,
backgroundColor: isActive ? '#747474' : '#d7dbe2',
transition: 'width 280ms ease, background-color 280ms ease',
}}
/>
</button>
);
})}
</div>
)}
</div>
@ -545,8 +909,8 @@ export const ShopSinglePage: React.FC = () => {
{tr(
isBare
? '0 Reviews'
: `${displayReviews.length} ${
displayReviews.length === 1 ? 'Review' : 'Reviews'
: `${reviewsCount} ${
reviewsCount === 1 ? 'Review' : 'Reviews'
}`
)}
</span>
@ -915,7 +1279,7 @@ export const ShopSinglePage: React.FC = () => {
transition: 'color 200ms cubic-bezier(0.22, 1, 0.36, 1)',
}}
>
{isProductShimmer ? tr('Review') : tr(`Review(${displayReviews.length})`)}
{isProductShimmer ? tr('Review') : tr(`Review(${reviewsCount})`)}
</button>
{/* Active Tab Indicator Bar */}
@ -1053,7 +1417,7 @@ export const ShopSinglePage: React.FC = () => {
>
{isProductShimmer
? tr('Customer Reviews')
: tr(`Customer Reviews (${displayReviews.length})`)}
: tr(`Customer Reviews (${reviewsCount})`)}
</span>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<img
@ -1150,6 +1514,13 @@ export const ShopSinglePage: React.FC = () => {
))}
</div>
</div>
<input
ref={reviewFileInputRef}
type="file"
accept="image/*"
onChange={handleReviewFileChange}
style={{ display: 'none' }}
/>
<textarea
rows={2}
value={reviewComment}
@ -1165,24 +1536,132 @@ export const ShopSinglePage: React.FC = () => {
resize: 'none',
}}
/>
<button
type="submit"
disabled={submittingReview || !reviewComment.trim()}
{reviewImage && (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
padding: '6px 8px',
borderRadius: 10,
backgroundColor: '#f8f8f8',
border: '1px solid #e8e4df',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
minWidth: 0,
}}
>
<img
src={reviewImage.previewUrl}
alt={tr('Attached image')}
style={{
width: 40,
height: 40,
borderRadius: 8,
objectFit: 'cover',
flexShrink: 0,
}}
/>
<span
style={{
fontFamily: 'var(--font-sans)',
fontSize: 11,
color: '#3d3d3d',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{reviewImage.file.name}
</span>
</div>
<button
type="button"
onClick={() => setReviewImage(null)}
style={{
border: 'none',
background: 'transparent',
color: '#d44747',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
cursor: 'pointer',
flexShrink: 0,
padding: '2px 4px',
}}
>
{tr('Remove')}
</button>
</div>
)}
<div
style={{
alignSelf: 'flex-end',
padding: '6px 14px',
borderRadius: 9,
backgroundColor: '#292a2e',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
cursor: 'pointer',
opacity: submittingReview || !reviewComment.trim() ? 0.6 : 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
}}
>
{submittingReview ? tr('Posting...') : tr('Post Review')}
</button>
<button
type="button"
disabled={submittingReview || pickingReviewImage}
onClick={() => {
void handlePickReviewImage();
}}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 5,
padding: '5px 10px',
borderRadius: 9,
border: '1px dashed #bcbcbc',
backgroundColor: '#f8f8f8',
color: '#3d3d3d',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
cursor:
submittingReview || pickingReviewImage
? 'not-allowed'
: 'pointer',
opacity: submittingReview || pickingReviewImage ? 0.6 : 1,
}}
>
<img
src="/assets/images/icon-upload-image-placeholder.svg"
alt=""
style={{ width: 14, height: 14, flexShrink: 0 }}
/>
<span>
{pickingReviewImage
? tr('Uploading...')
: tr('+ Upload Image')}
</span>
</button>
<button
type="submit"
disabled={submittingReview || !reviewComment.trim()}
style={{
padding: '6px 14px',
borderRadius: 9,
backgroundColor: '#292a2e',
color: '#ffffff',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
cursor: 'pointer',
opacity: submittingReview || !reviewComment.trim() ? 0.6 : 1,
}}
>
{submittingReview ? tr('Posting...') : tr('Post Review')}
</button>
</div>
</form>
)}
@ -1297,6 +1776,22 @@ export const ShopSinglePage: React.FC = () => {
>
{review.comment}
</div>
{review.imageUrl && (
<img
src={review.imageUrl}
alt={tr('Attached image')}
loading="lazy"
style={{
width: '100%',
maxWidth: 180,
maxHeight: 180,
borderRadius: 10,
objectFit: 'cover',
border: '1px solid #ece9e5',
}}
/>
)}
</div>
))
)}

101
src/pages/checkout/ShopCartPage.tsx

@ -107,7 +107,7 @@ export const ShopCartPage: React.FC = () => {
? bareTotalQty > 0
? `$${bareTotalOldPrice.toFixed(2)}`
: undefined
: undefined;
: livePricing?.formatted_compare_subtotal || undefined;
const footerTotalItemsLabel = useFigmaSnapshot
? 'Total 4 item'
@ -175,60 +175,65 @@ export const ShopCartPage: React.FC = () => {
}}
>
{/* Top Info Bar */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
padding: '0 2px',
}}
>
{(isCartShimmer || hasAnyItems || useMockFallback) && (
<div
style={{
display: 'inline-flex',
display: 'flex',
alignItems: 'center',
gap: 6,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#292a2e',
justifyContent: 'space-between',
gap: 12,
padding: '0 2px',
}}
>
{isCartShimmer ? (
<ShimmerBox width={108} height={14} borderRadius={5} />
) : (
<span>{tr(topInfoText)}</span>
{(isCartShimmer || hasAnyItems) && (
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 6,
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: '#292a2e',
}}
>
{isCartShimmer ? (
<ShimmerBox width={108} height={14} borderRadius={5} />
) : (
<span>{tr(topInfoText)}</span>
)}
{!isBare && isCartBusy && <InlineSpinner size={12} gold />}
</div>
)}
{!isBare && isCartBusy && <InlineSpinner size={12} gold />}
</div>
{!isCartShimmer && (hasAnyItems || useMockFallback) && (
<div
onClick={() => {
if (!isCartBusy) {
void handleClearOrRestore();
}
}}
role="button"
aria-label={tr(hasAnyItems ? 'Clear all' : 'Add sample item')}
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: hasAnyItems ? '#d44747' : '#d78e06',
textAlign: 'right',
cursor: 'pointer',
whiteSpace: 'nowrap',
userSelect: 'none',
}}
>
{tr(hasAnyItems ? 'Clear all' : isBare ? 'Restore' : '+ Add Sample')}
</div>
)}
</div>
{!isCartShimmer && (hasAnyItems || useMockFallback) && (
<div
onClick={() => {
if (!isCartBusy) {
void handleClearOrRestore();
}
}}
role="button"
aria-label={tr(hasAnyItems ? 'Clear all' : 'Add sample item')}
style={{
marginInlineStart: 'auto',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 10,
lineHeight: '13.9px',
color: hasAnyItems ? '#d44747' : '#d78e06',
textAlign: 'right',
cursor: 'pointer',
whiteSpace: 'nowrap',
userSelect: 'none',
}}
>
{tr(hasAnyItems ? 'Clear all' : isBare ? 'Restore' : '+ Add Sample')}
</div>
)}
</div>
)}
{/* Cart Item Cards */}
{isCartShimmer ? (

77
src/pages/checkout/ShopPaymentPage.tsx

@ -25,6 +25,7 @@ import { mapCartItemToReview } from '../../lib/mappers';
import { formatPhoneForDisplay, isValidPhoneString } from '../../lib/phone';
import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
useCheckoutSummaryQuery,
usePaymentMethodsQuery,
usePlaceOrderMutation,
} from '../../lib/shopQueries';
@ -53,8 +54,13 @@ export const ShopPaymentPage: React.FC = () => {
} = useShopApp();
const [paymentSheetOpen, setPaymentSheetOpen] = useState(false);
const checkoutSummaryQuery = useCheckoutSummaryQuery(
selectedShippingMethod?.code,
!isBare && isUserAuthenticated
);
const paymentMethodsQuery = usePaymentMethodsQuery(!isBare);
const placeOrderMutation = usePlaceOrderMutation();
const summaryData = checkoutSummaryQuery.data;
const paymentMethodsData = paymentMethodsQuery.data;
const submitting = placeOrderMutation.isPending;
@ -78,10 +84,30 @@ export const ShopPaymentPage: React.FC = () => {
useMockFallback,
]);
const livePricing = cart?.pricing;
const activeCart = summaryData?.cart ?? cart;
const summaryPricing = summaryData?.pricing;
const activeShippingMethod =
summaryData?.shipping_method ?? selectedShippingMethod;
const isSummaryLoading =
!isBare &&
isUserAuthenticated &&
(checkoutSummaryQuery.isPending || isCartLoading || isShippingMethodsLoading) &&
!summaryPricing;
const { rows, totalText } = useMemo(() => {
if (isBare || !livePricing) {
if (isBare || !summaryPricing) {
if (!isBare && cart?.pricing && checkoutSummaryQuery.isError) {
return {
rows: [
{
id: 'row-items',
label: `Items (${cart.pricing.total_quantity ?? cart.pricing.total_units ?? 0})`,
value: cart.pricing.formatted_subtotal,
},
],
totalText: cart.pricing.formatted_total,
};
}
return useMockFallback
? {
rows: undefined,
@ -92,32 +118,34 @@ export const ShopPaymentPage: React.FC = () => {
totalText: '$0.00',
};
}
const subtotalNum = Number(livePricing.subtotal) || 0;
const shipNum = Number(selectedShippingMethod?.price || 0);
const totalNum = Math.max(0, subtotalNum + shipNum);
const computedRows: SummaryLineRow[] = [
{
id: 'row-items',
label: `Items (${livePricing.total_quantity ?? livePricing.total_units ?? 0})`,
value: livePricing.formatted_subtotal,
label: `Items (${summaryPricing.total_quantity ?? summaryPricing.total_units ?? 0})`,
value: summaryPricing.formatted_subtotal,
},
{
id: 'row-shipping',
label:
selectedShippingMethod?.title ||
activeShippingMethod?.title ||
(useMockFallback ? 'Standard shipping' : 'Shipping'),
value:
selectedShippingMethod?.formatted_price ||
(useMockFallback ? '$5.00' : '$0.00'),
value: summaryPricing.formatted_shipping_fee,
},
];
return {
rows: computedRows,
totalText: `$${totalNum.toFixed(2)}`,
totalText: summaryPricing.formatted_total,
};
}, [isBare, livePricing, selectedShippingMethod, useMockFallback]);
}, [
activeShippingMethod,
cart,
checkoutSummaryQuery.isError,
isBare,
summaryPricing,
useMockFallback,
]);
const handleConfirmPurchase = async () => {
if (isBare) {
@ -158,8 +186,10 @@ export const ShopPaymentPage: React.FC = () => {
postal_code: '10003',
country: 'United States',
},
shipping_method: selectedShippingMethod?.code || 'standard',
shipping_method: activeShippingMethod?.code || 'standard',
payment_method: selectedPaymentMethod || 'google_pay',
// shortcut: trusts client to confirm payment without gateway capture, replace when real payment gateway webhook is wired
confirm_payment: true,
});
setPaymentSheetOpen(false);
@ -214,13 +244,15 @@ export const ShopPaymentPage: React.FC = () => {
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{!isBare && isCartLoading && !cart?.items?.length ? (
{!isBare &&
(isCartLoading || isSummaryLoading) &&
!activeCart?.items?.length ? (
<>
<ShimmerBox height={76} borderRadius={15} />
<ShimmerBox height={76} borderRadius={15} />
</>
) : !isBare && cart?.items?.length ? (
cart.items.map((item, idx) => (
) : !isBare && activeCart?.items?.length ? (
activeCart.items.map((item, idx) => (
<ReviewItemCard
key={item.id}
item={mapCartItemToReview(item, idx)}
@ -396,11 +428,7 @@ export const ShopPaymentPage: React.FC = () => {
<OrderSummaryRows
rows={rows}
totalText={isBare ? '$70.50' : totalText}
loading={
!isBare &&
(isCartLoading || isShippingMethodsLoading) &&
!livePricing
}
loading={isSummaryLoading}
/>
</div>
</section>
@ -410,14 +438,15 @@ export const ShopPaymentPage: React.FC = () => {
<StickyFooterBar
height={90}
price={isBare ? '$24.00' : totalText}
loadingPrice={!isBare && isCartLoading && !livePricing}
loadingPrice={isSummaryLoading}
topLabel="Total Cost"
buttonText="Payment"
buttonFontWeight={700}
iconSrc="/assets/images/icon-credit-card-white.svg"
targetRoute={ROUTES.checkoutReview}
disabled={
!isBare && (isCartLoading || !cart?.items || cart.items.length === 0)
!isBare &&
(isSummaryLoading || !activeCart?.items || activeCart.items.length === 0)
}
onButtonClick={() => {
if (isBare) {

171
src/pages/home/ShopHomePage.tsx

@ -267,52 +267,7 @@ export const ShopHomePage: React.FC = () => {
return (
<MobileShell width={375} height={1074} backgroundColor="#f3f1ef">
{/* Decorative Top Glow & Islamic Pattern */}
<div
style={{
position: 'absolute',
left: '50%',
top: -31,
transform: 'translateX(-50%)',
width: '92%',
maxWidth: 480,
height: 45,
borderRadius: '50%',
backgroundColor: '#d78e06',
filter: 'blur(50px)',
opacity: 0.7,
pointerEvents: 'none',
}}
/>
<div
style={{
position: 'absolute',
left: '50%',
top: -13,
transform: 'translateX(-50%)',
width: 190,
height: 35,
borderRadius: '50%',
backgroundColor: '#d78e06',
filter: 'blur(5px)',
opacity: 0.1,
pointerEvents: 'none',
}}
/>
<div
style={{
position: 'absolute',
left: '50%',
top: -3,
transform: 'translateX(-50%)',
width: 144,
height: 7,
borderRadius: '50%',
backgroundColor: '#d78e06',
filter: 'blur(2.5px)',
pointerEvents: 'none',
}}
/>
{/* Decorative Islamic Pattern (extends behind Hero Banner) */}
<img
src="/assets/images/bg-islamic-pattern.png"
alt=""
@ -343,26 +298,106 @@ export const ShopHomePage: React.FC = () => {
}}
/>
{/* Fluid Main Body */}
{/* Sticky Top Bar + Search Bar */}
<div
style={{
position: 'relative',
zIndex: 1,
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: 'calc(37px + var(--safe-top, 0px)) var(--page-px) 22px',
gap: 20,
position: 'sticky',
top: 0,
zIndex: 20,
backgroundColor: '#f3f1ef',
padding: 'calc(37px + var(--safe-top, 0px)) var(--page-px) 10px',
}}
>
<div
aria-hidden="true"
style={{
position: 'absolute',
inset: 0,
overflow: 'hidden',
pointerEvents: 'none',
}}
>
<div
style={{
position: 'absolute',
left: '50%',
top: -31,
transform: 'translateX(-50%)',
width: '92%',
maxWidth: 480,
height: 45,
borderRadius: '50%',
backgroundColor: '#d78e06',
filter: 'blur(50px)',
opacity: 0.7,
}}
/>
<div
style={{
position: 'absolute',
left: '50%',
top: -13,
transform: 'translateX(-50%)',
width: 190,
height: 35,
borderRadius: '50%',
backgroundColor: '#d78e06',
filter: 'blur(5px)',
opacity: 0.1,
}}
/>
<div
style={{
position: 'absolute',
left: '50%',
top: -3,
transform: 'translateX(-50%)',
width: 144,
height: 7,
borderRadius: '50%',
backgroundColor: '#d78e06',
filter: 'blur(2.5px)',
}}
/>
<img
src="/assets/images/bg-islamic-pattern.png"
alt=""
style={{
position: 'absolute',
left: 0,
top: 2,
width: '100%',
height: 375,
filter: 'brightness(0) invert(1)',
objectFit: 'cover',
}}
/>
<img
src="/assets/images/bg-islamic-pattern.png"
alt=""
style={{
position: 'absolute',
left: 0,
top: 0,
width: '100%',
height: 375,
opacity: 0.25,
filter: 'brightness(0) invert(1)',
objectFit: 'cover',
}}
/>
</div>
{/* Top Bar: Back + "Shop" + Notifications */}
<header
style={{
position: 'relative',
zIndex: 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
minHeight: 40,
marginBottom: 11,
marginBottom: 31,
}}
>
<button
@ -437,11 +472,27 @@ export const ShopHomePage: React.FC = () => {
</header>
{/* Search Bar & Filter Button */}
<SearchBar
showFilterButton={true}
onFilterClick={() => navigate(ROUTES.categories)}
onSubmit={(q) => navigate(ROUTES.search(q))}
/>
<div style={{ position: 'relative', zIndex: 1 }}>
<SearchBar
showFilterButton={true}
onFilterClick={() => navigate(ROUTES.categories)}
onSubmit={(q) => navigate(ROUTES.search(q))}
/>
</div>
</div>
{/* Fluid Main Body */}
<div
style={{
position: 'relative',
zIndex: 1,
flex: 1,
display: 'flex',
flexDirection: 'column',
padding: '10px var(--page-px) 22px',
gap: 20,
}}
>
{!isBare && loading && !feed ? (
<HomeFeedShimmer />

374
src/pages/orders/ShopSupportPage.tsx

@ -1,9 +1,10 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MobileShell } from '../../components/layout/MobileShell';
import { StandardPageHeader } from '../../components/layout/TopHeader';
import {
EmptyStateBox,
RetryBanner,
ShimmerBox,
} from '../../components/common/ShimmerSkeletons';
import { useShopApp } from '../../context/ShopAppContext';
@ -15,6 +16,7 @@ import {
useCreateSupportTicketMutation,
useOrderDetailQuery,
useSupportSubjectsQuery,
useSupportTicketsQuery,
} from '../../lib/shopQueries';
import {
isInFlutterWebView,
@ -23,6 +25,13 @@ import {
const MAX_SUPPORT_ATTACHMENT_BYTES = 25 * 1024 * 1024;
function isImageAttachment(url: string): boolean {
return (
url.startsWith('data:image/') ||
/\.(jpe?g|png|webp|gif)(\?|$)/i.test(url)
);
}
/**
* Node 4177:11244 — `shop-support` (Order Support Request Form, 375×1061)
*/
@ -41,8 +50,10 @@ export const ShopSupportPage: React.FC = () => {
const [attachmentIsObjectUrl, setAttachmentIsObjectUrl] = useState(false);
const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const ticketsSectionRef = useRef<HTMLDivElement | null>(null);
const subjectsQuery = useSupportSubjectsQuery(!isBare);
const ticketsQuery = useSupportTicketsQuery(!isBare && isUserAuthenticated);
const orderDetailQuery = useOrderDetailQuery(
orderId || '',
!isBare && Boolean(orderId)
@ -50,6 +61,16 @@ export const ShopSupportPage: React.FC = () => {
const createTicketMutation = useCreateSupportTicketMutation();
const subjects = subjectsQuery.data?.results ?? null;
const tickets = ticketsQuery.data?.results ?? null;
const sortedTickets = useMemo(() => {
if (!tickets) return [];
if (!orderId) return tickets;
return [...tickets].sort((a, b) => {
const aMatch = a.order_number === orderId ? 0 : 1;
const bMatch = b.order_number === orderId ? 0 : 1;
return aMatch - bMatch;
});
}, [orderId, tickets]);
const orderDetail = orderDetailQuery.data ?? null;
const submitting = createTicketMutation.isPending;
@ -142,11 +163,15 @@ export const ShopSupportPage: React.FC = () => {
attachment: attachmentFile,
attachment_url: attachmentFile ? undefined : attachmentUrl || undefined,
});
if (attachmentIsObjectUrl && attachmentUrl) {
URL.revokeObjectURL(attachmentUrl);
}
setDescription('');
setStagedEvidence('', undefined, false);
showToast(`Support ticket ${ticket.ticket_number} submitted`);
navigate(orderId ? ROUTES.orderDetail(orderId) : ROUTES.orders());
window.requestAnimationFrame(() => {
ticketsSectionRef.current?.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
});
});
} catch (err) {
showToast(err instanceof Error ? err.message : 'Could not submit request');
}
@ -159,6 +184,13 @@ export const ShopSupportPage: React.FC = () => {
!isBare &&
(subjectsQuery.isPending || (!subjects && subjectsQuery.isFetching)) &&
!subjects;
const isTicketsLoading =
!isBare &&
isUserAuthenticated &&
(ticketsQuery.isPending || (!tickets && ticketsQuery.isFetching)) &&
!tickets;
const isTicketsError =
!isBare && isUserAuthenticated && ticketsQuery.isError && !tickets;
const backTarget = orderId ? ROUTES.orderDetail(orderId) : ROUTES.account;
const displaySubjects =
@ -644,7 +676,7 @@ export const ShopSupportPage: React.FC = () => {
void handleSubmit();
}}
style={{
marginTop: 'auto',
marginTop: isBare ? 'auto' : 0,
width: '100%',
height: 52,
borderRadius: 11,
@ -681,6 +713,336 @@ export const ShopSupportPage: React.FC = () => {
{submitting ? tr('Submitting...') : tr('Submit Order')}
</span>
</button>
{/* Submitted Support Tickets & Admin Responses */}
{!isBare && (
<div
ref={ticketsSectionRef}
style={{
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 14,
lineHeight: '20px',
color: '#111111',
}}
>
{tr('Submitted Tickets')}
</span>
{isUserAuthenticated && tickets !== null && (
<span
style={{
minWidth: 22,
height: 20,
padding: '0 7px',
borderRadius: 999,
backgroundColor: 'rgba(215, 142, 6, 0.15)',
color: '#d78e06',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 11,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{ticketsQuery.data?.count ?? sortedTickets.length}
</span>
)}
</div>
{!isUserAuthenticated ? (
<button
type="button"
onClick={() => {
void requireAuth({ featureName: 'support requests' });
}}
style={{
width: '100%',
padding: '16px 14px',
borderRadius: 15,
backgroundColor: '#ffffff',
border: '1px solid #e8e4df',
cursor: 'pointer',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 13,
lineHeight: '19px',
color: '#d78e06',
textAlign: 'center',
}}
>
{tr('Sign in to view your submitted tickets.')}
</button>
) : isTicketsLoading ? (
<>
<ShimmerBox height={96} borderRadius={15} />
<ShimmerBox height={96} borderRadius={15} />
</>
) : isTicketsError ? (
<RetryBanner
message="Could not load support tickets. Tap Retry to refresh."
onRetry={() => void ticketsQuery.refetch()}
/>
) : sortedTickets.length === 0 ? (
<EmptyStateBox
message="No support tickets submitted yet."
compact
/>
) : (
sortedTickets.map((ticket) => {
const isResolved = ticket.status === 'resolved';
const statusLabel =
ticket.status === 'resolved'
? 'Resolved'
: ticket.status === 'open'
? 'Open'
: ticket.status || 'Open';
const resolvedAttachment = ticket.attachment_url
? resolveMediaUrl(ticket.attachment_url)
: '';
const adminReply = (ticket.admin_reply || '').trim();
return (
<div
key={ticket.id}
style={{
width: '100%',
padding: 12,
borderRadius: 15,
backgroundColor: '#ffffff',
border: '1px solid #e8e4df',
boxSizing: 'border-box',
display: 'flex',
flexDirection: 'column',
gap: 8,
}}
>
{/* Header: Ticket # + Subject + Status Badge */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
flexWrap: 'wrap',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
minWidth: 0,
flexWrap: 'wrap',
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 12,
lineHeight: '17px',
color: '#111111',
}}
>
{ticket.ticket_number}
</span>
<span style={{ color: '#bcbcbc', fontSize: 12 }}>·</span>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 12,
lineHeight: '17px',
color: '#3d3d3d',
}}
>
{tr(ticket.subject_label || 'Order Support')}
</span>
</div>
<span
style={{
padding: '3px 9px',
borderRadius: 999,
backgroundColor: isResolved
? 'rgba(14, 177, 60, 0.14)'
: 'rgba(239, 196, 126, 0.25)',
color: isResolved ? '#0eb13c' : '#d78e06',
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 11,
lineHeight: '15px',
whiteSpace: 'nowrap',
}}
>
{tr(statusLabel)}
</span>
</div>
{/* Date + Linked Order */}
{(ticket.formatted_date || ticket.order_number) && (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 8,
flexWrap: 'wrap',
}}
>
{ticket.formatted_date && (
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 500,
fontSize: 11,
lineHeight: '15px',
color: '#8b8b8b',
}}
>
{ticket.formatted_date}
</span>
)}
{ticket.order_number && (
<button
type="button"
onClick={() =>
navigate(ROUTES.orderDetail(ticket.order_number))
}
style={{
padding: 0,
border: 'none',
background: 'transparent',
cursor: 'pointer',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
lineHeight: '15px',
color: '#d78e06',
}}
>
{tr(`Order ${ticket.order_number}`)}
</button>
)}
</div>
)}
{/* Description */}
{ticket.description && (
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#292a2e',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
{ticket.description}
</div>
)}
{/* Attachment Link / Preview */}
{resolvedAttachment && (
<a
href={resolvedAttachment}
target="_blank"
rel="noopener noreferrer"
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 8,
alignSelf: 'flex-start',
padding: '5px 10px',
borderRadius: 10,
backgroundColor: '#f5f3f0',
fontFamily: 'var(--font-sans)',
fontWeight: 600,
fontSize: 11,
lineHeight: '15px',
color: '#111111',
}}
>
{isImageAttachment(resolvedAttachment) && (
<img
src={resolvedAttachment}
alt=""
style={{
width: 32,
height: 32,
borderRadius: 6,
objectFit: 'cover',
flexShrink: 0,
}}
/>
)}
<span>{tr('View attachment')}</span>
</a>
)}
{/* Admin Reply */}
{adminReply && (
<div
style={{
padding: '9px 11px',
borderRadius: 11,
backgroundColor: 'rgba(14, 177, 60, 0.08)',
border: '1px solid rgba(14, 177, 60, 0.28)',
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
<span
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 700,
fontSize: 11,
lineHeight: '15px',
color: '#0eb13c',
}}
>
{tr('Support Reply')}
</span>
<div
style={{
fontFamily: 'var(--font-sans)',
fontWeight: 400,
fontSize: 12,
lineHeight: '18px',
color: '#1f2937',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
{adminReply}
</div>
</div>
)}
</div>
);
})
)}
</div>
)}
</div>
</MobileShell>
);

Loading…
Cancel
Save