feat(pdp): redesign variant comparison table for multi-variant products, exclude media keys, and add calendar invites

This commit is contained in:
iFixKart Dev 2026-11-09 15:22:16 +05:30
parent 148ebceae4
commit 16dbaa0916
6 changed files with 335 additions and 194 deletions

View file

@ -248,7 +248,6 @@ export default async function ProductDetailPage({ params }: ProductDetailPagePro
const { product, reviews = [], related_products = [], specifications = [] } = data; const { product, reviews = [], related_products = [], specifications = [] } = data;
const related = related_products.slice(0, 5); const related = related_products.slice(0, 5);
const comparisonProducts = [product, ...related_products.filter((p: any) => p.product_id !== product.product_id)].slice(0, 5);
const specGroups = groupSpecs(specifications, product); const specGroups = groupSpecs(specifications, product);
const additionalInfoRows: { label: string; value: string }[] = []; const additionalInfoRows: { label: string; value: string }[] = [];
@ -458,8 +457,8 @@ export default async function ProductDetailPage({ params }: ProductDetailPagePro
{related.length > 0 && <YouMayAlsoLike products={related} />} {related.length > 0 && <YouMayAlsoLike products={related} />}
{comparisonProducts.length > 0 && ( {(product.variants?.length || 0) > 1 && (
<QuickComparisonTable products={comparisonProducts} /> <QuickComparisonTable product={product} />
)} )}
</div> </div>
</main> </main>

View file

@ -28,6 +28,9 @@ import {
Smartphone, Smartphone,
Wrench, Wrench,
ArrowRight, ArrowRight,
Calendar,
Download,
ExternalLink,
} from 'lucide-react'; } from 'lucide-react';
import { AnnouncementBar } from '@/layout/AnnouncementBar'; import { AnnouncementBar } from '@/layout/AnnouncementBar';
import { Header } from '@/layout/Header'; import { Header } from '@/layout/Header';
@ -96,6 +99,7 @@ function BookingSuccessContent() {
const needsVerify = searchParams.get('verify') === '1'; const needsVerify = searchParams.get('verify') === '1';
const [jobDetails, setJobDetails] = useState<any | null>(null); const [jobDetails, setJobDetails] = useState<any | null>(null);
const [calendarInvite, setCalendarInvite] = useState<any | null>(null);
const [layoutCMS, setLayoutCMS] = useState<any[]>([]); const [layoutCMS, setLayoutCMS] = useState<any[]>([]);
const [verifyState, setVerifyState] = useState<'idle' | 'verifying' | 'done'>( const [verifyState, setVerifyState] = useState<'idle' | 'verifying' | 'done'>(
needsVerify ? 'verifying' : 'idle' needsVerify ? 'verifying' : 'idle'
@ -276,6 +280,16 @@ function BookingSuccessContent() {
} }
}; };
useEffect(() => {
const target = jobId || (jobNoParam && jobNoParam !== 'SRV-BOOKING' ? jobNoParam : '');
if (target) {
serviceBookingService
.fetchCalendarInvite(target)
.then((data) => setCalendarInvite(data))
.catch(() => setCalendarInvite(null));
}
}, [jobId, jobNoParam]);
const job = unwrapJob(jobDetails); const job = unwrapJob(jobDetails);
const payment = firstPayment(job); const payment = firstPayment(job);
const isPaid = const isPaid =
@ -454,6 +468,45 @@ function BookingSuccessContent() {
</div> </div>
</div> </div>
{calendarInvite && (
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 p-5 rounded-lg flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-start gap-3.5">
<div className="w-10 h-10 rounded-full bg-blue-600 text-white flex items-center justify-center shrink-0 mt-0.5">
<Calendar className="w-5 h-5" />
</div>
<div>
<div className="text-[11px] font-bold uppercase tracking-wider text-blue-700">Walk-In Calendar Invite</div>
<h4 className="text-[15px] font-bold text-gray-900 mt-0.5">
Slot: {new Date(calendarInvite.scheduled_start).toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' })}
</h4>
<p className="text-[12px] text-gray-600 mt-1 max-w-xl">
Add this repair appointment to your personal calendar to receive automatic pre-service notifications and a reminder before your slot.
</p>
</div>
</div>
<div className="flex flex-wrap sm:flex-nowrap items-center gap-2 shrink-0">
<a
href={calendarInvite.google_calendar_url}
target="_blank"
rel="noopener noreferrer"
className="px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-[12px] font-bold rounded flex items-center gap-1.5 shadow-sm transition"
>
<Calendar className="w-3.5 h-3.5" />
Add to Google Calendar
<ExternalLink className="w-3 h-3 ml-0.5 opacity-80" />
</a>
<a
href={`http://localhost:8000${calendarInvite.ics_download_url}`}
download
className="px-4 py-2.5 bg-white hover:bg-gray-50 border border-gray-300 text-gray-800 text-[12px] font-semibold rounded flex items-center gap-1.5 shadow-sm transition"
>
<Download className="w-3.5 h-3.5" />
Download .ics Invite
</a>
</div>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div className="border border-[#e5e5e5] p-5 space-y-4"> <div className="border border-[#e5e5e5] p-5 space-y-4">
<div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-[#222] border-b border-[#e5e5e5] pb-2"> <div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-[#222] border-b border-[#e5e5e5] pb-2">

View file

@ -25,6 +25,8 @@ import {
Image as ImageIcon, Image as ImageIcon,
Maximize2, Maximize2,
KeyRound, KeyRound,
Download,
ExternalLink,
} from 'lucide-react'; } from 'lucide-react';
import { BlurHashImage } from '@/components/ui/BlurHashImage'; import { BlurHashImage } from '@/components/ui/BlurHashImage';
import { AnnouncementBar } from '@/layout/AnnouncementBar'; import { AnnouncementBar } from '@/layout/AnnouncementBar';
@ -61,6 +63,7 @@ export default function ServiceJobTrackingPage({
const { isAuthenticated, accessToken, authReady, bootstrapAuth } = useAuthStore(); const { isAuthenticated, accessToken, authReady, bootstrapAuth } = useAuthStore();
const [job, setJob] = useState<any>(null); const [job, setJob] = useState<any>(null);
const [calendarInvite, setCalendarInvite] = useState<any | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [errorMsg, setErrorMsg] = useState<string | null>(null); const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [actionLoading, setActionLoading] = useState(false); const [actionLoading, setActionLoading] = useState(false);
@ -99,6 +102,13 @@ export default function ServiceJobTrackingPage({
job_id: item?.job_id || job_id, job_id: item?.job_id || job_id,
job_no: item?.job_no, job_no: item?.job_no,
}); });
if (item?.fulfillment_type === 'WALK_IN' || item?.appointment) {
serviceBookingService
.fetchCalendarInvite(item?.job_id || job_id)
.then((cal) => setCalendarInvite(cal))
.catch(() => setCalendarInvite(null));
}
} catch (err: any) { } catch (err: any) {
setErrorMsg(err.message || 'Failed to retrieve tracking details.'); setErrorMsg(err.message || 'Failed to retrieve tracking details.');
} finally { } finally {
@ -533,10 +543,15 @@ export default function ServiceJobTrackingPage({
})()} })()}
{job.appointment && ( {job.appointment && (
<div className="bg-white border border-[#e5e5e5] p-5 space-y-3 text-[13px]"> <div className="bg-white border border-[#e5e5e5] p-5 space-y-4 text-[13px]">
<h4 className="font-semibold text-[#222] uppercase tracking-wider text-[11px] border-b border-[#e5e5e5] pb-2"> <div className="flex items-center justify-between border-b border-[#e5e5e5] pb-2">
Booking Schedule <h4 className="font-semibold text-[#222] uppercase tracking-wider text-[11px]">
</h4> Booking Schedule
</h4>
<span className="text-[11px] font-bold text-blue-600 bg-blue-50 px-2 py-0.5 rounded">
Walk-In
</span>
</div>
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<Calendar className="w-5 h-5 text-primary shrink-0 mt-0.5" /> <Calendar className="w-5 h-5 text-primary shrink-0 mt-0.5" />
<div> <div>
@ -550,16 +565,46 @@ export default function ServiceJobTrackingPage({
})} })}
</div> </div>
<div className="text-gray-500 font-mono text-[12px] mt-0.5"> <div className="text-gray-500 font-mono text-[12px] mt-0.5">
Start:{' '} Slot:{' '}
{new Date( {new Date(
job.appointment.scheduled_start job.appointment.scheduled_start
).toLocaleTimeString('en-US', { ).toLocaleTimeString('en-US', {
hour: '2-digit', hour: '2-digit',
minute: '2-digit', minute: '2-digit',
})}{' '}
–{' '}
{new Date(
job.appointment.scheduled_end
).toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
})} })}
</div> </div>
</div> </div>
</div> </div>
{calendarInvite && (
<div className="pt-2 border-t border-[#f0f0f0] space-y-2">
<a
href={calendarInvite.google_calendar_url}
target="_blank"
rel="noopener noreferrer"
className="w-full py-2 px-3 bg-blue-600 hover:bg-blue-700 text-white font-bold text-[12px] rounded flex items-center justify-center gap-1.5 transition shadow-sm"
>
<Calendar className="w-3.5 h-3.5" />
Add to Google Calendar
<ExternalLink className="w-3 h-3 ml-0.5 opacity-80" />
</a>
<a
href={`http://localhost:8000${calendarInvite.ics_download_url}`}
download
className="w-full py-2 px-3 bg-gray-50 hover:bg-gray-100 border border-gray-200 text-gray-700 font-semibold text-[12px] rounded flex items-center justify-center gap-1.5 transition"
>
<Download className="w-3.5 h-3.5" />
Download .ics Calendar File
</a>
</div>
)}
</div> </div>
)} )}

View file

@ -1,186 +1,213 @@
'use client'; 'use client';
import Link from 'next/link'; import { useState } from 'react';
import Image from 'next/image'; import { Check, ShoppingCart, ShieldCheck, FileText } from 'lucide-react';
import { useState } from 'react'; import BlurHashImage from '@/components/ui/BlurHashImage';
import { Check, ShoppingCart } from 'lucide-react'; import { ProductResponse, ProductVariantResponse } from '@/services/api/catalogService';
import BlurHashImage from '@/components/ui/BlurHashImage'; import { useCartStore } from '@/store/cartStore';
import { ProductResponse } from '@/services/api/catalogService'; import { formatCurrency, getImageUrl } from '@/lib/utils';
import { useCartStore } from '@/store/cartStore';
import { formatCatalogPriceLabel, formatCurrency, getImageUrl } from '@/lib/utils'; interface QuickComparisonTableProps {
product: ProductResponse;
interface QuickComparisonTableProps { }
products: ProductResponse[];
} function getVariantTitle(variant: ProductVariantResponse, fallbackIndex: number): string {
const validAttrs = (variant.attributes || []).filter((a) => {
function priceLabel(product: ProductResponse): string { const key = (a.attribute_name || a.attribute_code || '').toLowerCase().trim();
const label = formatCatalogPriceLabel(product); return a.attribute_value && !['media_key', 'parent_media_key'].includes(key);
return label === formatCurrency(0) ? '—' : label; });
}
if (validAttrs.length > 0) {
function productImage(product: ProductResponse): string { return validAttrs
return getImageUrl(product.images?.[0]?.image_url || product.variants?.[0]?.images?.[0]?.image_url); .map((a) => {
} const name = a.attribute_name ? `${a.attribute_name}: ` : '';
return `${name}${a.attribute_value}`;
function extraAttributes(product: ProductResponse): { label: string; values: string[] }[] { })
const buckets: Record<string, { label: string; values: Set<string> }> = {}; .join(' | ');
}
(product.variants || []).forEach((variant) => {
(variant.attributes || []).forEach((attr) => { return variant.sku || `Variant ${fallbackIndex + 1}`;
const raw = attr.attribute_name || attr.attribute_code || ''; }
const value = String(attr.attribute_value || '').trim();
if (!raw || !value) return; function getVariantImage(product: ProductResponse, variant: ProductVariantResponse): string {
const key = raw.trim().toLowerCase().replace(/[\s-]+/g, '_'); const img = variant.images?.[0]?.image_url || product.images?.[0]?.image_url;
if (!buckets[key]) { return getImageUrl(img);
let label = raw.replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()); }
if (['qul', 'qual'].includes(key)) label = 'Quality';
else if (['clr'].includes(key)) label = 'Color'; export function QuickComparisonTable({ product }: QuickComparisonTableProps) {
else if (['str'].includes(key)) label = 'Storage'; const addToCart = useCartStore((state) => state.addToCart);
buckets[key] = { const [addedVariantId, setAddedVariantId] = useState<string | null>(null);
label,
values: new Set(), const variants = product?.variants || [];
}; // Strictly only show when the product has multiple variants (> 1)
} if (variants.length <= 1) {
buckets[key].values.add(value); return null;
}); }
});
const handleAdd = async (variant: ProductVariantResponse) => {
return Object.values(buckets) await addToCart(product, variant, 1);
.map((item) => ({ setAddedVariantId(variant.variant_id);
label: item.label, setTimeout(() => setAddedVariantId(null), 1800);
values: Array.from(item.values), };
}))
.slice(0, 3); const labelCls =
} 'sticky left-0 z-10 w-[160px] min-w-[160px] px-5 py-4 text-[13px] font-semibold text-gray-700 text-left align-middle bg-[#f3f4f6] border-b border-gray-200';
const cellCls = 'px-5 py-4 min-w-[200px] align-middle text-center border-b border-gray-200';
function ctaKind(product: ProductResponse): 'view' | 'cart' {
return (product.variants?.length || 0) > 1 ? 'view' : 'cart'; return (
} <section className="mb-12">
<div className="flex items-center gap-2 mb-4">
export function QuickComparisonTable({ products }: QuickComparisonTableProps) { <h3 className="text-[20px] font-bold text-gray-800 tracking-tight">Variant Comparison</h3>
const addToCart = useCartStore((state) => state.addToCart); <span className="text-[12px] font-medium text-gray-500 bg-gray-100 px-2.5 py-0.5 rounded-full">
const [addedId, setAddedId] = useState<string | null>(null); {variants.length} Options
</span>
if (!products.length) return null; </div>
const handleAdd = async (product: ProductResponse) => { <div className="overflow-x-auto rounded-lg border border-gray-200 shadow-sm bg-white">
const variant = product.variants?.[0]; <table className="w-full border-collapse min-w-[700px]">
if (!variant) return; {/* Variant Header Row */}
await addToCart(product, variant, 1); <thead>
setAddedId(product.product_id); <tr className="bg-white">
setTimeout(() => setAddedId(null), 1800); <th className={`${labelCls} bg-white text-gray-400 font-normal`}>Option</th>
}; {variants.map((v, idx) => {
const img = getVariantImage(product, v);
const labelCls = const title = getVariantTitle(v, idx);
'sticky left-0 z-10 w-[150px] min-w-[150px] px-4 py-4 text-[13px] font-medium text-gray-500 text-left align-middle bg-[#f3f4f6]'; return (
const cellCls = 'px-5 py-4 min-w-[170px] align-middle text-center'; <th key={v.variant_id} className={`${cellCls} font-normal bg-white`}>
<div className="w-[100px] h-[100px] mx-auto bg-gray-50 border border-gray-200 rounded-lg p-2 flex items-center justify-center mb-3">
return ( <BlurHashImage
<section className="mb-10"> src={img}
<h3 className="text-[20px] font-semibold text-gray-800 mb-4 tracking-tight">Quick Comparison</h3> alt={title}
<div className="overflow-x-auto rounded-md border border-gray-200"> width={90}
<table className="w-full border-collapse min-w-[860px]"> height={90}
<thead> className="max-h-full max-w-full object-contain"
<tr className="bg-white"> />
<th className={labelCls} /> </div>
{products.map((prod) => { <div className="text-[13px] font-semibold text-gray-800 leading-snug line-clamp-2 px-1 min-h-[36px]">
const img = productImage(prod); {title}
return ( </div>
<th key={prod.product_id} className={`${cellCls} font-normal bg-white`}> </th>
<Link );
href={`/products/${prod.slug}`} })}
className="block text-[13px] font-medium text-gray-700 leading-snug hover:text-primary line-clamp-2 min-h-[36px] mb-3" </tr>
> </thead>
{prod.name}
</Link> <tbody>
<Link {/* 1. Name / Specifications Row */}
href={`/products/${prod.slug}`} <tr className="bg-[#fcfcfd]">
className="w-[92px] h-[92px] mx-auto bg-white border border-gray-200 rounded-md p-2 flex items-center justify-center hover:border-primary/40 transition-colors" <td className={labelCls}>Name / Specification</td>
> {variants.map((v, idx) => (
<BlurHashImage <td key={v.variant_id} className={`${cellCls} text-[13px] font-medium text-gray-800`}>
src={img} {getVariantTitle(v, idx)}
alt={prod.name} </td>
width={84} ))}
height={84} </tr>
className="max-h-full max-w-full object-contain"
/> {/* 2. Price Row */}
</Link> <tr className="bg-white">
</th> <td className={labelCls}>Price</td>
); {variants.map((v) => {
})} const price = Number(v.price) || 0;
</tr> const comparePrice = v.compare_price ? Number(v.compare_price) : 0;
</thead> const hasDiscount = comparePrice > price;
<tbody> const discountPercent = hasDiscount
<tr className="bg-[#f8f8f8]"> ? Math.round(((comparePrice - price) / comparePrice) * 100)
<td className={labelCls}>Price</td> : 0;
{products.map((prod) => (
<td key={prod.product_id} className={`${cellCls} text-[14px] font-bold text-gray-900`}> return (
{priceLabel(prod)} <td key={v.variant_id} className={cellCls}>
</td> <div className="flex items-center justify-center gap-2 flex-wrap">
))} <span className="text-[16px] font-bold text-gray-900">
</tr> {formatCurrency(price)}
</span>
<tr className="bg-white"> {hasDiscount && (
<td className={labelCls}>Add to cart</td> <>
{products.map((prod) => { <span className="text-[13px] text-gray-400 line-through">
const kind = ctaKind(prod); {formatCurrency(comparePrice)}
const justAdded = addedId === prod.product_id; </span>
return ( <span className="text-[11px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 px-1.5 py-0.5 rounded">
<td key={prod.product_id} className={cellCls}> {discountPercent}% OFF
{kind === 'view' ? ( </span>
<Link </>
href={`/products/${prod.slug}`} )}
className="inline-flex items-center justify-center min-w-[120px] bg-primary hover:bg-primary-hover text-white text-[13px] font-semibold px-4 py-2.5 rounded-md transition-colors" </div>
> </td>
View Products );
</Link> })}
) : ( </tr>
<button
type="button" {/* 3. Warranty Type Row */}
onClick={() => void handleAdd(prod)} <tr className="bg-[#fcfcfd]">
className="inline-flex items-center justify-center gap-1.5 min-w-[120px] bg-primary hover:bg-primary-hover text-white text-[13px] font-semibold px-4 py-2.5 rounded-md transition-colors cursor-pointer" <td className={labelCls}>
> <div className="flex items-center gap-1.5">
{justAdded ? <Check size={14} /> : <ShoppingCart size={14} />} <ShieldCheck size={15} className="text-primary flex-shrink-0" />
{justAdded ? 'Added' : 'Add To Cart'} <span>Warranty Type</span>
</button> </div>
)} </td>
</td> {variants.map((v) => (
); <td key={v.variant_id} className={`${cellCls} text-[13px] text-gray-700 font-medium`}>
})} {product.warranty_type || 'Standard Warranty'}
</tr> </td>
))}
<tr className="bg-[#f8f8f8]"> </tr>
<td className={`${labelCls} align-top`}>Additional information</td>
{products.map((prod) => { {/* 4. Summary Row */}
const attrs = extraAttributes(prod); <tr className="bg-white">
return ( <td className={labelCls}>
<td key={prod.product_id} className={`${cellCls} align-top text-[12px] leading-relaxed`}> <div className="flex items-center gap-1.5">
{attrs.length === 0 ? ( <FileText size={15} className="text-primary flex-shrink-0" />
<span className="text-gray-300">—</span> <span>Summary</span>
) : ( </div>
<div className="space-y-1.5 text-left inline-block"> </td>
{attrs.map((attr) => ( {variants.map((v) => (
<div key={attr.label}> <td key={v.variant_id} className={`${cellCls} text-[13px] text-gray-600 leading-relaxed max-w-[280px]`}>
<span className="text-gray-700 font-medium">{attr.label}: </span> {product.warranty_summary || '100% Quality Tested & Brand Verified'}
{attr.values.map((value, i) => ( </td>
<span key={value}> ))}
<Link href={`/products/${prod.slug}`} className="text-primary hover:underline"> </tr>
{value}
</Link> {/* Action Row */}
{i < attr.values.length - 1 ? <span className="text-gray-400">, </span> : null} <tr className="bg-[#fcfcfd]">
</span> <td className={labelCls}>Action</td>
))} {variants.map((v) => {
</div> const justAdded = addedVariantId === v.variant_id;
))} const isOutOfStock = v.status === 'inactive' || (v.available_stock !== undefined && v.available_stock <= 0);
</div>
)} return (
</td> <td key={v.variant_id} className={cellCls}>
); <button
})} type="button"
</tr> disabled={isOutOfStock}
</tbody> onClick={() => void handleAdd(v)}
</table> className={`inline-flex items-center justify-center gap-2 min-w-[130px] text-[13px] font-semibold px-4 py-2.5 rounded-md transition-all cursor-pointer shadow-sm ${
</div> isOutOfStock
</section> ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
); : justAdded
} ? 'bg-emerald-600 text-white'
: 'bg-primary hover:bg-primary-hover text-white hover:shadow'
}`}
>
{isOutOfStock ? (
'Out of Stock'
) : justAdded ? (
<>
<Check size={14} className="stroke-[2.5]" />
<span>Added</span>
</>
) : (
<>
<ShoppingCart size={14} />
<span>Add To Cart</span>
</>
)}
</button>
</td>
);
})}
</tr>
</tbody>
</table>
</div>
</section>
);
}

View file

@ -117,6 +117,8 @@ export interface ProductResponse {
created_at: string; created_at: string;
images: ProductImageResponse[]; images: ProductImageResponse[];
variants: ProductVariantResponse[]; variants: ProductVariantResponse[];
warranty_type?: string | null;
warranty_summary?: string | null;
rating?: number; rating?: number;
review_count?: number; review_count?: number;
badge?: 'HOT' | 'NEW' | 'SALE' | null; badge?: 'HOT' | 'NEW' | 'SALE' | null;

View file

@ -496,6 +496,21 @@ export const serviceBookingService = {
}); });
}, },
fetchCalendarInvite(jobId: string): Promise<{
job_id: string;
job_no: string;
appointment_id: string;
scheduled_start: string;
scheduled_end: string;
device_name: string;
google_calendar_url: string;
store_name: string;
store_address: string;
ics_download_url: string;
}> {
return apiFetch(`/api/v1/service/jobs/${jobId}/calendar-invite`);
},
fetchServicePageLayout(): Promise<any[]> { fetchServicePageLayout(): Promise<any[]> {
return apiFetch<any[]>('/api/v1/storefront/layout/services'); return apiFetch<any[]>('/api/v1/storefront/layout/services');
}, },