jai #16

Merged
jaipandey merged 4 commits from jai into main 2025-08-05 06:44:08 +00:00
4 changed files with 441 additions and 425 deletions
Showing only changes of commit 334996d343 - Show all commits

View File

@ -3,7 +3,6 @@ import { PiDotsThreeOutlineVerticalFill } from 'react-icons/pi';
import api from '../../config/api';
import { Transaction } from '../transactions/Transactions';
import { useNavigate } from 'react-router-dom';
import { FaCheck } from 'react-icons/fa';

View File

@ -12,6 +12,7 @@ type ContactSchema = [{
firstName: string
lastName: string
email: string
phone: string
}]
const Contacts = () => {
@ -121,7 +122,10 @@ const Contacts = () => {
<div className='px-1.5'>
<div className='flex justify-end my-2 cursor-pointer'>
<div
onClick={() => setShowModal((prev) => !prev)}
onClick={() => {
setShowModal((prev) => !prev);
setActionStatus("Add")
}}
className="flex items-center gap-2 bg-[var(--primary)] px-3 py-1.5 rounded-sm hover:opacity-90 ">
<IoMdAdd className="text-white" />
<button
@ -143,7 +147,7 @@ const Contacts = () => {
<tbody className="divide-y divide-gray-200">
{loading ? (
<tr>
<td colSpan="4" className="relative h-100"><LoaderUi/></td>
<td colSpan="4" className="relative h-100"><LoaderUi /></td>
</tr>
) : contacts.length === 0 ? (
<tr>

View File

@ -1,6 +1,6 @@
// ContactForm.tsx
import React, { useEffect, useState } from 'react';
import { FaSpinner } from 'react-icons/fa';
import React, { useEffect, useState } from "react";
import { FaSpinner } from "react-icons/fa";
export interface ContactData {
contactId?: number;
@ -10,32 +10,38 @@ export interface ContactData {
title: string;
company: string;
website: string;
phones: string[];
phone: string;
}
interface Props {
onSubmit: (data: ContactData) => void;
loading: boolean;
setShowModal: () => React.Dispatch<React.SetStateAction<boolean>>
actionStatus: string,
editJsonData: any
setShowModal: () => React.Dispatch<React.SetStateAction<boolean>>;
actionStatus: string;
editJsonData: any;
}
const ContactFormModal = ({ onSubmit, loading, setShowModal, actionStatus, editJsonData }: Props) => {
const ContactFormModal = ({
onSubmit,
loading,
setShowModal,
actionStatus,
editJsonData,
}: Props) => {
const [formData, setFormData] = useState<ContactData>({
email: '',
firstName: '',
lastName: '',
title: '',
company: '',
website: '',
phones: [''],
email: "",
firstName: "",
lastName: "",
title: "",
company: "",
website: "",
phone: "",
});
const [errors, setErrors] = useState<{ [key: string]: string }>({});
useEffect(() => {
if (actionStatus === 'Edit' && editJsonData) {
if (actionStatus === "Edit" && editJsonData) {
setFormData({
email: editJsonData.email,
firstName: editJsonData.firstName,
@ -43,160 +49,167 @@ const ContactFormModal = ({ onSubmit, loading, setShowModal, actionStatus, editJ
title: editJsonData.title,
company: editJsonData.company,
website: editJsonData.website,
phones: editJsonData.phones,
})
phone: editJsonData.phone,
});
}
}, [actionStatus, editJsonData])
}, [actionStatus, editJsonData]);
const handleChange = (field: keyof ContactData, value: string) => {
console.log(field, value);
setFormData((prev) => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors((prev) => ({ ...prev, [field]: '' }));
setErrors((prev) => ({ ...prev, [field]: "" }));
}
};
const handlePhoneChange = (index: number, value: string) => {
const numericValue = value.replace(/\D/g, ''); // Remove non-numeric
const updatedPhones = [...formData.phones];
updatedPhones[index] = numericValue;
setFormData((prev) => ({ ...prev, phones: updatedPhones }));
// const handlePhoneChange = (index: number, value: string) => {
// const numericValue = value.replace(/\D/g, ""); // Remove non-numeric
// const updatedPhones = [...formData.phone];
// updatedPhones[index] = numericValue;
// setFormData((prev) => ({ ...prev, phones: updatedPhones }));
const errorKey = `phones_${index}`;
if (errors[errorKey]) {
setErrors((prev) => ({ ...prev, [errorKey]: '' }));
}
};
// const errorKey = `phones_${index}`;
// if (errors[errorKey]) {
// setErrors((prev) => ({ ...prev, [errorKey]: "" }));
// }
// };
// const addPhoneField = () => {
// setFormData((prev) => ({ ...prev, phone: [...prev.phone, ''] }));
// };
const addPhoneField = () => {
setFormData((prev) => ({ ...prev, phones: [...prev.phones, ''] }));
};
const removePhoneField = (index: number) => {
const updatedPhones = formData.phones.filter((_, i) => i !== index);
setFormData((prev) => ({ ...prev, phones: updatedPhones }));
};
// const removePhoneField = (index: number) => {
// const updatedPhones = formData.phones.filter((_, i) => i !== index);
// setFormData((prev) => ({ ...prev, phones: updatedPhones }));
// };
const validate = () => {
const newErrors: { [key: string]: string } = {};
const nameRegex = /^[a-zA-Z\s\-']+$/;
const emailRegex = /\S+@\S+\.\S+/;
// const nameRegex = /^[a-zA-Z\s\-']+$/;
const urlRegex = /^(https?:\/\/)?([\w-]+\.)+[\w-]{2,}(\/.*)?$/;
const phoneRegex = /^\d+$/;
const phoneRegex =
/^\+?\d{1,4}?[-.\s]?\(?\d{2,5}\)?[-.\s]?\d{3,5}[-.\s]?\d{3,5}$/;
// Email
if (!formData.email.trim()) {
newErrors.email = 'Email is required';
} else if (!/\S+@\S+\.\S+/.test(formData.email)) {
newErrors.email = 'Invalid email address';
newErrors.email = "Email is required";
} else if (!emailRegex.test(formData.email)) {
newErrors.email = "Invalid email address";
}
// // First Name
// if (!formData.firstName.trim()) {
// newErrors.firstName = 'First name is required';
// } else if (!nameRegex.test(formData.firstName)) {
// newErrors.firstName = 'First name contains invalid characters';
// } else
// if (formData.firstName.trim() && !nameRegex.test(formData.firstName)) {
// newErrors.firstName = "First name contains invalid characters";
// }
// Last Name
if (!formData.lastName.trim()) {
newErrors.lastName = 'Last name is required';
} else if (!nameRegex.test(formData.lastName)) {
newErrors.lastName = 'Last name contains invalid characters';
newErrors.lastName = "Last name is required";
}
// else if (!nameRegex.test(formData.lastName)) {
// newErrors.lastName = "Last name contains invalid characters";
// }
// // Title
// if (!formData.title.trim()) {
// newErrors.title = 'Title is required';
// }
// Website (optional but validate if present)
if (formData.website.trim() && !urlRegex.test(formData.website)) {
newErrors.website = 'Invalid website URL';
newErrors.website = "Invalid website URL";
}
// Phones
// formData.phones.forEach((phone, index) => {
// if (!phone.trim()) {
// newErrors[`phones_${index}`] = 'Phone number is required';
// } else if (!phoneRegex.test(phone)) {
// newErrors[`phones_${index}`] = 'Phone number must contain only digits';
// }
// });
// Phone
if (formData.phone.trim() && !phoneRegex.test(formData.phone)) {
newErrors.phone = "Phone number must contain only digits";
}
return newErrors;
};
const handleSubmit = async () => {
const validationErrors = validate();
let type = 'Add'
let payload = formData
let type = "Add";
let payload = formData;
console.log(payload);
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors);
return;
}
try {
if (actionStatus === 'Edit') {
type = 'Edit'
if (actionStatus === "Edit") {
type = "Edit";
payload = {
...formData,
contactId: editJsonData.id
}
contactId: editJsonData.id,
};
}
await onSubmit(payload, type);
setFormData({
email: '',
firstName: '',
lastName: '',
title: '',
company: '',
website: '',
phones: [''],
email: "",
firstName: "",
lastName: "",
title: "",
company: "",
website: "",
phone: "",
});
setErrors({});
} catch (err) {
console.error('Submit failed:', err);
console.error("Submit failed:", err);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-white/5 backdrop-blur-sm bg-opacity-50">
<div className="bg-white rounded-md p-6 max-w-[700px] w-full shadow-lg relative">
<div className="ms-2 space-y-2 max-w-[60vw]">
<h2 className="text-lg font-medium text-slate-500">Add Contact</h2>
<h2 className="text-lg font-medium text-slate-500">{`${actionStatus} Contact`}</h2>
<div className="grid grid-cols-2 gap-3">
{[
{ label: 'First Name', field: 'firstName' },
{ label: 'Last Name', field: 'lastName' },
{ label: 'Email', field: 'email' },
{ label: 'Title', field: 'title' },
{ label: 'Company', field: 'company' },
{ label: 'Website', field: 'website' },
].map(({ label, field }) => (
{ label: "First Name", field: "firstName" },
{ label: "Last Name", field: "lastName" },
{ label: "Email", field: "email", fieldType: "email" },
{ label: "Title", field: "title" },
{ label: "Company", field: "company" },
{ label: "Website", field: "website", fieldType: "url" },
{ label: "Phone", field: "phone", fieldType: "tel" },
].map(({ label, field, fieldType }) => (
<div key={field} className="flex flex-col">
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">{label}</label>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">
{label}
</label>
<input
type={field === 'email' ? 'email' : 'text'}
value={(formData[field as keyof ContactData] as string) || ''}
onChange={(e) => handleChange(field as keyof ContactData, e.target.value)}
type={fieldType ? fieldType : "text"}
value={(formData[field as keyof ContactData] as string) || ""}
onChange={(e) =>
handleChange(field as keyof ContactData, e.target.value)
}
required={true}
className="px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
placeholder={`Enter ${label}`}
/>
{errors[field] && <span className="text-sm text-red-500 mt-1">{errors[field]}</span>}
{errors[field] && (
<span className="text-sm text-red-500 mt-1">
{errors[field]}
</span>
)}
</div>
))}
</div>
<div>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">Phone Numbers</label>
{/* <div>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">Phone Number</label>
<div className="space-y-2">
{formData?.phones?.map((phone, index) => (
<div key={index} className="flex flex-col gap-1">
@ -233,7 +246,7 @@ const ContactFormModal = ({ onSubmit, loading, setShowModal, actionStatus, editJ
+ Add another phone
</button>
</div>
</div>
</div> */}
<div className="flex justify-end">
<button
@ -241,7 +254,9 @@ const ContactFormModal = ({ onSubmit, loading, setShowModal, actionStatus, editJ
onClick={() => setShowModal((prev) => !prev)}
disabled={loading}
className="bg-gray-300 px-5 py-1.5 rounded-md text-slate-700 text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer me-3"
> Cancel
>
{" "}
Cancel
</button>
<button
type="button"
@ -255,13 +270,9 @@ const ContactFormModal = ({ onSubmit, loading, setShowModal, actionStatus, editJ
SAVING...
</>
) : (
`${actionStatus?.toUpperCase() || 'SAVE'} CONTACT`
`${actionStatus?.toUpperCase() || "SAVE"} CONTACT`
)}
</button>
</div>
</div>
</div>

View File

@ -1,6 +1,6 @@
// ContactForm.tsx
import React, { useState } from 'react';
import { FaSpinner } from 'react-icons/fa';
import React, { useState } from "react";
import { FaSpinner } from "react-icons/fa";
export interface ContactData {
contactId?: number;
@ -10,7 +10,7 @@ export interface ContactData {
title: string;
company: string;
website: string;
phones: string[];
phone: string;
}
interface Props {
@ -20,13 +20,13 @@ interface Props {
const ContactForm = ({ onSubmit, loading }: Props) => {
const [formData, setFormData] = useState<ContactData>({
email: '',
firstName: '',
lastName: '',
title: '',
company: '',
website: '',
phones: [''],
email: "",
firstName: "",
lastName: "",
title: "",
company: "",
website: "",
phone: "",
});
const [errors, setErrors] = useState<{ [key: string]: string }>({});
@ -34,44 +34,44 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
const handleChange = (field: keyof ContactData, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors((prev) => ({ ...prev, [field]: '' }));
setErrors((prev) => ({ ...prev, [field]: "" }));
}
};
const handlePhoneChange = (index: number, value: string) => {
const numericValue = value.replace(/\D/g, ''); // Remove non-numeric
const updatedPhones = [...formData.phones];
updatedPhones[index] = numericValue;
setFormData((prev) => ({ ...prev, phones: updatedPhones }));
// const handlePhoneChange = (index: number, value: string) => {
// const numericValue = value.replace(/\D/g, ""); // Remove non-numeric
// const updatedPhone = [...formData.phone];
// updatedPhone[index] = numericValue;
// setFormData((prev) => ({ ...prev, phone: updatedPhone }));
const errorKey = `phones_${index}`;
if (errors[errorKey]) {
setErrors((prev) => ({ ...prev, [errorKey]: '' }));
}
};
// const errorKey = `phone_${index}`;
// if (errors[errorKey]) {
// setErrors((prev) => ({ ...prev, [errorKey]: "" }));
// }
// };
// const addPhoneField = () => {
// setFormData((prev) => ({ ...prev, phone: [...prev.phone, ""] }));
// };
const addPhoneField = () => {
setFormData((prev) => ({ ...prev, phones: [...prev.phones, ''] }));
};
const removePhoneField = (index: number) => {
const updatedPhones = formData.phones.filter((_, i) => i !== index);
setFormData((prev) => ({ ...prev, phones: updatedPhones }));
};
// const removePhoneField = (index: number) => {
// const updatedPhone = formData.phone.filter((_, i) => i !== index);
// setFormData((prev) => ({ ...prev, phone: updatedPhone }));
// };
const validate = () => {
const newErrors: { [key: string]: string } = {};
const nameRegex = /^[a-zA-Z\s\-']+$/;
// const nameRegex = /^[a-zA-Z\s\-']+$/;
const urlRegex = /^(https?:\/\/)?([\w-]+\.)+[\w-]{2,}(\/.*)?$/;
const phoneRegex = /^\d+$/;
const phoneRegex =
/^\+?\d{1,4}?[-.\s]?\(?\d{2,5}\)?[-.\s]?\d{3,5}[-.\s]?\d{3,5}$/;
// Email
if (!formData.email.trim()) {
newErrors.email = 'Email is required';
newErrors.email = "Email is required";
} else if (!/\S+@\S+\.\S+/.test(formData.email)) {
newErrors.email = 'Invalid email address';
newErrors.email = "Invalid email address";
}
// // First Name
@ -83,9 +83,7 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
// Last Name
if (!formData.lastName.trim()) {
newErrors.lastName = 'Last name is required';
} else if (!nameRegex.test(formData.lastName)) {
newErrors.lastName = 'Last name contains invalid characters';
newErrors.lastName = "Last name is required";
}
// // Title
@ -93,25 +91,19 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
// newErrors.title = 'Title is required';
// }
// Website (optional but validate if present)
if (formData.website.trim() && !urlRegex.test(formData.website)) {
newErrors.website = 'Invalid website URL';
newErrors.website = "Invalid website URL";
}
// Phones
// formData.phones.forEach((phone, index) => {
// if (!phone.trim()) {
// newErrors[`phones_${index}`] = 'Phone number is required';
// } else if (!phoneRegex.test(phone)) {
// newErrors[`phones_${index}`] = 'Phone number must contain only digits';
// }
// });
// Phone
if (formData.phone.trim() && !phoneRegex.test(formData.phone)) {
newErrors.phone = "Phone number must contain only digits";
}
return newErrors;
};
const handleSubmit = async () => {
const validationErrors = validate();
if (Object.keys(validationErrors).length > 0) {
@ -123,53 +115,61 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
await onSubmit(formData);
setFormData({
email: '',
firstName: '',
lastName: '',
title: '',
company: '',
website: '',
phones: [''],
email: "",
firstName: "",
lastName: "",
title: "",
company: "",
website: "",
phone: "",
});
setErrors({});
} catch (err) {
console.error('Submit failed:', err);
console.error("Submit failed:", err);
}
};
return (
<div className="ms-2 space-y-2 max-w-[60vw]">
<h2 className="text-lg font-medium text-slate-500">Add Contact</h2>
<div className="grid grid-cols-2 gap-3">
{[
{ label: 'First Name', field: 'firstName' },
{ label: 'Last Name', field: 'lastName' },
{ label: 'Email', field: 'email' },
{ label: 'Title', field: 'title' },
{ label: 'Company', field: 'company' },
{ label: 'Website', field: 'website' },
].map(({ label, field }) => (
{ label: "First Name", field: "firstName" },
{ label: "Last Name", field: "lastName" },
{ label: "Email", field: "email", fieldType: "email" },
{ label: "Title", field: "title" },
{ label: "Company", field: "company" },
{ label: "Website", field: "website", fieldType: "url" },
{ label: "Phone", field: "phone", fieldType: "tel" },
].map(({ label, field, fieldType }) => (
<div key={field} className="flex flex-col">
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">{label}</label>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">
{label}
</label>
<input
type={field === 'email' ? 'email' : 'text'}
type={fieldType ? fieldType : "text"}
value={formData[field as keyof ContactData] as string}
onChange={(e) => handleChange(field as keyof ContactData, e.target.value)}
onChange={(e) =>
handleChange(field as keyof ContactData, e.target.value)
}
required={true}
className="px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
placeholder={`Enter ${label}`}
/>
{errors[field] && <span className="text-sm text-red-500 mt-1">{errors[field]}</span>}
{errors[field] && (
<span className="text-sm text-red-500 mt-1">{errors[field]}</span>
)}
</div>
))}
</div>
<div>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">Phone Numbers</label>
{/* <div>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">
Phone Numbers
</label>
<div className="space-y-2">
{formData.phones.map((phone, index) => (
{formData.phone.map((phone, index) => (
<div key={index} className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<input
@ -178,9 +178,9 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
onChange={(e) => handlePhoneChange(index, e.target.value)}
className="flex-1 px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
maxLength={15}
placeholder='Enter Phone Numbers'
placeholder="Enter Phone Numbers"
/>
{formData.phones.length > 1 && (
{formData.phone.length > 1 && (
<button
type="button"
onClick={() => removePhoneField(index)}
@ -190,8 +190,10 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
</button>
)}
</div>
{errors[`phones_${index}`] && (
<span className="text-sm text-red-500">{errors[`phones_${index}`]}</span>
{errors[`phone_${index}`] && (
<span className="text-sm text-red-500">
{errors[`phone_${index}`]}
</span>
)}
</div>
))}
@ -204,7 +206,7 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
+ Add another phone
</button>
</div>
</div>
</div> */}
<div className="flex justify-end">
<button
@ -219,7 +221,7 @@ const ContactForm = ({ onSubmit, loading }: Props) => {
SAVING...
</>
) : (
'SAVE CONTACT'
"SAVE CONTACT"
)}
</button>
</div>