fix(reviews): sync PDP hero average rating and reviews count with real product reviews

This commit is contained in:
iFixKart Dev 2026-11-17 18:36:37 +05:30
parent 15681f87bd
commit 6b4a1c56ec
3 changed files with 76 additions and 8 deletions

View file

@ -331,6 +331,13 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
} }
const { product, reviews = [], related_products = [], specifications = [] } = data; const { product, reviews = [], related_products = [], specifications = [] } = data;
const validRatings = (reviews || [])
.map((r: any) => Number(r.rating))
.filter((r: number) => !isNaN(r) && r > 0);
const calculatedRating = validRatings.length > 0
? Number((validRatings.reduce((sum: number, r: number) => sum + r, 0) / validRatings.length).toFixed(1))
: (product.rating ? Number(product.rating) : 5.0);
const totalReviewsCount = reviews.length;
const related = related_products.slice(0, 5); const related = related_products.slice(0, 5);
const specGroups = groupSpecs(specifications, product); const specGroups = groupSpecs(specifications, product);
@ -513,10 +520,10 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
name: 'iFixKart TechShop', name: 'iFixKart TechShop',
}, },
}, },
aggregateRating: reviews.length > 0 ? { aggregateRating: totalReviewsCount > 0 ? {
'@type': 'AggregateRating', '@type': 'AggregateRating',
ratingValue: '4.8', ratingValue: String(calculatedRating),
reviewCount: String(reviews.length), reviewCount: String(totalReviewsCount),
} : undefined, } : undefined,
}; };
@ -535,7 +542,8 @@ export default async function ProductDetailPage({ params, searchParams }: Produc
<div className="container mx-auto px-4 sm:px-6 lg:px-8 py-5"> <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-5">
<ProductInteractiveGrid <ProductInteractiveGrid
product={product} product={product}
initialReviewsCount={reviews.length} rating={calculatedRating}
initialReviewsCount={totalReviewsCount}
relatedProducts={related} relatedProducts={related}
initialVariantSku={activeVariant?.sku} initialVariantSku={activeVariant?.sku}
/> />

View file

@ -35,6 +35,7 @@ interface ProductInteractiveGridProps {
initialReviewsCount: number; initialReviewsCount: number;
relatedProducts?: ProductResponse[]; relatedProducts?: ProductResponse[];
initialVariantSku?: string; initialVariantSku?: string;
rating?: number;
} }
const FALLBACK_TECH_IMAGES: string[] = ['/images/placeholder-product.webp']; const FALLBACK_TECH_IMAGES: string[] = ['/images/placeholder-product.webp'];
@ -87,10 +88,46 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
initialReviewsCount, initialReviewsCount,
relatedProducts = [], relatedProducts = [],
initialVariantSku, initialVariantSku,
rating: propRating,
}) => { }) => {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const router = useRouter(); const router = useRouter();
const [currentRating, setCurrentRating] = useState<number>(() => {
if (typeof propRating === 'number' && !isNaN(propRating)) return propRating;
if (product.rating !== undefined && product.rating !== null) return Number(product.rating);
return 5.0;
});
const [currentReviewsCount, setCurrentReviewsCount] = useState<number>(initialReviewsCount || 0);
useEffect(() => {
if (typeof propRating === 'number' && !isNaN(propRating)) {
setCurrentRating(propRating);
} else if (product.rating !== undefined && product.rating !== null) {
setCurrentRating(Number(product.rating));
}
}, [propRating, product.rating]);
useEffect(() => {
setCurrentReviewsCount(initialReviewsCount || 0);
}, [initialReviewsCount]);
useEffect(() => {
const handleUpdate = (e: Event) => {
const customEvent = e as CustomEvent;
if (customEvent.detail && customEvent.detail.productId === product.product_id) {
if (typeof customEvent.detail.averageRating === 'number') {
setCurrentRating(customEvent.detail.averageRating);
}
if (typeof customEvent.detail.totalReviews === 'number') {
setCurrentReviewsCount(customEvent.detail.totalReviews);
}
}
};
window.addEventListener('ifixkart:reviews-summary-updated', handleUpdate);
return () => window.removeEventListener('ifixkart:reviews-summary-updated', handleUpdate);
}, [product.product_id]);
const getInitialIndex = () => { const getInitialIndex = () => {
const key = initialVariantSku || searchParams?.get('variant') || searchParams?.get('sku'); const key = initialVariantSku || searchParams?.get('variant') || searchParams?.get('sku');
if (key && product?.variants?.length) { if (key && product?.variants?.length) {
@ -553,12 +590,12 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
<Star <Star
key={i} key={i}
size={15} size={15}
className={i < Math.round(product.rating || 5) ? 'fill-amber-400 text-amber-400' : 'text-gray-300'} className={i < Math.round(currentRating) ? 'fill-amber-400 text-amber-400' : 'text-gray-300'}
/> />
))} ))}
</div> </div>
<span className="text-[13px] font-bold text-gray-800"> <span className="text-[13px] font-bold text-gray-800">
{Number(product.rating || 5.0).toFixed(1)} {Number(currentRating).toFixed(1)}
</span> </span>
<span className="text-gray-300 text-xs">•</span> <span className="text-gray-300 text-xs">•</span>
<button <button
@ -573,7 +610,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
}} }}
className="text-[13px] font-semibold text-primary hover:underline cursor-pointer flex items-center gap-1" className="text-[13px] font-semibold text-primary hover:underline cursor-pointer flex items-center gap-1"
> >
<span>{initialReviewsCount > 0 ? `${initialReviewsCount} Customer Review${initialReviewsCount > 1 ? 's' : ''}` : 'Customer Reviews (Write a review)'}</span> <span>{currentReviewsCount > 0 ? `${currentReviewsCount} Customer Review${currentReviewsCount > 1 ? 's' : ''}` : 'Customer Reviews (Write a review)'}</span>
</button> </button>
</div> </div>

View file

@ -32,6 +32,17 @@ export function ProductReviewsSection({
.then((res) => { .then((res) => {
setData(res); setData(res);
if (onReviewsCountChange) onReviewsCountChange(res.total_reviews); if (onReviewsCountChange) onReviewsCountChange(res.total_reviews);
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent('ifixkart:reviews-summary-updated', {
detail: {
productId,
averageRating: res.average_rating,
totalReviews: res.total_reviews,
},
})
);
}
}) })
.finally(() => { .finally(() => {
setIsLoading(false); setIsLoading(false);
@ -67,11 +78,23 @@ export function ProductReviewsSection({
const starKey = String(newReview.rating); const starKey = String(newReview.rating);
const newDist = { ...(prev?.star_distribution || {}) }; const newDist = { ...(prev?.star_distribution || {}) };
newDist[starKey] = (newDist[starKey] || 0) + 1; newDist[starKey] = (newDist[starKey] || 0) + 1;
const calculatedAvg = prev ? ((prev.average_rating * prev.total_reviews) + newReview.rating) / newTotal : newReview.rating;
if (onReviewsCountChange) onReviewsCountChange(newTotal); if (onReviewsCountChange) onReviewsCountChange(newTotal);
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent('ifixkart:reviews-summary-updated', {
detail: {
productId,
averageRating: Number(calculatedAvg.toFixed(1)),
totalReviews: newTotal,
},
})
);
}
return { return {
average_rating: prev ? ((prev.average_rating * prev.total_reviews) + newReview.rating) / newTotal : newReview.rating, average_rating: calculatedAvg,
total_reviews: newTotal, total_reviews: newTotal,
star_distribution: newDist, star_distribution: newDist,
verified_count: (prev?.verified_count || 0) + (newReview.verified_buyer ? 1 : 0), verified_count: (prev?.verified_count || 0) + (newReview.verified_buyer ? 1 : 0),