Merged in admin_dashboard (pull request #2)

Reset Password Validation done, Manage Submission Approve or Reject completed
This commit is contained in:
Senthamilselvi 2025-10-31 09:07:12 +00:00
commit 0e8557d49a
5 changed files with 413 additions and 232 deletions

View File

@ -2,6 +2,7 @@ import React from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom'; import { Link, useNavigate, useParams } from 'react-router-dom';
import AdminHeader from '@/components/admin/AdminHeader'; import AdminHeader from '@/components/admin/AdminHeader';
import { getSubmissionById } from '@/services/admin/submission'; import { getSubmissionById } from '@/services/admin/submission';
import apiClient from '@/services/api/apiClient';
const caretUpSrc = '/assets/images/caret-up.svg'; const caretUpSrc = '/assets/images/caret-up.svg';
const establishmentIconSrc = '/assets/images/Establishment.svg'; const establishmentIconSrc = '/assets/images/Establishment.svg';
@ -25,10 +26,10 @@ const employmentIcons = {
const ValidationReview = () => { const ValidationReview = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { id } = useParams(); const { id } = useParams();
const [toast, setToast] = React.useState(null);
const [isRejectOpen, setIsRejectOpen] = React.useState(false); const [isRejectOpen, setIsRejectOpen] = React.useState(false);
const [rejectReason, setRejectReason] = React.useState(''); const [rejectReason, setRejectReason] = React.useState('');
const [loading, setLoading] = React.useState(true); const [loading, setLoading] = React.useState(true);
const [actionLoading, setActionLoading] = React.useState(false);
const [error, setError] = React.useState(null); const [error, setError] = React.useState(null);
const [submissionData, setSubmissionData] = React.useState(null); const [submissionData, setSubmissionData] = React.useState(null);
@ -71,22 +72,69 @@ const ValidationReview = () => {
fetchSubmission(); fetchSubmission();
}, [id]); }, [id]);
const showApproveToast = () => { const handleApprove = async () => {
const establishmentName = submissionData?.establishment?.factory_name || 'Establishment'; if (actionLoading) return;
setToast({ type: 'success', text: `${establishmentName} has been approved successfully.` });
window.clearTimeout(showApproveToast._t); setActionLoading(true);
showApproveToast._t = window.setTimeout(() => setToast(null), 4000); try {
const response = await apiClient.put(`/approveOrRejectSubmission/${id}`, {
status: 'Approved',
remarks: ''
});
if (response?.data || response?.status === 'success') {
const establishmentName = submissionData?.establishment?.factory_name || 'Establishment';
navigate('/admin/validations', {
state: {
showSuccessToast: true,
successMessage: `${establishmentName} has been approved successfully.`
}
});
} else {
throw new Error('Failed to approve submission');
}
} catch (err) {
console.error('Approval failed:', err);
alert(err.response?.data?.message || err.message || 'Failed to approve submission. Please try again.');
} finally {
setActionLoading(false);
}
}; };
const handleRejectSubmit = () => { const handleRejectSubmit = async () => {
setToast({ if (actionLoading) return;
type: 'info',
text: rejectReason ? `Submission rejected. Reason: ${rejectReason}` : 'Submission rejected.' if (!rejectReason.trim()) {
}); alert('Please provide a reason for rejection.');
window.clearTimeout(showApproveToast._t); return;
showApproveToast._t = window.setTimeout(() => setToast(null), 4000); }
setIsRejectOpen(false);
setRejectReason(''); setActionLoading(true);
try {
const response = await apiClient.put(`/approveOrRejectSubmission/${id}`, {
status: 'Rejected',
remarks: rejectReason.trim()
});
if (response?.data || response?.status === 'success') {
const establishmentName = submissionData?.establishment?.factory_name || 'Establishment';
navigate('/admin/validations', {
state: {
showSuccessToast: true,
successMessage: `${establishmentName} has been rejected successfully.`
}
});
} else {
throw new Error('Failed to reject submission');
}
} catch (err) {
console.error('Rejection failed:', err);
alert(err.response?.data?.message || err.message || 'Failed to reject submission. Please try again.');
} finally {
setActionLoading(false);
setIsRejectOpen(false);
setRejectReason('');
}
}; };
if (loading) { if (loading) {
@ -253,22 +301,6 @@ const ValidationReview = () => {
<div className="min-h-screen bg-[#F6F5F1]"> <div className="min-h-screen bg-[#F6F5F1]">
<AdminHeader /> <AdminHeader />
<div className="max-w-[1280px] mx-auto px-4 py-6 space-y-6"> <div className="max-w-[1280px] mx-auto px-4 py-6 space-y-6">
{toast && (
<div className="rounded-md bg-[#F3FAF4] text-[#2F663C] flex items-center justify-between px-4 py-2">
<div className="flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
<path fillRule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm4.28 7.28a.75.75 0 0 0-1.06-1.06l-4.72 4.72-1.72-1.72a.75.75 0 1 0-1.06 1.06l2.25 2.25c.293.293.767.293 1.06 0l5.25-5.25Z" clipRule="evenodd" />
</svg>
<span className="text-sm">{toast.text}</span>
</div>
<button type="button" aria-label="Close" className="p-1 rounded hover:bg-black/5" onClick={() => setToast(null)}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
<path fillRule="evenodd" d="M5.47 5.47a.75.75 0 0 1 1.06 0L12 10.94l5.47-5.47a.75.75 0 1 1 1.06 1.06L13.06 12l5.47 5.47a.75.75 0 1 1-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 0 1-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 0 1 0-1.06Z" clipRule="evenodd" />
</svg>
</button>
</div>
)}
<nav className="flex items-center gap-2 text-sm text-[#8F9299]"> <nav className="flex items-center gap-2 text-sm text-[#8F9299]">
<Link to="/admin/dashboard" className="flex items-center gap-2 text-[#232528] hover:underline"> <Link to="/admin/dashboard" className="flex items-center gap-2 text-[#232528] hover:underline">
Dashboard Dashboard
@ -429,17 +461,19 @@ const ValidationReview = () => {
<div className="flex flex-col gap-3 md:flex-row md:items-center"> <div className="flex flex-col gap-3 md:flex-row md:items-center">
<button <button
type="button" type="button"
className="inline-flex h-11 w-full items-center justify-center rounded-[10px] border border-[#B52520] text-sm font-semibold text-[#B52520] transition-colors hover:bg-[#FEE2E2] md:w-[132px]" className="inline-flex h-11 w-full items-center justify-center rounded-[10px] border border-[#B52520] text-sm font-semibold text-[#B52520] transition-colors hover:bg-[#FEE2E2] md:w-[132px] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={() => setIsRejectOpen(true)} onClick={() => setIsRejectOpen(true)}
disabled={actionLoading}
> >
Reject Reject
</button> </button>
<button <button
type="button" type="button"
className="inline-flex h-11 w-full items-center justify-center rounded-[10px] bg-[#92722A] text-sm font-semibold text-white transition-colors hover:bg-[#B68A35] md:w-[132px]" className="inline-flex h-11 w-full items-center justify-center rounded-[10px] bg-[#92722A] text-sm font-semibold text-white transition-colors hover:bg-[#B68A35] md:w-[132px] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={showApproveToast} onClick={handleApprove}
disabled={actionLoading}
> >
Approve {actionLoading ? 'Processing...' : 'Approve'}
</button> </button>
</div> </div>
</div> </div>
@ -454,8 +488,12 @@ const ValidationReview = () => {
<button <button
type="button" type="button"
className="h-8 w-8 rounded-full text-[#6B7280] transition-colors hover:bg-[#F7F7F7] hover:text-[#232528]" className="h-8 w-8 rounded-full text-[#6B7280] transition-colors hover:bg-[#F7F7F7] hover:text-[#232528]"
onClick={() => setIsRejectOpen(false)} onClick={() => {
setIsRejectOpen(false);
setRejectReason('');
}}
aria-label="Close rejection dialog" aria-label="Close rejection dialog"
disabled={actionLoading}
> >
× ×
</button> </button>
@ -469,26 +507,29 @@ const ValidationReview = () => {
placeholder="Enter the reason for rejection..." placeholder="Enter the reason for rejection..."
value={rejectReason} value={rejectReason}
onChange={(event) => setRejectReason(event.target.value)} onChange={(event) => setRejectReason(event.target.value)}
disabled={actionLoading}
/> />
</label> </label>
</div> </div>
<div className="flex items-center justify-end gap-3 border-t border-[#E5E7EB] px-6 py-4"> <div className="flex items-center justify-end gap-3 border-t border-[#E5E7EB] px-6 py-4">
<button <button
type="button" type="button"
className="inline-flex h-10 items-center justify-center rounded-[10px] border border-[#C3C6CB] bg-white px-4 text-sm font-medium text-[#5F646D] transition-colors hover:bg-[#F7F7F7]" className="inline-flex h-10 items-center justify-center rounded-[10px] border border-[#C3C6CB] bg-white px-4 text-sm font-medium text-[#5F646D] transition-colors hover:bg-[#F7F7F7] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={() => { onClick={() => {
setIsRejectOpen(false); setIsRejectOpen(false);
setRejectReason(''); setRejectReason('');
}} }}
disabled={actionLoading}
> >
Cancel Cancel
</button> </button>
<button <button
type="button" type="button"
className="inline-flex h-10 items-center justify-center rounded-[10px] bg-[#92722A] px-5 text-sm font-semibold text-white transition-colors hover:bg-[#B68A35]" className="inline-flex h-10 items-center justify-center rounded-[10px] bg-[#92722A] px-5 text-sm font-semibold text-white transition-colors hover:bg-[#B68A35] disabled:opacity-50 disabled:cursor-not-allowed"
onClick={handleRejectSubmit} onClick={handleRejectSubmit}
disabled={actionLoading}
> >
Reject {actionLoading ? 'Processing...' : 'Reject'}
</button> </button>
</div> </div>
</div> </div>

View File

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate, useLocation } from 'react-router-dom';
import AdminHeader from '@/components/admin/AdminHeader'; import AdminHeader from '@/components/admin/AdminHeader';
import Table from '@/components/common/Table'; import Table from '@/components/common/Table';
import { SelectField } from '@/components/common/FormControls'; import { SelectField } from '@/components/common/FormControls';
@ -51,6 +51,7 @@ const Badge = ({ children, status }) => {
const ManageSubmissions = () => { const ManageSubmissions = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation();
const [submissions, setSubmissions] = React.useState([]); const [submissions, setSubmissions] = React.useState([]);
const [loading, setLoading] = React.useState(true); const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null); const [error, setError] = React.useState(null);
@ -60,8 +61,47 @@ const ManageSubmissions = () => {
const [emirate, setEmirate] = React.useState(''); const [emirate, setEmirate] = React.useState('');
const [status, setStatus] = React.useState(''); const [status, setStatus] = React.useState('');
const [currentPage, setCurrentPage] = React.useState(1); const [currentPage, setCurrentPage] = React.useState(1);
const [toast, setToast] = React.useState(null);
const pageSize = 10; const pageSize = 10;
const toastTimeoutRef = React.useRef(null);
const showToast = React.useCallback((type, message) => {
if (!message) return;
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
setToast({ type, message });
toastTimeoutRef.current = window.setTimeout(() => {
setToast(null);
toastTimeoutRef.current = null;
}, 4000);
}, []);
const closeToast = React.useCallback(() => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
setToast(null);
}, []);
React.useEffect(() => {
return () => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
}
};
}, []);
React.useEffect(() => {
if (location.state?.showSuccessToast && location.state?.successMessage) {
showToast('success', location.state.successMessage);
window.history.replaceState({}, document.title);
}
}, [location.state, showToast]);
React.useEffect(() => { React.useEffect(() => {
const fetchSubmissions = async () => { const fetchSubmissions = async () => {
try { try {
@ -194,6 +234,30 @@ const ManageSubmissions = () => {
<> <>
<div className="min-h-screen bg-[#F6F5F1]"> <div className="min-h-screen bg-[#F6F5F1]">
<AdminHeader /> <AdminHeader />
{toast && (
<div className="fixed top-6 inset-x-0 z-50 flex justify-center px-4">
<div
className={`text-sm rounded px-3 py-2 border flex items-start justify-between gap-3 shadow ${
toast.type === 'success'
? 'bg-[#F3FAF4] border-[#C6E7D8] text-[#2F663C]'
: 'bg-[#FEF2F2] border-[#FECACA] text-[#B91C1C]'
}`}
>
<div className="flex items-start gap-2">
<span>{toast.message}</span>
</div>
<button
type="button"
className="flex h-6 w-6 items-center justify-center rounded hover:bg-black/5"
onClick={closeToast}
>
</button>
</div>
</div>
)}
<div className="max-w-[1280px] mx-auto px-4 py-6 flex flex-col gap-6"> <div className="max-w-[1280px] mx-auto px-4 py-6 flex flex-col gap-6">
<nav className="flex items-center gap-2 text-sm text-[#8F9299]"> <nav className="flex items-center gap-2 text-sm text-[#8F9299]">
<Link to="/admin/dashboard" className="flex items-center gap-2 text-[#232528] hover:underline"> <Link to="/admin/dashboard" className="flex items-center gap-2 text-[#232528] hover:underline">

View File

@ -4,6 +4,58 @@ import apiClient from '@/services/api/apiClient';
const logoSrc = '/assets/images/FCSCLogo.svg'; const logoSrc = '/assets/images/FCSCLogo.svg';
const ToggleableInput = ({
label,
type = "password",
value,
onChange,
show,
toggleShow,
placeholder,
required = false,
}) => (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{label}
{required && <span className="text-red-500 ml-0.5">*</span>}
</label>
<div className="relative">
<input
type={show ? "text" : type}
value={value}
onChange={onChange}
placeholder={placeholder}
required={required}
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={toggleShow}
aria-label="Toggle visibility"
>
{show ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="m3 3 18 18" />
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
</div>
);
const ChangePassword = () => { const ChangePassword = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
@ -20,6 +72,27 @@ const ChangePassword = () => {
const [error, setError] = React.useState(""); const [error, setError] = React.useState("");
const [success, setSuccess] = React.useState(""); const [success, setSuccess] = React.useState("");
const validatePassword = (password) => {
const minLength = /.{8,}/;
const uppercase = /[A-Z]/;
const lowercase = /[a-z]/;
const number = /[0-9]/;
const specialChar = /[!@#$%^&*(),.?":{}|<>]/;
if (!minLength.test(password))
return "Password must be at least 8 characters long.";
if (!uppercase.test(password))
return "Password must contain at least one uppercase letter.";
if (!lowercase.test(password))
return "Password must contain at least one lowercase letter.";
if (!number.test(password))
return "Password must contain at least one number.";
if (!specialChar.test(password))
return "Password must contain at least one special character.";
return "";
};
const handleSubmit = async (e) => { const handleSubmit = async (e) => {
e.preventDefault(); e.preventDefault();
setError(""); setError("");
@ -35,6 +108,12 @@ const ChangePassword = () => {
return; return;
} }
const passwordError = validatePassword(newPassword);
if (passwordError) {
setError(passwordError);
return;
}
if (newPassword !== confirmPassword) { if (newPassword !== confirmPassword) {
setError("Passwords do not match."); setError("Passwords do not match.");
return; return;
@ -53,7 +132,14 @@ const ChangePassword = () => {
if (response?.data) { if (response?.data) {
setSuccess("Password changed successfully. Redirecting to login..."); setSuccess("Password changed successfully. Redirecting to login...");
setTimeout(() => navigate("/login"), 1500); setTimeout(() => {
navigate("/login", {
state: {
showSuccessToast: true,
successMessage: "Password reset successful. Please login with your new password."
}
});
}, 1500);
} else { } else {
setError("Something went wrong. Please try again."); setError("Something went wrong. Please try again.");
} }
@ -68,52 +154,6 @@ const ChangePassword = () => {
} }
}; };
const ToggleableInput = ({ label, type = "password", value, onChange, show, toggleShow, placeholder }) => (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{label}
</label>
<div className="relative">
<input
type={show ? "text" : type}
value={value}
onChange={onChange}
placeholder={placeholder}
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={toggleShow}
aria-label="Toggle visibility"
>
{show ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m3 3 18 18"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
</div>
);
return ( return (
<div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4"> <div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4">
<div className="w-full max-w-md"> <div className="w-full max-w-md">
@ -151,32 +191,54 @@ const ChangePassword = () => {
</div> </div>
<ToggleableInput <ToggleableInput
label="Verification Code" label="Verification Code"
type="password" required
value={otp} type="password"
onChange={(e) => setOtp(e.target.value)} value={otp}
show={showOtp} onChange={(e) => setOtp(e.target.value)}
toggleShow={() => setShowOtp((v) => !v)} show={showOtp}
placeholder="Enter 6-digit code" toggleShow={() => setShowOtp((v) => !v)}
/> placeholder="Enter 6-digit code"
/>
<ToggleableInput <ToggleableInput
label="New Password" label="New Password"
value={newPassword} required
onChange={(e) => setNewPassword(e.target.value)} value={newPassword}
show={showNewPassword} onChange={(e) => setNewPassword(e.target.value)}
toggleShow={() => setShowNewPassword((v) => !v)} show={showNewPassword}
placeholder="Enter new password" toggleShow={() => setShowNewPassword((v) => !v)}
/> placeholder="Enter new password"
/>
<ToggleableInput <ToggleableInput
label="Confirm New Password" label="Confirm New Password"
value={confirmPassword} required
onChange={(e) => setConfirmPassword(e.target.value)} value={confirmPassword}
show={showConfirmPassword} onChange={(e) => setConfirmPassword(e.target.value)}
toggleShow={() => setShowConfirmPassword((v) => !v)} show={showConfirmPassword}
placeholder="Re-enter new password" toggleShow={() => setShowConfirmPassword((v) => !v)}
/> placeholder="Re-enter new password"
/>
{newPassword && (
<ul className="text-xs text-gray-600 list-disc pl-5 space-y-1">
<li className={/.{8,}/.test(newPassword) ? "text-green-600" : ""}>
At least 8 characters
</li>
<li className={/[A-Z]/.test(newPassword) ? "text-green-600" : ""}>
At least one uppercase letter
</li>
<li className={/[a-z]/.test(newPassword) ? "text-green-600" : ""}>
At least one lowercase letter
</li>
<li className={/[0-9]/.test(newPassword) ? "text-green-600" : ""}>
At least one number
</li>
<li className={/[!@#$%^&*(),.?":{}|<>]/.test(newPassword) ? "text-green-600" : ""}>
At least one special character
</li>
</ul>
)}
<button <button
type="submit" type="submit"
@ -195,7 +257,7 @@ const ChangePassword = () => {
onClick={() => navigate(-1)} onClick={() => navigate(-1)}
className="w-full h-10 rounded-md border border-[#92722A] text-[#92722A] hover:bg-[#92722A]/10 text-sm" className="w-full h-10 rounded-md border border-[#92722A] text-[#92722A] hover:bg-[#92722A]/10 text-sm"
> >
Cancel Back
</button> </button>
</form> </form>
</div> </div>

View File

@ -1,11 +1,12 @@
import React from 'react'; import React from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useLocation } from 'react-router-dom';
import { login } from '@/services/auth/authService.js'; import { login } from '@/services/auth/authService.js';
import { RefreshCw } from "lucide-react"; import { RefreshCw } from "lucide-react";
const logoSrc = '/assets/images/FCSCLogo.svg'; const logoSrc = '/assets/images/FCSCLogo.svg';
const Login = () => { const Login = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation();
const [email, setEmail] = React.useState(''); const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState(''); const [password, setPassword] = React.useState('');
const [showPassword, setShowPassword] = React.useState(false); const [showPassword, setShowPassword] = React.useState(false);
@ -30,10 +31,6 @@ const Login = () => {
setCaptcha(code); setCaptcha(code);
}, []); }, []);
React.useEffect(() => {
generateCaptcha();
}, [generateCaptcha]);
const closeToast = React.useCallback(() => { const closeToast = React.useCallback(() => {
if (toastTimeoutRef.current) { if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current); window.clearTimeout(toastTimeoutRef.current);
@ -70,6 +67,18 @@ const Login = () => {
[navigate] [navigate]
); );
React.useEffect(() => {
generateCaptcha();
}, [generateCaptcha]);
React.useEffect(() => {
if (location.state?.showSuccessToast && location.state?.successMessage) {
showToast('success', location.state.successMessage);
window.history.replaceState({}, document.title);
}
}, [location.state, showToast]);
React.useEffect( React.useEffect(
() => () => { () => () => {
if (toastTimeoutRef.current) { if (toastTimeoutRef.current) {
@ -224,46 +233,46 @@ const Login = () => {
</div> </div>
<div> <div>
<label className="block text-sm font-medium text-gray-700 mb-1">Password</label> <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
<div className="relative"> <div className="relative">
<input <input
type={showPassword ? 'text' : 'password'} type={showPassword ? 'text' : 'password'}
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password" placeholder="Enter password"
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white" className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required required
/> />
<button <button
type="button" type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer" className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={() => setShowPassword((v) => !v)} onClick={() => setShowPassword((v) => !v)}
aria-label="Toggle password visibility" aria-label="Toggle password visibility"
> >
{showPassword ? ( {showPassword ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path <path
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
strokeWidth="2" strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24" d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/> />
<path <path
strokeLinecap="round" strokeLinecap="round"
strokeLinejoin="round" strokeLinejoin="round"
strokeWidth="2" strokeWidth="2"
d="m3 3 18 18" d="m3 3 18 18"
/> />
</svg> </svg>
) : ( ) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" /> <circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg> </svg>
)} )}
</button> </button>
</div> </div>
</div> </div>
<div className="mt-4"> <div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1"> <label className="block text-sm font-medium text-gray-700 mb-1">
@ -277,13 +286,13 @@ const Login = () => {
{captcha} {captcha}
</div> </div>
<button <button
type="button" type="button"
onClick={generateCaptcha} onClick={generateCaptcha}
className="flex items-center gap-1 text-sm text-[#92722A] hover:underline" className="flex items-center gap-1 text-sm text-[#92722A] hover:underline"
> >
<RefreshCw size={14} className="text-[#92722A]" /> <RefreshCw size={14} className="text-[#92722A]" />
Refresh Refresh
</button> </button>
</div> </div>
<p className="text-xs text-gray-500 mt-1"> <p className="text-xs text-gray-500 mt-1">
If you cannot read the code, click "Refresh" or type:{" "} If you cannot read the code, click "Refresh" or type:{" "}

View File

@ -11,9 +11,6 @@ const PublicContactForm = () => {
establishmentName: "", establishmentName: "",
establishmentId: "", establishmentId: "",
email: "", email: "",
// contactName: "",
// contactPhone: "",
// notes: "",
}); });
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
@ -28,6 +25,9 @@ const PublicContactForm = () => {
const [otp, setOtp] = useState(""); const [otp, setOtp] = useState("");
const [otpMsg, setOtpMsg] = useState(""); const [otpMsg, setOtpMsg] = useState("");
const [otpError, setOtpError] = useState(""); const [otpError, setOtpError] = useState("");
const [toast, setToast] = useState(null);
const toastTimeoutRef = React.useRef(null);
const generateCaptcha = () => { const generateCaptcha = () => {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
@ -42,6 +42,35 @@ const PublicContactForm = () => {
generateCaptcha(); generateCaptcha();
}, []); }, []);
useEffect(() => {
return () => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
}
};
}, []);
const showToast = (type, message) => {
if (!message) return;
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
setToast({ type, message });
toastTimeoutRef.current = window.setTimeout(() => {
setToast(null);
toastTimeoutRef.current = null;
}, 4000);
};
const closeToast = () => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
toastTimeoutRef.current = null;
}
setToast(null);
};
const validate = (data = formData) => { const validate = (data = formData) => {
const newErrors = {}; const newErrors = {};
@ -49,33 +78,12 @@ const PublicContactForm = () => {
if (!data.email.trim()) newErrors.email = "Registered Email is required."; if (!data.email.trim()) newErrors.email = "Registered Email is required.";
else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email))
newErrors.email = "Enter a valid email address."; newErrors.email = "Enter a valid email address.";
// if (!data.contactName.trim()) newErrors.contactName = "Contact Person Name is required.";
// if (!data.contactPhone.trim()) {
// newErrors.contactPhone = "Contact Phone is required.";
// } else if (!/^\d{10,12}$/.test(data.contactPhone)) {
// newErrors.contactPhone = "Enter a valid phone number (1012 digits).";
// }
setErrors(newErrors); setErrors(newErrors);
setIsValid(Object.keys(newErrors).length === 0); setIsValid(Object.keys(newErrors).length === 0);
return newErrors; return newErrors;
}; };
// const handleNameChange = (e) => {
// const { value } = e.target;
// const filtered = value.replace(/[^A-Za-z\s]/g, "");
// setFormData((prev) => ({ ...prev, contactName: filtered }));
// validate({ ...formData, contactName: filtered });
// };
// const handlePhoneChange = (e) => {
// let { value } = e.target;
// value = value.replace(/\D/g, "");
// if (value.length > 12) value = value.slice(0, 12);
// setFormData((prev) => ({ ...prev, contactPhone: value }));
// validate({ ...formData, contactPhone: value });
// };
const handleChange = (e) => { const handleChange = (e) => {
const { name, value } = e.target; const { name, value } = e.target;
const updated = { ...formData, [name]: value }; const updated = { ...formData, [name]: value };
@ -113,9 +121,12 @@ const PublicContactForm = () => {
const response = await apiClient.post("/forgot-password/request-otp", payload); const response = await apiClient.post("/forgot-password/request-otp", payload);
if (response?.data) { if (response?.data) {
navigate("/change-password", { showToast('success', 'OTP sent to your registered email successfully!');
state: { email: formData.email.trim() }, setTimeout(() => {
}); navigate("/change-password", {
state: { email: formData.email.trim() },
});
}, 1500);
} else { } else {
setErrorMsg("Something went wrong. Please try again."); setErrorMsg("Something went wrong. Please try again.");
} }
@ -165,7 +176,6 @@ const PublicContactForm = () => {
setLoading(false); setLoading(false);
} }
}; };
const handleResendOtp = () => { const handleResendOtp = () => {
setOtpMsg("A new OTP has been sent to your registered email."); setOtpMsg("A new OTP has been sent to your registered email.");
@ -174,6 +184,29 @@ const PublicContactForm = () => {
return ( return (
<div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4"> <div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4">
{toast && (
<div className="fixed top-6 inset-x-0 z-50 flex justify-center px-4">
<div
className={`text-sm rounded px-3 py-2 border flex items-start justify-between gap-3 shadow ${
toast.type === 'success'
? 'bg-[#F3FAF4] border-[#C6E7D8] text-[#2F663C]'
: 'bg-[#FEF2F2] border-[#FECACA] text-[#B91C1C]'
}`}
>
<div className="flex items-start gap-2">
<span>{toast.message}</span>
</div>
<button
type="button"
className="flex h-6 w-6 items-center justify-center rounded hover:bg-black/5"
onClick={closeToast}
>
</button>
</div>
</div>
)}
<div className="w-full max-w-md"> <div className="w-full max-w-md">
<div className="bg-white rounded-lg shadow-sm ring-1 ring-gray-200 overflow-hidden"> <div className="bg-white rounded-lg shadow-sm ring-1 ring-gray-200 overflow-hidden">
<div className="px-7 py-8 border-b border-gray-200 bg-[#F2ECCF] text-center"> <div className="px-7 py-8 border-b border-gray-200 bg-[#F2ECCF] text-center">
@ -210,8 +243,9 @@ const PublicContactForm = () => {
error={errors.establishmentName} error={errors.establishmentName}
/> />
<InputField <InputField
label="Establishment ID (if known)" label="Establishment ID"
name="establishmentId" name="establishmentId"
required
value={formData.establishmentId} value={formData.establishmentId}
onChange={handleChange} onChange={handleChange}
/> />
@ -224,35 +258,6 @@ const PublicContactForm = () => {
onChange={handleChange} onChange={handleChange}
error={errors.email} error={errors.email}
/> />
{/* <InputField
label="Contact Person Name"
name="contactName"
required
value={formData.contactName}
onChange={handleNameChange}
error={errors.contactName}
/>
<InputField
label="Contact Phone"
name="contactPhone"
value={formData.contactPhone}
onChange={handlePhoneChange}
error={errors.contactPhone}
placeholder="Enter phone number"
maxLength={12}
/>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Additional Notes
</label>
<textarea
name="notes"
rows="3"
value={formData.notes}
onChange={handleChange}
className="block w-full rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 py-2 text-sm bg-white"
></textarea>
</div> */}
<div className="mt-4"> <div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1"> <label className="block text-sm font-medium text-gray-700 mb-1">
@ -266,18 +271,18 @@ const PublicContactForm = () => {
{captcha} {captcha}
</div> </div>
<button <button
type="button" type="button"
onClick={generateCaptcha} onClick={generateCaptcha}
className="flex items-center gap-1 text-sm text-[#92722A] hover:underline" className="flex items-center gap-1 text-sm text-[#92722A] hover:underline"
> >
<RefreshCw size={14} className="text-[#92722A]" /> <RefreshCw size={14} className="text-[#92722A]" />
Refresh Refresh
</button> </button>
</div> </div>
<p className="text-xs text-gray-500 mt-1"> <p className="text-xs text-gray-500 mt-1">
If you cannot read the code, click "Refresh" or type:{" "} If you cannot read the code, click "Refresh" or type:{" "}
<span className="font-mono">{captcha}</span> <span className="font-mono">{captcha}</span>
</p> </p>
<input <input
type="text" type="text"
name="captcha" name="captcha"