From 3f3c5e36477ec0862dc781e3867b4d687c35361c Mon Sep 17 00:00:00 2001 From: iFixKart Dev Date: Fri, 6 Nov 2026 14:21:09 +0530 Subject: [PATCH] feat(storefront): Add checkout promo code validation and discount calculations --- app/checkout/page.tsx | 127 +++++++++++++++++++++- components/pdp/ProductInteractiveGrid.tsx | 7 +- sections/CategoriesSection.tsx | 5 +- 3 files changed, 129 insertions(+), 10 deletions(-) diff --git a/app/checkout/page.tsx b/app/checkout/page.tsx index 2bf7fa0..93e0ba2 100644 --- a/app/checkout/page.tsx +++ b/app/checkout/page.tsx @@ -11,7 +11,7 @@ import Link from 'next/link'; import { useCartStore } from '@/store/cartStore'; import { useAuthStore } from '@/store/authStore'; import { formatCurrency, getImageUrl, parseMoney } from '@/lib/utils'; -import { setAccessToken } from '@/services/api/client'; +import { setAccessToken, apiFetch } from '@/services/api/client'; import { createCheckoutOrder, createCustomerAddress, @@ -49,6 +49,7 @@ import { Trash2, KeyRound, Sparkles, + Tag, } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; import { creditService, WalletSummary } from '@/services/api/creditService'; @@ -84,6 +85,13 @@ export default function CheckoutPage() { const [outOfStockVariantIds, setOutOfStockVariantIds] = useState>( new Set() ); + + // Promo code & coupon states + const [couponCodeInput, setCouponCodeInput] = useState(''); + const [appliedCoupon, setAppliedCoupon] = useState(null); + const [appliedCouponDiscount, setAppliedCouponDiscount] = useState(0); + const [couponApplying, setCouponApplying] = useState(false); + const [addressForm, setAddressForm] = useState({ address_type: 'SHIPPING', full_name: '', @@ -105,9 +113,24 @@ export default function CheckoutPage() { const baseDeliveryFee = deliverySettings ? deliverySettings.delivery_charge : 99.0; const shipping = subtotal > 0 ? (isFreeDelivery ? 0 : baseDeliveryFee) : 0; - const taxable_amount = subtotal / 1.18; - const tax = Math.round((subtotal - taxable_amount) * 100) / 100; - const grossTotal = Math.round(subtotal + shipping); + // Coupon discount deduction + let couponDiscount = 0; + if (appliedCoupon) { + if (appliedCoupon.discount_type === 'PERCENT') { + couponDiscount = (subtotal * Number(appliedCoupon.discount_value || 0)) / 100; + if (appliedCoupon.max_discount_cap) { + couponDiscount = Math.min(couponDiscount, Number(appliedCoupon.max_discount_cap)); + } + } else { + couponDiscount = Number(appliedCoupon.discount_value || 0); + } + } + couponDiscount = Math.min(subtotal, Math.max(0, couponDiscount)); + + const postDiscountSubtotal = Math.max(0, subtotal - couponDiscount); + const taxable_amount = postDiscountSubtotal / 1.18; + const tax = Math.round((postDiscountSubtotal - taxable_amount) * 100) / 100; + const grossTotal = Math.round(postDiscountSubtotal + shipping); // Store credits deduction calculation const availableCredits = wallet?.active_balance || 0; @@ -346,6 +369,48 @@ export default function CheckoutPage() { }); }; + const handleApplyCoupon = async () => { + const code = couponCodeInput.trim().toUpperCase(); + if (!code) { + toast.error('Please enter a coupon code'); + return; + } + setCouponApplying(true); + try { + await syncCartItems( + cart.map((item) => ({ + variant_id: item.selectedVariant.variant_id, + qty: item.quantity, + })) + ); + const res = await apiFetch('/api/v1/cart/coupon/apply', { + method: 'POST', + body: JSON.stringify({ coupon_code: code }), + }); + if (res && res.coupon) { + setAppliedCoupon(res.coupon); + setAppliedCouponDiscount(Number(res.discount || 0)); + toast.success(`Coupon ${code} applied successfully! Saved ₹${Number(res.discount || 0).toFixed(0)}`); + } else { + toast.error('Could not apply coupon'); + } + } catch (err: any) { + toast.error(err.message || 'Invalid or ineligible coupon code'); + } finally { + setCouponApplying(false); + } + }; + + const handleRemoveCoupon = async () => { + setAppliedCoupon(null); + setAppliedCouponDiscount(0); + setCouponCodeInput(''); + try { + await apiFetch('/api/v1/cart/coupon/remove', { method: 'DELETE' }); + } catch {} + toast.info('Coupon removed'); + }; + const handlePlaceOrder = async (e: React.FormEvent) => { e.preventDefault(); setErrorMsg(null); @@ -382,6 +447,7 @@ export default function CheckoutPage() { address_id: selectedAddressId, payment_method: paymentMethod, use_wallet_credits: useWalletCredits, + coupon_code: appliedCoupon?.code || undefined, }); const scriptLoaded = await loadRazorpayScript(); @@ -1118,6 +1184,16 @@ export default function CheckoutPage() { + {/* Coupon Discount Row */} + {appliedCoupon && couponDiscount > 0 && ( +
+ + Coupon ({appliedCoupon.code}) + + -{formatCurrency(couponDiscount)} +
+ )} + {/* Store Credits Applied Row */} {useWalletCredits && appliedCredits > 0 && (
@@ -1129,6 +1205,49 @@ export default function CheckoutPage() { )}
+ {/* Promo Code Input or Applied Badge */} +
+ {!appliedCoupon ? ( +
+
+ + setCouponCodeInput(e.target.value.toUpperCase())} + className="w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-3 py-2 outline-none text-[12px] font-mono uppercase focus:border-primary focus:ring-1 focus:ring-primary/20" + /> +
+ +
+ ) : ( +
+
+ + {appliedCoupon.code} + + (-{formatCurrency(couponDiscount)}) + +
+ +
+ )} +
+ {/* Store Credit Redemption Card */} {Boolean(wallet && wallet.active_balance > 0) && (
diff --git a/components/pdp/ProductInteractiveGrid.tsx b/components/pdp/ProductInteractiveGrid.tsx index 885ed3c..c52d381 100644 --- a/components/pdp/ProductInteractiveGrid.tsx +++ b/components/pdp/ProductInteractiveGrid.tsx @@ -575,7 +575,8 @@ export const ProductInteractiveGrid: React.FC = ({ values: Array.from(d.values), })); - if (dims.length > 0) { + const hasMultiValuedDim = dims.some((d) => d.values.length > 1); + if (hasMultiValuedDim || (dims.length > 0 && product.variants.length <= 1)) { return dims.map((dim) => { const activeAttr = (selectedVariant?.attributes || []).find((a: any) => a.attribute_code === dim.code); const currentVal = activeAttr?.attribute_value || selections[dim.code] || ''; @@ -646,7 +647,7 @@ export const ProductInteractiveGrid: React.FC = ({ return (
{product.variants.map((v: any, idx: number) => { @@ -667,7 +668,7 @@ export const ProductInteractiveGrid: React.FC = ({ : 'border-gray-200 bg-white text-gray-700 hover:border-gray-300' }`} > - {v.label || v.sku || `Variant ${idx + 1}`} + {v.name || v.label || v.sku || `Variant ${idx + 1}`} ); })} diff --git a/sections/CategoriesSection.tsx b/sections/CategoriesSection.tsx index 00b9b1f..d3b9b6d 100644 --- a/sections/CategoriesSection.tsx +++ b/sections/CategoriesSection.tsx @@ -286,9 +286,8 @@ export const CategoriesSection: React.FC = ({ }} > {categories.map((cat) => { - const primarySrc = getImageUrl( - cat.image_url || cat.image || cat.icon_url - ); + const rawCatImg = cat.image_url || cat.image || cat.icon_url; + const primarySrc = rawCatImg ? getImageUrl(rawCatImg) : ''; const fallbackSrc = productThumbs[cat.category_id] || productThumbs[cat.id] ||