Skip to content

Instantly share code, notes, and snippets.

@Gaurav8757
Created June 24, 2024 12:51
Show Gist options
  • Save Gaurav8757/42674ec67d8a798d345caeb42b0f2af0 to your computer and use it in GitHub Desktop.
Save Gaurav8757/42674ec67d8a798d345caeb42b0f2af0 to your computer and use it in GitHub Desktop.
Use ContentEditable
function MasterView() {
const [allDetailsData, setAllDetailsData] = useState([]);
const handleNumericInput = (e) => {
const input = e.target.innerText;
const numericInput = input.replace(/[^\d.]/g, ''); // Remove any non-numeric characters
if (input !== numericInput) {
e.target.innerText = numericInput; // Update the contentEditable element with numeric value
}
};
const handleInputChange = async (itemId, value) => {
try {
// Find the item in the current data state
const itemToUpdate = allDetailsData.find(item => item._id === itemId);
if (!itemToUpdate) {
throw new Error(`Item with ID ${itemId} not found.`);
}
// Parse the input value to a float
const parsedPercentage = parseFloat(value) || 0;
// Check if cvpercentage is not 0 and is different from the current value
if (parsedPercentage === itemToUpdate.cvpercentage) {
// If not different or is zero, return without updating
return;
}
// Calculate advisorPayout and advisorPayable based on the updated cvpercentage
let advisorPayout, advisorPayable;
if (
itemToUpdate.policyType === 'COMP' &&
itemToUpdate.productCode === 'PVT-CAR' &&
itemToUpdate.payoutOn === 'OD'
) {
advisorPayout = calculateAdvisorPayoutAmount(parseFloat(itemToUpdate.odPremium), parsedPercentage);
advisorPayable = calculateAdvisorPayableAmount(parseFloat(itemToUpdate.finalEntryFields), advisorPayout);
} else {
advisorPayout = calculateAdvisorPayoutAmount(parseFloat(itemToUpdate.netPremium), parsedPercentage);
advisorPayable = calculateAdvisorPayableAmount(parseFloat(itemToUpdate.finalEntryFields), advisorPayout);
}
// Create updated item data with only necessary changes
const updatedItem = {
...itemToUpdate,
cvpercentage: parsedPercentage,
advisorPayoutAmount: parseFloat(advisorPayout.toFixed(2)),
advisorPayableAmount: parseFloat(advisorPayable.toFixed(2)),
};
// Update the state with the new calculated values
const updatedData = allDetailsData.map(item =>
item._id === itemId ? updatedItem : item
);
setAllDetailsData(updatedData);
// Call the API to save the changes
await updateInsuranceAPI(
itemId,
updatedItem.cvpercentage,
updatedItem.advisorPayoutAmount,
updatedItem.advisorPayableAmount
);
} catch (error) {
console.error("Error handling advisor payout change:", error);
toast.error("Failed to handle advisor payout change. Please try again.");
}
};
const updateInsuranceAPI = async (itemId, cvpercentage, advisorPayoutAmount, advisorPayableAmount) => {
try {
const resp = await axios.put(`${VITE_DATA}/data/api/updatedata/${itemId}`, {
cvpercentage,
advisorPayoutAmount,
advisorPayableAmount
});
// Assuming the backend returns a success message in resp.data.status
toast.success(`${resp.data.status}`, {
position: "top-center",
autoClose: 1000, // Adjusted autoClose time to 1 second (1000 ms)
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
// Optionally trigger a data refresh after update
// await onUpdateInsurance();
} catch (error) {
console.error("Error updating insurance details:", error);
toast.error("Failed to update insurance details. Please try again.");
}
};
return (<>
<tbody className="divide-y divide-gray-200 overflow-y-hidden ">
{filteredData?.map((data) => (
<tr key={data._id} className="border-b dark:border-neutral-200 text-sm font-medium hover:bg-orange-100">
<td
contentEditable={true}
className="whitespace-nowrap px-0.5 w-20 h-10 py-0 border border-black text-center"
dir="ltr"
onInput={(e) => handleNumericInput(e)}
onBlur={(e) => handleInputChange(data._id, e.target.innerText)}
name="cvpercentage"
>
{data.cvpercentage}
</td>
</tr>
))}
</tbody>
</>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment