fix(coupons): add date range validation and prevent object error alerts #31
68
src/App.tsx
68
src/App.tsx
|
|
@ -23,6 +23,34 @@ import { DatabaseBackupTab } from './components/database/DatabaseBackupTab';
|
||||||
import { ReportsExportTab } from './components/database/ReportsExportTab';
|
import { ReportsExportTab } from './components/database/ReportsExportTab';
|
||||||
import { AdminLoginForm } from './components/auth/AdminLoginForm';
|
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() {
|
export default function App() {
|
||||||
const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token'));
|
const [userToken, setUserToken] = useState<string | null>(localStorage.getItem('access_token'));
|
||||||
const [loggedInUser, setLoggedInUser] = useState<any>(null);
|
const [loggedInUser, setLoggedInUser] = useState<any>(null);
|
||||||
|
|
@ -260,7 +288,7 @@ export default function App() {
|
||||||
setUserToken(token);
|
setUserToken(token);
|
||||||
fetchUserProfile(token);
|
fetchUserProfile(token);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setAdminAuthError(err.response?.data?.detail || 'Invalid administrative credentials.');
|
setAdminAuthError(extractErrorMessage(err, 'Invalid administrative credentials.'));
|
||||||
} finally {
|
} finally {
|
||||||
setAdminAuthLoading(false);
|
setAdminAuthLoading(false);
|
||||||
}
|
}
|
||||||
|
|
@ -287,7 +315,7 @@ export default function App() {
|
||||||
await fetchUserProfile(userToken!);
|
await fetchUserProfile(userToken!);
|
||||||
await fetchRazorpayAdminData();
|
await fetchRazorpayAdminData();
|
||||||
} catch (err: any) {
|
} 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]);
|
setAdminLogs((prev) => [`[Admin Sync] FAILED: ${errorMsg}`, ...prev]);
|
||||||
} finally {
|
} finally {
|
||||||
setAdminSyncing(false);
|
setAdminSyncing(false);
|
||||||
|
|
@ -329,7 +357,7 @@ export default function App() {
|
||||||
setTimeout(() => setDbBackupSuccess(null), 8000);
|
setTimeout(() => setDbBackupSuccess(null), 8000);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setDbBackupError(
|
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 {
|
} finally {
|
||||||
setDbBackupDownloading(null);
|
setDbBackupDownloading(null);
|
||||||
|
|
@ -395,7 +423,7 @@ export default function App() {
|
||||||
setReportExportSuccess(`Successfully downloaded ${reportType} report (${filename})`);
|
setReportExportSuccess(`Successfully downloaded ${reportType} report (${filename})`);
|
||||||
setTimeout(() => setReportExportSuccess(null), 8000);
|
setTimeout(() => setReportExportSuccess(null), 8000);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setReportExportError(err.response?.data?.detail || 'Failed to export report CSV.');
|
setReportExportError(extractErrorMessage(err, 'Failed to export report CSV.'));
|
||||||
} finally {
|
} finally {
|
||||||
setReportDownloading(null);
|
setReportDownloading(null);
|
||||||
}
|
}
|
||||||
|
|
@ -413,7 +441,7 @@ export default function App() {
|
||||||
});
|
});
|
||||||
setCustomerDrawerData(res.data);
|
setCustomerDrawerData(res.data);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Failed to load customer details.');
|
alert(extractErrorMessage(err, 'Failed to load customer details.'));
|
||||||
} finally {
|
} finally {
|
||||||
setCustomerDrawerLoading(false);
|
setCustomerDrawerLoading(false);
|
||||||
}
|
}
|
||||||
|
|
@ -438,7 +466,7 @@ export default function App() {
|
||||||
);
|
);
|
||||||
setAdminLogs((prev) => [`[Customer Control] ${res.data.message}`, ...prev]);
|
setAdminLogs((prev) => [`[Customer Control] ${res.data.message}`, ...prev]);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Failed to update account status.');
|
alert(extractErrorMessage(err, 'Failed to update account status.'));
|
||||||
} finally {
|
} finally {
|
||||||
setCustomerStatusToggling(false);
|
setCustomerStatusToggling(false);
|
||||||
}
|
}
|
||||||
|
|
@ -489,7 +517,7 @@ export default function App() {
|
||||||
setAdminModulesList((prev) =>
|
setAdminModulesList((prev) =>
|
||||||
prev.map((m) => (m.id === mod.id ? { ...m, is_active: !newActive, status: !newActive ? 'active' : 'inactive' } : m))
|
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);
|
setSelectedEditModule(null);
|
||||||
setAdminLogs((prev) => [`[Catalog] Updated metadata for '${editModuleName}'`, ...prev]);
|
setAdminLogs((prev) => [`[Catalog] Updated metadata for '${editModuleName}'`, ...prev]);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Failed to update module details.');
|
alert(extractErrorMessage(err, 'Failed to update module details.'));
|
||||||
} finally {
|
} finally {
|
||||||
setEditModuleSaving(false);
|
setEditModuleSaving(false);
|
||||||
}
|
}
|
||||||
|
|
@ -552,7 +580,7 @@ export default function App() {
|
||||||
setAdminPlansList((prev) =>
|
setAdminPlansList((prev) =>
|
||||||
prev.map((p) => (p.base_code === plan.base_code ? { ...p, is_active: !newActive } : p))
|
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,
|
...prev,
|
||||||
]);
|
]);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Failed to update plan.');
|
alert(extractErrorMessage(err, 'Failed to update plan.'));
|
||||||
} finally {
|
} finally {
|
||||||
setEditPriceSaving(false);
|
setEditPriceSaving(false);
|
||||||
}
|
}
|
||||||
|
|
@ -683,7 +711,7 @@ export default function App() {
|
||||||
}
|
}
|
||||||
setShowCreatePlanModal(false);
|
setShowCreatePlanModal(false);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setCreatePlanError(err.response?.data?.detail || 'Failed to create custom plan.');
|
setCreatePlanError(extractErrorMessage(err, 'Failed to create custom plan.'));
|
||||||
} finally {
|
} finally {
|
||||||
setCreatePlanSaving(false);
|
setCreatePlanSaving(false);
|
||||||
}
|
}
|
||||||
|
|
@ -743,6 +771,12 @@ export default function App() {
|
||||||
const handleSaveCoupon = async (e: React.FormEvent) => {
|
const handleSaveCoupon = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!couponFormData.code.trim() || !userToken) return;
|
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);
|
setCouponSaving(true);
|
||||||
try {
|
try {
|
||||||
const headers = { Authorization: `Bearer ${userToken}` };
|
const headers = { Authorization: `Bearer ${userToken}` };
|
||||||
|
|
@ -785,7 +819,7 @@ export default function App() {
|
||||||
setSelectedEditCoupon(null);
|
setSelectedEditCoupon(null);
|
||||||
await fetchRazorpayAdminData();
|
await fetchRazorpayAdminData();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Failed to save coupon.');
|
alert(extractErrorMessage(err, 'Failed to save coupon.'));
|
||||||
} finally {
|
} finally {
|
||||||
setCouponSaving(false);
|
setCouponSaving(false);
|
||||||
}
|
}
|
||||||
|
|
@ -812,7 +846,7 @@ export default function App() {
|
||||||
setAdminCouponsList((prev) =>
|
setAdminCouponsList((prev) =>
|
||||||
prev.map((item) => (item.id === c.id ? { ...item, is_active: !newActive } : item))
|
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));
|
setAdminCouponsList((prev) => prev.filter((item) => item.id !== c.id));
|
||||||
setAdminLogs((prev) => [`[Coupons] Deleted promo code ${c.code}.`, ...prev]);
|
setAdminLogs((prev) => [`[Coupons] Deleted promo code ${c.code}.`, ...prev]);
|
||||||
} catch (err: any) {
|
} 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.');
|
throw new Error('Invoice URL is missing in server response.');
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Could not download invoice.');
|
alert(extractErrorMessage(err, 'Could not download invoice.'));
|
||||||
} finally {
|
} finally {
|
||||||
setDownloadingInvoiceId(null);
|
setDownloadingInvoiceId(null);
|
||||||
}
|
}
|
||||||
|
|
@ -864,7 +898,7 @@ export default function App() {
|
||||||
const res = await axios.post(`${API_BASE}/api/admin/payments/${paymentId}/share-invoice`, {}, { headers });
|
const res = await axios.post(`${API_BASE}/api/admin/payments/${paymentId}/share-invoice`, {}, { headers });
|
||||||
alert(res.data?.message || 'Invoice shared successfully via email!');
|
alert(res.data?.message || 'Invoice shared successfully via email!');
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(err.response?.data?.detail || 'Could not share invoice.');
|
alert(extractErrorMessage(err, 'Could not share invoice.'));
|
||||||
} finally {
|
} finally {
|
||||||
setSharingInvoiceId(null);
|
setSharingInvoiceId(null);
|
||||||
}
|
}
|
||||||
|
|
@ -892,7 +926,7 @@ export default function App() {
|
||||||
setCreateAdminName('');
|
setCreateAdminName('');
|
||||||
await fetchRazorpayAdminData();
|
await fetchRazorpayAdminData();
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
alert(`Admin creation failed: ${err.response?.data?.detail || err.message}`);
|
alert(`Admin creation failed: ${extractErrorMessage(err, 'Admin creation failed.')}`);
|
||||||
} finally {
|
} finally {
|
||||||
setAdminActionLoading(false);
|
setAdminActionLoading(false);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
||||||
if (!mode) return null;
|
if (!mode) return null;
|
||||||
|
|
||||||
const isEdit = mode === 'edit';
|
const isEdit = mode === 'edit';
|
||||||
|
const isDateRangeInvalid = Boolean(data.startDate && data.endDate && data.endDate <= data.startDate);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
|
<div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
|
||||||
|
|
@ -171,7 +172,9 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
||||||
type="date"
|
type="date"
|
||||||
value={data.startDate}
|
value={data.startDate}
|
||||||
onChange={(e) => onChange('startDate', e.target.value)}
|
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'
|
||||||
|
}`}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -180,10 +183,19 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
||||||
type="date"
|
type="date"
|
||||||
value={data.endDate}
|
value={data.endDate}
|
||||||
onChange={(e) => onChange('endDate', e.target.value)}
|
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'
|
||||||
|
}`}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{isDateRangeInvalid && (
|
||||||
|
<div className="text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-200 rounded-xl px-3 py-2 flex items-center gap-2">
|
||||||
|
<span>⚠️</span>
|
||||||
|
<span>Invalid date range: Expiration date must be later than start date.</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* BLOCK 3: Scope & Item Restrictions */}
|
{/* BLOCK 3: Scope & Item Restrictions */}
|
||||||
|
|
@ -329,8 +341,8 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={saving}
|
disabled={saving || isDateRangeInvalid}
|
||||||
className="flex-1 py-2.5 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors flex items-center justify-center gap-1.5 shadow-md shadow-indigo-600/20 cursor-pointer disabled:opacity-50"
|
className="flex-1 py-2.5 rounded-xl text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white transition-colors flex items-center justify-center gap-1.5 shadow-md shadow-indigo-600/20 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
{saving ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : isEdit ? 'Save Changes' : 'Save & Publish Coupon'}
|
{saving ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : isEdit ? 'Save Changes' : 'Save & Publish Coupon'}
|
||||||
</button>
|
</button>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue