- Updated ProductIndex component to improve category and product filtering with memoization. - Refactored Combobox components for better performance and usability. - Added PurchaseController routes for managing purchases with appropriate permissions. - Created comprehensive tests for purchase management, covering creation, updating, and deletion scenarios. - Ensured proper handling of raw materials and their variants during purchase operations. - Implemented validation for required fields in purchase creation and updates.
69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
import {
|
|
clearPurchaseDraft,
|
|
savePurchaseDraft,
|
|
type PurchaseDraftData,
|
|
} from '@/lib/purchase-draft';
|
|
import { router } from '@inertiajs/react';
|
|
import { useEffect, useRef } from 'react';
|
|
|
|
type DraftType = 'create' | 'edit';
|
|
|
|
export function usePurchaseDraftSave(
|
|
type: DraftType,
|
|
data: PurchaseDraftData,
|
|
userId?: number,
|
|
delay = 500,
|
|
) {
|
|
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const dataRef = useRef(data);
|
|
dataRef.current = data;
|
|
const submittedRef = useRef(false);
|
|
|
|
useEffect(() => {
|
|
const offBefore = router.on('before', (event) => {
|
|
if (event.detail.visit.method !== 'get') {
|
|
submittedRef.current = true;
|
|
}
|
|
});
|
|
const offError = router.on('error', () => {
|
|
submittedRef.current = false;
|
|
});
|
|
|
|
return () => {
|
|
offBefore();
|
|
offError();
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
timeoutRef.current = setTimeout(() => {
|
|
if (!submittedRef.current) {
|
|
savePurchaseDraft(type, dataRef.current, userId);
|
|
}
|
|
timeoutRef.current = null;
|
|
}, delay);
|
|
|
|
return () => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
};
|
|
}, [data, type, userId, delay]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
if (submittedRef.current) {
|
|
clearPurchaseDraft(type, userId);
|
|
} else {
|
|
savePurchaseDraft(type, dataRef.current, userId);
|
|
}
|
|
};
|
|
}, [type, userId]);
|
|
}
|