407 lines
16 KiB
TypeScript
407 lines
16 KiB
TypeScript
import React, { useState, useMemo } from 'react';
|
|
import { View, ScrollView } from 'react-native';
|
|
import { useLocalSearchParams, useRouter } from 'expo-router';
|
|
import dayjs from 'dayjs';
|
|
import { tw, useMarkDataFetchers , BottomDialog, MyText, MyTouchableOpacity } from 'common-ui';
|
|
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
|
import { useAuthenticatedRoute } from '@/hooks/useAuthenticatedRoute';
|
|
import { useAuth } from '@/src/contexts/AuthContext';
|
|
|
|
import { trpc } from '@/src/trpc-client';
|
|
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
|
import { useGetCart } from '@/hooks/cart-query-hooks';
|
|
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
|
import { useRegion } from '@/src/hooks/useRegion';
|
|
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
|
|
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
|
|
import { useAddressStore } from '@/src/store/addressStore';
|
|
import type { FlashDeliveryProps } from '@packages/shared';
|
|
import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared';
|
|
|
|
const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false }) => {
|
|
const params = useLocalSearchParams();
|
|
const router = useRouter();
|
|
const { isAuthenticated } = useAuth();
|
|
|
|
// Slots are per-region and the order is placed with this same region
|
|
// (see PaymentAndOrderComponent), so scope the query to it.
|
|
const { regionId } = useRegion();
|
|
|
|
// Protect checkout route and preserve query params
|
|
useAuthenticatedRoute({
|
|
targetUrl: isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/checkout' : '/(drawer)/(tabs)/home/checkout',
|
|
queryParams: params
|
|
});
|
|
|
|
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
|
|
const { data: cartData, refetch: refetchCart } = useGetCart({}, cartType);
|
|
|
|
const { data: addresses, refetch: refetchAddresses } = trpc.user.address.getUserAddresses.useQuery(
|
|
undefined,
|
|
{ enabled: isAuthenticated }
|
|
);
|
|
const { data: slotsData, refetch: refetchSlots } = trpc.user.slots.getSlots.useQuery(
|
|
{ regionId: regionId ?? undefined },
|
|
{ enabled: regionId != null }
|
|
);
|
|
const constsData = useRegionalConsts();
|
|
const products = useCentralProductStore((state) => state.products);
|
|
const productsById = useCentralProductStore((state) => state.productsById);
|
|
const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
|
|
|
|
useMarkDataFetchers(() => {
|
|
refetchCart();
|
|
refetchAddresses();
|
|
refetchSlots();
|
|
});
|
|
|
|
const { selectedAddressId } = useAddressStore();
|
|
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
|
|
|
|
|
|
|
const cartItems = cartData?.items || [];
|
|
|
|
// Memoized flash-eligible product IDs
|
|
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]);
|
|
|
|
// Parse slots parameter from URL (format: "1:1,2,3;2:4,5")
|
|
const selectedSlots = useMemo(() => {
|
|
const slots: Record<number, number> = {};
|
|
if (params.slots) {
|
|
const slotGroups = (params.slots as string).split(';');
|
|
slotGroups.forEach(group => {
|
|
const [slotIdStr, itemIdsStr] = group.split(':');
|
|
const slotId = Number(slotIdStr);
|
|
const itemIds = itemIdsStr.split(',').map(Number);
|
|
itemIds.forEach(itemId => {
|
|
slots[itemId] = slotId;
|
|
});
|
|
});
|
|
}
|
|
return slots;
|
|
}, [params.slots]);
|
|
|
|
const selectedItems = cartItems.filter(item => {
|
|
// For flash delivery, check if product supports flash delivery
|
|
if (isFlashDelivery) {
|
|
return flashEligibleProductIds.has(item.skuId);
|
|
}
|
|
// For regular delivery, only include items with assigned slots
|
|
return selectedSlots[item.id];
|
|
});
|
|
|
|
// Read-only items grouped by their chosen delivery slot, sorted by slot time.
|
|
const groupedItems = useMemo(() => {
|
|
if (isFlashDelivery) {
|
|
return [
|
|
{ slotId: null as number | null, label: null as string | null, sortKey: 0, items: selectedItems },
|
|
];
|
|
}
|
|
const groups = new Map<number, typeof selectedItems>();
|
|
selectedItems.forEach((item) => {
|
|
const slotId = selectedSlots[item.id];
|
|
if (slotId == null) return;
|
|
const list = groups.get(slotId) ?? [];
|
|
list.push(item);
|
|
groups.set(slotId, list);
|
|
});
|
|
return Array.from(groups.entries())
|
|
.map(([slotId, items]) => {
|
|
const slot = slotsData?.slots?.find((candidate) => candidate.id === slotId);
|
|
const deliveryTime = slot ? dayjs(slot.deliveryTime) : null;
|
|
return {
|
|
slotId: slotId as number | null,
|
|
label: (deliveryTime
|
|
? deliveryTime.format('ddd, DD MMM h:mm A')
|
|
: `Slot #${slotId}`) as string | null,
|
|
sortKey: deliveryTime ? deliveryTime.valueOf() : Number.MAX_SAFE_INTEGER,
|
|
items,
|
|
};
|
|
})
|
|
.sort((a, b) => a.sortKey - b.sortKey);
|
|
}, [isFlashDelivery, selectedItems, selectedSlots, slotsData]);
|
|
|
|
React.useEffect(() => {
|
|
if (params.coupons) {
|
|
const ids = String(params.coupons)
|
|
.split(',')
|
|
.map((value) => Number(value))
|
|
.filter((value) => Number.isFinite(value));
|
|
setSelectedCouponIds(ids);
|
|
}
|
|
}, [params.coupons]);
|
|
|
|
const totalPrice = selectedItems
|
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
.reduce(
|
|
(sum, item) => {
|
|
const product = productsById[item.skuId];
|
|
const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : (product?.price || 0);
|
|
return sum + price * item.quantity;
|
|
},
|
|
0
|
|
);
|
|
|
|
// Total savings = sum of (market price - offered price) * quantity, per in-stock item.
|
|
const totalSavings = selectedItems
|
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
.reduce(
|
|
(sum, item) => {
|
|
const product = productsById[item.skuId];
|
|
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) * item.quantity;
|
|
},
|
|
0
|
|
);
|
|
|
|
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(
|
|
{ regionId: regionId ?? undefined },
|
|
{ enabled: isAuthenticated }
|
|
);
|
|
|
|
const eligibleCoupons = useMemo(() => {
|
|
if (!couponsRaw?.data) return [];
|
|
return couponsRaw.data.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) > totalPrice) {
|
|
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: '',
|
|
exclusiveApply: coupon.exclusiveApply,
|
|
discountPercent: coupon.discountPercent,
|
|
flatDiscount: coupon.flatDiscount,
|
|
applicableSkuIds: [
|
|
...(coupon.applicableProducts || []).map((p: any) => p.skuId),
|
|
...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []),
|
|
],
|
|
isEligible,
|
|
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
|
};
|
|
}).filter(coupon => coupon.ineligibilityReason !== 'Usage limit exceeded');
|
|
}, [couponsRaw, totalPrice]);
|
|
|
|
const selectedCoupons = useMemo(
|
|
() =>
|
|
eligibleCoupons?.filter(
|
|
(coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible
|
|
) ?? [],
|
|
[eligibleCoupons, selectedCouponIds]
|
|
);
|
|
|
|
// Lines being ordered, with their effective unit price, for the shared helpers.
|
|
const cartLines = useMemo<CartLine[]>(
|
|
() =>
|
|
selectedItems
|
|
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
|
|
.map((item) => {
|
|
const product = productsById[item.skuId];
|
|
const unitPrice = isFlashDelivery
|
|
? (product?.flashPrice ?? product?.price ?? 0)
|
|
: (product?.price || 0);
|
|
return { skuId: item.skuId, quantity: item.quantity, unitPrice: Number(unitPrice) };
|
|
}),
|
|
[selectedItems, productSlotsMap, productsById, isFlashDelivery]
|
|
);
|
|
|
|
const discountAmount = useMemo(
|
|
() =>
|
|
selectedCoupons?.reduce(
|
|
(sum, coupon) =>
|
|
sum +
|
|
computeCouponDiscount(
|
|
computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }),
|
|
coupon
|
|
),
|
|
0
|
|
) || 0,
|
|
[selectedCoupons, cartLines]
|
|
);
|
|
|
|
const finalTotal = totalPrice - discountAmount;
|
|
|
|
const deliveryCharge = useMemo(() => {
|
|
const threshold = isFlashDelivery
|
|
? constsData?.flashFreeDeliveryThreshold
|
|
: constsData?.freeDeliveryThreshold;
|
|
const charge = isFlashDelivery
|
|
? constsData?.flashDeliveryCharge
|
|
: constsData?.deliveryCharge;
|
|
return finalTotal < threshold ? charge : 0;
|
|
}, [finalTotal, constsData, isFlashDelivery]);
|
|
|
|
const finalTotalWithDelivery = finalTotal + deliveryCharge;
|
|
|
|
// Handle empty cart case — deliberately after every hook, so the hook order stays
|
|
// stable across the cart-loading transition (this used to be a Rules-of-Hooks
|
|
// violation: the coupon query and the four memos above sat below this guard).
|
|
if (selectedItems.length === 0) {
|
|
return (
|
|
<View style={tw`flex-1 bg-gray-50 items-center justify-center p-6`}>
|
|
<MaterialIcons name="shopping-cart" size={64} color="#9CA3AF" />
|
|
<MyText style={tw`text-xl font-semibold text-gray-900 mt-4 text-center`}>
|
|
{cartItems.length === 0 ? "Your cart is empty" : "No items to checkout"}
|
|
</MyText>
|
|
<MyText style={tw`text-gray-500 text-center mt-2 mb-6`}>
|
|
{cartItems.length === 0
|
|
? "Add some delicious items to your cart before checking out"
|
|
: isFlashDelivery
|
|
? "None of your cart items are available for flash delivery"
|
|
: "Please select delivery slots for your items"
|
|
}
|
|
</MyText>
|
|
<MyTouchableOpacity
|
|
style={tw`bg-brand500 py-3 px-6 rounded-lg`}
|
|
onPress={() => router.back()}
|
|
>
|
|
<MyText style={tw`text-white font-semibold`}>Back to Shopping</MyText>
|
|
</MyTouchableOpacity>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
|
|
|
|
|
|
return (
|
|
<View style={tw`flex-1 bg-gray-50`}>
|
|
|
|
{/* Checkout Type Header */}
|
|
<View style={tw`bg-white px-4 py-3 mb-4 border-b border-gray-100 mt-6`}>
|
|
<View style={tw`flex-row items-center`}>
|
|
<MyTouchableOpacity
|
|
onPress={() => router.back()}
|
|
style={tw`p-2 -ml-2 mr-1`}
|
|
activeOpacity={0.7}
|
|
>
|
|
<MaterialIcons name="chevron-left" size={28} color="#374151" />
|
|
</MyTouchableOpacity>
|
|
<MaterialIcons
|
|
name={isFlashDelivery ? "flash-on" : "schedule"}
|
|
size={24}
|
|
color={isFlashDelivery ? "#f81260" : "#374151"}
|
|
/>
|
|
<MyText style={[
|
|
tw`text-lg font-bold ml-2`,
|
|
{ color: isFlashDelivery ? '#f81260' : '#374151' }
|
|
]}>
|
|
{isFlashDelivery ? "1 Hr Delivery Checkout" : "Scheduled Delivery Checkout"}
|
|
</MyText>
|
|
</View>
|
|
</View>
|
|
|
|
<ScrollView
|
|
style={tw`flex-1`}
|
|
contentContainerStyle={tw`p-4 pb-32`}
|
|
showsVerticalScrollIndicator={false}
|
|
>
|
|
{/* Items (grouped by delivery slot) */}
|
|
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
|
|
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Items</MyText>
|
|
{groupedItems.map((group) => (
|
|
<View key={group.slotId ?? 'flash'}>
|
|
{group.label && (
|
|
<View
|
|
style={tw`flex-row items-center self-start mt-3 mb-1 rounded-full bg-gray-100 px-2.5 py-1`}
|
|
>
|
|
<MaterialIcons name="schedule" size={13} color="#1570EF" style={tw`mr-1`} />
|
|
<MyText style={tw`text-xs font-semibold text-gray-800`}>
|
|
{group.label}
|
|
</MyText>
|
|
</View>
|
|
)}
|
|
{group.items.map((item) => {
|
|
const product = productsById[item.skuId];
|
|
const price = isFlashDelivery
|
|
? (product?.flashPrice ?? product?.price ?? 0)
|
|
: (product?.price || 0);
|
|
return (
|
|
<View
|
|
key={item.id}
|
|
style={tw`flex-row items-center justify-between py-2 border-b border-gray-50`}
|
|
>
|
|
<View style={tw`flex-1 mr-3`}>
|
|
<MyText style={tw`text-sm text-gray-900`} numberOfLines={1}>
|
|
{product?.name}
|
|
</MyText>
|
|
{!!product?.unitNotation && (
|
|
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
|
|
{product.unitNotation}
|
|
</MyText>
|
|
)}
|
|
</View>
|
|
<MyText style={tw`text-xs text-gray-500 mr-3`}>x{item.quantity}</MyText>
|
|
<MyText style={tw`text-sm font-bold text-gray-900`}>
|
|
₹{Number(price) * item.quantity}
|
|
</MyText>
|
|
</View>
|
|
);
|
|
})}
|
|
</View>
|
|
))}
|
|
</View>
|
|
|
|
{/* Coupon */}
|
|
{selectedCoupons.length > 0 && (
|
|
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
|
|
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Coupon</MyText>
|
|
{selectedCoupons.map((coupon) => (
|
|
<View key={coupon.id} style={tw`flex-row items-center justify-between py-2`}>
|
|
<MyText style={tw`text-sm font-medium text-gray-900`}>{coupon.code}</MyText>
|
|
<MyText style={tw`text-sm font-bold text-green-600`}>
|
|
{coupon.discountType === 'percentage'
|
|
? `${coupon.discountValue}% off`
|
|
: `₹${coupon.discountValue} off`}
|
|
</MyText>
|
|
</View>
|
|
))}
|
|
</View>
|
|
)}
|
|
|
|
<CheckoutAddressDisplay />
|
|
|
|
<PaymentAndOrderComponent
|
|
selectedAddress={selectedAddressId}
|
|
selectedSlots={selectedSlots}
|
|
selectedCouponIds={selectedCouponIds}
|
|
cartItems={selectedItems}
|
|
totalPrice={totalPrice}
|
|
totalSavings={totalSavings}
|
|
discountAmount={discountAmount}
|
|
finalTotal={finalTotal}
|
|
finalTotalWithDelivery={finalTotalWithDelivery}
|
|
deliveryCharge={deliveryCharge}
|
|
constsData={constsData}
|
|
selectedCoupons={selectedCoupons}
|
|
isFlashDelivery={isFlashDelivery}
|
|
/>
|
|
</ScrollView>
|
|
|
|
</View>
|
|
);
|
|
};
|
|
|
|
export default CheckoutPage;
|