955 lines
41 KiB
TypeScript
955 lines
41 KiB
TypeScript
import React, { useState, useEffect, useMemo } from 'react'
|
|
import { useNavigate } from '@tanstack/react-router'
|
|
import dayjs from 'dayjs'
|
|
import { useQueryClient } from '@tanstack/react-query'
|
|
import { Quantifier, BottomDialog, Dropdown } from 'web-components'
|
|
import { Truck, Trash2, Ticket, ChevronRight, Clock, X, Info, ShoppingBag } from 'lucide-react'
|
|
import { trpc } from '../lib/trpc-client'
|
|
import { useAuth } from '../lib/auth-context'
|
|
import { useRegion, useRegionParams } from '../contexts/RegionContext'
|
|
import { useAddressStore } from '../lib/stores/address-store'
|
|
import { AddressForm } from './AddressForm'
|
|
import { useCentralProductStore } from '../lib/stores/central-product-store'
|
|
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
|
|
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
|
|
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
|
|
|
|
const formatDeliverySlot = (deliveryTime: string): string => {
|
|
const time = dayjs(deliveryTime)
|
|
const endTime = time.add(1, 'hour')
|
|
const startPeriod = time.format('A')
|
|
const endPeriod = endTime.format('A')
|
|
|
|
const range =
|
|
startPeriod === endPeriod
|
|
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
|
|
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
|
|
|
|
return `${time.format('ddd, DD MMM ')}${range}`
|
|
}
|
|
|
|
interface DeliverySlotGroupItem {
|
|
id: number
|
|
name: string
|
|
quantity: number
|
|
unitNotation?: string
|
|
image?: string
|
|
}
|
|
|
|
interface DeliverySlotGroup {
|
|
slotId: number
|
|
label: string
|
|
items: DeliverySlotGroupItem[]
|
|
}
|
|
|
|
interface DeliverySlotMergeSuggestion {
|
|
slotId: number
|
|
label: string
|
|
}
|
|
|
|
function DeliverySlotSummary({
|
|
groups,
|
|
mergeSuggestion,
|
|
onMerge,
|
|
}: {
|
|
groups: DeliverySlotGroup[]
|
|
mergeSuggestion?: DeliverySlotMergeSuggestion | null
|
|
onMerge?: () => void
|
|
}) {
|
|
const [openGroup, setOpenGroup] = useState<DeliverySlotGroup | null>(null)
|
|
|
|
if (groups.length === 0) return null
|
|
|
|
return (
|
|
<div data-testid="delivery-slot-summary" className="mb-4 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
|
|
<div className="border-b border-gray-100 bg-gray-50 px-4 py-3">
|
|
<p className="text-base font-bold text-gray-900">Delivery Slot</p>
|
|
</div>
|
|
|
|
<div className="p-4">
|
|
{groups.map((group, index) => (
|
|
<div
|
|
key={group.slotId}
|
|
className={`flex items-center justify-between py-2.5 ${index > 0 ? 'border-t border-gray-100' : ''}`}
|
|
>
|
|
<div className="mr-3 flex flex-1 items-center">
|
|
<Clock className="mr-2 h-4 w-4 text-gray-500" />
|
|
<p className="flex-1 text-sm text-gray-700">{group.label}</p>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
data-testid={`delivery-slot-items-${group.slotId}`}
|
|
onClick={() => setOpenGroup(group)}
|
|
className="flex items-center"
|
|
>
|
|
<span className="text-sm font-medium text-brand-600">
|
|
{group.items.length} {group.items.length === 1 ? 'item' : 'items'}
|
|
</span>
|
|
<ChevronRight className="h-4 w-4 text-brand-600" />
|
|
</button>
|
|
</div>
|
|
))}
|
|
|
|
{!!mergeSuggestion && (
|
|
<div
|
|
data-testid="delivery-slot-merge"
|
|
className="mt-3 flex items-center justify-between rounded-xl border border-brand-200 bg-brand-50 px-3 py-2.5"
|
|
>
|
|
<div className="mr-2 flex flex-1 items-center">
|
|
<p className="ml-2 flex-1 text-sm font-medium text-brand-700">
|
|
Deliver All items at {mergeSuggestion.label}
|
|
</p>
|
|
</div>
|
|
<button type="button" data-testid="delivery-slot-merge-apply" onClick={onMerge} className="p-1">
|
|
<ChevronRight className="h-5 w-5 text-brand-600" />
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<BottomDialog open={!!openGroup} onClose={() => setOpenGroup(null)}>
|
|
<div className="p-6">
|
|
<div className="mb-4 flex items-start justify-between">
|
|
<div className="mr-3 flex-1">
|
|
<p className="text-lg font-bold text-gray-900">Items</p>
|
|
<p className="mt-0.5 text-xs text-gray-500">{openGroup?.label}</p>
|
|
</div>
|
|
<button type="button" onClick={() => setOpenGroup(null)} className="p-1" aria-label="Close">
|
|
<X className="h-5 w-5 text-gray-400" />
|
|
</button>
|
|
</div>
|
|
|
|
{openGroup?.items.map((item) => (
|
|
<div key={item.id} className="flex items-center border-b border-gray-50 py-3">
|
|
{item.image ? (
|
|
<img src={item.image} alt="" className="mr-3 h-10 w-10 rounded-lg bg-gray-100 object-cover" />
|
|
) : (
|
|
<div className="mr-3 h-10 w-10 rounded-lg bg-gray-100" />
|
|
)}
|
|
<div className="flex-1">
|
|
<p className="truncate text-sm text-gray-900">{item.name}</p>
|
|
{!!item.unitNotation && <p className="mt-0.5 text-xs text-gray-500">{item.unitNotation}</p>}
|
|
</div>
|
|
<p className="text-sm font-bold text-gray-900">x{item.quantity}</p>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</BottomDialog>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export function CartPage({ isFlashDelivery = false }: { isFlashDelivery?: boolean }) {
|
|
const navigate = useNavigate()
|
|
const queryClient = useQueryClient()
|
|
const { isAuthenticated } = useAuth()
|
|
const regionParams = useRegionParams()
|
|
const { regionId: currentRegionId } = useRegion()
|
|
const { selectedAddressId, setSelectedAddressId } = useAddressStore()
|
|
const utils = trpc.useUtils()
|
|
const cartType: 'regular' | 'flash' = isFlashDelivery ? 'flash' : 'regular'
|
|
|
|
const [quantities, setQuantities] = useState<Record<number, number>>({})
|
|
const { data: cartData, isLoading, error } = useGetCart(cartType)
|
|
|
|
const productIds = cartData?.items.map((item) => item.skuId) || []
|
|
|
|
const { data: slotsData, isLoading: isSlotsLoading } = trpc.user.cart.getCartSlots.useQuery(
|
|
{ productIds, ...regionParams },
|
|
{ enabled: productIds.length > 0, refetchOnWindowFocus: false }
|
|
)
|
|
|
|
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(undefined, {
|
|
enabled: isAuthenticated,
|
|
})
|
|
const { data: constsData } = useGetEssentialConsts()
|
|
const products = useCentralProductStore((state) => state.products)
|
|
const productsById = useCentralProductStore((state) => state.productsById)
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
|
|
|
|
const cartItems = cartData?.items || []
|
|
|
|
const flashEligibleProductIds = useMemo(() => {
|
|
if (!products.length) return new Set<number>()
|
|
return new Set(products.filter((product) => productSlotsMap[product.id]?.isFlashAvailable).map((product) => product.id))
|
|
}, [products, productSlotsMap])
|
|
|
|
const baseTotalPrice = useMemo(
|
|
() =>
|
|
cartItems
|
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
.reduce((sum, item) => {
|
|
const product = productsById[item.skuId]
|
|
const price = product?.price || 0
|
|
return sum + price * (quantities[item.id] || item.quantity)
|
|
}, 0),
|
|
[cartItems, quantities, productsById, productSlotsMap]
|
|
)
|
|
|
|
const generateCouponDescription = (coupon: any): string => {
|
|
let desc = ''
|
|
if (coupon.discountPercent) desc += `${coupon.discountPercent}% off`
|
|
else if (coupon.flatDiscount) desc += `₹${coupon.flatDiscount} off`
|
|
if (coupon.minOrder) desc += ` on orders above ₹${coupon.minOrder}`
|
|
if (coupon.maxValue) desc += ` (max discount ₹${coupon.maxValue})`
|
|
return desc
|
|
}
|
|
|
|
const eligibleCoupons = useMemo(() => {
|
|
if (!(couponsRaw as any)?.data) return []
|
|
return ((couponsRaw as any).data as any[])
|
|
.map((coupon) => {
|
|
let isEligible = true
|
|
let ineligibilityReason = ''
|
|
if (coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser) {
|
|
isEligible = false
|
|
ineligibilityReason = 'Usage limit exceeded'
|
|
}
|
|
if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) {
|
|
isEligible = false
|
|
ineligibilityReason = `Min order ₹${coupon.minOrder}`
|
|
}
|
|
return {
|
|
id: coupon.id,
|
|
code: coupon.couponCode,
|
|
discountType: coupon.discountPercent ? 'percentage' : 'flat',
|
|
discountValue: parseFloat(coupon.discountPercent || coupon.flatDiscount || '0'),
|
|
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
|
|
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
|
description: generateCouponDescription(coupon),
|
|
exclusiveApply: coupon.exclusiveApply,
|
|
isEligible,
|
|
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
|
}
|
|
})
|
|
.filter((coupon) => coupon.ineligibilityReason !== 'Usage limit exceeded')
|
|
}, [couponsRaw, baseTotalPrice])
|
|
|
|
const updateCartItem = useUpdateCartItem(cartType)
|
|
const removeFromCart = useRemoveFromCart(cartType)
|
|
|
|
const [selectedSlots, setSelectedSlots] = useState<Record<number, number>>({})
|
|
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null)
|
|
const [couponDialogOpen, setCouponDialogOpen] = useState(false)
|
|
const [showAddAddress, setShowAddAddress] = useState(false)
|
|
const [regionPickOpen, setRegionPickOpen] = useState(false)
|
|
const [pendingRegionId, setPendingRegionId] = useState<number | null>(null)
|
|
const [pendingAddresses, setPendingAddresses] = useState<any[]>([])
|
|
|
|
const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(undefined, {
|
|
enabled: isAuthenticated,
|
|
})
|
|
const addresses = (addressesData as any)?.data ?? []
|
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
|
const pendingRegionName = (regionsData as any)?.regions?.find((r: any) => r.id === pendingRegionId)?.name ?? ''
|
|
const selectedAddress = addresses.find((a: any) => a.id === selectedAddressId)
|
|
|
|
const handleAddressAdded = async (addressId?: number) => {
|
|
setShowAddAddress(false)
|
|
if (!addressId) return
|
|
const fresh = await utils.user.address.getUserAddresses.fetch().catch(() => null)
|
|
const created = (fresh as any)?.data?.find((a: any) => a.id === addressId)
|
|
const createdRegionId = created?.regionId ?? null
|
|
if (createdRegionId == null || currentRegionId == null || createdRegionId === currentRegionId) {
|
|
setSelectedAddressId(addressId)
|
|
return
|
|
}
|
|
const inRegion = ((fresh as any)?.data ?? []).filter((a: any) => a.regionId === createdRegionId)
|
|
setPendingAddresses(inRegion)
|
|
setPendingRegionId(createdRegionId)
|
|
setRegionPickOpen(true)
|
|
}
|
|
|
|
const getAvailableSlotsForProduct = useMemo(() => {
|
|
return (productId: number) => {
|
|
if (!slotsData || !(slotsData as any)[productId]) return []
|
|
return ((slotsData as any)[productId] as any[])
|
|
.filter((slot) => dayjs(slot.deliveryTime).isAfter(dayjs()) && dayjs(slot.freezeTime).isAfter(dayjs()))
|
|
.map((slot) => {
|
|
const time = dayjs(slot.deliveryTime)
|
|
const endTime = time.add(1, 'hour')
|
|
const startPeriod = time.format('A')
|
|
const endPeriod = endTime.format('A')
|
|
const timeRange =
|
|
startPeriod === endPeriod
|
|
? `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
|
|
: `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
|
|
return {
|
|
label: `Delivery: ${time.format('ddd, DD MMM ')}${timeRange} - Close time: ${dayjs(slot.freezeTime).format('h:mm a')}`,
|
|
value: slot.id,
|
|
}
|
|
})
|
|
}
|
|
}, [slotsData])
|
|
|
|
const selectedCoupons = useMemo(
|
|
() =>
|
|
selectedCouponId ? eligibleCoupons?.filter((coupon) => coupon.id === selectedCouponId && coupon.isEligible) : [],
|
|
[eligibleCoupons, selectedCouponId]
|
|
)
|
|
|
|
const totalPrice = cartItems
|
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
.reduce((sum, item) => {
|
|
const product = productsById[item.skuId]
|
|
const quantity = quantities[item.id] || item.quantity
|
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : product?.price || 0
|
|
return sum + Number(price) * quantity
|
|
}, 0)
|
|
|
|
const totalSavings = cartItems
|
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
.reduce((sum, item) => {
|
|
const product = productsById[item.skuId]
|
|
const quantity = quantities[item.id] || item.quantity
|
|
const marketPrice = Number(product?.marketPrice || 0)
|
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : product?.price || 0
|
|
const saving = marketPrice - Number(price)
|
|
return sum + (saving > 0 ? saving : 0) * quantity
|
|
}, 0)
|
|
|
|
const dropdownData = useMemo(
|
|
() =>
|
|
eligibleCoupons?.map((coupon) => {
|
|
const discount =
|
|
coupon.discountType === 'percentage'
|
|
? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity)
|
|
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice)
|
|
const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : ''
|
|
const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : ''}`
|
|
const label = coupon.isEligible ? baseLabel : `${baseLabel} (${coupon.ineligibilityReason})`
|
|
return { label, value: coupon.id, disabled: !coupon.isEligible }
|
|
}) || [],
|
|
[eligibleCoupons, totalPrice]
|
|
)
|
|
|
|
const discountAmount = useMemo(
|
|
() =>
|
|
selectedCoupons?.reduce(
|
|
(sum, coupon) =>
|
|
sum +
|
|
(coupon.discountType === 'percentage'
|
|
? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity)
|
|
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice)),
|
|
0
|
|
) || 0,
|
|
[selectedCoupons, totalPrice]
|
|
)
|
|
|
|
const finalTotal = totalPrice - discountAmount
|
|
|
|
const deliveryCharge = useMemo(() => {
|
|
const threshold = isFlashDelivery ? (constsData as any)?.flashFreeDeliveryThreshold : (constsData as any)?.freeDeliveryThreshold
|
|
const charge = isFlashDelivery ? (constsData as any)?.flashDeliveryCharge : (constsData as any)?.deliveryCharge
|
|
return finalTotal < threshold ? charge : 0
|
|
}, [finalTotal, constsData, isFlashDelivery])
|
|
|
|
const freeDeliveryThreshold = useMemo(() => {
|
|
return isFlashDelivery ? (constsData as any)?.flashFreeDeliveryThreshold : (constsData as any)?.freeDeliveryThreshold
|
|
}, [constsData, isFlashDelivery])
|
|
|
|
const finalTotalWithDelivery = finalTotal + deliveryCharge
|
|
const hasAvailableItems = cartItems.some((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
|
|
const slotGroups = useMemo<DeliverySlotGroup[]>(() => {
|
|
if (isFlashDelivery || cartItems.length === 0) return []
|
|
const groupMap = new Map<number, DeliverySlotGroup>()
|
|
cartItems.forEach((item) => {
|
|
const slotId = selectedSlots[item.id]
|
|
if (slotId === undefined || slotId === null) return
|
|
if (!groupMap.has(slotId)) {
|
|
let label = ''
|
|
if (slotsData) {
|
|
for (const productId of Object.keys(slotsData as any)) {
|
|
const slot = ((slotsData as any)[Number(productId)] as any[])?.find((s) => s.id === slotId)
|
|
if (slot) {
|
|
label = formatDeliverySlot(slot.deliveryTime)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
groupMap.set(slotId, { slotId, label, items: [] })
|
|
}
|
|
const product = productsById[item.skuId]
|
|
groupMap.get(slotId)!.items.push({
|
|
id: item.id,
|
|
name: product?.name || 'Item',
|
|
quantity: quantities[item.id] || item.quantity,
|
|
unitNotation: product?.unitNotation,
|
|
image: product?.images?.[0],
|
|
})
|
|
})
|
|
return Array.from(groupMap.values()).sort((a, b) => a.slotId - b.slotId)
|
|
}, [isFlashDelivery, cartItems, selectedSlots, slotsData, productsById, quantities])
|
|
|
|
const mergeSuggestion = useMemo<DeliverySlotMergeSuggestion | null>(() => {
|
|
if (isFlashDelivery || slotGroups.length <= 1) return null
|
|
const majority = slotGroups.reduce((best, group) => (group.items.length > best.items.length ? group : best))
|
|
const inStockItems = cartItems.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
const now = dayjs()
|
|
const feasible =
|
|
inStockItems.length > 0 &&
|
|
inStockItems.every((item) =>
|
|
(((slotsData as any)?.[item.skuId] || []) as any[]).some(
|
|
(slot) => slot.id === majority.slotId && dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now)
|
|
)
|
|
)
|
|
if (!feasible) return null
|
|
return { slotId: majority.slotId, label: majority.label }
|
|
}, [isFlashDelivery, slotGroups, cartItems, productSlotsMap, slotsData])
|
|
|
|
const handleMergeSlots = () => {
|
|
if (!mergeSuggestion) return
|
|
setSelectedSlots((prev) => {
|
|
const next = { ...prev }
|
|
cartItems.forEach((item) => {
|
|
if (!productSlotsMap[item.skuId]?.isOutOfStock) {
|
|
next[item.id] = mergeSuggestion.slotId
|
|
}
|
|
})
|
|
return next
|
|
})
|
|
}
|
|
|
|
useEffect(() => {
|
|
const initial: Record<number, number> = {}
|
|
cartItems.forEach((item) => {
|
|
initial[item.id] = item.quantity
|
|
})
|
|
setQuantities(initial)
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [cartData])
|
|
|
|
// Auto-select delivery slots for each cart item
|
|
useEffect(() => {
|
|
if (cartItems.length === 0) return
|
|
const cartSlotIds = (cartData?.items || []).reduce((acc, item) => {
|
|
acc[item.id] = item.slotId
|
|
return acc
|
|
}, {} as Record<number, number | null | undefined>)
|
|
const next: Record<number, number> = {}
|
|
cartItems.forEach((item) => {
|
|
const existingSlotId = cartSlotIds ? cartSlotIds[item.id] : undefined
|
|
if (isFlashDelivery) {
|
|
next[item.id] = 0
|
|
return
|
|
}
|
|
const productSlots = (slotsData as any)?.[item.skuId]
|
|
if (!productSlots || productSlots.length === 0) return
|
|
const now = dayjs()
|
|
const upcomingSlots = (productSlots as any[])
|
|
.filter((slot) => dayjs(slot.deliveryTime).isAfter(now) && dayjs(slot.freezeTime).isAfter(now))
|
|
.sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)))
|
|
if (upcomingSlots.length === 0) return
|
|
if (existingSlotId) {
|
|
next[item.id] = upcomingSlots.some((slot) => slot.id === existingSlotId) ? existingSlotId : upcomingSlots[0].id
|
|
} else {
|
|
next[item.id] = upcomingSlots[0].id
|
|
}
|
|
})
|
|
setSelectedSlots(next)
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [slotsData, cartData, isFlashDelivery])
|
|
|
|
const handleRemove = (item: any, productName?: string) => {
|
|
if (!window.confirm(`Remove ${productName ?? 'this item'} from cart?`)) return
|
|
removeFromCart.mutate(item.skuId)
|
|
}
|
|
|
|
const handleCheckout = () => {
|
|
const availableItems = cartItems
|
|
.filter((item) => {
|
|
if (productSlotsMap[item.skuId]?.isOutOfStock) return false
|
|
if (isFlashDelivery) return flashEligibleProductIds.has(item.skuId)
|
|
return selectedSlots[item.id]
|
|
})
|
|
.map((item) => item.id)
|
|
|
|
if (availableItems.length === 0) {
|
|
const outOfStockItems = cartItems.filter((item) => productSlotsMap[item.skuId]?.isOutOfStock)
|
|
let errorMessage = 'Please check your cart items and try again.'
|
|
if (outOfStockItems.length === cartItems.length) {
|
|
errorMessage = 'All items in your cart are currently out of stock. Please remove them and add available items.'
|
|
} else if (isFlashDelivery) {
|
|
errorMessage =
|
|
'None of the items in your cart are available for flash delivery. Please remove ineligible items or switch to regular delivery.'
|
|
} else {
|
|
const itemsWithoutSlots = cartItems.filter(
|
|
(item) => !selectedSlots[item.id] && !productSlotsMap[item.skuId]?.isOutOfStock
|
|
)
|
|
if (itemsWithoutSlots.length > 0) {
|
|
errorMessage = `${itemsWithoutSlots.length} item(s) don't have a delivery slot. Please remove them or select a slot for each item.`
|
|
}
|
|
}
|
|
window.alert(errorMessage)
|
|
return
|
|
}
|
|
|
|
if (!isFlashDelivery && availableItems.length < cartItems.length) {
|
|
const itemsWithoutSlots = cartItems.filter(
|
|
(item) => !selectedSlots[item.id] && !productSlotsMap[item.skuId]?.isOutOfStock
|
|
)
|
|
if (itemsWithoutSlots.length > 0) {
|
|
window.alert(`${itemsWithoutSlots.length} item(s) don't have a delivery slot. Please select a slot or remove the item.`)
|
|
return
|
|
}
|
|
}
|
|
|
|
const itemsBySlot: Record<number, number[]> = {}
|
|
availableItems.forEach((itemId) => {
|
|
const slotId = isFlashDelivery ? 0 : selectedSlots[itemId]
|
|
if (!itemsBySlot[slotId]) itemsBySlot[slotId] = []
|
|
itemsBySlot[slotId].push(itemId)
|
|
})
|
|
|
|
const slotParams = Object.entries(itemsBySlot)
|
|
.map(([slotId, itemIds]) => `${slotId}:${itemIds.join(',')}`)
|
|
.join(';')
|
|
|
|
navigate({
|
|
to: isFlashDelivery ? '/flash/checkout' : '/home/checkout',
|
|
search: {
|
|
slots: slotParams,
|
|
...(selectedCouponId ? { coupons: String(selectedCouponId) } : {}),
|
|
deliveryPrice: String(deliveryCharge),
|
|
},
|
|
} as any)
|
|
}
|
|
|
|
if (isLoading || (isSlotsLoading && !isFlashDelivery)) {
|
|
return (
|
|
<div className="flex flex-1 items-center justify-center bg-gray-50">
|
|
<p className="font-medium text-gray-500">Loading cart...</p>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
if (error) {
|
|
return (
|
|
<div className="flex flex-1 flex-col items-center justify-center bg-gray-50">
|
|
<p className="mt-4 text-lg font-bold text-gray-900">Oops!</p>
|
|
<p className="mt-2 text-gray-500">Failed to load your cart</p>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="flex-1 bg-gray-50">
|
|
<div className="border-b border-gray-100 bg-white px-4 py-3">
|
|
<div className="flex items-center">
|
|
<button type="button" onClick={() => window.history.back()} className="-ml-2 mr-1 p-2" aria-label="Back">
|
|
<ChevronRight className="h-7 w-7 rotate-180 text-gray-700" />
|
|
</button>
|
|
{isFlashDelivery ? (
|
|
<Clock className="h-6 w-6 text-pink-600" />
|
|
) : (
|
|
<Truck className="h-6 w-6 text-gray-700" />
|
|
)}
|
|
<p className={`ml-2 text-lg font-bold ${isFlashDelivery ? 'text-pink-600' : 'text-gray-700'}`}>
|
|
{isFlashDelivery ? '1 Hr Delivery Cart' : 'Scheduled Delivery Cart'}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mx-auto w-full max-w-3xl px-4 pb-32">
|
|
{cartItems.length === 0 ? (
|
|
<div className="flex flex-col items-center justify-center py-12">
|
|
<div className="mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-gray-100">
|
|
<Truck className="h-8 w-8 text-gray-400" />
|
|
</div>
|
|
<p className="text-lg font-bold text-gray-900">Your cart is empty</p>
|
|
<p className="mt-2 px-8 text-center text-gray-500">Looks like you haven't added anything to your cart yet.</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => navigate({ to: '/home' })}
|
|
className="mt-6 rounded-xl bg-brand-500 px-6 py-3 font-bold text-white"
|
|
>
|
|
Start Shopping
|
|
</button>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div className="mb-4 rounded-2xl border border-gray-100 bg-white shadow-sm">
|
|
{cartItems.map((item, index) => {
|
|
const productSlots = getAvailableSlotsForProduct(item.skuId)
|
|
const selectedSlotForItem = selectedSlots[item.id]
|
|
const isFlashEligible = isFlashDelivery ? flashEligibleProductIds.has(item.skuId) : true
|
|
const product = productsById[item.skuId]
|
|
const productSlotInfo = productSlotsMap[item.skuId]
|
|
let isAvailable = true
|
|
if (productSlotInfo?.isOutOfStock) isAvailable = false
|
|
else if (isFlashDelivery) {
|
|
if (!isFlashEligible) isAvailable = false
|
|
} else if (productSlots.length === 0) {
|
|
isAvailable = false
|
|
}
|
|
const quantity = quantities[item.id] || item.quantity
|
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : product?.price || 0
|
|
const itemPrice = Number(price) * quantity
|
|
|
|
return (
|
|
<div key={item.id}>
|
|
<div className="p-4">
|
|
<div className="mb-2 flex items-center">
|
|
<img
|
|
src={product?.images?.[0]}
|
|
alt={product?.name ?? ''}
|
|
onClick={() =>
|
|
navigate({
|
|
to: isFlashDelivery ? '/flash/product/$id' : '/home/product/$id',
|
|
params: { id: String(item.skuId) },
|
|
})
|
|
}
|
|
className="mr-3 h-8 w-8 cursor-pointer rounded-lg bg-gray-100 object-cover"
|
|
/>
|
|
<p
|
|
onClick={() =>
|
|
navigate({
|
|
to: isFlashDelivery ? '/flash/product/$id' : '/home/product/$id',
|
|
params: { id: String(item.skuId) },
|
|
})
|
|
}
|
|
className="mr-3 flex-1 cursor-pointer text-sm text-gray-900 line-clamp-2"
|
|
>
|
|
{product?.name}
|
|
</p>
|
|
<p className="mr-2 text-xs text-gray-500">
|
|
{product?.productType !== 'combo' ? product?.unitNotation || '' : ''}
|
|
</p>
|
|
<div className="w-[120px]">
|
|
<Quantifier
|
|
testID={`cart-item-${item.id}`}
|
|
value={quantities[item.id] || item.quantity}
|
|
setValue={(value) => {
|
|
if (value === 0) {
|
|
if (!window.confirm('Remove this item from your cart?')) {
|
|
setQuantities((prev) => ({ ...prev, [item.id]: 1 }))
|
|
return
|
|
}
|
|
removeFromCart.mutate(item.skuId)
|
|
} else {
|
|
setQuantities((prev) => ({ ...prev, [item.id]: value }))
|
|
updateCartItem.mutate({ skuId: item.skuId, quantity: value })
|
|
}
|
|
}}
|
|
step={product?.incrementStep}
|
|
unit={product?.unitNotation}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{!isFlashDelivery && (
|
|
<div className="mt-2 flex items-center justify-between">
|
|
<div className="mr-4 flex-1">
|
|
<Dropdown
|
|
label="Select Delivery Slot"
|
|
testID={`cart-slot-picker-${item.id}`}
|
|
options={productSlots}
|
|
value={selectedSlotForItem || ''}
|
|
onValueChange={(value) =>
|
|
setSelectedSlots((prev) => ({ ...prev, [item.id]: Number(value) }))
|
|
}
|
|
/>
|
|
{productSlots.length === 0 && (
|
|
<p className="mt-1 text-xs text-gray-500">No delivery slots available</p>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<p className="font-medium text-brand-900">₹{itemPrice}</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleRemove(item, product?.name)}
|
|
className="p-1"
|
|
aria-label={`Remove ${product?.name ?? 'item'}`}
|
|
>
|
|
<Trash2 className="h-5 w-5 text-red-500" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{isFlashDelivery && (
|
|
<div className="mt-2 flex justify-end">
|
|
<div className="flex items-center gap-2">
|
|
<p className="font-medium text-brand-900">₹{itemPrice}</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleRemove(item, product?.name)}
|
|
className="p-1"
|
|
aria-label={`Remove ${product?.name ?? 'item'}`}
|
|
>
|
|
<Trash2 className="h-5 w-5 text-red-500" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{!isAvailable && (
|
|
<div className="mt-2 self-start rounded-md bg-red-50 px-2 py-1">
|
|
<p className="text-xs font-bold text-red-600">
|
|
{productSlotInfo?.isOutOfStock
|
|
? 'Out of Stock'
|
|
: isFlashDelivery && !flashEligibleProductIds.has(item.skuId)
|
|
? 'Not available for flash delivery. Please remove'
|
|
: 'No delivery slots available'}
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
{index < cartItems.length - 1 && <div className="mx-4 h-px bg-gray-200" />}
|
|
</div>
|
|
)
|
|
})}
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
{cartItems.length > 0 && (
|
|
<button
|
|
type="button"
|
|
onClick={() => navigate({ to: isFlashDelivery ? '/flash' : '/home' })}
|
|
className="mb-4 flex items-center self-start rounded-lg bg-gray-100 px-4 py-2 font-medium text-gray-700"
|
|
>
|
|
{isFlashDelivery ? 'Go to Scheduled Delivery' : 'Go to 1 Hr Delivery'}
|
|
</button>
|
|
)}
|
|
|
|
{hasAvailableItems && (
|
|
<div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
|
|
<div className="mb-3 flex items-center">
|
|
<div className="mr-3 flex h-8 w-8 items-center justify-center rounded-full bg-pink-50">
|
|
<Ticket className="h-4 w-4 text-pink-500" />
|
|
</div>
|
|
<p className="text-base font-bold text-gray-900">Offers & Coupons</p>
|
|
</div>
|
|
<Dropdown
|
|
label="Available Coupons"
|
|
testID="cart-coupon-dropdown"
|
|
options={dropdownData.map((d) => ({ label: d.label, value: d.value }))}
|
|
value={selectedCouponId || ''}
|
|
onValueChange={(value) => setSelectedCouponId(value ? Number(value) : null)}
|
|
/>
|
|
{eligibleCoupons.length === 0 && (
|
|
<p className="ml-1 mt-2 text-xs text-gray-400">No coupons available for this order</p>
|
|
)}
|
|
{selectedCouponId && (
|
|
<button type="button" onClick={() => setSelectedCouponId(null)} className="mt-3 self-end text-xs font-medium text-gray-400">
|
|
Remove coupon
|
|
</button>
|
|
)}
|
|
{!isAuthenticated && (
|
|
<button type="button" onClick={() => navigate({ to: '/login' })} className="ml-1 mt-2 text-xs">
|
|
<span className="text-blue-500 underline">Log In</span>
|
|
<span className="text-gray-400"> To find offers and coupons</span>
|
|
</button>
|
|
)}
|
|
<button type="button" onClick={() => navigate({ to: '/me/coupons' })} className="ml-1 mt-2 text-xs text-blue-500 underline">
|
|
Add Coupons to account
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
{!isFlashDelivery && cartItems.length > 0 && (
|
|
<DeliverySlotSummary groups={slotGroups} mergeSuggestion={mergeSuggestion} onMerge={handleMergeSlots} />
|
|
)}
|
|
|
|
{isAuthenticated && (
|
|
<div className="mb-4 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
|
|
<div className="flex items-center justify-between border-b border-gray-100 bg-gray-50 px-4 py-3">
|
|
<p className="text-base font-bold text-gray-900">Delivery Address</p>
|
|
<button type="button" onClick={() => setShowAddAddress(true)} className="text-sm font-medium text-brand-600">
|
|
+ Add New
|
|
</button>
|
|
</div>
|
|
<div className="p-4">
|
|
{selectedAddress ? (
|
|
<div>
|
|
<p className="truncate font-bold text-gray-900">
|
|
{selectedAddress.name} • {selectedAddress.phone}
|
|
</p>
|
|
<p className="mt-0.5 text-sm text-gray-500 line-clamp-2">
|
|
{selectedAddress.addressLine1}, {selectedAddress.city} - {selectedAddress.pincode}
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<p className="text-sm text-gray-500">No address selected</p>
|
|
)}
|
|
{addresses
|
|
.filter((a: any) => a.id !== selectedAddressId)
|
|
.slice(0, 3)
|
|
.map((address: any) => (
|
|
<button
|
|
key={address.id}
|
|
type="button"
|
|
data-testid={`cart-address-${address.id}`}
|
|
onClick={() => setSelectedAddressId(address.id)}
|
|
className="mt-3 w-full border-t border-gray-100 pt-3 text-left"
|
|
>
|
|
<p className="truncate text-sm font-medium text-gray-900">
|
|
{address.name} • {address.phone}
|
|
</p>
|
|
<p className="mt-0.5 truncate text-xs text-gray-500">
|
|
{address.addressLine1}, {address.city} - {address.pincode}
|
|
</p>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{hasAvailableItems && (
|
|
<div className="mb-6 mt-4 overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
|
|
<div className="border-b border-gray-100 bg-gray-50 px-4 py-3">
|
|
<p className="text-base font-bold text-gray-900">Bill Details</p>
|
|
</div>
|
|
<div className="p-4">
|
|
<div className="mb-3 flex items-center justify-between">
|
|
<p className="text-gray-500">Item Total</p>
|
|
<p className="font-medium text-gray-900">₹{Math.trunc(totalPrice)}</p>
|
|
</div>
|
|
{totalSavings > 1 && (
|
|
<div className="mb-3 flex items-center justify-between">
|
|
<p className="text-gray-500">Total Discount</p>
|
|
<p className="font-medium text-green-600">₹{Math.trunc(totalSavings)}</p>
|
|
</div>
|
|
)}
|
|
{discountAmount > 0 && (
|
|
<div className="mb-3 flex items-center justify-between">
|
|
<p className="text-gray-500">Product Discount</p>
|
|
<p className="font-medium text-green-600">-₹{Math.trunc(discountAmount)}</p>
|
|
</div>
|
|
)}
|
|
<div className="mb-3 flex items-center justify-between">
|
|
<p className="text-gray-500">Delivery Fee</p>
|
|
<p className={`font-medium ${deliveryCharge === 0 ? 'text-green-600' : 'text-gray-900'}`}>
|
|
{deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`}
|
|
</p>
|
|
</div>
|
|
{deliveryCharge > 0 && (freeDeliveryThreshold || 0) > 0 && finalTotal < (freeDeliveryThreshold || 0) && (
|
|
<div className="mb-3 flex items-center rounded-lg bg-blue-50 p-2.5">
|
|
<ShoppingBag className="mr-2 h-4 w-4 text-blue-600" />
|
|
<p className="flex-1 text-xs font-medium text-blue-700">
|
|
Add products worth ₹{((freeDeliveryThreshold || 0) - finalTotal).toFixed(0)} for free delivery
|
|
</p>
|
|
</div>
|
|
)}
|
|
<div className="my-2 h-px bg-gray-100" />
|
|
<div className="mt-2 flex items-center justify-between">
|
|
<p className="text-lg font-bold text-gray-900">To Pay</p>
|
|
<p className="text-xl font-bold text-gray-900">₹{Math.trunc(finalTotalWithDelivery)}</p>
|
|
</div>
|
|
{(discountAmount > 0 || deliveryCharge === 0 || totalSavings > 1) && (
|
|
<div className="mt-4 flex items-center justify-center rounded-lg bg-green-50 p-2">
|
|
<p className="text-xs font-bold text-green-700">
|
|
You saved ₹
|
|
{Math.trunc(discountAmount + totalSavings + (deliveryCharge === 0 ? (constsData as any)?.deliveryCharge || 0 : 0))} on
|
|
this order
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="border-t border-gray-100 bg-gray-50 p-4">
|
|
<div className="flex gap-3">
|
|
<button
|
|
type="button"
|
|
onClick={() => navigate({ to: isFlashDelivery ? '/flash' : '/home' })}
|
|
className="flex-1 rounded-xl border border-gray-200 bg-white py-3.5 font-bold text-gray-700 shadow-sm"
|
|
>
|
|
Shop More
|
|
</button>
|
|
<button
|
|
type="button"
|
|
data-testid="checkout-button"
|
|
onClick={handleCheckout}
|
|
className="flex flex-1 flex-row items-center justify-center rounded-xl bg-brand-500 py-3.5 font-bold text-white shadow-md"
|
|
>
|
|
Checkout
|
|
<ChevronRight className="ml-1 h-4 w-4" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<BottomDialog open={couponDialogOpen} onClose={() => setCouponDialogOpen(false)}>
|
|
<div className="p-6">
|
|
<div className="mb-6 flex items-center">
|
|
<div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-pink-50">
|
|
<Ticket className="h-5 w-5 text-pink-500" />
|
|
</div>
|
|
<p className="text-xl font-bold text-gray-900">Applied Coupons</p>
|
|
</div>
|
|
{selectedCoupons.map((coupon) => (
|
|
<div key={coupon.id} className="mb-4 rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
|
|
<div className="flex items-start justify-between">
|
|
<div>
|
|
<p className="text-lg font-bold text-gray-900">{coupon.code}</p>
|
|
<p className="mt-1 text-sm text-gray-500">{coupon.description}</p>
|
|
</div>
|
|
<div className="rounded bg-green-50 px-2 py-1">
|
|
<p className="text-xs font-bold text-green-700">
|
|
{coupon.discountType === 'percentage' ? `${coupon.discountValue}% OFF` : `₹${coupon.discountValue} OFF`}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
{coupon.maxValue && <p className="mt-2 text-xs text-gray-400">Maximum discount up to ₹{coupon.maxValue}</p>}
|
|
</div>
|
|
))}
|
|
<button
|
|
type="button"
|
|
onClick={() => setCouponDialogOpen(false)}
|
|
className="mt-4 w-full rounded-xl bg-gray-900 py-3.5 font-bold text-white"
|
|
>
|
|
Close
|
|
</button>
|
|
</div>
|
|
</BottomDialog>
|
|
|
|
<BottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
|
|
<div className="p-2">
|
|
<AddressForm onSuccess={handleAddressAdded} />
|
|
</div>
|
|
</BottomDialog>
|
|
|
|
<BottomDialog open={regionPickOpen} onClose={() => setRegionPickOpen(false)}>
|
|
<div className="p-6">
|
|
<p className="text-lg font-extrabold text-gray-900">
|
|
{pendingRegionName ? `Addresses in ${pendingRegionName}` : 'Choose an address'}
|
|
</p>
|
|
<p className="mb-4 mt-1 text-sm text-gray-500">
|
|
Your new address is in a different region. Pick one of its addresses to deliver to.
|
|
</p>
|
|
{pendingAddresses.map((address: any) => (
|
|
<button
|
|
key={address.id}
|
|
type="button"
|
|
data-testid={`cart-region-address-${address.id}`}
|
|
onClick={() => {
|
|
setSelectedAddressId(address.id)
|
|
setRegionPickOpen(false)
|
|
}}
|
|
className="w-full border-b border-gray-100 py-3 text-left"
|
|
>
|
|
<p className="truncate font-bold text-gray-900">
|
|
{address.name} • {address.phone}
|
|
</p>
|
|
<p className="mt-0.5 text-sm text-gray-500 line-clamp-2">
|
|
{address.addressLine1}, {address.city} - {address.pincode}
|
|
</p>
|
|
</button>
|
|
))}
|
|
<button
|
|
type="button"
|
|
onClick={() => setRegionPickOpen(false)}
|
|
className="mt-4 w-full rounded-xl bg-gray-900 py-3.5 font-bold text-white"
|
|
>
|
|
Close
|
|
</button>
|
|
</div>
|
|
</BottomDialog>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default CartPage
|