Correction in Assign Task popup.
This commit is contained in:
parent
aa50aeff98
commit
a6c6a73899
@ -2,71 +2,78 @@ import React, { useState, useEffect, useRef } from "react";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { changeMaster } from "../../slices/localVariablesSlice";
|
||||
import useMaster from "../../hooks/masterHook/useMaster";
|
||||
import { employee } from "../../data/masters";
|
||||
import { useForm, Controller } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { getCachedData } from "../../slices/apiDataManager";
|
||||
import { useProjects } from "../../hooks/useProjects";
|
||||
import { useEmployeesAllOrByProjectId } from "../../hooks/useEmployees";
|
||||
import { TasksRepository } from "../../repositories/ProjectRepository";
|
||||
import showToast from "../../services/toastService";
|
||||
|
||||
const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
// Calculate maxPlanned based on assignData
|
||||
const maxPlanned =
|
||||
assignData?.workItem?.workItem?.plannedWork -
|
||||
assignData?.workItem?.workItem?.completedWork;
|
||||
|
||||
// Zod schema for form validation
|
||||
const schema = z.object({
|
||||
selectedEmployees: z
|
||||
.array(z.string())
|
||||
.min(1, { message: "At least one employee must be selected" }),
|
||||
.min(1, { message: "At least one employee must be selected" }), // Added custom message here for consistency
|
||||
description: z.string().min(1, { message: "Description is required" }),
|
||||
plannedTask: z.preprocess(
|
||||
(val) => parseInt(val, 10),
|
||||
(val) => parseInt(val, 10), // Preprocess value to integer
|
||||
z
|
||||
.number({
|
||||
required_error: "Planned task is required",
|
||||
invalid_type_error: "Planned task must be a number",
|
||||
invalid_type_error: "Target for Today must be a number",
|
||||
})
|
||||
.int()
|
||||
.positive({ message: "Planned task must be a positive number" })
|
||||
.int() // Ensure it's an integer
|
||||
.positive({ message: "Planned task must be a positive number" }) // Must be positive
|
||||
.max(maxPlanned, {
|
||||
// Max value validation
|
||||
message: `Planned task cannot exceed ${maxPlanned}`,
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
// State for help popovers (though not fully implemented in provided snippets)
|
||||
const [isHelpVisibleTarget, setIsHelpVisibleTarget] = useState(false);
|
||||
const helpPopupRefTarget = useRef(null);
|
||||
|
||||
const [isHelpVisible, setIsHelpVisible] = useState(false);
|
||||
|
||||
// Refs for Bootstrap Popovers
|
||||
const infoRef = useRef(null);
|
||||
const infoRef1 = useRef(null);
|
||||
|
||||
// Initialize Bootstrap Popovers on component mount
|
||||
useEffect(() => {
|
||||
|
||||
if (infoRef.current) {
|
||||
new bootstrap.Popover(infoRef.current, {
|
||||
trigger: 'focus',
|
||||
placement: 'right',
|
||||
html: true,
|
||||
content: `<div>Pending Task assign for today</div>`,
|
||||
});
|
||||
// Check if Bootstrap is available globally
|
||||
if (typeof bootstrap !== 'undefined') {
|
||||
if (infoRef.current) {
|
||||
new bootstrap.Popover(infoRef.current, {
|
||||
trigger: 'focus',
|
||||
placement: 'right',
|
||||
html: true,
|
||||
content: `<div>Total Pending tasks of the Activity</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
if (infoRef1.current) {
|
||||
new bootstrap.Popover(infoRef1.current, {
|
||||
trigger: 'focus',
|
||||
placement: 'right',
|
||||
html: true,
|
||||
content: `<div>Target task for today</div>`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn("Bootstrap is not available. Popovers might not function.");
|
||||
}
|
||||
}, []); // Empty dependency array ensures this runs once on mount
|
||||
|
||||
if (infoRef1.current) {
|
||||
new bootstrap.Popover(infoRef1.current, {
|
||||
trigger: 'focus',
|
||||
placement: 'right',
|
||||
html: true,
|
||||
content: `<div>Target task for today</div>`,
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
const [plannedTask, setPlannedTask] = useState();
|
||||
// Redux state and hooks
|
||||
const selectedProject = useSelector(
|
||||
(store) => store.localVariables.projectId
|
||||
);
|
||||
@ -74,15 +81,15 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
selectedProject,
|
||||
false
|
||||
);
|
||||
|
||||
const dispatch = useDispatch();
|
||||
const { data, loading } = useMaster();
|
||||
const { loading } = useMaster(); // Assuming this is for jobRoleData loading
|
||||
const jobRoleData = getCachedData("Job Role");
|
||||
|
||||
// Local component states
|
||||
const [selectedRole, setSelectedRole] = useState("all");
|
||||
const [selectedEmployees, setSelectedEmployees] = useState([]);
|
||||
const [displayedSelection, setDisplayedSelection] = useState("");
|
||||
const [displayedSelection, setDisplayedSelection] = useState(""); // This state is not updated in the provided code, consider if it's still needed or how it should be updated
|
||||
|
||||
// React Hook Form setup
|
||||
const {
|
||||
handleSubmit,
|
||||
control,
|
||||
@ -90,84 +97,90 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
watch,
|
||||
formState: { errors },
|
||||
reset,
|
||||
trigger, // <--- IMPORTANT: Destructure 'trigger' here
|
||||
} = useForm({
|
||||
defaultValues: {
|
||||
selectedEmployees: [],
|
||||
description: "",
|
||||
plannedTask: "",
|
||||
},
|
||||
resolver: zodResolver(schema),
|
||||
resolver: zodResolver(schema), // Integrate Zod schema with react-hook-form
|
||||
});
|
||||
|
||||
// Handler for employee checkbox changes
|
||||
const handleCheckboxChange = (event, user) => {
|
||||
const isChecked = event.target.checked;
|
||||
let updatedSelectedEmployees = watch("selectedEmployees") || [];
|
||||
let updatedSelectedEmployees = watch("selectedEmployees") || []; // Get current selected employees from form state
|
||||
|
||||
if (isChecked) {
|
||||
// Add employee if checked and not already in the list
|
||||
if (!updatedSelectedEmployees.includes(user.id)) {
|
||||
updatedSelectedEmployees = [...updatedSelectedEmployees, user.id];
|
||||
}
|
||||
} else {
|
||||
// Remove employee if unchecked
|
||||
updatedSelectedEmployees = updatedSelectedEmployees.filter(
|
||||
(id) => id !== user.id
|
||||
);
|
||||
}
|
||||
|
||||
// Update the form state with the new list of selected employees
|
||||
setValue("selectedEmployees", updatedSelectedEmployees);
|
||||
trigger("selectedEmployees"); // <--- IMPORTANT: Trigger validation here
|
||||
};
|
||||
|
||||
// Effect to dispatch action for Job Role master data
|
||||
useEffect(() => {
|
||||
dispatch(changeMaster("Job Role"));
|
||||
// Cleanup function to reset selected role when component unmounts or dispatch changes
|
||||
return () => setSelectedRole("all");
|
||||
}, [dispatch]);
|
||||
|
||||
// Handler for role filter change
|
||||
const handleRoleChange = (event) => {
|
||||
setSelectedRole(event.target.value);
|
||||
};
|
||||
|
||||
// Filter employees based on selected role
|
||||
const filteredEmployees =
|
||||
selectedRole === "all"
|
||||
? employees
|
||||
: employees?.filter(
|
||||
(emp) => String(emp.jobRoleId || "") === selectedRole
|
||||
);
|
||||
(emp) => String(emp.jobRoleId || "") === selectedRole
|
||||
);
|
||||
|
||||
// Form submission handler
|
||||
const onSubmit = async (data) => {
|
||||
const selectedEmployeeIds = data.selectedEmployees;
|
||||
|
||||
// Prepare taskTeam data (only IDs are needed for the backend based on previous context)
|
||||
const taskTeamWithDetails = selectedEmployeeIds
|
||||
.map((empId) => {
|
||||
const employee = employees.find((e) => e.id === empId);
|
||||
const jobRole = jobRoleData?.find((r) => r.id === employee?.jobRoleId);
|
||||
return employee
|
||||
? employee.id
|
||||
: null;
|
||||
return empId; // Return just the ID as per previous discussions
|
||||
})
|
||||
.filter(Boolean);
|
||||
.filter(Boolean); // Ensure no nulls if employee not found (though unlikely with current logic)
|
||||
|
||||
// Format data for API call
|
||||
const formattedData = {
|
||||
taskTeam: taskTeamWithDetails,
|
||||
plannedTask: data.plannedTask,
|
||||
description: data.description,
|
||||
assignmentDate: new Date().toISOString(),
|
||||
assignmentDate: new Date().toISOString(), // Current date/time
|
||||
workItemId: assignData?.workItem?.workItem.id,
|
||||
};
|
||||
|
||||
try {
|
||||
let response = await TasksRepository.assignTask(formattedData);
|
||||
showToast("Task Successfully Assigned", "success");
|
||||
reset();
|
||||
onClose();
|
||||
// Call API to assign task
|
||||
await TasksRepository.assignTask(formattedData);
|
||||
showToast("Task Successfully Assigned", "success"); // Show success toast
|
||||
reset(); // Reset form fields
|
||||
onClose(); // Close the modal
|
||||
} catch (error) {
|
||||
console.log(error.response);
|
||||
showToast("something wrong", "error");
|
||||
console.error("Error assigning task:", error); // Log the full error for debugging
|
||||
showToast("Something went wrong. Please try again.", "error"); // Show generic error toast
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
dispatch(changeMaster("Job Role"));
|
||||
return () => setSelectedRole("all");
|
||||
}, [dispatch]);
|
||||
|
||||
// Handler to close the modal and reset form
|
||||
const closedModel = () => {
|
||||
reset();
|
||||
onClose();
|
||||
@ -200,7 +213,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
assignData?.workItem?.workItem?.activityMaster
|
||||
?.activityName,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.filter(Boolean) // Filter out any undefined/null values
|
||||
.map((item, index, array) => (
|
||||
<span key={index} className="d-flex align-items-center">
|
||||
{item}
|
||||
@ -232,7 +245,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
<li key="all">
|
||||
<button
|
||||
type="button"
|
||||
className="dropdown-item py-1" // Added py-1 for vertical padding
|
||||
className="dropdown-item py-1"
|
||||
onClick={() =>
|
||||
handleRoleChange({
|
||||
target: { value: "all" },
|
||||
@ -246,7 +259,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
<li key={user.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="dropdown-item py-1" // Added py-1 for vertical padding
|
||||
className="dropdown-item py-1"
|
||||
value={user.id}
|
||||
onClick={handleRoleChange}
|
||||
>
|
||||
@ -256,24 +269,24 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{employeeLoading && <div>Loading...</div>}
|
||||
{employeeLoading && <div>Loading employees...</div>}
|
||||
{!employeeLoading &&
|
||||
filteredEmployees?.length === 0 &&
|
||||
employees && <div>No employees found</div>}
|
||||
employees && (
|
||||
<div>No employees found for the selected role.</div>
|
||||
)}
|
||||
|
||||
<div className="row">
|
||||
<div className="col-12 h-sm-25 overflow-auto mt-2">
|
||||
{selectedRole !== "" && (
|
||||
<div className="row">
|
||||
{loading ? (
|
||||
{loading ? ( // Assuming 'loading' here refers to master data loading
|
||||
<div className="col-12">
|
||||
<p className="text-center">Loading...</p>
|
||||
<p className="text-center">Loading roles...</p>
|
||||
</div>
|
||||
) : filteredEmployees?.length > 0 ? (
|
||||
filteredEmployees?.map((emp) => {
|
||||
@ -282,7 +295,10 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
);
|
||||
|
||||
return (
|
||||
<div key={emp.id} className="col-6 col-md-4 col-lg-3 mb-3">
|
||||
<div
|
||||
key={emp.id}
|
||||
className="col-6 col-md-4 col-lg-3 mb-3"
|
||||
>
|
||||
<div className="form-check d-flex align-items-start">
|
||||
<Controller
|
||||
name="selectedEmployees"
|
||||
@ -294,7 +310,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
type="checkbox"
|
||||
id={`employee-${emp?.id}`}
|
||||
value={emp.id}
|
||||
checked={field.value.includes(emp.id)}
|
||||
checked={field.value?.includes(emp.id)}
|
||||
onChange={(e) => {
|
||||
handleCheckboxChange(e, emp);
|
||||
}}
|
||||
@ -305,7 +321,10 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
<p className="mb-0" style={{ fontSize: "13px" }}>
|
||||
{emp.firstName} {emp.lastName}
|
||||
</p>
|
||||
<small className="text-muted" style={{ fontSize: "11px" }}>
|
||||
<small
|
||||
className="text-muted"
|
||||
style={{ fontSize: "11px" }}
|
||||
>
|
||||
{loading ? (
|
||||
<span className="placeholder-glow">
|
||||
<span className="placeholder col-6"></span>
|
||||
@ -319,7 +338,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
) : (
|
||||
<div className="col-12">
|
||||
<p className="text-center">No employees found for the selected role.</p>
|
||||
</div>
|
||||
@ -328,6 +347,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="col-12 h-25 overflow-auto"
|
||||
style={{ maxHeight: "200px" }}
|
||||
@ -351,9 +371,6 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
className=" btn-close-white p-0 m-0"
|
||||
aria-label="Close"
|
||||
onClick={() => {
|
||||
const employeeToRemove = employees.find(
|
||||
(e) => e.id === empId
|
||||
);
|
||||
const updatedSelected = watch(
|
||||
"selectedEmployees"
|
||||
).filter((id) => id !== empId);
|
||||
@ -361,6 +378,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
"selectedEmployees",
|
||||
updatedSelected
|
||||
);
|
||||
trigger("selectedEmployees"); // <--- IMPORTANT: Trigger validation on removing badge
|
||||
}}
|
||||
>
|
||||
<i className="icon-base bx bx-x icon-md "></i>
|
||||
@ -374,6 +392,13 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!loading && errors.selectedEmployees && (
|
||||
<div className="danger-text mt-1">
|
||||
<p>{errors.selectedEmployees.message}</p> {/* Use message from Zod schema */}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pending Task of Activity section */}
|
||||
<div className="col-md text-start mx-0 px-0">
|
||||
<div className="form-check form-check-inline mt-3 px-1">
|
||||
<label className="form-text text-dark align-items-center d-flex" htmlFor="inlineCheckbox1">
|
||||
@ -414,7 +439,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Target for Today input and validation */}
|
||||
<div className="col-md text-start mx-0 px-0">
|
||||
<div className="form-check form-check-inline mt-2 px-1 mb-2 text-start">
|
||||
<label
|
||||
@ -424,7 +449,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
<span>Target for Today</span> <span style={{ marginLeft: '46px' }}>:</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="form-check form-check-inline col-sm-3 mt-2" style={{ marginLeft: '-28px' }}>
|
||||
<div className="form-check form-check-inline col-sm-3 mt-2" style={{ marginLeft: '-28px' }}>
|
||||
<Controller
|
||||
name="plannedTask"
|
||||
control={control}
|
||||
@ -449,7 +474,6 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
data-bs-trigger="focus"
|
||||
data-bs-placement="right"
|
||||
data-bs-html="true"
|
||||
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
|
||||
@ -469,7 +493,6 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
{errors.plannedTask && (
|
||||
@ -486,14 +509,11 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{errors.selectedEmployees && (
|
||||
<div className="danger-text mt-1">
|
||||
<p>{errors.selectedEmployees.message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Description field */}
|
||||
<label
|
||||
className="form-text fs-7 m-1 text-lg text-dark"
|
||||
htmlFor="inlineCheckbox1"
|
||||
htmlFor="descriptionTextarea" // Changed htmlFor for better accessibility
|
||||
>
|
||||
Description
|
||||
</label>
|
||||
@ -504,7 +524,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
<textarea
|
||||
{...field}
|
||||
className="form-control"
|
||||
id="exampleFormControlTextarea1"
|
||||
id="descriptionTextarea" // Changed id for better accessibility
|
||||
rows="2"
|
||||
/>
|
||||
)}
|
||||
@ -516,6 +536,7 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit and Cancel buttons */}
|
||||
<div className="col-12 d-flex justify-content-center align-items-center gap-sm-6 gap-8 text-center mt-1">
|
||||
<button type="submit" className="btn btn-sm btn-primary ">
|
||||
Submit
|
||||
@ -539,4 +560,5 @@ const AssignRoleModel = ({ assignData, onClose }) => {
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AssignRoleModel;
|
||||
|
Loading…
x
Reference in New Issue
Block a user