Auto save fixed

This commit is contained in:
Malini 2026-03-02 21:00:09 +05:30
parent 281d98cf13
commit 3424868c57

View File

@ -1335,6 +1335,162 @@ useEffect(() => {
endDate: ''
}));
// Auto-save functionality
const [lastAutoSave, setLastAutoSave] = React.useState(null);
const autoSaveInterval = React.useRef(null);
// Auto-save every 2 minutes
React.useEffect(() => {
// Clear any existing interval
if (autoSaveInterval.current) {
clearInterval(autoSaveInterval.current);
}
// Set up new interval for auto-save every 2 minutes (120000 ms)
autoSaveInterval.current = setInterval(() => {
autoSaveDraft();
}, 120000); // 2 minutes = 120000 ms
// Cleanup interval on unmount
return () => {
if (autoSaveInterval.current) {
clearInterval(autoSaveInterval.current);
}
};
}, [products, surveyData]); // Re-setup when products or survey data changes
// Auto-save function
const autoSaveDraft = async () => {
try {
// Check if there's any data to save
const hasAnyData = products.some(product =>
product.product ||
product.unit ||
product.capacity ||
product.octQuantity || product.novQuantity || product.decQuantity ||
product.janQuantity || product.febQuantity || product.marQuantity ||
product.aprQuantity || product.mayQuantity || product.junQuantity ||
product.octCost || product.novCost || product.decCost ||
product.janCost || product.febCost || product.marCost ||
product.aprCost || product.mayCost || product.junCost ||
product.variationReason || product.otherVariationReason ||
product.zeroTargetReason || product.otherZeroTargetReason ||
product.remarks
);
if (!hasAnyData) {
return; // Don't auto-save if no data
}
// Save to localStorage for persistence across page refreshes
const autoSaveData = {
establishment_id: localStorage.getItem('establishment_id'),
quarter: surveyData.quarter,
year: surveyData.year,
products: products,
timestamp: new Date().toISOString()
};
localStorage.setItem('autoSaveData', JSON.stringify(autoSaveData));
// Prepare data for backend saving
const submissionData = {
establishment_id: localStorage.getItem('establishment_id'),
quarter: surveyData.quarter,
year: surveyData.year,
products: products.map(product => ({
product_id: product.product || null,
unit_id: product.unit || '0',
annual_installed_capacity: product.capacity || '0',
previous_quantity_period_one: product.octQuantity || '0',
previous_quantity_period_two: product.novQuantity || '0',
previous_quantity_period_three: product.decQuantity || '0',
previous_cost_period_one: product.octCost || '0',
previous_cost_period_two: product.novCost || '0',
previous_cost_period_three: product.decCost || '0',
current_quantity_period_one: product.janQuantity || '0',
current_quantity_period_two: product.febQuantity || '0',
current_quantity_period_three: product.marQuantity || '0',
current_cost_period_one: product.janCost || '0',
current_cost_period_two: product.febCost || '0',
current_cost_period_three: product.marCost || '0',
forecast_quantity_period_one: product.aprQuantity || '0',
forecast_quantity_period_two: product.mayQuantity || '0',
forecast_quantity_period_three: product.junQuantity || '0',
forecast_cost_period_one: product.aprCost || '0',
forecast_cost_period_two: product.mayCost || '0',
forecast_cost_period_three: product.junCost || '0',
variation_reason_master_id: product.variationReason === null ? null : (product.variationReason || '0'),
other_variation_reason: product.otherVariationReason || '0',
zero_target_reason_master_id: product.zeroTargetReason === null ? null : (product.zeroTargetReason || '0'),
other_zero_target_reason: product.otherZeroTargetReason || '0',
remarks: product.remarks || '',
is_active: true
}))
};
// Save to backend
await submitSurvey(submissionData);
// Update last auto-save timestamp
setLastAutoSave(new Date());
// Show toast notification for auto-save
toast.success('Draft auto-saved successfully', {
position: "top-right",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
} catch (error) {
console.error('Auto-save failed:', error);
toast.error('Auto-save failed. Please save manually.', {
position: "top-right",
autoClose: 3000,
});
}
};
// Restore auto-save data on component mount
React.useEffect(() => {
const autoSaveDataStr = localStorage.getItem('autoSaveData');
if (autoSaveDataStr) {
try {
const autoSaveData = JSON.parse(autoSaveDataStr);
// Check if auto-save data matches current establishment, quarter, and year
const currentEstablishmentId = localStorage.getItem('establishment_id');
const isSameContext = autoSaveData.establishment_id === currentEstablishmentId &&
autoSaveData.quarter === (quarter || '') &&
autoSaveData.year === (year || '');
if (isSameContext && autoSaveData.products && autoSaveData.products.length > 0) {
// Restore products from auto-save
onProductsChange(autoSaveData.products);
// Restore last auto-save timestamp
setLastAutoSave(new Date(autoSaveData.timestamp));
// Show notification that data was restored
toast.info('Previous work restored from auto-save', {
position: "top-right",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
}
} catch (error) {
console.error('Error restoring auto-save data:', error);
}
}
}, []); // Only run once on mount
// const location = useLocation();
// Update surveyData when props or location changes
@ -3006,13 +3162,22 @@ useEffect(() => {
</div>
<div className="flex items-center gap-3">
{!location.state?.isResubmit && (
<button
className="inline-flex items-center justify-center h-9 px-4 rounded-md border border-[#92722A] text-[#92722A] bg-transparent hover:bg-[#F5F0E1] transition-colors"
onClick={handleSaveDraft}
disabled={isSavingDraft}
>
{isSavingDraft ? 'Saving...' : 'Save as Draft'}
</button>
<div className="flex items-center gap-2">
<button
className="inline-flex items-center justify-center h-9 px-4 rounded-md border border-[#92722A] text-[#92722A] bg-transparent hover:bg-[#F5F0E1] transition-colors"
onClick={handleSaveDraft}
disabled={isSavingDraft}
>
{isSavingDraft ? 'Saving...' : 'Save as Draft'}
</button>
{/* {lastAutoSave && (
<div className="text-xs text-gray-500">
<span className="inline-flex items-center">
Auto-saved: {lastAutoSave.toLocaleTimeString()}
</span>
</div>
)} */}
</div>
)}
<button
onClick={handleNext}