created new contact form

This commit is contained in:
Pramod Mahajan 2025-05-16 19:14:34 +05:30
parent a1ee9dac38
commit c7b5a0ba7d

View File

@ -1,40 +1,82 @@
import React, { useEffect } from "react";
import { useForm, useFieldArray, FormProvider } from "react-hook-form";
import React, { useEffect, useState } from "react";
import {
useForm,
useFieldArray,
FormProvider,
useFormContext,
} from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import TagInput from "../common/TagInput";
import { z } from "zod";
import IconButton from "../common/IconButton";
import useMaster from "../../hooks/masterHook/useMaster";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import { useBuckets } from "../../hooks/useDirectory";
import {useProjects} from "../../hooks/useProjects";
export const directorySchema = z.object({
firstName: z.string().min(1, "First Name is required"),
lastName: z.string().min(1, "Last Name is required"),
export const ContactSchema = z.object({
Name: z.string().min(1, "Name is required"),
organization: z.string().min(1, "Organization name is required"),
type: z.string().min(1, "Type is required"),
ContactCategoryId: z.string().optional(),
address: z.string().optional(),
description: z.string().min(1, { message: "Description is required" }),
email: z
.array(z.string().email("Invalid email"))
.nonempty("At least one email required"),
phone: z
.array(z.string().regex(/^\d{10}$/, "Phone must be 10 digits"))
.nonempty("At least one phone number is required"),
tags: z.array(z.string()).optional(),
description: z.string().min( 1, {message: "Description is required"} ),
ProjectId :z.string().optional(),
ContactEmails: z
.array(
z.object({
label: z.string(),
emailAddress: z.string().email("Invalid email"),
})
)
.optional()
.default([]),
ContactPhones: z
.array(
z.object({
label: z.string(),
phoneNumber: z.string().regex(/^\d{10}$/, "Phone must be 10 digits"),
})
)
.optional()
.default([]),
tags: z
.array(
z.object({
id: z.string().nullable(),
name: z.string(),
})
)
.optional(),
BucketIds: z.array(z.string()).optional(),
});
const ManageDirectory = ({submitContact,onCLosed}) => {
const selectedMaster = useSelector(
(store) => store.localVariables.selectedMaster
);
const [categoryData, setCategoryData] = useState([]);
const [TagsData, setTagsData] = useState([]);
const { data, loading } = useMaster();
const {buckets, loading: bucketsLoaging} = useBuckets();
const {projects, loading: projectLoading} = useProjects();
const [IsSubmitting,setSubmitting] = useState(false)
const dispatch = useDispatch();
const ManageDirectory = () => {
const methods = useForm({
resolver: zodResolver(directorySchema),
resolver: zodResolver(ContactSchema),
defaultValues: {
firstName: "",
lastName: "",
Name: "",
organization: "",
type: "",
ContactCategoryId: null,
address: "",
description: "",
email: [""],
phone: [""],
ProjectId:null,
ContactEmails: [],
ContactPhones: [],
tags: [],
BucketIds: [],
},
});
@ -44,6 +86,9 @@ const ManageDirectory = () => {
control,
getValues,
trigger,
setValue,
watch,
reset,
formState: { errors },
} = methods;
@ -51,160 +96,357 @@ const ManageDirectory = () => {
fields: emailFields,
append: appendEmail,
remove: removeEmail,
} = useFieldArray({ control, name: "email" });
} = useFieldArray({ control, name: "ContactEmails" });
const {
fields: phoneFields,
append: appendPhone,
remove: removePhone,
} = useFieldArray({ control, name: "phone" });
} = useFieldArray({ control, name: "ContactPhones" });
useEffect(() => {
if (emailFields.length === 0) appendEmail("");
if (phoneFields.length === 0) appendPhone("");
if (emailFields.length === 0) appendEmail("");
if (phoneFields.length === 0) appendPhone("");
}, [emailFields.length, phoneFields.length]);
const onSubmit = (data) => {
// console.log("Submitted:\n" + JSON.stringify(data, null, 2));
};
const handleAddEmail = async () => {
const emails = getValues("email");
const emails = getValues("ContactEmails");
const lastIndex = emails.length - 1;
const valid = await trigger(`email.${lastIndex}`);
if (valid) appendEmail("");
const valid = await trigger(`ContactEmails.${lastIndex}.emailAddress`);
if (valid) {
appendEmail({ label: "Work", emailAddress: "" });
}
};
const handleAddPhone = async () => {
const phones = getValues("phone");
const phones = getValues("ContactPhones");
const lastIndex = phones.length - 1;
const valid = await trigger(`phone.${lastIndex}`);
if (valid) appendPhone("");
const valid = await trigger(`ContactPhones.${lastIndex}.phoneNumber`);
if (valid) {
appendPhone({ label: "Office", phoneNumber: "" });
}
};
useEffect(() => {
if (selectedMaster === "Contact Category") {
setCategoryData(data);
} else {
setTagsData(data);
}
}, [selectedMaster, data]);
const watchBucketIds = watch("BucketIds");
const toggleBucketId = (id) => {
const updated = watchBucketIds?.includes(id)
? watchBucketIds.filter((val) => val !== id)
: [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true });
};
const handleCheckboxChange = (id) => {
const updated = watchBucketIds.includes(id)
? watchBucketIds.filter((i) => i !== id)
: [...watchBucketIds, id];
setValue("BucketIds", updated, { shouldValidate: true });
};
const onSubmit = ( data ) =>
{
setSubmitting(true)
submitContact( data, reset, setSubmitting )
};
return (
<FormProvider {...methods}>
<form className="p-2 p-sm-0" onSubmit={handleSubmit(onSubmit)}>
<div className="text-start d-flex align-items-center">
<IconButton size={15} iconClass="bx bx-user-plus" color="primary" />{" "}
<h6 className="m-0 fw-18"> Create New Contact</h6>
</div>
<div className="row">
<div className="col-md-6">
<label className="form-label">First Name</label>
<input className="form-control form-control-sm" {...register("firstName")} />
{errors.firstName && <small className="danger-text">{errors.firstName.message}</small>}
<label className="form-label">Name</label>
<input
className="form-control form-control-sm"
{...register("Name")}
/>
{errors.Name && (
<small className="danger-text">{errors.Name.message}</small>
)}
</div>
<div className="col-md-6">
<label className="form-label">Last Name</label>
<input className="form-control form-control-sm" {...register("lastName")} />
{errors.lastName && <small className="danger-text">{errors.lastName.message}</small>}
<label className="form-label">Organization</label>
<input
className="form-control form-control-sm"
{...register("organization")}
/>
{errors.organization && (
<small className="danger-text">
{errors.organization.message}
</small>
)}
</div>
</div>
<div className="col-12">
<label className="form-label">Organization</label>
<input className="form-control form-control-sm" {...register("organization")} />
{errors.organization && <small className="danger-text">{errors.organization.message}</small>}
</div>
<div className="row">
<div className="row mt-1">
<div className="col-md-6">
<label className="form-label">Email</label>
{emailFields.map((field, index) => (<>
<div key={field.id} className="d-flex align-items-center mb-1">
<input
type="email"
className="form-control form-control-sm"
{...register(`email.${index}`)}
placeholder="email@example.com"
/>
{index === emailFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddEmail}
{emailFields.map((field, index) => (
<div
key={field.id}
className="row d-flex align-items-center mb-1"
>
<div className="col-5">
<label className="form-label">Label</label>
<select
className="form-select form-select-sm"
{...register(`ContactEmails.${index}.label`)}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1"
onClick={() => removeEmail(index)}
>
<i className="bx bx-x bx-xs" />
</button>
)}
<option value="Work">Work</option>
<option value="Personal">Personal</option>
<option value="Other">Other</option>
</select>
{errors.ContactEmails?.[index]?.label && (
<small className="danger-text">
{errors.ContactEmails[index].label.message}
</small>
)}
</div>
<div className="col-7">
<label className="form-label">Email</label>
<div className="d-flex align-items-center">
<input
type="email"
className="form-control form-control-sm"
{...register(`ContactEmails.${index}.emailAddress`)}
placeholder="email@example.com"
/>
{index === emailFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddEmail}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1 p-0"
onClick={() => removeEmail(index)}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-x bx-xs" />
</button>
)}
</div>
{errors.ContactEmails?.[index]?.emailAddress && (
<small className="danger-text">
{errors.ContactEmails[index].emailAddress.message}
</small>
)}
</div>
</div>
{errors.email?.[index] && (
<small className="danger-text ms-2">
{errors.email[index]?.message}
</small>
)}
</>
))}
</div>
<div className="col-md-6">
<label className="form-label">Phone</label>
{phoneFields.map((field, index) => (<>
<div key={field.id} className="d-flex align-items-center mb-1">
<input
type="text"
className="form-control form-control-sm"
{...register(`phone.${index}`)}
placeholder="9876543210"
/>
{index === phoneFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddPhone}
{phoneFields.map((field, index) => (
<div
key={field.id}
className="row d-flex align-items-center mb-2"
>
<div className="col-5">
<label className="form-label">Label</label>
<select
className="form-select form-select-sm"
{...register(`ContactPhones.${index}.label`)}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1"
onClick={() => removePhone(index)} // Remove the phone field
>
<i className="bx bx-x bx-xs" />
</button>
)}
<option value="Office">Office</option>
<option value="Personal">Personal</option>
<option value="Business">Business</option>
</select>
{errors.phone?.[index]?.label && (
<small className="danger-text">
{errors.ContactPhones[index].label.message}
</small>
)}
</div>
<div className="col-7">
<label className="form-label">Phone</label>
<div className="d-flex align-items-center">
<input
type="text"
className="form-control form-control-sm"
{...register(`ContactPhones.${index}.phoneNumber`)}
placeholder="9876543210"
/>
{index === phoneFields.length - 1 ? (
<button
type="button"
className="btn btn-xs btn-primary ms-1"
onClick={handleAddPhone}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-plus bx-xs" />
</button>
) : (
<button
type="button"
className="btn btn-xs btn-danger ms-1"
onClick={() => removePhone(index)}
style={{ width: "24px", height: "24px" }}
>
<i className="bx bx-x bx-xs" />
</button>
)}
</div>
{errors.ContactPhones?.[index]?.phoneNumber && (
<small className="danger-text">
{errors.ContactPhones[index].phoneNumber.message}
</small>
)}
</div>
</div>
{errors.phone?.[ index ] && <small className="danger-text ms-2">{errors.phone[ index ]?.message}</small>}
</>
))}
</div>
</div>
<div className="row my-1">
<div className="col-md-6">
<label className="form-label">Type</label>
<input className="form-control form-control-sm" {...register("type")} />
{errors.type && <small className="danger-text">{errors.type.message}</small>}
<label className="form-label">Category</label>
<select
defaultValue=""
className="form-select form-select-sm"
{...register("ContactCategoryId")}
onClick={() => dispatch(changeMaster("Contact Category"))}
>
{loading && !categoryData ? (
<option disabled value="">
Loading...
</option>
) : (
<>
<option disabled selected value="">
Select Category
</option>
{categoryData?.map((cate) => (
<option key={cate.id} value={cate.id}>
{cate.name}
</option>
))}
</>
)}
</select>
{errors.ContactCategoryId && (
<small className="danger-text">{errors.ContactCategoryId.message}</small>
)}
</div>
<div className="col-md-6">
<TagInput name="tags" label="Tags" />
<TagInput name="tags" label="Tags" options={data} />
</div>
</div>
<div className="row">
<div className="col-md-6 text-start">
<label className="form-label mb-2">Select Label</label>
<div
className="row px-1"
style={{ maxHeight: "100px", overflowY: "auto" }}
>
{bucketsLoaging && <p>Loading...</p>}
{buckets?.map((item) => (
<div className="col-6 col-sm-6 " key={item.id}>
<div className="form-check mb-2">
<input
type="checkbox"
className="form-check-input"
id={`item-${item.id}`}
checked={watchBucketIds.includes(item.id)}
onChange={() => handleCheckboxChange(item.id)}
/>
<label
className="form-check-label"
htmlFor={`item-${item.id}`}
>
{item.name}
</label>
</div>
</div>
))}
</div>
{errors.BucketIds && (
<small className="text-danger">{errors.BucketIds.message}</small>
)}
</div>
<div className="col-12 col-md-6">
<label className="form-label">Category</label>
<select
defaultValue=""
className="form-select form-select-sm"
{...register("ProjectId")}
>
{loading && !categoryData ? (
<option disabled value="">
Loading...
</option>
) : (
<>
<option disabled selected value="">
Select Project
</option>
{projects?.map((project) => (
<option key={project.id} value={project.id}>
{project.name}
</option>
))}
</>
)}
</select>
{errors.category && (
<small className="danger-text">{errors.category.message}</small>
)}
</div>
</div>
<div className="col-12">
<label className="form-label">Address</label>
<textarea className="form-control form-control-sm" rows="2" {...register("address")} />
<textarea
className="form-control form-control-sm"
rows="2"
{...register("address")}
/>
</div>
<div className="col-12">
<label className="form-label">Description</label>
<textarea className="form-control form-control-sm" rows="2" {...register("description")} />
{errors.description && <small className="danger-text">{errors.description.message}</small>}
<textarea
className="form-control form-control-sm"
rows="2"
{...register("description")}
/>
{errors.description && (
<small className="danger-text">{errors.description.message}</small>
)}
</div>
<div className="d-flex justify-content-evenly py-2">
<button className="btn btn-sm btn-primary" type="submit">Submit</button>
<button className="btn btn-sm btn-secondary" type="button">Cancel</button>
<div className="d-flex justify-content-center gap-1 py-2">
<button className="btn btn-sm btn-primary" type="submit">
{IsSubmitting ? "Please Wait..." : "Submit"}
</button>
<button className="btn btn-sm btn-secondary" type="button" onClick={onCLosed}>
Cancel
</button>
</div>
</form>
</FormProvider>