diff --git a/app/checkout/page.tsx b/app/checkout/page.tsx index 93e0ba2..6973af9 100644 --- a/app/checkout/page.tsx +++ b/app/checkout/page.tsx @@ -20,8 +20,10 @@ import { initiatePayment, cancelPayment, verifyPayment, + fetchAvailableCoupons, type CustomerAddress, type CheckoutCreateResponse, + type AvailableCoupon, } from '@/services/api/checkoutService'; import { deliveryService, DeliverySettings } from '@/services/api/deliveryService'; import GoogleAuthModal from '@/components/auth/GoogleAuthModal'; @@ -91,6 +93,8 @@ export default function CheckoutPage() { const [appliedCoupon, setAppliedCoupon] = useState(null); const [appliedCouponDiscount, setAppliedCouponDiscount] = useState(0); const [couponApplying, setCouponApplying] = useState(false); + const [availableCoupons, setAvailableCoupons] = useState([]); + const [loadingCoupons, setLoadingCoupons] = useState(false); const [addressForm, setAddressForm] = useState({ address_type: 'SHIPPING', @@ -116,7 +120,9 @@ export default function CheckoutPage() { // Coupon discount deduction let couponDiscount = 0; if (appliedCoupon) { - if (appliedCoupon.discount_type === 'PERCENT') { + if (appliedCoupon.discount_amount !== undefined && appliedCoupon.discount_amount !== null) { + couponDiscount = Number(appliedCoupon.discount_amount); + } else if (appliedCoupon.discount_type === 'PERCENT' || appliedCoupon.discount_type === 'PERCENTAGE') { couponDiscount = (subtotal * Number(appliedCoupon.discount_value || 0)) / 100; if (appliedCoupon.max_discount_cap) { couponDiscount = Math.min(couponDiscount, Number(appliedCoupon.max_discount_cap)); @@ -125,6 +131,9 @@ export default function CheckoutPage() { couponDiscount = Number(appliedCoupon.discount_value || 0); } } + if (appliedCouponDiscount > 0 && couponDiscount === 0) { + couponDiscount = appliedCouponDiscount; + } couponDiscount = Math.min(subtotal, Math.max(0, couponDiscount)); const postDiscountSubtotal = Math.max(0, subtotal - couponDiscount); @@ -170,6 +179,16 @@ export default function CheckoutPage() { creditService.getMyWallet().then(setWallet).catch(() => null); }, [isAuthenticated, authReady]); + useEffect(() => { + setLoadingCoupons(true); + fetchAvailableCoupons() + .then((coupons) => { + setAvailableCoupons(coupons || []); + }) + .catch(() => {}) + .finally(() => setLoadingCoupons(false)); + }, [isAuthenticated, authReady]); + const syncAndValidateCart = async () => { if (!isAuthenticated) return; setErrorMsg(null); @@ -369,12 +388,13 @@ export default function CheckoutPage() { }); }; - const handleApplyCoupon = async () => { - const code = couponCodeInput.trim().toUpperCase(); + const handleApplyCoupon = async (customCode?: string) => { + const code = (customCode || couponCodeInput).trim().toUpperCase(); if (!code) { toast.error('Please enter a coupon code'); return; } + setCouponCodeInput(code); setCouponApplying(true); try { await syncCartItems( @@ -385,12 +405,12 @@ export default function CheckoutPage() { ); const res = await apiFetch('/api/v1/cart/coupon/apply', { method: 'POST', - body: JSON.stringify({ coupon_code: code }), + body: JSON.stringify({ code, 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)}`); + setAppliedCouponDiscount(Number(res.discount || res.discount_amount || 0)); + toast.success(`Coupon ${code} applied successfully! Saved ₹${Number(res.discount || res.discount_amount || 0).toFixed(0)}`); } else { toast.error('Could not apply coupon'); } @@ -1206,34 +1226,105 @@ 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" - /> + <> +
+
+ + 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" + /> +
+
- -
+ + {/* Available Promotional Coupons List */} + {availableCoupons.length > 0 && ( +
+
+ + Available Offers & Coupons + + + {availableCoupons.length} {availableCoupons.length === 1 ? 'offer' : 'offers'} + +
+ +
+ {availableCoupons.map((c) => { + const isEligible = c.is_eligible !== false; + return ( +
+
+
+
+ + {c.code} + + + {c.discount_type === 'PERCENTAGE' || (c.discount_type as string) === 'PERCENT' + ? `${c.discount_value}% OFF` + : `₹${c.discount_value} OFF`} + {c.max_discount_cap ? ` (Up to ₹${c.max_discount_cap})` : ''} + +
+

+ {c.description || c.title} +

+
+ {c.min_order_amount > 0 && ( + Min spend: ₹{c.min_order_amount} + )} + {c.first_order_only && ( + ★ First Order Only + )} + {!isEligible && c.ineligibility_reason && ( + ({c.ineligibility_reason}) + )} +
+
+ + +
+
+ ); + })} +
+
+ )} + ) : (
{appliedCoupon.code} - + (-{formatCurrency(couponDiscount)})
diff --git a/services/api/checkoutService.ts b/services/api/checkoutService.ts index 706f04e..5af9f30 100644 --- a/services/api/checkoutService.ts +++ b/services/api/checkoutService.ts @@ -47,6 +47,21 @@ export interface RazorpayInitiateResponse { invoice_no?: string | null; } +export interface AvailableCoupon { + coupon_id: string; + code: string; + title: string; + description?: string | null; + discount_type: 'PERCENTAGE' | 'FIXED' | 'FREE_SHIPPING'; + discount_value: number; + max_discount_cap?: number | null; + min_order_amount: number; + first_order_only: boolean; + valid_to?: string | null; + is_eligible: boolean; + ineligibility_reason?: string | null; +} + export async function syncCartItems(items: SyncCartItem[]) { return apiFetch<{ message: string; cart_id: string }>('/api/v1/cart/items', { method: 'PUT', @@ -75,6 +90,10 @@ export async function fetchCustomerAddresses() { return apiFetch('/api/v1/customer/profile/addresses'); } +export async function fetchAvailableCoupons() { + return apiFetch('/api/v1/storefront/coupons'); +} + export async function createCustomerAddress(address: Omit & { address_id?: string }) { return apiFetch('/api/v1/customer/profile/addresses', { method: 'POST',