From 0b9af0c94600ff2e2e03d47265360770678d86ed Mon Sep 17 00:00:00 2001 From: Urvish Date: Tue, 3 Nov 2026 15:35:17 +0530 Subject: [PATCH] fix(coupons): add date range validation and prevent object error alerts --- src/App.tsx | 68 +++++++++++++++++++------- src/components/coupons/CouponModal.tsx | 20 ++++++-- 2 files changed, 67 insertions(+), 21 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index e766b11..5b137a5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -23,6 +23,34 @@ import { DatabaseBackupTab } from './components/database/DatabaseBackupTab'; import { ReportsExportTab } from './components/database/ReportsExportTab'; import { AdminLoginForm } from './components/auth/AdminLoginForm'; +export function extractErrorMessage(err: any, fallback: string = 'An error occurred.'): string { + if (!err) return fallback; + const detail = err.response?.data?.detail ?? err.response?.data?.message ?? err.message; + if (typeof detail === 'string') { + return detail; + } + if (detail && typeof detail === 'object') { + if (typeof detail.message === 'string' && detail.message) { + return detail.message; + } + if (Array.isArray(detail.issues) && detail.issues.length > 0) { + return detail.issues.map((i: any) => i.msg || JSON.stringify(i)).join('; '); + } + if (Array.isArray(detail.context?.issues) && detail.context.issues.length > 0) { + return detail.context.issues.map((i: any) => i.msg || JSON.stringify(i)).join('; '); + } + if (Array.isArray(detail) && detail.length > 0) { + return detail.map((i: any) => i.msg || (typeof i === 'string' ? i : JSON.stringify(i))).join('; '); + } + try { + return JSON.stringify(detail); + } catch { + return fallback; + } + } + return fallback; +} + export default function App() { const [userToken, setUserToken] = useState(localStorage.getItem('access_token')); const [loggedInUser, setLoggedInUser] = useState(null); @@ -260,7 +288,7 @@ export default function App() { setUserToken(token); fetchUserProfile(token); } catch (err: any) { - setAdminAuthError(err.response?.data?.detail || 'Invalid administrative credentials.'); + setAdminAuthError(extractErrorMessage(err, 'Invalid administrative credentials.')); } finally { setAdminAuthLoading(false); } @@ -287,7 +315,7 @@ export default function App() { await fetchUserProfile(userToken!); await fetchRazorpayAdminData(); } catch (err: any) { - const errorMsg = err.response?.data?.detail || err.message || String(err); + const errorMsg = extractErrorMessage(err, 'Failed to sync with Razorpay Gateway.'); setAdminLogs((prev) => [`[Admin Sync] FAILED: ${errorMsg}`, ...prev]); } finally { setAdminSyncing(false); @@ -329,7 +357,7 @@ export default function App() { setTimeout(() => setDbBackupSuccess(null), 8000); } catch (err: any) { setDbBackupError( - err.response?.data?.detail || 'Failed to download database backup. Ensure database client is active.' + extractErrorMessage(err, 'Failed to download database backup. Ensure database client is active.') ); } finally { setDbBackupDownloading(null); @@ -395,7 +423,7 @@ export default function App() { setReportExportSuccess(`Successfully downloaded ${reportType} report (${filename})`); setTimeout(() => setReportExportSuccess(null), 8000); } catch (err: any) { - setReportExportError(err.response?.data?.detail || 'Failed to export report CSV.'); + setReportExportError(extractErrorMessage(err, 'Failed to export report CSV.')); } finally { setReportDownloading(null); } @@ -413,7 +441,7 @@ export default function App() { }); setCustomerDrawerData(res.data); } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to load customer details.'); + alert(extractErrorMessage(err, 'Failed to load customer details.')); } finally { setCustomerDrawerLoading(false); } @@ -438,7 +466,7 @@ export default function App() { ); setAdminLogs((prev) => [`[Customer Control] ${res.data.message}`, ...prev]); } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to update account status.'); + alert(extractErrorMessage(err, 'Failed to update account status.')); } finally { setCustomerStatusToggling(false); } @@ -489,7 +517,7 @@ export default function App() { setAdminModulesList((prev) => prev.map((m) => (m.id === mod.id ? { ...m, is_active: !newActive, status: !newActive ? 'active' : 'inactive' } : m)) ); - alert(err.response?.data?.detail || 'Failed to update module status.'); + alert(extractErrorMessage(err, 'Failed to update module status.')); } }; @@ -525,7 +553,7 @@ export default function App() { setSelectedEditModule(null); setAdminLogs((prev) => [`[Catalog] Updated metadata for '${editModuleName}'`, ...prev]); } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to update module details.'); + alert(extractErrorMessage(err, 'Failed to update module details.')); } finally { setEditModuleSaving(false); } @@ -552,7 +580,7 @@ export default function App() { setAdminPlansList((prev) => prev.map((p) => (p.base_code === plan.base_code ? { ...p, is_active: !newActive } : p)) ); - alert(err.response?.data?.detail || 'Failed to update plan status.'); + alert(extractErrorMessage(err, 'Failed to update plan status.')); } }; @@ -613,7 +641,7 @@ export default function App() { ...prev, ]); } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to update plan.'); + alert(extractErrorMessage(err, 'Failed to update plan.')); } finally { setEditPriceSaving(false); } @@ -683,7 +711,7 @@ export default function App() { } setShowCreatePlanModal(false); } catch (err: any) { - setCreatePlanError(err.response?.data?.detail || 'Failed to create custom plan.'); + setCreatePlanError(extractErrorMessage(err, 'Failed to create custom plan.')); } finally { setCreatePlanSaving(false); } @@ -743,6 +771,12 @@ export default function App() { const handleSaveCoupon = async (e: React.FormEvent) => { e.preventDefault(); if (!couponFormData.code.trim() || !userToken) return; + + if (couponFormData.startDate && couponFormData.endDate && couponFormData.endDate <= couponFormData.startDate) { + alert('Invalid date range: Expiration date must be later than start date.'); + return; + } + setCouponSaving(true); try { const headers = { Authorization: `Bearer ${userToken}` }; @@ -785,7 +819,7 @@ export default function App() { setSelectedEditCoupon(null); await fetchRazorpayAdminData(); } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to save coupon.'); + alert(extractErrorMessage(err, 'Failed to save coupon.')); } finally { setCouponSaving(false); } @@ -812,7 +846,7 @@ export default function App() { setAdminCouponsList((prev) => prev.map((item) => (item.id === c.id ? { ...item, is_active: !newActive } : item)) ); - alert(err.response?.data?.detail || 'Failed to update coupon status.'); + alert(extractErrorMessage(err, 'Failed to update coupon status.')); } }; @@ -825,7 +859,7 @@ export default function App() { setAdminCouponsList((prev) => prev.filter((item) => item.id !== c.id)); setAdminLogs((prev) => [`[Coupons] Deleted promo code ${c.code}.`, ...prev]); } catch (err: any) { - alert(err.response?.data?.detail || 'Failed to delete coupon.'); + alert(extractErrorMessage(err, 'Failed to delete coupon.')); } }; @@ -850,7 +884,7 @@ export default function App() { throw new Error('Invoice URL is missing in server response.'); } } catch (err: any) { - alert(err.response?.data?.detail || 'Could not download invoice.'); + alert(extractErrorMessage(err, 'Could not download invoice.')); } finally { setDownloadingInvoiceId(null); } @@ -864,7 +898,7 @@ export default function App() { const res = await axios.post(`${API_BASE}/api/admin/payments/${paymentId}/share-invoice`, {}, { headers }); alert(res.data?.message || 'Invoice shared successfully via email!'); } catch (err: any) { - alert(err.response?.data?.detail || 'Could not share invoice.'); + alert(extractErrorMessage(err, 'Could not share invoice.')); } finally { setSharingInvoiceId(null); } @@ -892,7 +926,7 @@ export default function App() { setCreateAdminName(''); await fetchRazorpayAdminData(); } catch (err: any) { - alert(`Admin creation failed: ${err.response?.data?.detail || err.message}`); + alert(`Admin creation failed: ${extractErrorMessage(err, 'Admin creation failed.')}`); } finally { setAdminActionLoading(false); } diff --git a/src/components/coupons/CouponModal.tsx b/src/components/coupons/CouponModal.tsx index e5178f8..aea761a 100644 --- a/src/components/coupons/CouponModal.tsx +++ b/src/components/coupons/CouponModal.tsx @@ -42,6 +42,7 @@ export const CouponModal: React.FC = ({ if (!mode) return null; const isEdit = mode === 'edit'; + const isDateRangeInvalid = Boolean(data.startDate && data.endDate && data.endDate <= data.startDate); return (
@@ -171,7 +172,9 @@ export const CouponModal: React.FC = ({ type="date" value={data.startDate} onChange={(e) => onChange('startDate', e.target.value)} - className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 cursor-pointer" + className={`w-full bg-white border rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none cursor-pointer ${ + isDateRangeInvalid ? 'border-rose-400 focus:border-rose-500' : 'border-slate-200 focus:border-indigo-500' + }`} />
@@ -180,10 +183,19 @@ export const CouponModal: React.FC = ({ type="date" value={data.endDate} onChange={(e) => onChange('endDate', e.target.value)} - className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 cursor-pointer" + className={`w-full bg-white border rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none cursor-pointer ${ + isDateRangeInvalid ? 'border-rose-400 focus:border-rose-500' : 'border-slate-200 focus:border-indigo-500' + }`} />
+ + {isDateRangeInvalid && ( +
+ ⚠️ + Invalid date range: Expiration date must be later than start date. +
+ )} {/* BLOCK 3: Scope & Item Restrictions */} @@ -329,8 +341,8 @@ export const CouponModal: React.FC = ({