Merge pull request 'fix(coupons): add date range validation and prevent object error alerts' (#31) from fix/coupon-date-validation-ui into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-web-ui/pulls/31 Reviewed-by: Amit Salunke <amit@noreply.localhost>
This commit is contained in:
commit
fccb283057
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 { 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<string | null>(localStorage.getItem('access_token'));
|
||||
const [loggedInUser, setLoggedInUser] = useState<any>(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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
|||
if (!mode) return null;
|
||||
|
||||
const isEdit = mode === 'edit';
|
||||
const isDateRangeInvalid = Boolean(data.startDate && data.endDate && data.endDate <= data.startDate);
|
||||
|
||||
return (
|
||||
<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"
|
||||
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'
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
|
|
@ -180,10 +183,19 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
|||
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'
|
||||
}`}
|
||||
/>
|
||||
</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>
|
||||
|
||||
{/* BLOCK 3: Scope & Item Restrictions */}
|
||||
|
|
@ -329,8 +341,8 @@ export const CouponModal: React.FC<CouponModalProps> = ({
|
|||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
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={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 disabled:cursor-not-allowed"
|
||||
>
|
||||
{saving ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : isEdit ? 'Save Changes' : 'Save & Publish Coupon'}
|
||||
</button>
|
||||
|
|
|
|||
Loading…
Reference in New Issue