All files / src/components/Chatbot/Result AwaitAndResponseAction.tsx

100% Statements 139/139
89.47% Branches 51/57
100% Functions 3/3
100% Lines 139/139

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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179    1x     1x     1x             1x                   1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x   34x 10x 10x 10x   34x 9x 9x 9x 9x   34x 20x 10x 10x 1x 1x 1x 1x 1x 1x 10x 1x 1x 1x 1x 10x 10x 10x 10x 10x 9x 9x 9x 10x 34x   34x 34x   16x 11x 10x 10x 10x   10x 10x 10x 10x   10x 1x 1x 1x   9x 10x 9x 7x 10x 7x 7x 7x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 4x 3x 2x 7x 1x 1x 1x 1x 1x   7x 5x 5x 5x 5x 1x 4x 2x 2x 5x 5x 1x 4x 5x   7x 7x 7x 6x 7x 7x 11x 1x 1x 1x 16x     5x 5x 16x     34x   34x 34x  
'use client';
 
import { useEffect, useRef, useState } from 'react';
 
// Constants
import { LOADING_OVERLAY_DELAY } from '@/constants';
 
// Types
import {
  ActionAwaitAndResponseProps,
  ChartKey,
  ChartMode,
  CHATBOT_STATUS,
} from '@/types';
import { FilterType } from '@/providers/statistic';
import {
  getFilterChanges,
  normalizeTimeRange,
  normalizeTimeRangeSeparators,
} from '@/utils';
 
/**
 * Handling action processing state and resetting action args.
 * Used by employee info, training info, and other chat action hooks.
 */
export const AwaitAndResponseAction = ({
  args,
  result = {},
  status,
  isProcessing,
  onProcessing,
  children,
  onChangeFilter,
  filter,
  isNew = false,
  isComparison = false,
  isChatLoading = false,
  actionId = '',
  saveActionId,
  prevActionId,
  savePrevActionId,
}: ActionAwaitAndResponseProps) => {
  const [isExecuting, saveIsExecuting] = useState(false);
  const processingStartedRef = useRef(false);
  const requestId = result?.requestId;
 
  const startProcessing = () => {
    processingStartedRef.current = true;
    onProcessing(true);
  };
 
  const stopProcessing = () => {
    processingStartedRef.current = false;
    onProcessing(false);
    saveIsExecuting(false);
  };
 
  useEffect(() => {
    if (isComparison) {
      if (
        isNew &&
        isChatLoading &&
        requestId &&
        isNew &&
        !actionId &&
        prevActionId !== requestId &&
        !isProcessing
      ) {
        saveIsExecuting(true);
        startProcessing();
        saveActionId?.(requestId);
      }
    } else {
      if (
        status === CHATBOT_STATUS.IN_PROGRESS ||
        status === CHATBOT_STATUS.EXECUTING
      ) {
        saveIsExecuting(true);
        startProcessing();
      }
    }
  }, [isNew, isChatLoading, isComparison, isProcessing]);
 
  useEffect(() => {
    if (status === CHATBOT_STATUS.COMPLETE) {
      // Stop processing if started
      if (isExecuting || processingStartedRef.current) {
        if (isComparison) {
          const { mode, subject, nestedMode } = args;
          const normalizedMode = mode?.toLowerCase() as ChartMode;
          const trimTime = normalizeTimeRangeSeparators(result?.time);
 
          const normalizedTime = normalizeTimeRange(
            result?.time ?? '',
            normalizedMode,
          );
 
          if (result?.error && !requestId) {
            stopProcessing();
            return;
          }
 
          if (
            (mode || result?.time || subject || nestedMode) &&
            actionId &&
            actionId === requestId
          ) {
            const normalizedTotalMode = nestedMode?.toLowerCase() as ChartMode;
            const normalizedSubject = (
              subject === 'SLOTS' ? ChartKey.SLOT : subject?.toLowerCase()
            ) as ChartKey;
 
            const {
              hasModeChange,
              hasTotalModeChange,
              hasTimeChange,
              hasSubjectChange,
            } = getFilterChanges({
              filter,
              mode,
              normalizedMode,
              nestedMode,
              normalizedTotalMode,
              trimTime,
              normalizedTime,
              subject,
              normalizedSubject,
            });
 
            if (
              !hasModeChange &&
              !hasTotalModeChange &&
              !hasTimeChange &&
              !hasSubjectChange
            ) {
              saveActionId?.('');
              savePrevActionId?.(requestId || '');
              stopProcessing();
              return;
            }
 
            onChangeFilter?.({
              ...filter,
              shouldSyncChangeMode: false,
              mode: hasModeChange ? normalizedMode : filter?.mode,
              totalMode: hasTotalModeChange
                ? normalizedTotalMode
                : hasModeChange
                  ? normalizedMode
                  : filter?.totalMode,
              timeRange: hasTimeChange ? normalizedTime : filter?.timeRange,
              comparisonKey: hasSubjectChange
                ? normalizedSubject
                : filter?.comparisonKey,
            } as FilterType);
 
            saveActionId?.('');
            savePrevActionId?.(requestId || '');
            setTimeout(() => {
              stopProcessing();
            }, LOADING_OVERLAY_DELAY);
          }
        } else {
          onChangeFilter?.(filter as FilterType);
          stopProcessing();
        }
      } else {
        // Covers: error case, or component mounted when status was already
        // complete (fresh mount after re-render), so isProcessing never clears.
        onProcessing(false);
      }
    }
    // Only status and result changes should trigger this effect
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status, result, isExecuting, actionId, requestId, isChatLoading]);
 
  return <>{children}</>;
};