All files / apps/host/src/hooks useRequestActions.ts

100% Statements 19/19
100% Branches 7/7
100% Functions 6/6
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88                            2x         12x 12x   12x   1x       1x         12x   1x               12x             3x 2x               1x         3x 3x         12x 1x     12x 1x     12x                  
import { useCallback, useState } from 'react';
 
import { TICKET_STATE } from '@repo/constants/ticket';
 
import { AnimatedPendingRequestCardData, CardAction } from '@/types/card';
 
import { useCreateOutcome } from './useCreateOutcome';
 
interface UseRequestActionsProps {
  onApprove?: (requestId: string) => void;
  onReject?: (requestId: string) => void;
  onSuccess?: () => void;
}
 
export const useRequestActions = ({
  onApprove,
  onReject,
  onSuccess,
}: UseRequestActionsProps = {}) => {
  const [action, setAction] = useState<CardAction>({ type: 'idle' });
  const { mutate: createOutcome } = useCreateOutcome(onSuccess);
 
  const handleApprove = useCallback(
    (item: AnimatedPendingRequestCardData) => {
      createOutcome({
        id: item.id,
        data: { state: TICKET_STATE.APPROVE },
      });
      onApprove?.(item.id);
    },
    [createOutcome, onApprove],
  );
 
  const handleProceed = useCallback(
    (requestId: string) => {
      createOutcome({
        id: requestId,
        data: { state: TICKET_STATE.PROCEED },
      });
    },
    [createOutcome],
  );
 
  const handleReject = useCallback(
    (
      requestId: string,
      note: string,
      isMaintenanceRequestProcessing = false,
      isCompleteMaintenanceRequest = false,
    ) => {
      if (isMaintenanceRequestProcessing) {
        createOutcome({
          id: requestId,
          data: {
            state: isCompleteMaintenanceRequest ? TICKET_STATE.DONE : TICKET_STATE.CLOSE,
            note,
          },
        });
      } else {
        createOutcome({
          id: requestId,
          data: { state: TICKET_STATE.REJECT, note },
        });
      }
      setAction({ type: 'submit', id: requestId });
      onReject?.(requestId);
    },
    [createOutcome, onReject],
  );
 
  const cancelAction = useCallback((requestId: string) => {
    setAction({ type: 'cancel', id: requestId });
  }, []);
 
  const resetAction = useCallback(() => {
    setAction({ type: 'idle' });
  }, []);
 
  return {
    action,
    handleApprove,
    handleReject,
    cancelAction,
    resetAction,
    handleProceed,
  };
};