feat(storefront): Add checkout promo code validation and discount calculations
This commit is contained in:
parent
f9797fee68
commit
3f3c5e3647
3 changed files with 129 additions and 10 deletions
|
|
@ -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<Set<string>>(
|
||||
new Set()
|
||||
);
|
||||
|
||||
// Promo code & coupon states
|
||||
const [couponCodeInput, setCouponCodeInput] = useState('');
|
||||
const [appliedCoupon, setAppliedCoupon] = useState<any | null>(null);
|
||||
const [appliedCouponDiscount, setAppliedCouponDiscount] = useState<number>(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<any>('/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() {
|
|||
</span>
|
||||
</div>
|
||||
|
||||
{/* Coupon Discount Row */}
|
||||
{appliedCoupon && couponDiscount > 0 && (
|
||||
<div className="flex justify-between text-emerald-700 font-semibold text-[13px] pt-1">
|
||||
<span className="flex items-center gap-1">
|
||||
<Tag className="w-3.5 h-3.5" /> Coupon ({appliedCoupon.code})
|
||||
</span>
|
||||
<span>-{formatCurrency(couponDiscount)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Store Credits Applied Row */}
|
||||
{useWalletCredits && appliedCredits > 0 && (
|
||||
<div className="flex justify-between text-emerald-700 font-semibold text-[13px] pt-1">
|
||||
|
|
@ -1129,6 +1205,49 @@ export default function CheckoutPage() {
|
|||
)}
|
||||
</div>
|
||||
|
||||
{/* Promo Code Input or Applied Badge */}
|
||||
<div className="pt-2 border-t border-gray-100 space-y-2">
|
||||
{!appliedCoupon ? (
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Tag className="w-3.5 h-3.5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Promo / Coupon code"
|
||||
value={couponCodeInput}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleApplyCoupon}
|
||||
disabled={couponApplying || !couponCodeInput.trim()}
|
||||
className="bg-primary hover:brightness-95 text-white font-bold px-3 py-2 rounded-lg text-[12px] transition cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
{couponApplying ? 'Applying...' : 'Apply'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-2.5 bg-emerald-50 border border-emerald-200 rounded-lg flex items-center justify-between text-[12px]">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tag className="w-3.5 h-3.5 text-emerald-600" />
|
||||
<span className="font-bold font-mono text-emerald-900">{appliedCoupon.code}</span>
|
||||
<span className="text-[11px] text-emerald-700">
|
||||
(-{formatCurrency(couponDiscount)})
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRemoveCoupon}
|
||||
className="text-[11px] font-semibold text-red-600 hover:underline cursor-pointer"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Store Credit Redemption Card */}
|
||||
{Boolean(wallet && wallet.active_balance > 0) && (
|
||||
<div className="p-3 bg-emerald-50/70 border border-emerald-200/90 rounded-lg space-y-1.5">
|
||||
|
|
|
|||
|
|
@ -575,7 +575,8 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
|
|||
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<ProductInteractiveGridProps> = ({
|
|||
return (
|
||||
<div className="space-y-1.5">
|
||||
<label className="block text-[12px] font-bold uppercase tracking-wider text-gray-700">
|
||||
Select Variant: <span className="font-semibold text-primary">{(selectedVariant as any)?.label || selectedVariant?.sku}</span>
|
||||
Select Variant: <span className="font-semibold text-primary">{(selectedVariant as any)?.name || (selectedVariant as any)?.label || selectedVariant?.sku}</span>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{product.variants.map((v: any, idx: number) => {
|
||||
|
|
@ -667,7 +668,7 @@ export const ProductInteractiveGrid: React.FC<ProductInteractiveGridProps> = ({
|
|||
: '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}`}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
|
|
|||
|
|
@ -286,9 +286,8 @@ export const CategoriesSection: React.FC<CategoriesSectionProps> = ({
|
|||
}}
|
||||
>
|
||||
{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] ||
|
||||
|
|
|
|||
Loading…
Reference in a new issue