diff --git a/app/account/page.tsx b/app/account/page.tsx index 5d63093..e0570d6 100644 --- a/app/account/page.tsx +++ b/app/account/page.tsx @@ -19,13 +19,21 @@ import { Trash2, Check, ShieldCheck, + Shield, ShoppingBag, Loader2, KeyRound, X, + Wallet, + Clock, + Coins, + Sparkles, + ArrowUpRight, + ArrowDownRight, } from 'lucide-react'; import { useAuthStore } from '@/store/authStore'; import { apiFetch, clearTokens } from '@/services/api/client'; +import { creditService, WalletSummary } from '@/services/api/creditService'; import { formatCurrency } from '@/lib/utils'; import GoogleAuthModal from '@/components/auth/GoogleAuthModal'; import { AnnouncementBar } from '@/layout/AnnouncementBar'; @@ -37,12 +45,14 @@ import { PhoneInput, PincodeInput } from '@/components/PhoneInput'; import { validatePhone, validatePincode, validateAddress } from '@/lib/validation'; import { FloatingButtons } from '@/components/FloatingButtons'; -type TabType = 'dashboard' | 'orders' | 'addresses' | 'settings'; +type TabType = 'dashboard' | 'orders' | 'wallet' | 'addresses' | 'warranties' | 'settings'; const VALID_TABS: TabType[] = [ 'dashboard', 'orders', + 'wallet', 'addresses', + 'warranties', 'settings', ]; @@ -72,10 +82,23 @@ interface Order { created_at: string; } -const TABS: { id: TabType; label: string; icon: typeof User }[] = [ +interface Warranty { + warranty_id: string; + reference_type: string; + reference_id: string; + serial_no_imei?: string; + start_date: string; + end_date: string; + status: string; + warranty_type: string; +} + +const TABS: { id: TabType; label: string; icon: any }[] = [ { id: 'dashboard', label: 'Dashboard', icon: User }, { id: 'orders', label: 'Order History', icon: Package }, + { id: 'wallet', label: 'Store Credits & Wallet', icon: Wallet }, { id: 'addresses', label: 'Address Book', icon: MapPin }, + { id: 'warranties', label: 'My Warranties', icon: ShieldCheck }, { id: 'settings', label: 'Settings', icon: Settings }, ]; @@ -102,7 +125,9 @@ function AccountDashboardPage() { const [profile, setProfile] = useState(null); const [addresses, setAddresses] = useState([]); + const [warranties, setWarranties] = useState([]); const [orders, setOrders] = useState([]); + const [wallet, setWallet] = useState(null); const [loading, setLoading] = useState(true); const [addressModalOpen, setAddressModalOpen] = useState(false); @@ -171,6 +196,12 @@ function AccountDashboardPage() { const ords = await apiFetch('/api/v1/orders'); setOrders(ords); + + const warrs = await apiFetch('/api/v1/warranties'); + setWarranties(warrs); + + const walletData = await creditService.getMyWallet().catch(() => null); + setWallet(walletData); } catch (err: any) { console.error(err); setErrorMsg(err.message || 'Failed to retrieve account records.'); @@ -514,7 +545,35 @@ function AccountDashboardPage() { manage your account here.

-
+
+
+
+
+ + Store Credits + + + Spendable + +
+

+ {formatCurrency(wallet?.active_balance || 0)} +

+ {Boolean(wallet?.pending_balance && wallet.pending_balance > 0) && ( +

+ + {formatCurrency(wallet?.pending_balance || 0)} pending unlock +

+ )} +
+ +
@@ -820,6 +879,223 @@ function AccountDashboardPage() { )} + + {/* Store Credits & Wallet Tab */} + {activeTab === 'wallet' && ( +
+ {/* Metric Stat Cards */} +
+
+
+ + Spendable Credits + +
+ +
+
+

+ {formatCurrency(wallet?.active_balance || 0)} +

+

+ ✓ Ready to apply at checkout +

+
+ +
+
+ + Pending Credits + +
+ +
+
+

+ {formatCurrency(wallet?.pending_balance || 0)} +

+

+ ⏳ Locked during return window +

+
+ +
+
+ + Lifetime Earned + +
+ +
+
+

+ {formatCurrency(wallet?.lifetime_earned || 0)} +

+

+ Total rewards accumulated +

+
+
+ + {/* Educational Cashback Rules Card */} +
+

+ + How iFixKart Store Credits Work +

+
+
+

1. 🛒 Purchases & Services

+

+ You earn 5% Store Credit cashback on all delivered product orders and repair jobs. +

+
+
+

2. ⏳ Return Window Maturation

+

+ Credits remain pending during the active return window (e.g. 7 days for sales, 3 days for repairs). +

+
+
+

3. 🎁 1-Click Checkout Use

+

+ Once the window closes, credits unlock automatically to spendable balance for future checkout orders. +

+
+
+
+ + {/* Transaction Ledger Table */} +
+
+

+ Credits Ledger & History +

+ + {wallet?.transactions?.length || 0} transaction{wallet?.transactions?.length === 1 ? '' : 's'} + +
+ + {!wallet?.transactions || wallet.transactions.length === 0 ? ( +
+ +

No credit activity yet

+

+ Place an order or complete a repair service to start accumulating store credits! +

+
+ ) : ( +
+ + + + + + + + + + + + + {wallet.transactions.map((tx) => { + const isCredit = tx.credit_amount > 0; + return ( + + + + + + + + + ); + })} + +
DateDescriptionReferenceStatusUnlock DateCredit Amount
+ {tx.created_at ? new Date(tx.created_at).toLocaleDateString() : '—'} + + {tx.description || `${tx.transaction_type} for ${tx.reference_type}`} + + {tx.reference_no || tx.reference_id} + + {tx.status === 'COMPLETED' || tx.status === 'MATURED' ? ( + + ✓ Active + + ) : tx.status === 'PENDING' ? ( + + ⏳ Pending + + ) : tx.status === 'VOIDED' ? ( + + ✕ Voided + + ) : ( + + {tx.status} + + )} + + {tx.status === 'PENDING' && tx.matures_at ? ( + + Unlocks {new Date(tx.matures_at).toLocaleDateString()} + + ) : tx.status === 'COMPLETED' || tx.status === 'MATURED' ? ( + Unlocked + ) : ( + '—' + )} + + {isCredit ? `+${formatCurrency(tx.credit_amount)}` : formatCurrency(tx.credit_amount)} +
+
+ )} +
+
+ )} + + {/* Warranties */} + {activeTab === 'warranties' && ( +
+ {warranties.length === 0 ? ( +
+ +

+ No active warranties found. +

+

+ Warranties for purchased products and repair services will appear here automatically. +

+
+ ) : ( +
+ {warranties.map((warr) => ( +
+
+ + {warr.warranty_type} + + + {warr.status} + +
+ {warr.serial_no_imei && ( +

+ IMEI / Serial: {warr.serial_no_imei} +

+ )} +

+ Valid: {new Date(warr.start_date).toLocaleDateString()} – {new Date(warr.end_date).toLocaleDateString()} +

+
+ ))} +
+ )} +
+ )}
diff --git a/app/cart/page.tsx b/app/cart/page.tsx index eb79944..d5eb6a9 100644 --- a/app/cart/page.tsx +++ b/app/cart/page.tsx @@ -5,6 +5,7 @@ */ 'use client'; +import { useEffect, useState } from 'react'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { useCartStore } from '@/store/cartStore'; @@ -23,8 +24,7 @@ import { Truck, Tag, } from 'lucide-react'; - -const FREE_SHIPPING_THRESHOLD = 999; +import { deliveryService, DeliverySettings } from '@/services/api/deliveryService'; function resolveItemImage(item: { product: { images?: { image_url?: string }[]; name?: string }; @@ -41,12 +41,25 @@ export default function CartPage() { const removeFromCart = useCartStore((state) => state.removeFromCart); const updateQuantity = useCartStore((state) => state.updateQuantity); const getCartTotal = useCartStore((state) => state.getCartTotal); + const [deliverySettings, setDeliverySettings] = useState(null); + + useEffect(() => { + deliveryService.getDeliverySettings().then(setDeliverySettings).catch(() => {}); + }, []); const subtotal = getCartTotal(); - const shipping = subtotal > 0 && subtotal < FREE_SHIPPING_THRESHOLD ? 15.0 : 0; + const isFreeDelivery = Boolean( + deliverySettings?.free_delivery_enabled && + deliverySettings?.free_delivery_min_order_amount && + subtotal >= deliverySettings.free_delivery_min_order_amount + ); + const baseDeliveryFee = deliverySettings ? deliverySettings.delivery_charge : 99.0; + const shipping = subtotal > 0 ? (isFreeDelivery ? 0 : baseDeliveryFee) : 0; const total = subtotal + shipping; - const progressPercent = Math.min(100, (subtotal / FREE_SHIPPING_THRESHOLD) * 100); - const amountNeeded = Math.max(0, FREE_SHIPPING_THRESHOLD - subtotal); + + const freeThreshold = deliverySettings?.free_delivery_min_order_amount || 999; + const progressPercent = Math.min(100, (subtotal / freeThreshold) * 100); + const amountNeeded = Math.max(0, freeThreshold - subtotal); return (
@@ -198,33 +211,35 @@ export default function CartPage() { Order summary - {/* Free shipping progress */} -
-
- -

- {shipping === 0 ? ( - - You've unlocked free shipping! - - ) : ( - <> - Add{' '} - - {formatCurrency(amountNeeded)} - {' '} - more for free shipping - - )} -

+ {/* Dynamic Free shipping progress (only when enabled by admin) */} + {deliverySettings?.free_delivery_enabled && ( +
+
+ +

+ {shipping === 0 ? ( + + You've unlocked free shipping! + + ) : ( + <> + Add{' '} + + {formatCurrency(amountNeeded)} + {' '} + more for free shipping + + )} +

+
+
+
+
-
-
-
-
+ )}
diff --git a/app/checkout/page.tsx b/app/checkout/page.tsx index 8d6255a..2bf7fa0 100644 --- a/app/checkout/page.tsx +++ b/app/checkout/page.tsx @@ -23,6 +23,7 @@ import { type CustomerAddress, type CheckoutCreateResponse, } from '@/services/api/checkoutService'; +import { deliveryService, DeliverySettings } from '@/services/api/deliveryService'; import GoogleAuthModal from '@/components/auth/GoogleAuthModal'; import { Header } from '@/layout/Header'; import { Footer } from '@/layout/Footer'; @@ -47,8 +48,10 @@ import { RefreshCw, Trash2, KeyRound, + Sparkles, } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; +import { creditService, WalletSummary } from '@/services/api/creditService'; type CheckoutStep = 'shipping' | 'payment' | 'review'; @@ -69,7 +72,10 @@ export default function CheckoutPage() { const [authModalOpen, setAuthModalOpen] = useState(false); const [addresses, setAddresses] = useState([]); const [selectedAddressId, setSelectedAddressId] = useState(null); - const [paymentMethod, setPaymentMethod] = useState<'COD' | 'RAZORPAY'>('COD'); + const paymentMethod = 'RAZORPAY'; + const [wallet, setWallet] = useState(null); + const [deliverySettings, setDeliverySettings] = useState(null); + const [useWalletCredits, setUseWalletCredits] = useState(false); const [loadingAddresses, setLoadingAddresses] = useState(false); const [submitting, setSubmitting] = useState(false); const [errorMsg, setErrorMsg] = useState(null); @@ -90,11 +96,26 @@ export default function CheckoutPage() { }); const subtotal = getCartTotal(); - // Free shipping on INR orders over ₹999; ₹99 flat shipping for orders below ₹999 - const shipping = subtotal > 0 && subtotal < 999 ? 99.0 : 0; + // Dynamic shipping calculation from backend admin settings + const isFreeDelivery = Boolean( + deliverySettings?.free_delivery_enabled && + deliverySettings?.free_delivery_min_order_amount && + subtotal >= deliverySettings.free_delivery_min_order_amount + ); + const baseDeliveryFee = deliverySettings ? deliverySettings.delivery_charge : 99.0; + const shipping = subtotal > 0 ? (isFreeDelivery ? 0 : baseDeliveryFee) : 0; - const tax = Math.round(subtotal * 0.18 * 100) / 100; - const total = subtotal + shipping + tax; + const taxable_amount = subtotal / 1.18; + const tax = Math.round((subtotal - taxable_amount) * 100) / 100; + const grossTotal = Math.round(subtotal + shipping); + + // Store credits deduction calculation + const availableCredits = wallet?.active_balance || 0; + const maxCreditsToApply = Math.min(availableCredits, grossTotal); + const appliedCredits = useWalletCredits ? maxCreditsToApply : 0; + const finalPayableTotal = Math.max(0, grossTotal - appliedCredits); + const total = finalPayableTotal; + const estimatedCashback = Math.round(finalPayableTotal * 0.05); const hasOutOfStockItems = cart.some((item) => outOfStockVariantIds.has(item.selectedVariant.variant_id) @@ -102,6 +123,7 @@ export default function CheckoutPage() { useEffect(() => { void bootstrapAuth(); + deliveryService.getDeliverySettings().then(setDeliverySettings).catch(() => {}); }, [bootstrapAuth]); useEffect(() => { @@ -122,6 +144,7 @@ export default function CheckoutPage() { setAuthModalOpen(false); loadAddresses(); void syncAndValidateCart(); + creditService.getMyWallet().then(setWallet).catch(() => null); }, [isAuthenticated, authReady]); const syncAndValidateCart = async () => { @@ -358,94 +381,89 @@ export default function CheckoutPage() { const orderData = await createCheckoutOrder({ address_id: selectedAddressId, payment_method: paymentMethod, + use_wallet_credits: useWalletCredits, }); - if (paymentMethod === 'COD') { + const scriptLoaded = await loadRazorpayScript(); + if (!scriptLoaded) { + throw new Error( + 'Razorpay SDK failed to load. Please check your internet connection.' + ); + } + + const initRes = await initiatePayment(orderData.order_id); + + if (initRes.zero_amount) { clearCart(); - setOrderResult(orderData); + setOrderResult({ + ...orderData, + payment_status: 'PAYMENT_CAPTURED', + status: 'ORDER_CONFIRMED', + invoice_id: initRes.invoice_id || orderData.invoice_id, + invoice_no: initRes.invoice_no || orderData.invoice_no, + }); setSubmitting(false); - } else { - const scriptLoaded = await loadRazorpayScript(); - if (!scriptLoaded) { - throw new Error( - 'Razorpay SDK failed to load. Please check your internet connection.' - ); - } + return; + } - const initRes = await initiatePayment(orderData.order_id); + const selAddr = addresses.find((a) => a.address_id === selectedAddressId); - if (initRes.zero_amount) { - clearCart(); - setOrderResult({ - ...orderData, - payment_status: 'PAYMENT_CAPTURED', - status: 'ORDER_CONFIRMED', - invoice_id: initRes.invoice_id || orderData.invoice_id, - invoice_no: initRes.invoice_no || orderData.invoice_no, - }); - setSubmitting(false); - return; - } + const options = { + key: initRes.rzp_key_id, + amount: initRes.amount, + currency: initRes.currency, + name: 'iFixKart', + description: `Order #${orderData.order_no}`, + order_id: initRes.rzp_order_id, + redirect: false, + prefill: { + name: selAddr?.full_name || '', + contact: selAddr?.phone || '', + }, + theme: { + color: '#1976F3', + }, + handler: async function (response: any) { + try { + setSubmitting(true); + const verifyRes = await verifyPayment({ + order_id: orderData.order_id, + razorpay_order_id: response.razorpay_order_id, + razorpay_payment_id: response.razorpay_payment_id, + razorpay_signature: response.razorpay_signature, + }); - const selAddr = addresses.find((a) => a.address_id === selectedAddressId); - - const options = { - key: initRes.rzp_key_id, - amount: initRes.amount, - currency: initRes.currency, - name: 'iFixKart', - description: `Order #${orderData.order_no}`, - order_id: initRes.rzp_order_id, - redirect: false, - prefill: { - name: selAddr?.full_name || '', - contact: selAddr?.phone || '', - }, - theme: { - color: '#1976F3', - }, - handler: async function (response: any) { + clearCart(); + setOrderResult({ + ...orderData, + payment_status: 'PAYMENT_CAPTURED', + status: 'ORDER_CONFIRMED', + invoice_no: verifyRes.invoice_no || orderData.invoice_no, + }); + } catch (vErr: any) { + setErrorMsg(vErr.message || 'Payment verification failed.'); + } finally { + setSubmitting(false); + } + }, + modal: { + escape: true, + handleback: true, + confirm_close: true, + ondismiss: async function () { + setSubmitting(false); + setErrorMsg('Payment popup was closed before completion. Order cancelled.'); try { - setSubmitting(true); - const verifyRes = await verifyPayment({ - order_id: orderData.order_id, - razorpay_order_id: response.razorpay_order_id, - razorpay_payment_id: response.razorpay_payment_id, - razorpay_signature: response.razorpay_signature, - }); - - clearCart(); - setOrderResult({ - ...orderData, - payment_status: 'PAYMENT_CAPTURED', - status: 'ORDER_CONFIRMED', - invoice_no: verifyRes.invoice_no || orderData.invoice_no, - }); - } catch (vErr: any) { - setErrorMsg(vErr.message || 'Payment verification failed.'); - } finally { - setSubmitting(false); + await cancelPayment(orderData.order_id, 'Payment popup closed by customer'); + } catch (cErr) { + console.error('Failed to cancel payment session:', cErr); } }, - modal: { - escape: true, - handleback: true, - confirm_close: true, - ondismiss: async function () { - setSubmitting(false); - setErrorMsg('Payment popup was closed before completion. Order cancelled.'); - try { - await cancelPayment(orderData.order_id, 'Payment popup closed by customer'); - } catch (cErr) { - console.error('Failed to cancel payment session:', cErr); - } - }, - }, - }; + }, + }; - const rzp = new (window as any).Razorpay(options); - rzp.open(); - } + const rzp = new (window as any).Razorpay(options); + rzp.open(); } catch (err: any) { const detail = err.message || 'Failed to place order'; @@ -835,65 +853,25 @@ export default function CheckoutPage() {
-
@@ -1112,13 +1092,13 @@ export default function CheckoutPage() {
- Subtotal + Item Total {formatCurrency(subtotal)}
-
- GST (18%) +
+ Includes GST (18%) {formatCurrency(tax)} @@ -1137,12 +1117,57 @@ export default function CheckoutPage() { )}
+ + {/* Store Credits Applied Row */} + {useWalletCredits && appliedCredits > 0 && ( +
+ + Store Credits Applied + + -{formatCurrency(appliedCredits)} +
+ )}
+ {/* Store Credit Redemption Card */} + {Boolean(wallet && wallet.active_balance > 0) && ( +
+ +

+ {useWalletCredits + ? `Deducting ${formatCurrency(appliedCredits)} from your order total.` + : 'Check to deduct available store credits from this order.'} +

+
+ )} +
- Total + Payable Amount - {formatCurrency(total)} + {formatCurrency(finalPayableTotal)} + +
+ + {/* Cashback Reward Earn Preview */} +
+ + + You will earn ≈ {formatCurrency(estimatedCashback)} Store Credit (5%) after the return window.
diff --git a/app/services/page.tsx b/app/services/page.tsx index e857f10..436f58e 100644 --- a/app/services/page.tsx +++ b/app/services/page.tsx @@ -94,6 +94,7 @@ export default function ServiceBookingPage() { null | 'preparing' | 'verifying' >(null); const paymentHandledRef = useRef(false); + const isPrefillingRef = useRef(false); // Dynamic CMS Layout Sections State const [layoutCMS, setLayoutCMS] = useState([]); @@ -252,9 +253,73 @@ export default function ServiceBookingPage() { void loadLocations(); }, []); + // Pre-fill from URL + useEffect(() => { + if (typeof window === 'undefined') return; + const qs = new URLSearchParams(window.location.search); + const prefillBrandId = qs.get('brand_id'); + const prefillSeriesId = qs.get('series_id'); + const prefillModelId = qs.get('model_id'); + const prefillServiceTypeId = qs.get('service_type_id'); + const prefillVariantSku = qs.get('variant_sku'); + + if (prefillBrandId && prefillSeriesId && prefillModelId) { + isPrefillingRef.current = true; + const initFlow = async () => { + try { + const type = qs.get('device_type') || 'mobile'; + setDeviceType(type); + + const brandsData = await serviceBookingService.fetchBrands(type); + setBrands(brandsData); + const brandObj = brandsData.find((b: any) => b.brand_id === prefillBrandId); + if (brandObj) setSelectedBrand(brandObj); + + const seriesData = await serviceBookingService.fetchSeriesByBrand(prefillBrandId, type); + setSeriesList(seriesData); + const seriesObj = seriesData.find((s: any) => s.series_id === prefillSeriesId); + if (seriesObj) setSelectedSeries(seriesObj); + + const modelsData = await serviceBookingService.fetchModelsBySeries(prefillSeriesId); + setModels(modelsData); + const modelObj = modelsData.find((m: any) => m.model_id === prefillModelId); + if (modelObj) { + setSelectedModel(modelObj); + const config = await serviceBookingService.fetchRepairConfig(prefillModelId); + setRepairConfig(config); + + if (config.categories && config.categories.length > 0) { + const categoryObj = prefillServiceTypeId + ? config.categories.find((c: any) => c.service_type_id === prefillServiceTypeId) + : config.categories[0]; + + if (categoryObj) { + setSelectedCategory(categoryObj); + if (categoryObj.variants && categoryObj.variants.length > 0) { + const variantObj = prefillVariantSku + ? categoryObj.variants.find((v: any) => v.name === prefillVariantSku) + : categoryObj.variants[0]; + + if (variantObj) { + setSelectedVariant(variantObj); + } + } + } + } + } + } catch (err) { + console.error("Error prefilling data", err); + } finally { + isPrefillingRef.current = false; + } + }; + initFlow(); + } + }, []); + // Load Brands when Device Type changes useEffect(() => { - if (!deviceType) return; + if (!deviceType || isPrefillingRef.current) return; loadBrands(deviceType); }, [deviceType]); @@ -263,12 +328,14 @@ export default function ServiceBookingPage() { try { const data = await serviceBookingService.fetchBrands(type); setBrands(data); - setSelectedBrand(null); - setSelectedSeries(null); - setSelectedModel(null); - setRepairConfig(null); - setSelectedCategory(null); - setSelectedVariant(null); + if (!isPrefillingRef.current) { + setSelectedBrand(null); + setSelectedSeries(null); + setSelectedModel(null); + setRepairConfig(null); + setSelectedCategory(null); + setSelectedVariant(null); + } } catch (err: any) { toast.error(err.message || 'Failed to load brands.'); } finally { @@ -476,6 +543,7 @@ export default function ServiceBookingPage() { }, service_id: serviceId || 'OTHER_SERVICE', custom_service_name: customServiceName || undefined, + quoted_price: selectedVariant.price, customer_name: custName.trim() || undefined, customer_email: custEmail.trim() || undefined, device_type: deviceType, diff --git a/app/services/success/page.tsx b/app/services/success/page.tsx index 2a0e8e3..3f7e997 100644 --- a/app/services/success/page.tsx +++ b/app/services/success/page.tsx @@ -100,6 +100,76 @@ function BookingSuccessContent() { const [verifyState, setVerifyState] = useState<'idle' | 'verifying' | 'done'>( needsVerify ? 'verifying' : 'idle' ); + const [isRetrying, setIsRetrying] = useState(false); + + const handleRetryPayment = async () => { + if (!jobId && !jobNoParam) return; + setIsRetrying(true); + try { + const loadRazorpayScript = (): Promise => { + return new Promise((resolve) => { + if (document.querySelector('script[src="https://checkout.razorpay.com/v1/checkout.js"]')) { + resolve(true); + return; + } + const script = document.createElement('script'); + script.src = 'https://checkout.razorpay.com/v1/checkout.js'; + script.onload = () => resolve(true); + script.onerror = () => resolve(false); + document.body.appendChild(script); + }); + }; + + const rzpLoaded = await loadRazorpayScript(); + if (!rzpLoaded) { + throw new Error('Razorpay SDK failed to load. Please check your network connection.'); + } + + // If we don't have jobDetails loaded yet, use the query param ID + const targetId = jobDetails?.job_id || jobId || jobNoParam; + + const pmtOrder = await serviceBookingService.initiateServicePayment(targetId, { + payment_type: 'ADVANCE', + amount: Math.max(1, Math.round(qAmount > 0 ? qAmount : 100)), // fallback to query amount or minimum + provider: 'RAZORPAY', + }); + + const rzpKey = pmtOrder.rzp_key_id || process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID || 'rzp_test_TTUzPFYF0hRV89'; + + const options = { + key: rzpKey, + amount: pmtOrder.amount, + currency: pmtOrder.currency || 'INR', + name: 'iFixKart Commerce', + description: `Advance Booking Deposit (${jobNoParam})`, + order_id: pmtOrder.rzp_order_id, + redirect: false, + handler: (response: any) => { + const qs = new URLSearchParams(searchParams.toString()); + qs.set('payment_id', String(pmtOrder.payment_id || '')); + qs.set('amount', String(pmtOrder.amount)); + qs.set('method', 'Razorpay'); + qs.set('rzp_payment_id', String(response.razorpay_payment_id || '')); + qs.set('rzp_order_id', String(response.razorpay_order_id || '')); + qs.set('rzp_signature', String(response.razorpay_signature || '')); + qs.set('verify', '1'); + router.replace(`/services/success?${qs.toString()}`); + }, + modal: { + escape: true, + handleback: true, + confirm_close: true, + }, + }; + + const rzp = new (window as any).Razorpay(options); + rzp.open(); + } catch (err: any) { + toast.error(err.message || 'Failed to initiate payment retry.'); + } finally { + setIsRetrying(false); + } + }; useEffect(() => { void bootstrapAuth(); @@ -364,6 +434,23 @@ function BookingSuccessContent() { ? 'is saved. Complete the advance payment to lock your technician slot.' : 'is confirmed. Your advance payment is complete and our team is preparing your repair schedule.'}

+ {isPending && ( +
+ +
+ )}
diff --git a/components/pdp/ProductInteractiveGrid.tsx b/components/pdp/ProductInteractiveGrid.tsx index f93f6fa..4db1ee7 100644 --- a/components/pdp/ProductInteractiveGrid.tsx +++ b/components/pdp/ProductInteractiveGrid.tsx @@ -19,7 +19,9 @@ import { HelpCircle, GitCompare, ChevronUp, - ChevronDown + ChevronDown, + Wrench, + Sparkles, } from 'lucide-react'; interface ProductInteractiveGridProps { @@ -247,6 +249,18 @@ export const ProductInteractiveGrid: React.FC = ({ } }, [galleryImages, selectedImage, failedImages, selectedVariantIndex, selectedVariant?.variant_id]); + const handleBookService = () => { + if (!selectedVariant) return; + const qs = new URLSearchParams(); + if (product.device_type) qs.set('device_type', product.device_type); + if (product.brand_id) qs.set('brand_id', product.brand_id); + if (product.device_series_id) qs.set('series_id', product.device_series_id); + if (product.device_model_id) qs.set('model_id', product.device_model_id); + if (product.mapped_service_category_id) qs.set('service_type_id', product.mapped_service_category_id); + qs.set('variant_sku', selectedVariant.sku); + router.push(`/services?${qs.toString()}`); + }; + const handleAddToCart = () => { if (selectedVariant) { const available = selectedVariant.available_stock; @@ -434,6 +448,16 @@ export const ProductInteractiveGrid: React.FC = ({ )}
+ {/* Store Credit Cashback Incentive Badge */} + {selectedPrice > 0 && ( +
+ + + Earn 5% Store Credit (≈ {formatCurrency(Math.round(selectedPrice * 0.05))}) after 7-day return window + +
+ )} + {/* Interactive Variant Attribute Selectors */} {product.variants && product.variants.length > 0 && (
@@ -589,8 +613,8 @@ export const ProductInteractiveGrid: React.FC = ({ onClick={() => toggleWishlist(product)} className={`flex items-center gap-1.5 cursor-pointer ${isInWishlist ? 'text-primary' : 'hover:text-primary'}`} > - - Wishlist + + {isInWishlist ? 'Saved' : 'Wishlist'}
+ + {product.is_service_booking && ( +
+
+ +
+

Need Professional Installation?

+

+ Book a doorstep or store service for this part. We will assign an expert engineer to install it for you. +

+
+
+ +
+ )}
diff --git a/components/store/CartDrawer.tsx b/components/store/CartDrawer.tsx index 9112482..d3f1766 100644 --- a/components/store/CartDrawer.tsx +++ b/components/store/CartDrawer.tsx @@ -4,12 +4,13 @@ */ 'use client'; -import { useEffect } from 'react'; +import { useEffect, useState } from 'react'; import Link from 'next/link'; import { X, Trash2, Plus, Minus, ShoppingBag, ArrowRight, Truck } from 'lucide-react'; import { useCartStore } from '@/store/cartStore'; import { formatCurrency, getImageUrl } from '@/lib/utils'; import { requireLoginForCheckout } from '@/lib/requireLoginForCheckout'; +import { deliveryService, DeliverySettings } from '@/services/api/deliveryService'; function resolveItemImage(item: { product: { images?: { image_url?: string }[]; name?: string }; @@ -27,9 +28,11 @@ export function CartDrawer() { const removeFromCart = useCartStore((state) => state.removeFromCart); const updateQuantity = useCartStore((state) => state.updateQuantity); const getCartTotal = useCartStore((state) => state.getCartTotal); + const [deliverySettings, setDeliverySettings] = useState(null); useEffect(() => { if (!isOpen) return; + deliveryService.getDeliverySettings().then(setDeliverySettings).catch(() => {}); const prev = document.body.style.overflow; document.body.style.overflow = 'hidden'; const onKey = (e: KeyboardEvent) => { @@ -46,7 +49,7 @@ export function CartDrawer() { const total = getCartTotal(); const itemCount = cart.reduce((sum, i) => sum + (i.quantity || 1), 0); - const freeShippingThreshold = 999; + const freeShippingThreshold = deliverySettings?.free_delivery_min_order_amount || 999; const progressPercent = Math.min(100, (total / freeShippingThreshold) * 100); const amountNeeded = Math.max(0, freeShippingThreshold - total); @@ -80,8 +83,8 @@ export function CartDrawer() {
- {/* Free shipping bar */} - {cart.length > 0 && ( + {/* Dynamic Free shipping bar (only when enabled by admin) */} + {deliverySettings?.free_delivery_enabled && cart.length > 0 && (
diff --git a/components/store/TopBar.tsx b/components/store/TopBar.tsx index c5cd7ac..d69aa9e 100644 --- a/components/store/TopBar.tsx +++ b/components/store/TopBar.tsx @@ -34,9 +34,9 @@ export function TopBar() {
- {/* Right Free Shipping Text */} + {/* Right Delivery Text */}
- Free Shipping on orders over ₹999! + Express Pan-India Delivery | 100% Genuine Spare Parts
diff --git a/lib/faqDefaults.ts b/lib/faqDefaults.ts index a7a2cb3..91173b2 100644 --- a/lib/faqDefaults.ts +++ b/lib/faqDefaults.ts @@ -38,7 +38,7 @@ export const DEFAULT_FAQ_PAGE: FaqPageData = { { question: 'What payment modes are available for refurbished mobiles?', answer: - 'You can pay with Visa and Mastercard debit or credit cards, UPI, net banking, RuPay, and Razorpay-supported wallets. Cash on delivery may not be available on every listing.', + 'You can pay with Visa and Mastercard debit or credit cards, UPI, net banking, RuPay, and Razorpay-supported wallets. All orders require secure online prepaid payment.', }, { question: 'Will I get a warranty card with the product?', diff --git a/lib/homepageDefaults.ts b/lib/homepageDefaults.ts index 6644ec5..92c0459 100644 --- a/lib/homepageDefaults.ts +++ b/lib/homepageDefaults.ts @@ -56,7 +56,7 @@ export const DEFAULT_PROMO_CARDS: any[] = []; export const DEFAULT_PROMO_BANNERS: any[] = []; export const DEFAULT_TRUST_FEATURES = [ - { title: 'Free Shipping', desc: 'On orders over ₹1,000', icon: 'Truck' }, + { title: 'Fast Express Shipping', desc: 'Pan-India Insured Delivery', icon: 'Truck' }, { title: 'Flexible & Easy Return', desc: 'Return within 14 days', icon: 'RefreshCcw' }, { title: '24/7 Support Services', desc: 'Any Time Customer Support', icon: 'Headphones' }, @@ -173,7 +173,7 @@ export const DEFAULT_SECTION_TITLES: Record('/api/v1/checkout/create', { method: 'POST', body: JSON.stringify({ address_id: payload.address_id, - payment_method: payload.payment_method || 'COD', + payment_method: payload.payment_method || 'RAZORPAY', coupon_code: payload.coupon_code, + use_wallet_credits: Boolean(payload.use_wallet_credits), }), }); } diff --git a/services/api/creditService.ts b/services/api/creditService.ts new file mode 100644 index 0000000..0b4e8e0 --- /dev/null +++ b/services/api/creditService.ts @@ -0,0 +1,57 @@ +import { apiFetch } from './client'; + +export interface WalletTransaction { + transaction_id: string; + transaction_type: 'EARN' | 'REDEEM' | 'REFUND' | 'ADJUSTMENT' | string; + reference_type: string; + reference_id: string; + reference_no: string; + base_amount: number; + percentage_applied: number | null; + credit_amount: number; + status: 'PENDING' | 'MATURED' | 'COMPLETED' | 'VOIDED' | 'EXPIRED' | string; + matures_at: string | null; + matured_at: string | null; + voided_at: string | null; + void_reason: string | null; + description: string | null; + created_at: string | null; +} + +export interface WalletSummary { + wallet_id: string; + customer_id: string; + active_balance: number; + pending_balance: number; + lifetime_earned: number; + lifetime_redeemed: number; + currency: string; + is_locked: boolean; + transactions: WalletTransaction[]; +} + +export interface CreditSettings { + credits_enabled: boolean; + credits_sales_percentage: number; + credits_sales_return_window_days: number; + credits_service_percentage: number; + credits_service_claim_window_days: number; + credits_minimum_order_value: number; + credits_expiry_days: number; +} + +export const creditService = { + /** + * Retrieves the current customer's spendable balance, pending balance, and transaction history. + */ + async getMyWallet(): Promise { + return apiFetch('/api/v1/credits/my-wallet'); + }, + + /** + * Retrieves current credit & return window parameters. + */ + async getCreditSettings(): Promise { + return apiFetch('/api/v1/credits/settings', { skipAuth: true }); + }, +}; diff --git a/services/api/deliveryService.ts b/services/api/deliveryService.ts new file mode 100644 index 0000000..a6e880f --- /dev/null +++ b/services/api/deliveryService.ts @@ -0,0 +1,25 @@ +import { apiFetch } from './client'; + +export interface DeliverySettings { + delivery_charge: number; + free_delivery_enabled: boolean; + free_delivery_min_order_amount: number; +} + +export const deliveryService = { + /** + * Retrieves active delivery fee and dynamic free delivery configuration. + */ + async getDeliverySettings(): Promise { + try { + return await apiFetch('/api/v1/settings/delivery', { skipAuth: true }); + } catch { + // Fallback defaults if offline or uninitialized + return { + delivery_charge: 99.0, + free_delivery_enabled: false, + free_delivery_min_order_amount: 999.0, + }; + } + }, +}; diff --git a/services/api/serviceBooking.ts b/services/api/serviceBooking.ts index 0482e4f..bcff09d 100644 --- a/services/api/serviceBooking.ts +++ b/services/api/serviceBooking.ts @@ -65,6 +65,7 @@ export interface ServiceBookingPayload { }; service_id?: string; custom_service_name?: string; + quoted_price?: number; customer_name?: string; customer_email?: string; customer_phone?: string; @@ -402,7 +403,7 @@ export const serviceBookingService = { serviceId )}&target_date=${encodeURIComponent(targetDate)}` ); - if (Array.isArray(data) && data.length > 0) return data; + if (Array.isArray(data)) return data; } catch { /* fall through */ } diff --git a/services/api/storefrontService.ts b/services/api/storefrontService.ts index c88f56b..8cfbc2d 100644 --- a/services/api/storefrontService.ts +++ b/services/api/storefrontService.ts @@ -254,7 +254,7 @@ export const MOCK_REVIEWS: ProductReview[] = [ ]; export const MOCK_TRUST_BADGES: TrustBadge[] = [ - { id: 'tb1', title: 'Free Shipping', subtitle: 'On order over $100', icon: 'truck' }, + { id: 'tb1', title: 'Express Delivery', subtitle: 'Fast & Insured Pan-India', icon: 'truck' }, { id: 'tb2', title: 'Flexible & Easy Return', subtitle: 'Return within 14 days', icon: 'refresh' }, { id: 'tb3', title: '24/7 Support Services', subtitle: 'Any Time Customer Support', icon: 'headset' }, { id: 'tb4', title: 'Secure payment', subtitle: '100% Fast & Secure Payment', icon: 'shield' },