Compare commits
2 commits
d9fc579f7b
...
7ab2d71569
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ab2d71569 | ||
|
|
3dca930fb3 |
10 changed files with 1153 additions and 142 deletions
|
|
@ -25,18 +25,19 @@ import TestingPhaseNote from "@/components/TestingPhaseNote";
|
|||
|
||||
import dayjs from "dayjs";
|
||||
import { trpc } from "@/src/trpc-client";
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||
import { useCentralProductStore, type Product } from '@/src/store/centralProductStore';
|
||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
||||
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
||||
import { useRegion } from '@/src/hooks/useRegion';
|
||||
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
|
||||
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
|
||||
import LoginWall from '@/components/LoginWall';
|
||||
import CartAddressGate from '@/components/CartAddressGate';
|
||||
import { useAddressStore } from '@/src/store/addressStore';
|
||||
import { useCheckoutStore } from '@/src/store/checkoutStore';
|
||||
import type { FlashDeliveryProps } from '@packages/shared';
|
||||
import { computeCouponStack, computeEligibleSubtotal, type CartLine } from '@packages/shared';
|
||||
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared';
|
||||
|
||||
const formatDeliverySlot = (deliveryTime: string): string => {
|
||||
const time = dayjs(deliveryTime);
|
||||
|
|
@ -51,6 +52,97 @@ const formatDeliverySlot = (deliveryTime: string): string => {
|
|||
return `${time.format('ddd, DD MMM ')}${range}`;
|
||||
};
|
||||
|
||||
/** One row of the "products this coupon applies to" list. */
|
||||
type CouponTargetRow =
|
||||
| {
|
||||
key: string;
|
||||
name: string;
|
||||
unitNotation?: string;
|
||||
image?: string;
|
||||
}
|
||||
| {
|
||||
key: string;
|
||||
/** Target SKU that is no longer in the region's catalog. */
|
||||
unavailableSkuId: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The products a coupon is restricted to, one row per DISTINCT product name —
|
||||
* the coupon targets SKUs, but several SKUs of the same product are the same
|
||||
* line to a customer. A target whose SKU is not in the catalog (suspended or
|
||||
* deleted SKUs are filtered out of the product store) still gets a row, so the
|
||||
* count shown next to the coupon never silently shrinks — which also matches
|
||||
* the backend, where a stale target simply stops matching.
|
||||
*/
|
||||
const buildCouponTargetRows = (
|
||||
skuIds: number[],
|
||||
productsById: Record<number, Product>
|
||||
): CouponTargetRow[] => {
|
||||
const rows: CouponTargetRow[] = [];
|
||||
const seenNames = new Set<string>();
|
||||
|
||||
skuIds.forEach((skuId) => {
|
||||
const product = productsById[skuId];
|
||||
if (!product?.name) {
|
||||
rows.push({ key: `sku-${skuId}`, unavailableSkuId: skuId });
|
||||
return;
|
||||
}
|
||||
if (seenNames.has(product.name)) return;
|
||||
seenNames.add(product.name);
|
||||
rows.push({
|
||||
key: `name-${product.name}`,
|
||||
name: product.name,
|
||||
unitNotation: product.unitNotation,
|
||||
image: product.images?.[0],
|
||||
});
|
||||
});
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
/** Inline product list for one coupon — rendered inside the coupon dropdown's
|
||||
* option (the dropdown provides the bounded, scrollable container). */
|
||||
function CouponTargetRows({ rows }: { rows: CouponTargetRow[] }) {
|
||||
return (
|
||||
<View style={tw`pt-1`}>
|
||||
{rows.map((row) => (
|
||||
<View
|
||||
key={row.key}
|
||||
style={tw`flex-row items-center px-4 py-2 border-b border-gray-100 last:border-b-0`}
|
||||
>
|
||||
{'unavailableSkuId' in row ? (
|
||||
<>
|
||||
<View style={tw`w-8 h-8 rounded-lg bg-gray-100 items-center justify-center mr-3`}>
|
||||
<MaterialIcons name="inventory-2" size={16} color="#9CA3AF" />
|
||||
</View>
|
||||
<MyText style={tw`text-xs text-gray-500 flex-1`}>
|
||||
Product unavailable · #{row.unavailableSkuId}
|
||||
</MyText>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Image
|
||||
source={{ uri: row.image }}
|
||||
style={tw`w-8 h-8 rounded-lg bg-gray-100 mr-3`}
|
||||
/>
|
||||
<View style={tw`flex-1`}>
|
||||
<MyText style={tw`text-sm text-gray-900`} numberOfLines={2}>
|
||||
{row.name}
|
||||
</MyText>
|
||||
{!!row.unitNotation && (
|
||||
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
|
||||
{row.unitNotation}
|
||||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface DeliverySlotGroupItem {
|
||||
id: number;
|
||||
name: string;
|
||||
|
|
@ -262,19 +354,6 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
);
|
||||
}, [products, productSlotsMap]);
|
||||
|
||||
// Base total price without discounts for coupon eligibility check
|
||||
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]
|
||||
);
|
||||
|
||||
// Cart lines (in-stock only) with their effective unit price, in the shared
|
||||
// shape the coupon helpers expect. Declared before the coupon list so coupon
|
||||
// targeting can be evaluated against the cart.
|
||||
|
|
@ -298,7 +377,10 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
|
||||
// Every coupon we're allowed to surface (the API already drops expired,
|
||||
// invalidated, usage-limit-exceeded and other users' personal coupons).
|
||||
// Ineligible ones are kept but flagged with the reason, and sorted to the end.
|
||||
// Whether each one applies to THIS cart is decided locally — the shared
|
||||
// resolver, the same rules the backend applies at placeOrder — so changing the
|
||||
// cart never has to ask the server again. Ineligible ones are kept, flagged with
|
||||
// the reason, and sorted to the end.
|
||||
const eligibleCoupons = useMemo(() => {
|
||||
if (!couponsRaw?.data) return [];
|
||||
const isFirstOrder = couponsRaw.isFirstOrder ?? true;
|
||||
|
|
@ -307,20 +389,17 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
// Target SKUs live on the coupon row itself (empty => whole cart).
|
||||
const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [];
|
||||
|
||||
let reason: string | undefined;
|
||||
if (coupon.regionId != null && regionId != null && coupon.regionId !== regionId) {
|
||||
reason = "Not valid in your region";
|
||||
} else if (coupon.isFirstOrderOnly && !isFirstOrder) {
|
||||
reason = "Valid on your first order only";
|
||||
} else if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) {
|
||||
const shortfall = Math.ceil(parseFloat(coupon.minOrder) - baseTotalPrice);
|
||||
reason = `Add ₹${shortfall} more to use this coupon`;
|
||||
} else if (
|
||||
applicableSkuIds.length > 0 &&
|
||||
computeEligibleSubtotal(cartLines, { applicableSkuIds }) <= 0
|
||||
) {
|
||||
reason = "No applicable items in your cart";
|
||||
}
|
||||
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,
|
||||
|
|
@ -337,14 +416,14 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
discountPercent: coupon.discountPercent,
|
||||
flatDiscount: coupon.flatDiscount,
|
||||
applicableSkuIds,
|
||||
isEligible: !reason,
|
||||
ineligibilityReason: reason,
|
||||
isEligible,
|
||||
ineligibilityReason,
|
||||
};
|
||||
});
|
||||
|
||||
// Applicable coupons first, disabled ones at the end (stable within groups).
|
||||
return mapped.sort((a, b) => Number(b.isEligible) - Number(a.isEligible));
|
||||
}, [couponsRaw, baseTotalPrice, cartLines, regionId]);
|
||||
}, [couponsRaw, cartLines, regionId]);
|
||||
|
||||
const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType);
|
||||
const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType);
|
||||
|
|
@ -360,6 +439,9 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
const [selectedSlots, setSelectedSlots] = useState<Record<number, number>>({});
|
||||
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
||||
const [couponDialogOpen, setCouponDialogOpen] = useState(false);
|
||||
// Coupon whose per-product discount split is open (only product-specific ones
|
||||
// have an "i" in the bill).
|
||||
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
|
|
@ -437,6 +519,17 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
const selectedIds = new Set(selectedCoupons.map((c) => c.id));
|
||||
return (
|
||||
eligibleCoupons?.map((coupon) => {
|
||||
// The products this coupon is restricted to (empty => whole cart). One row
|
||||
// per distinct product name; the same array drives the label and the list,
|
||||
// so the count always matches what is rendered.
|
||||
const targetRows = buildCouponTargetRows(coupon.applicableSkuIds, productsById);
|
||||
const detail = targetRows.length > 0
|
||||
? {
|
||||
label: `Applies to ${targetRows.length} product${targetRows.length === 1 ? '' : 's'}`,
|
||||
render: () => <CouponTargetRows rows={targetRows} />,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
// Disabled coupons can't be applied: row 1 shows just the code (with the
|
||||
// italic "Disabled" badge), row 2 the reason. No "Save" preview.
|
||||
if (!coupon.isEligible) {
|
||||
|
|
@ -445,6 +538,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
value: coupon.id,
|
||||
disabled: true,
|
||||
note: coupon.ineligibilityReason,
|
||||
detail,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -459,10 +553,11 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
label: `${coupon.code} - ${coupon.description} (Save ₹${save})`,
|
||||
value: coupon.id,
|
||||
disabled: false,
|
||||
detail,
|
||||
};
|
||||
}) || []
|
||||
);
|
||||
}, [eligibleCoupons, cartLines, selectedCoupons]);
|
||||
}, [eligibleCoupons, cartLines, selectedCoupons, productsById]);
|
||||
|
||||
// The coupon dropdown is a multi-select: it toggles an id and reports the whole
|
||||
// new list. An exclusive coupon still replaces every other selection (and
|
||||
|
|
@ -505,6 +600,24 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
[couponDiscounts]
|
||||
);
|
||||
|
||||
// Where each applied coupon's discount landed, per cart line — the bill's "i"
|
||||
// popup for product-specific coupons. Totals come from the same waterfall as the
|
||||
// bill's own figures, so the popup's rows always add up to the coupon's line.
|
||||
const couponBreakdowns = useMemo(() => {
|
||||
const byId = new Map<number, CouponLineBreakdown>();
|
||||
computeCouponLineBreakdowns(cartLines, selectedCoupons).forEach((entry) => {
|
||||
byId.set(entry.couponId, entry);
|
||||
});
|
||||
return byId;
|
||||
}, [cartLines, selectedCoupons]);
|
||||
|
||||
// Cart lines by SKU, for the popup's quantity × price line.
|
||||
// The coupon whose per-product split is open, if it is still applied.
|
||||
const breakdownCoupon =
|
||||
breakdownCouponId != null ? couponById.get(breakdownCouponId) : undefined;
|
||||
const breakdown =
|
||||
breakdownCouponId != null ? couponBreakdowns.get(breakdownCouponId) : undefined;
|
||||
|
||||
const finalTotal = totalPrice - discountAmount;
|
||||
|
||||
const deliveryCharge = useMemo(
|
||||
|
|
@ -1224,6 +1337,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
</View>
|
||||
|
||||
<BottomDropdown
|
||||
testID="coupon-dropdown"
|
||||
label="Available Coupons"
|
||||
options={dropdownData}
|
||||
value={selectedCouponIds}
|
||||
|
|
@ -1360,16 +1474,31 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
key={coupon.id}
|
||||
style={tw`flex-row justify-between items-center mb-3`}
|
||||
>
|
||||
<MyTouchableOpacity
|
||||
style={tw`flex-row items-center flex-1 mr-2`}
|
||||
onPress={() => setCouponDialogOpen(true)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<MaterialIcons name="local-offer" size={14} color="#EC4899" style={tw`mr-1.5`} />
|
||||
<MyText style={tw`text-pink-600 font-medium`}>
|
||||
{coupon.code}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
<View style={tw`flex-row items-center flex-1 mr-2`}>
|
||||
<MyTouchableOpacity
|
||||
style={tw`flex-row items-center`}
|
||||
onPress={() => setCouponDialogOpen(true)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<MaterialIcons name="local-offer" size={14} color="#EC4899" style={tw`mr-1.5`} />
|
||||
<MyText style={tw`text-pink-600 font-medium`}>
|
||||
{coupon.code}
|
||||
</MyText>
|
||||
</MyTouchableOpacity>
|
||||
{/* Product-specific coupon: how much came off each product. A
|
||||
sibling of the row above, so it cannot open the applied-
|
||||
coupons dialog by accident. */}
|
||||
{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 style={tw`text-green-600 font-medium`}>
|
||||
-₹{Math.trunc(couponDiscounts[coupon.id] || 0)}
|
||||
</MyText>
|
||||
|
|
@ -1540,6 +1669,14 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
</ScrollView>
|
||||
</AppContainer>
|
||||
|
||||
{/* Per-product discount split of one applied coupon (the bill's "i") */}
|
||||
<CouponBreakdownDialog
|
||||
coupon={breakdownCoupon ? { id: breakdownCoupon.id, code: breakdownCoupon.code } : null}
|
||||
breakdown={breakdown ?? null}
|
||||
cartLines={cartLines}
|
||||
onClose={() => setBreakdownCouponId(null)}
|
||||
/>
|
||||
|
||||
{/* Coupon Details Dialog */}
|
||||
<BottomDialog
|
||||
open={couponDialogOpen}
|
||||
|
|
|
|||
|
|
@ -15,9 +15,10 @@ 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, type CartLine } from '@packages/shared';
|
||||
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } from '@packages/shared';
|
||||
|
||||
const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false }) => {
|
||||
const params = useLocalSearchParams();
|
||||
|
|
@ -58,6 +59,8 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
|
||||
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);
|
||||
|
||||
|
||||
|
||||
|
|
@ -170,36 +173,61 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
{ 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: Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [],
|
||||
isEligible,
|
||||
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
||||
};
|
||||
}).filter(coupon => coupon.ineligibilityReason !== 'Usage limit exceeded');
|
||||
}, [couponsRaw, totalPrice]);
|
||||
// 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.
|
||||
|
|
@ -216,19 +244,14 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
[selectedCouponIds, couponById]
|
||||
);
|
||||
|
||||
// Lines being ordered, with their effective unit price, for the shared helpers.
|
||||
const cartLines = useMemo<CartLine[]>(
|
||||
// Coupons the customer picked in the cart that no longer apply to this order —
|
||||
// shown, not silently dropped.
|
||||
const droppedCoupons = useMemo(
|
||||
() =>
|
||||
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]
|
||||
selectedCouponIds
|
||||
.map((id) => couponById.get(id))
|
||||
.filter((coupon): coupon is NonNullable<typeof coupon> => !!coupon && !coupon.isEligible),
|
||||
[selectedCouponIds, couponById]
|
||||
);
|
||||
|
||||
const discountAmount = useMemo(
|
||||
|
|
@ -236,6 +259,22 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
[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(() => {
|
||||
|
|
@ -360,12 +399,25 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
</View>
|
||||
|
||||
{/* Coupon */}
|
||||
{selectedCoupons.length > 0 && (
|
||||
{(selectedCoupons.length > 0 || droppedCoupons.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>
|
||||
<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 style={tw`text-sm font-bold text-green-600`}>
|
||||
{coupon.discountType === 'percentage'
|
||||
? `${coupon.discountValue}% off`
|
||||
|
|
@ -373,15 +425,34 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
</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} 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 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={selectedCouponIds}
|
||||
selectedCouponIds={selectedCoupons.map((coupon) => coupon.id)}
|
||||
cartItems={selectedItems}
|
||||
totalPrice={totalPrice}
|
||||
totalSavings={totalSavings}
|
||||
|
|
@ -395,6 +466,13 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
/>
|
||||
</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>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -29,11 +29,20 @@ import { LinearGradient } from "expo-linear-gradient";
|
|||
|
||||
const { height: screenHeight } = Dimensions.get("window");
|
||||
|
||||
// Height of the expanded "Your Cart" sheet: the full 80% of the screen the dialog
|
||||
// allows. Deliberate (not a max) so the items list below can be `flex-1`: it takes
|
||||
// exactly the leftover space and scrolls while the Subtotal / "Go to cart" footer
|
||||
// stays pinned at the bottom of the sheet.
|
||||
const CART_SHEET_HEIGHT = screenHeight * 0.8;
|
||||
// How tall the expanded "Your Cart" sheet may get before its items list starts
|
||||
// scrolling. Deliberately a MAX, not a height: the sheet is content-sized, so a
|
||||
// one-item cart is a short sheet and a long one stops here. 70px is reserved for
|
||||
// BottomDialog's own chrome (its handle plus the paddingBottom it puts under our
|
||||
// children, 40 on iOS / 20 on Android) so the dialog itself never scrolls and the
|
||||
// Subtotal / "Go to cart" footer can't be dragged.
|
||||
//
|
||||
// The items list is `shrink` (flexShrink 1, flexBasis auto), NOT `flex-1`: flex-1
|
||||
// is flexBasis 0%, which contributes nothing to an auto-height parent and collapses
|
||||
// the list. With flexBasis auto the list contributes its content height, so the
|
||||
// sheet sizes to the content and, once the max above is hit, the list — the only
|
||||
// shrinkable child, header/progress/footer keep flexShrink 0 — takes the leftover
|
||||
// space and scrolls.
|
||||
const CART_SHEET_MAX_HEIGHT = Math.round(screenHeight * 0.8) - 70;
|
||||
|
||||
const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => {
|
||||
if (unit?.toLowerCase() === 'kg' && quantity < 1) {
|
||||
|
|
@ -231,7 +240,7 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
)}
|
||||
</View>
|
||||
<BottomDialog open={isExpanded} onClose={() => setIsExpanded(false)} enableDismiss={true}>
|
||||
<View style={{ height: CART_SHEET_HEIGHT }}>
|
||||
<View style={{ maxHeight: CART_SHEET_MAX_HEIGHT }}>
|
||||
{/* Header */}
|
||||
<View style={tw`px-6 py-5 border-b border-slate-100 flex-row items-center justify-between`}>
|
||||
<View>
|
||||
|
|
@ -269,8 +278,13 @@ const FloatingCartBar: React.FC<FloatingCartBarProps> = ({
|
|||
</View>
|
||||
)}
|
||||
|
||||
{/* Items List */}
|
||||
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-6 py-4`}>
|
||||
{/* Items List — the only scrolling region. flexBasis auto (not flex-1's
|
||||
0%) is what lets the sheet size to this list's content and shrink it
|
||||
back once the sheet hits its max height. */}
|
||||
<ScrollView
|
||||
style={{ flexBasis: 'auto', flexShrink: 1 }}
|
||||
contentContainerStyle={tw`px-6 py-4`}
|
||||
>
|
||||
{cartItems.map((item, index) => (
|
||||
<React.Fragment key={item.id}>
|
||||
<View style={tw`py-4`}>
|
||||
|
|
|
|||
|
|
@ -11,11 +11,19 @@ import { useGetEssentialConsts, useSlots } from '@/src/hooks/prominent-api-hooks
|
|||
import dayjs from 'dayjs';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
|
||||
// Height of the sheet's content box: the full 80% of the screen the dialog allows.
|
||||
// Deliberate (not a max): the slot list is `flex-1`, so a definite height is what
|
||||
// lets it take exactly the leftover space and scroll while the quantity row and the
|
||||
// Cancel / Add to Cart row stay pinned at the bottom of the sheet.
|
||||
const SHEET_HEIGHT = Dimensions.get('window').height * 0.8;
|
||||
// How tall the sheet's content box may get before the slot list starts scrolling.
|
||||
// Deliberately a MAX, not a height: a product with two slots gets a short sheet, a
|
||||
// product with many slots stops here. 70px is reserved for BottomDialog's own chrome
|
||||
// (its handle plus the paddingBottom it puts under our children, 40 on iOS /
|
||||
// 20 on Android) so the dialog itself never scrolls and the quantity / action rows
|
||||
// can't be dragged.
|
||||
//
|
||||
// The slot list is `shrink` (flexShrink 1, flexBasis auto), NOT `flex-1`: flex-1 is
|
||||
// flexBasis 0%, which contributes nothing to an auto-height parent and collapses the
|
||||
// list. With flexBasis auto the list contributes its content height, so the sheet
|
||||
// sizes to the content and, once the max above is hit, the list — the only
|
||||
// shrinkable child — takes the leftover space and scrolls.
|
||||
const SHEET_MAX_HEIGHT = Math.round(Dimensions.get('window').height * 0.8) - 70;
|
||||
|
||||
const formatTimeRange = (deliveryTime: string) => {
|
||||
const time = dayjs(deliveryTime);
|
||||
|
|
@ -164,7 +172,7 @@ export default function AddToCartDialog() {
|
|||
{/* Bottom sheet: only the bottom inset matters here — a top inset would just
|
||||
add dead space between the handle and the header. */}
|
||||
<SafeAreaView edges={['bottom']}>
|
||||
<View style={[tw`p-6`, { height: SHEET_HEIGHT }]}>
|
||||
<View style={[tw`p-6`, { maxHeight: SHEET_MAX_HEIGHT }]}>
|
||||
<View style={tw`flex-row items-center mb-2`}>
|
||||
<View style={tw`w-10 h-10 bg-blue-50 rounded-full items-center justify-center mr-3`}>
|
||||
<MaterialIcons name="schedule" size={20} color="#3B82F6" />
|
||||
|
|
@ -179,10 +187,14 @@ export default function AddToCartDialog() {
|
|||
</View>
|
||||
</View>
|
||||
|
||||
{/* The only scrolling region: this shrinks to whatever space is left in
|
||||
the capped box above, so the quantity row and the Cancel / Add to
|
||||
Cart row underneath it never move. */}
|
||||
<ScrollView style={tw`flex-1`} showsVerticalScrollIndicator={false}>
|
||||
{/* The only scrolling region. flexBasis auto (not flex-1's 0%) is what lets
|
||||
the sheet size to this list's content and shrink it back once the sheet
|
||||
hits its max height, so the quantity row and the Cancel / Add to Cart row
|
||||
underneath never move. */}
|
||||
<ScrollView
|
||||
style={{ flexBasis: 'auto', flexShrink: 1 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{availableSlots.map((slot: any) => (
|
||||
<MyTouchableOpacity
|
||||
key={slot.id}
|
||||
|
|
|
|||
127
apps/user-ui/src/components/CouponBreakdownDialog.tsx
Normal file
127
apps/user-ui/src/components/CouponBreakdownDialog.tsx
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import React, { useMemo } from 'react';
|
||||
import { Image, View } from 'react-native';
|
||||
import { tw, BottomDialog, MyText, MyTouchableOpacity } from 'common-ui';
|
||||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||||
import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||
import type { CartLine, CouponLineBreakdown } from '@packages/shared';
|
||||
|
||||
interface CouponBreakdownDialogProps {
|
||||
/** The applied coupon whose split is shown; null keeps the dialog closed. */
|
||||
coupon: { id: number; code: string } | null;
|
||||
/** Its per-line discount split (from computeCouponLineBreakdowns). */
|
||||
breakdown: CouponLineBreakdown | null;
|
||||
/** The cart lines the order is priced from, for the qty × price line. */
|
||||
cartLines: CartLine[];
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a product-specific coupon's discount landed, product by product — the
|
||||
* dialog behind the "i" next to an applied coupon (cart bill and checkout coupon
|
||||
* block). The rows come from `computeCouponLineBreakdowns`, the same waterfall the
|
||||
* bill uses, and they are reconciled to whole rupees, so they always add up to the
|
||||
* coupon's total shown here and on the bill.
|
||||
*
|
||||
* Note: this must be opened from an inline row, never from inside another dialog —
|
||||
* a BottomDialog is a native Modal and must not be nested.
|
||||
*/
|
||||
const CouponBreakdownDialog: React.FC<CouponBreakdownDialogProps> = ({
|
||||
coupon,
|
||||
breakdown,
|
||||
cartLines,
|
||||
onClose,
|
||||
}) => {
|
||||
const productsById = useCentralProductStore((state) => state.productsById);
|
||||
|
||||
const cartLineBySkuId = useMemo(
|
||||
() => new Map(cartLines.map((line) => [line.skuId, line])),
|
||||
[cartLines]
|
||||
);
|
||||
|
||||
// Only the lines the money actually landed on, biggest first.
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
(breakdown?.lines ?? [])
|
||||
.filter((line) => line.discount > 0)
|
||||
.sort((a, b) => b.discount - a.discount),
|
||||
[breakdown]
|
||||
);
|
||||
|
||||
return (
|
||||
<BottomDialog open={!!coupon && !!breakdown} onClose={onClose}>
|
||||
<View style={tw`p-6`} testID="coupon-breakdown-dialog">
|
||||
<View style={tw`flex-row items-start justify-between mb-1`}>
|
||||
<View style={tw`flex-1 mr-3`}>
|
||||
<MyText style={tw`text-lg font-bold text-gray-900`}>
|
||||
Product discount
|
||||
</MyText>
|
||||
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
|
||||
{coupon?.code} · applied to specific products
|
||||
</MyText>
|
||||
</View>
|
||||
<MyTouchableOpacity onPress={onClose} style={tw`p-1`}>
|
||||
<MaterialIcons name="close" size={22} color="#9CA3AF" />
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<MyText style={tw`text-sm text-gray-500 mt-4`}>
|
||||
No per-product split to show for this order.
|
||||
</MyText>
|
||||
) : (
|
||||
rows.map((row) => {
|
||||
const product = productsById[row.skuId];
|
||||
const line = cartLineBySkuId.get(row.skuId);
|
||||
return (
|
||||
<View
|
||||
key={row.skuId}
|
||||
testID={`coupon-breakdown-row-${row.skuId}`}
|
||||
style={tw`flex-row items-center py-3 border-b border-gray-50`}
|
||||
>
|
||||
<Image
|
||||
source={{ uri: product?.images?.[0] }}
|
||||
style={tw`w-10 h-10 rounded-lg bg-gray-100 mr-3`}
|
||||
/>
|
||||
<View style={tw`flex-1 mr-2`}>
|
||||
<MyText style={tw`text-sm text-gray-900`} numberOfLines={2}>
|
||||
{product?.name || `Product #${row.skuId}`}
|
||||
</MyText>
|
||||
{!!line && (
|
||||
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
|
||||
{line.quantity} × ₹{Math.trunc(line.unitPrice)}
|
||||
</MyText>
|
||||
)}
|
||||
</View>
|
||||
<MyText style={tw`text-sm font-bold text-green-600`}>
|
||||
−₹{row.discount}
|
||||
</MyText>
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
<View style={tw`flex-row justify-between items-center mt-4`}>
|
||||
<MyText style={tw`text-sm font-bold text-gray-900`}>
|
||||
Total from this coupon
|
||||
</MyText>
|
||||
<MyText style={tw`text-base font-bold text-green-600`}>
|
||||
−₹{Math.trunc(breakdown?.discount ?? 0)}
|
||||
</MyText>
|
||||
</View>
|
||||
<MyText style={tw`text-xs text-gray-400 mt-1`}>
|
||||
Applies to the listed products only — the rest of the cart is not
|
||||
discounted by this coupon.
|
||||
</MyText>
|
||||
|
||||
<MyTouchableOpacity
|
||||
style={tw`mt-4 bg-gray-900 py-3.5 rounded-xl items-center`}
|
||||
onPress={onClose}
|
||||
>
|
||||
<MyText style={tw`text-white font-bold`}>Close</MyText>
|
||||
</MyTouchableOpacity>
|
||||
</View>
|
||||
</BottomDialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default CouponBreakdownDialog;
|
||||
|
|
@ -50,27 +50,40 @@ const coupon = (over: Record<string, unknown> = {}) => ({
|
|||
...over,
|
||||
})
|
||||
|
||||
/** Mount the cart with one line (2 x 215) and the given eligible coupons. */
|
||||
async function mountCart(coupons: unknown[]) {
|
||||
const SECOND_SKU_ID = 4 // Mutton, price 839
|
||||
|
||||
/** Mount the cart with one line (2 x 215), optionally a second (1 x 839). */
|
||||
async function mountCart(coupons: unknown[], withSecondLine = false) {
|
||||
setupApiMocks({
|
||||
procedures: {
|
||||
'user.cart.getCartSlots': { [PRODUCT_ID]: [futureSlot()] },
|
||||
'user.cart.getCartSlots': {
|
||||
[PRODUCT_ID]: [futureSlot()],
|
||||
...(withSecondLine ? { [SECOND_SKU_ID]: [futureSlot()] } : {}),
|
||||
},
|
||||
'user.coupon.getEligible': { data: coupons },
|
||||
},
|
||||
})
|
||||
|
||||
await StorageServiceCasual.setItem(
|
||||
'cart_items',
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 1,
|
||||
skuId: PRODUCT_ID,
|
||||
quantity: 2,
|
||||
slotId: SLOT_ID,
|
||||
addedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
)
|
||||
const lines = [
|
||||
{
|
||||
id: 1,
|
||||
skuId: PRODUCT_ID,
|
||||
quantity: 2,
|
||||
slotId: SLOT_ID,
|
||||
addedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
if (withSecondLine) {
|
||||
lines.push({
|
||||
id: 2,
|
||||
skuId: SECOND_SKU_ID,
|
||||
quantity: 1,
|
||||
slotId: SLOT_ID,
|
||||
addedAt: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
await StorageServiceCasual.setItem('cart_items', JSON.stringify(lines))
|
||||
|
||||
renderWithProviders(<CartPage />)
|
||||
await waitFor(() => expect(screen.getByText('Chicken Breast 500 g')).toBeVisible())
|
||||
|
|
@ -81,9 +94,9 @@ async function mountCart(coupons: unknown[]) {
|
|||
async function selectCoupon() {
|
||||
fireEvent.press(screen.getByText('Select a coupon'))
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId(`undefined-option-${COUPON_ID}`)).toBeVisible()
|
||||
expect(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`)).toBeVisible()
|
||||
)
|
||||
fireEvent.press(screen.getByTestId(`undefined-option-${COUPON_ID}`))
|
||||
fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`))
|
||||
}
|
||||
|
||||
describe('Cart coupon application', () => {
|
||||
|
|
@ -187,12 +200,123 @@ describe('Cart coupon application', () => {
|
|||
expect(screen.getAllByText(/Min order ₹1000/).length).toBeGreaterThan(0)
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByTestId(`undefined-option-${COUPON_ID}`))
|
||||
fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}`))
|
||||
|
||||
expect(screen.queryByText('Product Discount')).toBeNull()
|
||||
expect(screen.queryByText('Coupon Applied')).toBeNull()
|
||||
})
|
||||
|
||||
it('expands a product-specific coupon to list the products it applies to', async () => {
|
||||
// Product 2 = Chicken Breast 500 g, product 4 = Mutton (both in the fixture
|
||||
// catalog, neither needs to be in the cart).
|
||||
await mountCart([coupon({ discountPercent: '10', skuIds: [2, 4] })])
|
||||
|
||||
fireEvent.press(screen.getByText('Select a coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Applies to 2 products')).toBeVisible()
|
||||
)
|
||||
// Collapsed by default.
|
||||
expect(screen.queryByText('Mutton')).toBeNull()
|
||||
|
||||
fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`))
|
||||
|
||||
expect(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).toBeVisible()
|
||||
expect(screen.getByText('Mutton')).toBeVisible()
|
||||
// Product 2 is already rendered by the cart line above, so count the occurrences.
|
||||
expect(screen.getAllByText('Chicken Breast 500 g').length).toBeGreaterThan(1)
|
||||
|
||||
// Expanding must not select the coupon (the selected-coupon chip appears only
|
||||
// when it is actually applied).
|
||||
expect(screen.queryByTestId('coupon-chip-SAVE10')).toBeNull()
|
||||
|
||||
// Pressing the trigger again collapses it.
|
||||
fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`))
|
||||
expect(screen.queryByText('Mutton')).toBeNull()
|
||||
})
|
||||
|
||||
it('collapses the previously expanded coupon and keeps unresolved targets visible', async () => {
|
||||
await mountCart([
|
||||
coupon({ id: COUPON_ID, discountPercent: '10', skuIds: [2] }),
|
||||
// 999999 is not in the catalog (e.g. a suspended SKU): it still gets a row.
|
||||
coupon({ id: 78, couponCode: 'MUTTON20', discountPercent: '20', skuIds: [999999] }),
|
||||
])
|
||||
|
||||
fireEvent.press(screen.getByText('Select a coupon'))
|
||||
|
||||
// One product each, so both triggers read "1 product".
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText('Applies to 1 product').length).toBe(2)
|
||||
)
|
||||
|
||||
fireEvent.press(screen.getByTestId(`coupon-dropdown-option-${COUPON_ID}-detail`))
|
||||
expect(screen.getAllByText('Chicken Breast 500 g').length).toBeGreaterThan(1)
|
||||
|
||||
// Opening the second coupon's list closes the first one.
|
||||
fireEvent.press(screen.getByTestId('coupon-dropdown-option-78-detail'))
|
||||
expect(screen.getByText('Product unavailable · #999999')).toBeVisible()
|
||||
expect(screen.queryByTestId(`coupon-dropdown-option-${COUPON_ID}-detail-list`)).toBeNull()
|
||||
})
|
||||
|
||||
it('measures minOrder on the coupon-targeted items, not the whole cart', async () => {
|
||||
// Cart = 430 (2 x 215) + 839 (1 x Mutton) = 1269. The coupon only targets the
|
||||
// 430 line and needs 500: measured against the whole cart it would look
|
||||
// eligible, which is exactly what the backend refuses at placeOrder.
|
||||
await mountCart([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID], minOrder: '500' })], true)
|
||||
|
||||
fireEvent.press(screen.getByText('Select a coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText(/Add ₹70 more to use this coupon/).length).toBeGreaterThan(0)
|
||||
)
|
||||
})
|
||||
|
||||
it('reports missing targets ahead of minOrder', async () => {
|
||||
// Target set matches nothing in the cart and minOrder is above the whole cart:
|
||||
// "no applicable items" is the truthful reason, not "add ₹N more".
|
||||
await mountCart([coupon({ discountPercent: '10', skuIds: [999999], minOrder: '2000' })], true)
|
||||
|
||||
fireEvent.press(screen.getByText('Select a coupon'))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText(/No applicable items in your cart/).length).toBeGreaterThan(0)
|
||||
)
|
||||
expect(screen.queryByText(/Add ₹/)).toBeNull()
|
||||
})
|
||||
|
||||
it('shows a per-product breakdown for a product-specific coupon', async () => {
|
||||
// 2 x 215 (targeted) + 1 x 839 (Mutton, not targeted): the coupon is 10% of the
|
||||
// 430 targeted line only, so its whole discount lands on product 2.
|
||||
await mountCart([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID] })], true)
|
||||
|
||||
await selectCoupon()
|
||||
// The bill line for the coupon: 10% of 430.
|
||||
expect(screen.getByText('-₹43')).toBeVisible()
|
||||
|
||||
fireEvent.press(screen.getByTestId(`coupon-breakdown-${COUPON_ID}`))
|
||||
|
||||
expect(screen.getByTestId('coupon-breakdown-dialog')).toBeVisible()
|
||||
expect(screen.getByText('Product discount')).toBeVisible()
|
||||
// Only the targeted product gets a row…
|
||||
expect(screen.getByTestId(`coupon-breakdown-row-${PRODUCT_ID}`)).toBeVisible()
|
||||
expect(screen.queryByTestId(`coupon-breakdown-row-${SECOND_SKU_ID}`)).toBeNull()
|
||||
// …and its share is the coupon's whole discount, shown twice: the row and the
|
||||
// "total from this coupon" line below it.
|
||||
expect(screen.getAllByText('−₹43').length).toBe(2)
|
||||
|
||||
fireEvent.press(screen.getByText('Close'))
|
||||
expect(screen.queryByTestId('coupon-breakdown-dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('offers no breakdown for a coupon that applies to the whole cart', async () => {
|
||||
await mountCart([coupon({ discountPercent: '10' })], true)
|
||||
|
||||
await selectCoupon()
|
||||
|
||||
expect(screen.getByTestId(`coupon-chip-SAVE10`)).toBeVisible()
|
||||
expect(screen.queryByTestId(`coupon-breakdown-${COUPON_ID}`)).toBeNull()
|
||||
})
|
||||
|
||||
it('hides a coupon that has hit its per-user usage limit', async () => {
|
||||
await mountCart([
|
||||
coupon({ discountPercent: '10', maxLimitForUser: 1, usages: [{ id: 1 }] }),
|
||||
|
|
|
|||
|
|
@ -187,6 +187,46 @@ describe('Checkout coupon discount calculation', () => {
|
|||
expect(screen.getByText('Free')).toBeVisible()
|
||||
})
|
||||
|
||||
it('does not apply or send a coupon whose targets are gone from the order', async () => {
|
||||
// Picked in the cart (?coupons=77) but its target SKU is not in this order:
|
||||
// the old code showed it as applied and still sent the id, which placeOrder
|
||||
// rejects. It is now shown as not applied, with the reason, and dropped.
|
||||
const api = await mountCheckout([coupon({ discountPercent: '10', skuIds: [999999] })])
|
||||
|
||||
expect(screen.queryByText('Product Discount')).toBeNull()
|
||||
expect(screen.getByText('Not applied')).toBeVisible()
|
||||
expect(screen.getByText('No applicable items in your cart')).toBeVisible()
|
||||
expect(screen.getAllByText(`₹${TOTAL}`).length).toBeGreaterThan(0)
|
||||
|
||||
fireEvent.press(screen.getByTestId('place-order-button'))
|
||||
|
||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder'))
|
||||
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({
|
||||
couponIds: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('shows the per-product split for an applied product-specific coupon', async () => {
|
||||
// 2 x 215, coupon targets product 2 only: the whole 10% (43) lands on it.
|
||||
await mountCheckout([coupon({ discountPercent: '10', skuIds: [PRODUCT_ID] })])
|
||||
|
||||
expect(screen.getByText('-₹43')).toBeVisible()
|
||||
// The "i" only exists for product-specific coupons.
|
||||
fireEvent.press(screen.getByTestId(`coupon-breakdown-${COUPON_ID}`))
|
||||
|
||||
expect(screen.getByTestId('coupon-breakdown-dialog')).toBeVisible()
|
||||
expect(screen.getByTestId(`coupon-breakdown-row-${PRODUCT_ID}`)).toBeVisible()
|
||||
// Row plus the "Total from this coupon" line.
|
||||
expect(screen.getAllByText('−₹43').length).toBe(2)
|
||||
})
|
||||
|
||||
it('offers no per-product split for a whole-cart coupon', async () => {
|
||||
await mountCheckout([coupon({ discountPercent: '10' })])
|
||||
|
||||
expect(screen.getByText('-₹43')).toBeVisible()
|
||||
expect(screen.queryByTestId(`coupon-breakdown-${COUPON_ID}`)).toBeNull()
|
||||
})
|
||||
|
||||
it('sends the selected coupon id with the order', async () => {
|
||||
const api = await mountCheckout([coupon({ discountPercent: '10' })])
|
||||
|
||||
|
|
|
|||
254
change-log.txt
254
change-log.txt
|
|
@ -5249,3 +5249,257 @@ user-ui
|
|||
* temp local D1 delta (outside repo): rebuild coupons + coupon_usage +
|
||||
coupon_applicable_users + order_status to drop the NOT NULL.
|
||||
No tests run; migrations not run.
|
||||
|
||||
2026-10-17 09:58:20 user-ui: "Applies to N products" inline expansion in the cart's coupon dropdown.
|
||||
|
||||
User: "I want a clickable 'applies to n products' for product specific coupons ... expand a
|
||||
coupon's view and show the products list. I don't want to embed one dialog in another."
|
||||
Decisions: show DISTINCT PRODUCT NAMES; the product list has its OWN inner scroll.
|
||||
|
||||
packages/ui/src/components/bottom-dropdown.tsx
|
||||
+ DropdownOption.detail?: { label: string; render: () => React.ReactNode } - an optional
|
||||
expander under an option row. The dropdown owns the trigger + open/closed state and wraps
|
||||
render() in a bounded ScrollView (max-h-60, nestedScrollEnabled); the caller owns the content.
|
||||
+ useState expandedValue (one open at a time; toggling another collapses the previous).
|
||||
+ row is now wrapped in a View so text/trigger/list are siblings - the trigger is NOT nested
|
||||
inside the option TouchableOpacity, so expanding can never toggle or close the selection.
|
||||
+ reset expandedValue in handleDone and the onClose handler, next to setSearchQuery('').
|
||||
+ testIDs `${testID}-option-${value}-detail` / `-detail-list`, matching the existing convention.
|
||||
No behaviour change for the ~15 existing BottomDropdown consumers (detail is optional).
|
||||
|
||||
apps/user-ui/components/cart-page.tsx
|
||||
+ buildCouponTargetRows(skuIds, productsById) - dedupes by product NAME and emits one row per
|
||||
distinct name; targets whose SKU is not in the catalog (suspended/deleted SKUs are filtered
|
||||
out of productsById) each get an "unavailable" row so the count never silently shrinks.
|
||||
+ CouponTargetRows({ rows }) - presentational: 32px image, name, unit notation, or the muted
|
||||
"Product unavailable - #<skuId>" fallback.
|
||||
~ dropdownData: for every coupon with targets (eligible AND disabled), one rows array is built
|
||||
once and used for BOTH the label ("Applies to N products", N = rows.length) and the content,
|
||||
so the number always matches the rows rendered.
|
||||
+ testID="coupon-dropdown" on the coupon dropdown.
|
||||
testID consequence: the dropdown had no testID, so options were reachable as
|
||||
`undefined-option-<id>`; they are now `coupon-dropdown-option-<id>` - 3 references updated in
|
||||
apps/user-ui/tests/screens/cart-coupons.test.tsx + a new expander test case.
|
||||
|
||||
Not done (offered, not requested): the same expander in the cart's "Applied Coupons" dialog; an
|
||||
"In cart" chip on the rows.
|
||||
|
||||
2026-10-17 10:12:47 user-ui: "Applies to N products" expander - implementation notes + a pre-existing test staleness.
|
||||
|
||||
Implemented as planned (see the 09:58:20 entry). Extra detail worth recording:
|
||||
* cart-page.tsx: buildCouponTargetRows() returns the rows ONCE per coupon inside the dropdownData
|
||||
memo; the same array drives both the trigger label and the rendered list, so the count can never
|
||||
disagree with what is shown. Depends on productsById (added to the memo deps).
|
||||
* The expander is attached to eligible AND disabled coupons (a disabled coupon is exactly where
|
||||
"which products does it want" matters). Covered by the new second test case.
|
||||
* Row styling: 32px image, name, unit notation, `last:border-b-0` (twrnc `last:` variants are
|
||||
already used elsewhere in the repo). Inner scroll container is the dropdown's
|
||||
`max-h-60` + `nestedScrollEnabled` ScrollView - same pattern as its own option list (max-h-80).
|
||||
|
||||
Typecheck (not tests): apps/user-ui, apps/admin-ui, apps/web-ui, apps/fallback-ui all clean.
|
||||
Tests deliberately NOT run (AGENTS: no suite runs unless asked).
|
||||
|
||||
PRE-EXISTING FINDING (untouched by this change): apps/user-ui/tests/screens/cart-coupons.test.tsx
|
||||
asserts the text 'Coupon Applied' at lines 123, 177, 193 and 268, but no cart-page code renders it -
|
||||
`git grep 'Coupon Applied'` only matches the order-detail screens (user-ui/app/(drawer)/(tabs)/me/
|
||||
my-orders/[id].tsx, web-ui, admin-web). Line 123 is a getByText, so that test can only pass if the
|
||||
string is rendered somewhere I have not found; the three queryByText lines pass vacuously. My own
|
||||
new test therefore asserts the selected-coupon CHIP (coupon-chip-SAVE10) instead of that string.
|
||||
|
||||
2026-10-17 10:31:02 common-ui: BottomDropdown's option list uses the available height (up to ~80% of the screen).
|
||||
|
||||
Feedback: "the coupons bottom dialog is taking only upto 50% height and enabling scroll. I want it to
|
||||
take as much as 80% if needed and then enable scroll".
|
||||
|
||||
Cause: the option list inside the dropdown's BottomDialog was capped with `tw`max-h-80`` (320px).
|
||||
BottomDialog is content-sized (auto height, BottomDialog keeps its 85% backstop), so that cap is
|
||||
what set the dialog's height: 320 + the dialog chrome (handle, title, search field, Done row, its
|
||||
own scroll-content paddingBottom ~260px) => the dialog stopped at roughly half the screen and the
|
||||
320px list started scrolling.
|
||||
|
||||
packages/ui/src/components/bottom-dropdown.tsx
|
||||
+ SCREEN_HEIGHT (Dimensions.get('window').height) and
|
||||
OPTION_LIST_MAX_HEIGHT = max(200, round(SCREEN_HEIGHT * 0.8) - 260) - i.e. "leave ~260px for the
|
||||
chrome, hand the rest of the 80% budget to the list", floored so tiny screens still get a usable
|
||||
window. On a 932pt screen: 486px list => dialog ~739px (79%); 667pt: 274px => ~527px (79%);
|
||||
568pt: 200px => ~453px (80%).
|
||||
~ the option list ScrollView: `tw`max-h-80`` -> style={{ maxHeight: OPTION_LIST_MAX_HEIGHT }} and
|
||||
gained `nestedScrollEnabled` (it scrolls inside the dialog's own ScrollView on Android).
|
||||
~ short lists are unaffected: the dialog stays content-sized (a 2-coupon list is still a short
|
||||
sheet), which is the "as much as 80% IF NEEDED" part.
|
||||
Untouched: BottomDialog's 0.85*SCREEN_HEIGHT cap stays as the backstop, and no shared dialog
|
||||
default changed (setting it to 0.8 globally would push the cart sheets - 0.8*S content + chrome -
|
||||
~65px past their ceiling and make their pinned footer draggable). The Done row stays pinned below
|
||||
the list, matching the pinned-action-row preference from the cart sheets.
|
||||
|
||||
2026-10-17 10:52:36 user-ui: the cart + Add-to-Cart sheets now grow with their content up to ~80% instead of always being 80%.
|
||||
|
||||
Request: "I want the same behaviour for the expanded form of the floating cart bar and the add to
|
||||
cart dialog too" - i.e. the dropdown change: as tall as the content needs, up to ~80%, and only then
|
||||
scroll (footer/action row staying pinned).
|
||||
|
||||
Both sheets had a DEFINITE height (screenHeight * 0.8), taken from the earlier "pinned footer" work:
|
||||
the list was `flex-1` and that only works inside a definite height, because `flex-1` is
|
||||
`flexBasis: 0%` - inside an auto-height parent it contributes 0 to the parent's size and collapses.
|
||||
So the sheet was always 80% tall, mostly empty for a 1-2 item cart.
|
||||
|
||||
The fix is flexBasis: the list becomes `shrink` (flexShrink: 1, flexBasis AUTO) instead of `flex-1`,
|
||||
and the sheet becomes content-sized with a max:
|
||||
* short cart -> the list's natural (content) height is what sizes the sheet -> short sheet
|
||||
* long cart -> the sheet hits its maxHeight, the negative free space goes to the only
|
||||
shrinkable child (the list; header/progress/footer keep RN's default flexShrink 0)
|
||||
-> the list gets exactly maxHeight - header - footer and scrolls; footer pinned
|
||||
Cap: screenHeight * 0.8 minus 70px reserved for BottomDialog's own chrome (handle 25 + its scroll
|
||||
content paddingBottom 40 iOS / 20 Android, worst case 40 + margin) so the dialog itself never
|
||||
scrolls and the pinned row cannot be dragged - the same chrome-reservation approach as the
|
||||
dropdown list cap (10:31:02).
|
||||
|
||||
apps/user-ui/components/floating-cart-bar.tsx
|
||||
~ CART_SHEET_HEIGHT = screenHeight * 0.8 -> CART_SHEET_MAX_HEIGHT = round(screenHeight * 0.8) - 70
|
||||
(comment rewritten: max, why not flex-1)
|
||||
~ sheet View: style={{ height: ... }} -> style={{ maxHeight: ... }}
|
||||
~ items list ScrollView: tw`flex-1` -> tw`shrink`
|
||||
apps/user-ui/src/components/AddToCartDialog.tsx
|
||||
~ SHEET_HEIGHT = Dimensions.get('window').height * 0.8 -> SHEET_MAX_HEIGHT (same formula/comment)
|
||||
~ sheet View: [tw`p-6`, { height: SHEET_HEIGHT }] -> [tw`p-6`, { maxHeight: SHEET_MAX_HEIGHT }]
|
||||
~ slot list ScrollView: tw`flex-1` -> tw`shrink`
|
||||
Untouched: BottomDialog's 0.85 cap (backstop), everything else in both sheets.
|
||||
|
||||
2026-10-17 11:04:58 CORRECTION to 10:52:36: the lists use an explicit flex basis/shrink, not tw`shrink`.
|
||||
|
||||
I first wrote `tw`shrink`` for the two lists. twrnc resolves a bare `shrink` through the theme's
|
||||
flexShrink.DEFAULT (ClassParser -> flexGrowShrink('Shrink', '', theme.flexShrink)); if that theme
|
||||
entry is missing, `Number(undefined ?? '')` is 0, i.e. the class would silently mean `shrink-0`
|
||||
and the list would stop shrinking - the sheet would hit its max height and the list would overflow
|
||||
instead of scrolling. Not worth the dependency, so both now say it outright:
|
||||
|
||||
<ScrollView style={{ flexBasis: 'auto', flexShrink: 1 }} ...>
|
||||
|
||||
(flexBasis 'auto' is RN's default, written out because it is the whole point of the fix: flex-1's
|
||||
`0%` basis is why the list used to collapse in an auto-height parent.)
|
||||
Verified statically in node_modules/twrnc/dist/esm/resolve/flex.js: `flex-1` -> {flexGrow: 1,
|
||||
flexBasis: '0%'} (no flexShrink), which is exactly the collapse the earlier sheet work hit.
|
||||
apps/user-ui typechecks clean.
|
||||
|
||||
2026-10-17 12:20:41 shared + user-ui: one local coupon-eligibility rule set for cart and checkout.
|
||||
|
||||
Context (user): "previously our api endpoint returned only eligible coupons. On every product change
|
||||
we needed to call backend because eligibility changed. Now that we return all eligible ones. We don't
|
||||
need to keep calling again. Just locally compute and enable/disable coupons."
|
||||
|
||||
Verified before changing anything: the endpoint already returns every coupon the customer may see
|
||||
(apps/backend/src/trpc/apis/user-apis/apis/coupon.ts:36-64 - its own comment says region / first-order
|
||||
/ usage / min-order ineligibility is deliberately NOT filtered, "the client shows those coupons
|
||||
disabled with a reason"), both readers send only { regionId } (cart-page.tsx:334,
|
||||
checkout-page.tsx:168), so no cart change ever refetches them; the only invalidation is after
|
||||
redeeming a code (me/coupons/index.tsx:140). So no backend change is needed - the gap was that the
|
||||
LOCAL rules were duplicated and incomplete on checkout.
|
||||
|
||||
packages/shared/cart-pricing.ts
|
||||
+ CouponEligibilityFields / CouponEligibilityContext / CouponEligibility +
|
||||
evaluateCouponEligibility(coupon, { cartLines, regionId, isFirstOrder })
|
||||
Rules in the server's order (validateAndGetCoupons): region -> first-order-only ->
|
||||
targeted-with-no-eligible-line -> minOrder vs the ELIGIBLE subtotal. Targeting is checked BEFORE
|
||||
minOrder on purpose: with no eligible line the subtotal is 0 and "Add Rs X more" would be a lie.
|
||||
apps/user-ui/components/cart-page.tsx
|
||||
~ eligibleCoupons now calls the shared resolver (same strings as before); baseTotalPrice memo,
|
||||
which existed only for the old whole-cart minOrder check, is deleted.
|
||||
BEHAVIOUR CHANGE (agreed): minOrder is measured against the eligible (targeted) subtotal, not the
|
||||
whole cart, so the cart now agrees with the backend for product-specific coupons.
|
||||
apps/user-ui/components/checkout-page.tsx
|
||||
+ cartLines memo MOVED above the coupon block (the resolver needs it; same move cart-page made).
|
||||
~ eligibility mapped through the shared resolver: adds the region, first-order and product-target
|
||||
checks the checkout page was missing, and drops its ad-hoc 'Usage limit exceeded' filter (the
|
||||
server never returns used-up coupons).
|
||||
+ dropped coupons are no longer silent: they are listed under the applied ones with their reason.
|
||||
~ selectedCouponIds passed to PaymentAndOrderComponent is now the LOCALLY ELIGIBLE set
|
||||
(selectedCoupons.map(c => c.id)) instead of the raw URL list, so the ids sent to placeOrder match
|
||||
the discount shown on screen.
|
||||
|
||||
2026-10-17 12:41:09 Correction/extension to 12:20:41 - the resolver also carries the usage limit.
|
||||
|
||||
The checkout test "Usage-limit coupons are filtered out of the eligible list entirely" pins that a
|
||||
coupon with maxLimitForUser reached is not applied. The endpoint already filters those out, but the
|
||||
client check is worth keeping: a coupon used within the session can still sit in the CACHED list, and
|
||||
without the local rule the customer would only find out at placeOrder ("Coupon usage limit exceeded").
|
||||
|
||||
packages/shared/cart-pricing.ts
|
||||
+ CouponEligibilityFields.maxLimitForUser / usages, and a 'Usage limit exceeded' rule placed FIRST
|
||||
(the backend's order in validateAndGetCoupons is usage-limit -> region -> first-order -> targeting
|
||||
-> minOrder).
|
||||
apps/user-ui/components/{cart-page,checkout-page}.tsx: pass maxLimitForUser/usages through.
|
||||
|
||||
Tests (written, NOT run - no suite runs unless asked):
|
||||
apps/user-ui/tests/screens/cart-coupons.test.tsx
|
||||
~ mountCart(coupons, withSecondLine?) - can seed 2 x 215 + 1 x 839 now
|
||||
+ 'measures minOrder on the coupon-targeted items, not the whole cart': targets only the 430
|
||||
line, minOrder 500 => "Add Rs 70 more" (against the whole cart it would look eligible)
|
||||
+ 'reports missing targets ahead of minOrder': target 999999 + minOrder 2000 => "No applicable
|
||||
items in your cart", not "Add Rs N more"
|
||||
apps/user-ui/tests/screens/checkout-coupons.test.tsx
|
||||
+ 'does not apply or send a coupon whose targets are gone from the order': shown as "Not applied"
|
||||
with the reason, discount untouched, and couponIds: undefined in the placeOrder input.
|
||||
Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean.
|
||||
|
||||
2026-10-17 13:02:58 user-ui + shared: per-product discount breakdown for product-specific coupons in the bill.
|
||||
|
||||
Request: "in the billing section, if there is a product specific coupon applied, show an i symbol
|
||||
beside it. On clicking it, open a bottom dialog and then show the per product discount applied there."
|
||||
|
||||
The per-line split did not exist: runStack() computed a per-line `portion` but only kept it grouped
|
||||
into shareByGroup (sub-orders), which is what computeCartPricing needs. So:
|
||||
|
||||
packages/shared/cart-pricing.ts
|
||||
+ StackCouponResult.shareByLine (Map<line index, raw portion>) - additive, the existing consumer
|
||||
(computeCartPricing -> shareByGroup) is untouched.
|
||||
+ roundSharesOnto(rawShares, total) - extracted from computeCartPricing's inline
|
||||
scale/round/fold-drift block; computeCartPricing now calls it, same behaviour.
|
||||
+ computeCouponLineBreakdowns(lines, coupons): CouponLineBreakdown[] =
|
||||
{ couponId, discount, lines: [{ skuId, discount }] } - same sequential waterfall as
|
||||
computeCouponStack, and each coupon's per-line shares are reconciled onto its rounded discount,
|
||||
so the popup's rows sum exactly to the figure on the bill.
|
||||
apps/user-ui/components/cart-page.tsx
|
||||
+ state breakdownCouponId; memos couponBreakdowns (by coupon id), cartLineBySkuId, breakdownRows
|
||||
(only non-zero lines, biggest first).
|
||||
~ bill row: the coupon code keeps opening "Applied Coupons", and a SIBLING info-outline button
|
||||
(testID coupon-breakdown-<id>) is rendered only when applicableSkuIds.length > 0.
|
||||
+ BottomDialog (no nesting — a sibling dialog, like the others on this screen) with
|
||||
testID coupon-breakdown-dialog: one row per discounted product (image, name, qty x unit price,
|
||||
its share), a "Total from this coupon" line and a note that the rest of the cart is not
|
||||
discounted. Closes if the coupon stops being applied.
|
||||
|
||||
Maths verified by running the shared module directly (npx tsx, not the test suite):
|
||||
10% whole cart on 430+839 -> coupon 127, rows 43 + 84 = 127 OK
|
||||
10% targeted at sku 2 -> coupon 43, rows 43 OK (one row)
|
||||
10% then flat 50 -> 127 (43+84) and 50 (17+33) OK (waterfall preserved)
|
||||
10% whole + 20% on sku 4 -> 127 (43+84) and 151 (single row) OK
|
||||
maxValue 50 on 10% -> 50 (17+33) OK
|
||||
3 lines, 10% / 33% -> 30 / 99, rows sum OK (rounding drift folded into the largest share)
|
||||
Tests added (written, NOT run): cart-coupons.test.tsx - per-product breakdown opens with only the
|
||||
targeted product's row and a total matching the bill line; a whole-cart coupon shows no info button.
|
||||
Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean.
|
||||
|
||||
2026-10-17 13:21:33 user-ui: the per-product breakdown is now on checkout's coupon block too, and shared.
|
||||
|
||||
Request: "show in the coupon block too, if applied".
|
||||
|
||||
apps/user-ui/src/components/CouponBreakdownDialog.tsx (NEW)
|
||||
+ The dialog extracted from cart-page: props { coupon, breakdown, cartLines, onClose }, reads
|
||||
productsById from the store itself, and keeps the same testIDs (coupon-breakdown-dialog,
|
||||
coupon-breakdown-row-<skuId>). One implementation -> both screens' numbers and wording cannot
|
||||
drift. Its comment records that it must be opened from an inline row, never from inside another
|
||||
dialog (a BottomDialog is a native Modal; nesting is what we avoid elsewhere).
|
||||
apps/user-ui/components/cart-page.tsx
|
||||
~ the inline dialog (and its cartLineBySkuId / breakdownRows memos, now inside the component) is
|
||||
replaced by <CouponBreakdownDialog .../>; keeps breakdownCoupon/breakdown + couponBreakdowns.
|
||||
Deliberately NOT added inside the cart's "Applied Coupons" dialog: that is already a dialog, so an
|
||||
"i" there would mean nesting one BottomDialog in another.
|
||||
apps/user-ui/components/checkout-page.tsx
|
||||
+ couponBreakdowns memo (computeCouponLineBreakdowns over its own cartLines/selectedCoupons),
|
||||
breakdownCouponId state, and breakdownCoupon/breakdown lookups.
|
||||
+ the "i" (testID coupon-breakdown-<id>) beside each APPLIED coupon that has applicableSkuIds, in
|
||||
the same row as the code; the dropped ones keep their "Not applied" + reason row and get no "i".
|
||||
+ <CouponBreakdownDialog .../> next to the other dialogs.
|
||||
Tests (written, NOT run): checkout-coupons.test.tsx - the split opens for a product-specific applied
|
||||
coupon (row + total = the coupon's discount) and a whole-cart coupon shows no "i".
|
||||
Typecheck: user-ui, admin-ui, web-ui, fallback-ui, db_helper_sqlite, backend - all clean.
|
||||
|
|
|
|||
|
|
@ -128,11 +128,102 @@ interface StackLine extends CartLine {
|
|||
group: number
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- *
|
||||
* Local coupon eligibility
|
||||
*
|
||||
* The coupon endpoint hands the customer every coupon they may SEE (it only
|
||||
* drops expired / invalidated / used-up / other people's coupons); whether a
|
||||
* coupon applies to the CURRENT cart is decided locally, so a cart change never
|
||||
* costs a request. These rules are the local twin of the backend's
|
||||
* `validateAndGetCoupons` cart checks — keep them, and their wording, in step
|
||||
* with packages/db_helper_sqlite/src/user-apis/order.ts.
|
||||
* -------------------------------------------------------------------------- */
|
||||
|
||||
/** The coupon fields that decide whether it may be applied to a cart. */
|
||||
export interface CouponEligibilityFields {
|
||||
regionId?: number | null
|
||||
isFirstOrderOnly?: boolean | null
|
||||
minOrder?: string | number | null
|
||||
/** per-user spending limit, and how many times THIS user has already used it */
|
||||
maxLimitForUser?: number | null
|
||||
usages?: unknown[] | null
|
||||
/** targeted SKU ids; empty/null => the whole cart */
|
||||
applicableSkuIds?: number[] | null
|
||||
}
|
||||
|
||||
export interface CouponEligibilityContext {
|
||||
/** in-stock cart lines — exactly what the coupon would discount */
|
||||
cartLines: CartLine[]
|
||||
/** the region the cart is being built in */
|
||||
regionId: number | null
|
||||
/** whether the customer is still eligible for first-order-only coupons */
|
||||
isFirstOrder: boolean
|
||||
}
|
||||
|
||||
export interface CouponEligibility {
|
||||
isEligible: boolean
|
||||
/** Why it cannot be applied — the string the UI shows. Absent when eligible. */
|
||||
reason?: string
|
||||
/** Goods subtotal the coupon discounts (whole cart, or just its targeted lines). */
|
||||
eligibleSubtotal: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a coupon can be applied to this cart, and why not when it can't.
|
||||
* Rule order matches the backend: region, then first-order-only, then product
|
||||
* targeting, then minOrder — targeting BEFORE minOrder, because a coupon whose
|
||||
* targets are all missing has an eligible subtotal of 0 and "add ₹X more" would
|
||||
* be the wrong reason (the server reports "does not apply to any items").
|
||||
* minOrder is compared against the ELIGIBLE subtotal, exactly as the server does.
|
||||
*/
|
||||
export function evaluateCouponEligibility(
|
||||
coupon: CouponEligibilityFields,
|
||||
context: CouponEligibilityContext
|
||||
): CouponEligibility {
|
||||
const applicableSkuIds = Array.isArray(coupon.applicableSkuIds) ? coupon.applicableSkuIds : []
|
||||
const targets = applicableSkuIds.length > 0 ? applicableSkuIds : null
|
||||
const eligibleSubtotal = computeEligibleSubtotal(context.cartLines, {
|
||||
applicableSkuIds: targets,
|
||||
})
|
||||
|
||||
const fail = (reason: string): CouponEligibility => ({
|
||||
isEligible: false,
|
||||
reason,
|
||||
eligibleSubtotal,
|
||||
})
|
||||
|
||||
if (coupon.maxLimitForUser && (coupon.usages?.length ?? 0) >= coupon.maxLimitForUser) {
|
||||
return fail('Usage limit exceeded')
|
||||
}
|
||||
if (
|
||||
coupon.regionId != null &&
|
||||
context.regionId != null &&
|
||||
coupon.regionId !== context.regionId
|
||||
) {
|
||||
return fail('Not valid in your region')
|
||||
}
|
||||
if (coupon.isFirstOrderOnly && !context.isFirstOrder) {
|
||||
return fail('Valid on your first order only')
|
||||
}
|
||||
if (targets && eligibleSubtotal <= 0) {
|
||||
return fail('No applicable items in your cart')
|
||||
}
|
||||
|
||||
const minOrder = toNum(coupon.minOrder)
|
||||
if (minOrder > eligibleSubtotal) {
|
||||
return fail(`Add ₹${Math.ceil(minOrder - eligibleSubtotal)} more to use this coupon`)
|
||||
}
|
||||
|
||||
return { isEligible: true, eligibleSubtotal }
|
||||
}
|
||||
|
||||
interface StackCouponResult {
|
||||
couponId: number
|
||||
discount: number
|
||||
/** where this coupon's discount landed, keyed by the line's group (sub-order) */
|
||||
shareByGroup: Map<number, number>
|
||||
/** the same money, keyed by the index of the line it landed on */
|
||||
shareByLine: Map<number, number>
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -157,6 +248,7 @@ function runStack(
|
|||
const eligible = idx.reduce((sum, i) => sum + remaining[i], 0)
|
||||
let discount = 0
|
||||
const shareByGroup = new Map<number, number>()
|
||||
const shareByLine = new Map<number, number>()
|
||||
|
||||
if (eligible > 0) {
|
||||
const raw = computeCouponDiscount(eligible, coupon)
|
||||
|
|
@ -167,16 +259,85 @@ function runStack(
|
|||
remaining[i] = Math.max(0, remaining[i] - portion)
|
||||
const group = lines[i].group
|
||||
shareByGroup.set(group, (shareByGroup.get(group) ?? 0) + portion)
|
||||
shareByLine.set(i, (shareByLine.get(i) ?? 0) + portion)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
perCoupon.push({ couponId: coupon.id, discount, shareByGroup })
|
||||
perCoupon.push({ couponId: coupon.id, discount, shareByGroup, shareByLine })
|
||||
}
|
||||
|
||||
return { perCoupon, remaining }
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale raw proportional shares onto `total` whole rupees so they sum exactly:
|
||||
* round each share, then fold the 1-rupee drift into the largest one.
|
||||
*/
|
||||
function roundSharesOnto(rawShares: number[], total: number): number[] {
|
||||
const rawSum = rawShares.reduce((sum, v) => sum + v, 0)
|
||||
if (rawSum <= 0 || rawShares.length === 0) return rawShares.map(() => 0)
|
||||
|
||||
const scaled = rawShares.map((v) => (v * total) / rawSum)
|
||||
const rounded = scaled.map((v) => Math.round(v))
|
||||
const drift = total - rounded.reduce((sum, v) => sum + v, 0)
|
||||
|
||||
if (drift !== 0) {
|
||||
let maxI = 0
|
||||
for (let i = 1; i < scaled.length; i++) {
|
||||
if (scaled[i] > scaled[maxI]) maxI = i
|
||||
}
|
||||
rounded[maxI] += drift
|
||||
}
|
||||
|
||||
return rounded
|
||||
}
|
||||
|
||||
/** One cart line's share of a coupon's discount. */
|
||||
export interface CouponLineDiscount {
|
||||
skuId: number
|
||||
discount: number
|
||||
}
|
||||
|
||||
/** A coupon's discount split over the cart lines it landed on. */
|
||||
export interface CouponLineBreakdown {
|
||||
couponId: number
|
||||
/** the coupon's total discount — the figure the bill shows for it */
|
||||
discount: number
|
||||
/** per-line shares, reconciled so they sum exactly to `discount` */
|
||||
lines: CouponLineDiscount[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Where each applied coupon's discount went, per cart line — what the bill's
|
||||
* "applies to specific products" popup shows. Uses the same sequential waterfall
|
||||
* as `computeCouponStack`, so the total here always matches the coupon's line in
|
||||
* the bill, and the per-line shares are reconciled onto that total (whole rupees)
|
||||
* so the popup's rows add up exactly.
|
||||
*/
|
||||
export function computeCouponLineBreakdowns(
|
||||
lines: CartLine[],
|
||||
coupons: TargetedCoupon[]
|
||||
): CouponLineBreakdown[] {
|
||||
const grouped: StackLine[] = lines.map((line) => ({ ...line, group: 0 }))
|
||||
const { perCoupon } = runStack(grouped, coupons)
|
||||
|
||||
return perCoupon.map((entry) => {
|
||||
const indexes = [...entry.shareByLine.keys()].sort((a, b) => a - b)
|
||||
const rawShares = indexes.map((i) => entry.shareByLine.get(i) ?? 0)
|
||||
const rounded = roundSharesOnto(rawShares, entry.discount)
|
||||
|
||||
return {
|
||||
couponId: entry.couponId,
|
||||
discount: entry.discount,
|
||||
lines: indexes.map((i, position) => ({
|
||||
skuId: grouped[i].skuId,
|
||||
discount: rounded[position],
|
||||
})),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-coupon discount each coupon contributes when applied in the given order,
|
||||
* rounded to whole rupees, plus the total. This is the single source of truth the
|
||||
|
|
@ -249,21 +410,10 @@ export function computeCartPricing(params: {
|
|||
|
||||
const groups = [...coupon.shareByGroup.keys()].sort((a, b) => a - b)
|
||||
const rawShares = groups.map((g) => coupon.shareByGroup.get(g) ?? 0)
|
||||
const rawSum = rawShares.reduce((sum, v) => sum + v, 0)
|
||||
|
||||
// Scale the raw shares onto the rounded discount, round each sub-order share,
|
||||
// and fold the 1-rupee drift into the largest share so they sum exactly.
|
||||
const scaled =
|
||||
rawSum > 0 ? rawShares.map((v) => (v * coupon.discount) / rawSum) : rawShares
|
||||
const rounded = scaled.map((v) => Math.round(v))
|
||||
const drift = coupon.discount - rounded.reduce((sum, v) => sum + v, 0)
|
||||
if (drift !== 0 && rounded.length > 0) {
|
||||
let maxI = 0
|
||||
for (let i = 1; i < rounded.length; i++) {
|
||||
if (scaled[i] > scaled[maxI]) maxI = i
|
||||
}
|
||||
rounded[maxI] += drift
|
||||
}
|
||||
const rounded = roundSharesOnto(rawShares, coupon.discount)
|
||||
|
||||
groups.forEach((group, i) => {
|
||||
if (rounded[i] !== 0) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import React, { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { Text, View, TouchableOpacity, ScrollView, TextInput } from 'react-native';
|
||||
import { Text, View, TouchableOpacity, ScrollView, TextInput, Dimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { BottomDialog } from './dialog';
|
||||
import MyText from './text';
|
||||
|
|
@ -14,6 +14,19 @@ export interface DropdownOption extends BaseDropdownOption {
|
|||
disabled?: boolean;
|
||||
/** Optional second line shown under the label (e.g. why it is disabled). */
|
||||
note?: string;
|
||||
/**
|
||||
* Optional expander rendered under the option row — e.g. "Applies to 3 products"
|
||||
* on a product-restricted coupon. The dropdown owns the trigger and the
|
||||
* open/closed state (one option open at a time) and wraps `render()` in a bounded
|
||||
* scroll container; the caller owns the content. Deliberately NOT a nested
|
||||
* dialog: the expanded content lives inline, inside the option block.
|
||||
*/
|
||||
detail?: {
|
||||
/** Trigger text, e.g. "Applies to 3 products". */
|
||||
label: string;
|
||||
/** Content shown when expanded. */
|
||||
render: () => React.ReactNode;
|
||||
};
|
||||
}
|
||||
|
||||
interface BottomDropdownProps extends DropdownBaseProps<DropdownOption> {
|
||||
|
|
@ -30,6 +43,21 @@ interface BottomDropdownProps extends DropdownBaseProps<DropdownOption> {
|
|||
testID?: string;
|
||||
}
|
||||
|
||||
const SCREEN_HEIGHT = Dimensions.get('window').height;
|
||||
|
||||
/**
|
||||
* How tall the option list may grow before it starts scrolling.
|
||||
*
|
||||
* The dialog is content-sized (BottomDialog has an auto height with an 85%
|
||||
* backstop), so the list cap is what actually decides how tall the dropdown
|
||||
* dialog gets. This hands the list everything left of an 80%-of-screen budget
|
||||
* after the dialog's own chrome — handle, title, bottom padding, and (when
|
||||
* present) the search field and the Done row, ~260px on a phone — so a long
|
||||
* list (coupons, products, …) fills the sheet up to about 80% and only then
|
||||
* scrolls. Short lists are unaffected: the dialog stays content-sized.
|
||||
*/
|
||||
const OPTION_LIST_MAX_HEIGHT = Math.max(200, Math.round(SCREEN_HEIGHT * 0.8) - 260);
|
||||
|
||||
const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
||||
label,
|
||||
topLabel,
|
||||
|
|
@ -49,6 +77,8 @@ const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
|||
const { theme } = useTheme();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
// Which option's `detail` is expanded (one at a time).
|
||||
const [expandedValue, setExpandedValue] = useState<string | number | null>(null);
|
||||
const debounceTimeoutRef = useRef<number | null>(null);
|
||||
|
||||
// Debounced search function
|
||||
|
|
@ -107,6 +137,7 @@ const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
|||
const handleDone = () => {
|
||||
setIsOpen(false);
|
||||
setSearchQuery(''); // Clear search when done
|
||||
setExpandedValue(null); // Collapse any open detail
|
||||
if (debounceTimeoutRef.current) {
|
||||
clearTimeout(debounceTimeoutRef.current);
|
||||
debounceTimeoutRef.current = null;
|
||||
|
|
@ -174,6 +205,7 @@ const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
|||
<BottomDialog open={isOpen} onClose={() => {
|
||||
setIsOpen(false);
|
||||
setSearchQuery(''); // Clear search when closed
|
||||
setExpandedValue(null); // Collapse any open detail
|
||||
if (debounceTimeoutRef.current) {
|
||||
clearTimeout(debounceTimeoutRef.current);
|
||||
debounceTimeoutRef.current = null;
|
||||
|
|
@ -200,7 +232,10 @@ const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
|||
</View>
|
||||
)}
|
||||
|
||||
<ScrollView style={tw`max-h-80`}>
|
||||
<ScrollView
|
||||
style={{ maxHeight: OPTION_LIST_MAX_HEIGHT }}
|
||||
nestedScrollEnabled
|
||||
>
|
||||
{filteredOptions.length === 0 && searchQuery ? (
|
||||
<View style={tw`py-8 px-4 items-center`}>
|
||||
<Text style={tw`text-gray-500 text-center`}>
|
||||
|
|
@ -211,10 +246,11 @@ const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
|||
filteredOptions.map((option) => {
|
||||
const selected = isSelected(option.value);
|
||||
const isDisabled = option.disabled || disabled;
|
||||
const isDetailOpen = expandedValue === option.value;
|
||||
const [code, rest] = (option.label as string).split(' - ', 2);
|
||||
return (
|
||||
<View key={option.value}>
|
||||
<TouchableOpacity
|
||||
key={option.value}
|
||||
testID={`${testID}-option-${option.value}`}
|
||||
accessibilityLabel={`${testID}-option-${option.value}`}
|
||||
style={[
|
||||
|
|
@ -253,6 +289,45 @@ const BottomDropdown: React.FC<BottomDropdownProps> = ({
|
|||
<Ionicons name="checkmark" size={20} color={colors.brand500} />
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
|
||||
{/* Inline expander — a sibling of the row, so opening/closing it can
|
||||
never toggle or dismiss the selection. */}
|
||||
{!!option.detail && (
|
||||
<>
|
||||
<TouchableOpacity
|
||||
testID={`${testID}-option-${option.value}-detail`}
|
||||
accessibilityLabel={`${testID}-option-${option.value}-detail`}
|
||||
style={tw`mx-2 px-4 pb-2 -mt-1 flex-row items-center`}
|
||||
onPress={() => setExpandedValue(isDetailOpen ? null : option.value)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<Ionicons
|
||||
name={isDetailOpen ? 'chevron-up' : 'chevron-down'}
|
||||
size={13}
|
||||
color={colors.brand500}
|
||||
style={tw`mr-1`}
|
||||
/>
|
||||
<Text style={tw`text-xs font-medium text-brand500`}>
|
||||
{option.detail.label}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
{isDetailOpen && (
|
||||
<View style={tw`mx-2 mb-2 rounded-md border border-gray-100 bg-gray-50 overflow-hidden`}>
|
||||
<ScrollView
|
||||
testID={`${testID}-option-${option.value}-detail-list`}
|
||||
accessibilityLabel={`${testID}-option-${option.value}-detail-list`}
|
||||
style={tw`max-h-60`}
|
||||
nestedScrollEnabled
|
||||
showsVerticalScrollIndicator={true}
|
||||
>
|
||||
{option.detail.render()}
|
||||
</ScrollView>
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue