484 lines
20 KiB
TypeScript
484 lines
20 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 CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
|
|
import { useAddressStore } from '@/src/store/addressStore';
|
|
import type { FlashDeliveryProps } from '@packages/shared';
|
|
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } 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 ?? 0 },
|
|
{ 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[]>([]);
|
|
// Coupon whose per-product discount split is open (product-specific coupons only).
|
|
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);
|
|
|
|
|
|
|
|
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 }
|
|
);
|
|
|
|
// Lines being ordered, with their effective unit price, for the shared helpers.
|
|
// Declared before the coupon list so eligibility can be evaluated locally.
|
|
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]
|
|
);
|
|
|
|
// Same local rules as the cart screen (and the backend's placeOrder checks), so
|
|
// a coupon that was applied in the cart can never be silently carried into the
|
|
// order: it is either still valid here, or it is listed below with its reason.
|
|
const eligibleCoupons = useMemo(() => {
|
|
if (!couponsRaw?.data) return [];
|
|
const isFirstOrder = couponsRaw.isFirstOrder ?? true;
|
|
|
|
return couponsRaw.data.map(coupon => {
|
|
const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [];
|
|
|
|
const { isEligible, reason: ineligibilityReason } = evaluateCouponEligibility(
|
|
{
|
|
regionId: coupon.regionId,
|
|
isFirstOrderOnly: coupon.isFirstOrderOnly,
|
|
minOrder: coupon.minOrder,
|
|
maxLimitForUser: coupon.maxLimitForUser,
|
|
usages: coupon.usages,
|
|
applicableSkuIds,
|
|
},
|
|
{ cartLines, regionId, isFirstOrder }
|
|
);
|
|
|
|
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,
|
|
isEligible,
|
|
ineligibilityReason,
|
|
};
|
|
});
|
|
}, [couponsRaw, cartLines, regionId]);
|
|
|
|
// Coupons applied, kept in the order the user selected them: coupons stack
|
|
// sequentially, so the order changes the result.
|
|
const couponById = useMemo(
|
|
() => new Map(eligibleCoupons.map((coupon) => [coupon.id, coupon])),
|
|
[eligibleCoupons]
|
|
);
|
|
|
|
const selectedCoupons = useMemo(
|
|
() =>
|
|
selectedCouponIds
|
|
.map((id) => couponById.get(id))
|
|
.filter((coupon): coupon is NonNullable<typeof coupon> => !!coupon && coupon.isEligible),
|
|
[selectedCouponIds, couponById]
|
|
);
|
|
|
|
// Coupons the customer picked in the cart that no longer apply to this order —
|
|
// shown, not silently dropped.
|
|
const droppedCoupons = useMemo(
|
|
() =>
|
|
selectedCouponIds
|
|
.map((id) => couponById.get(id))
|
|
.filter((coupon): coupon is NonNullable<typeof coupon> => !!coupon && !coupon.isEligible),
|
|
[selectedCouponIds, couponById]
|
|
);
|
|
|
|
const discountAmount = useMemo(
|
|
() => computeCouponStack(cartLines, selectedCoupons).discountTotal,
|
|
[selectedCoupons, cartLines]
|
|
);
|
|
|
|
// Where each applied coupon's discount landed, per cart line — the "i" next to a
|
|
// product-specific coupon. Same waterfall as the discount above, so the popup's
|
|
// rows always add up to what this page charges.
|
|
const couponBreakdowns = useMemo(() => {
|
|
const byId = new Map<number, CouponLineBreakdown>();
|
|
computeCouponLineBreakdowns(cartLines, selectedCoupons).forEach((entry) => {
|
|
byId.set(entry.couponId, entry);
|
|
});
|
|
return byId;
|
|
}, [cartLines, selectedCoupons]);
|
|
|
|
const breakdownCoupon =
|
|
breakdownCouponId != null ? couponById.get(breakdownCouponId) : undefined;
|
|
const breakdown =
|
|
breakdownCouponId != null ? couponBreakdowns.get(breakdownCouponId) : undefined;
|
|
|
|
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 testID="checkout-empty" style={tw`flex-1 bg-gray-50 items-center justify-center p-6`}>
|
|
<MaterialIcons name="shopping-cart" size={64} color="#9CA3AF" />
|
|
<MyText testID="checkout-empty-title" 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 testID="checkout-empty-copy" 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
|
|
testID="checkout-empty-back"
|
|
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 testID="checkout-header" 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
|
|
testID="checkout-header-back"
|
|
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 testID="checkout-header-title" 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 testID="checkout-items-section" 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'} testID={`checkout-slot-group-${group.slotId ?? 'flash'}`}>
|
|
{group.label && (
|
|
<View
|
|
testID={`checkout-slot-label-${group.slotId ?? 'flash'}`}
|
|
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}
|
|
testID={`checkout-item-${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 || droppedCoupons.length > 0) && (
|
|
<View testID="checkout-coupon-section" 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} testID={`checkout-coupon-${coupon.id}`} style={tw`flex-row items-center justify-between py-2`}>
|
|
<View style={tw`flex-row items-center flex-1 mr-2`}>
|
|
<MyText style={tw`text-sm font-medium text-gray-900`}>{coupon.code}</MyText>
|
|
{/* Product-specific coupon: the per-product split behind it. */}
|
|
{coupon.applicableSkuIds.length > 0 && (
|
|
<MyTouchableOpacity
|
|
testID={`coupon-breakdown-${coupon.id}`}
|
|
onPress={() => setBreakdownCouponId(coupon.id)}
|
|
style={tw`p-1 ml-0.5`}
|
|
activeOpacity={0.7}
|
|
>
|
|
<MaterialIcons name="info-outline" size={14} color="#EC4899" />
|
|
</MyTouchableOpacity>
|
|
)}
|
|
</View>
|
|
<MyText testID={`checkout-coupon-value-${coupon.id}`} style={tw`text-sm font-bold text-green-600`}>
|
|
{coupon.discountType === 'percentage'
|
|
? `${coupon.discountValue}% off`
|
|
: `₹${coupon.discountValue} off`}
|
|
</MyText>
|
|
</View>
|
|
))}
|
|
{/* Picked in the cart but no longer applicable to this order — shown with
|
|
the reason instead of vanishing (the cart has the full picker). */}
|
|
{droppedCoupons.map((coupon) => (
|
|
<View key={coupon.id} testID={`checkout-coupon-dropped-${coupon.id}`} style={tw`py-2`}>
|
|
<View style={tw`flex-row items-center justify-between`}>
|
|
<MyText style={tw`text-sm font-medium text-gray-400 line-through`}>
|
|
{coupon.code}
|
|
</MyText>
|
|
<MyText style={tw`text-sm text-gray-400`}>Not applied</MyText>
|
|
</View>
|
|
{!!coupon.ineligibilityReason && (
|
|
<MyText testID={`checkout-coupon-reason-${coupon.id}`} style={tw`text-xs text-gray-400 mt-0.5`}>
|
|
{coupon.ineligibilityReason}
|
|
</MyText>
|
|
)}
|
|
</View>
|
|
))}
|
|
</View>
|
|
)}
|
|
|
|
<CheckoutAddressDisplay />
|
|
|
|
{/* Only the coupons that survived the local check: the ids sent to
|
|
placeOrder are the ids the discount above is computed from. */}
|
|
<PaymentAndOrderComponent
|
|
selectedAddress={selectedAddressId}
|
|
selectedSlots={selectedSlots}
|
|
selectedCouponIds={selectedCoupons.map((coupon) => coupon.id)}
|
|
cartItems={selectedItems}
|
|
totalPrice={totalPrice}
|
|
totalSavings={totalSavings}
|
|
discountAmount={discountAmount}
|
|
finalTotal={finalTotal}
|
|
finalTotalWithDelivery={finalTotalWithDelivery}
|
|
deliveryCharge={deliveryCharge}
|
|
constsData={constsData}
|
|
selectedCoupons={selectedCoupons}
|
|
isFlashDelivery={isFlashDelivery}
|
|
/>
|
|
</ScrollView>
|
|
|
|
{/* Per-product discount split of one applied coupon (the coupon block's "i") */}
|
|
<CouponBreakdownDialog
|
|
coupon={breakdownCoupon ? { id: breakdownCoupon.id, code: breakdownCoupon.code } : null}
|
|
breakdown={breakdown ?? null}
|
|
cartLines={cartLines}
|
|
onClose={() => setBreakdownCouponId(null)}
|
|
/>
|
|
</View>
|
|
);
|
|
};
|
|
|
|
export default CheckoutPage;
|