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

98.12% Statements 157/160
89.85% Branches 62/69
100% Functions 3/3
98.12% Lines 157/160

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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220    1x     1x     1x             1x                   1x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x   59x 25x 25x 25x   59x 16x 16x 16x 16x   59x 42x 1x       1x   1x 1x   1x 1x 1x 1x 1x 1x 41x 39x 41x 24x 24x 24x 59x 59x 59x 59x 59x 59x 59x 59x 59x   59x 42x 18x 2x 2x 2x   18x 18x 8x 7x     5x         2x     18x 16x 16x 16x   16x 16x 16x 16x   16x 1x 1x 1x       16x     2x 2x 2x 2x   13x 16x 11x 8x 16x 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     2x 2x 2x 2x 2x 2x   7x 4x 4x 4x 4x 1x 3x 2x 1x 4x 4x   7x 7x 7x 5x 7x 16x 6x 6x 2x 2x 6x       1x 1x 6x 6x 18x     2x 2x 18x     59x   59x 59x  
'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 AwaitAndResponseActionForChangeMode = ({
  args,
  result = {},
  status,
  isProcessing,
  onProcessing,
  children,
  onChangeFilter,
  filter,
  isNew = 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 (isNew && requestId && !isProcessing) {
      if (!actionId && prevActionId !== requestId) {
        saveIsExecuting(true);
        startProcessing();
        saveActionId?.(requestId);
      } else if (actionId && actionId !== requestId) {
        // Recover from stale actionId: close previous request and attach the new one.
        savePrevActionId?.(actionId);
        saveActionId?.(requestId);
 
        if (!isExecuting && !processingStartedRef.current) {
          saveIsExecuting(true);
          startProcessing();
        }
      }
    } else if (
      status === CHATBOT_STATUS.IN_PROGRESS ||
      status === CHATBOT_STATUS.EXECUTING
    ) {
      saveIsExecuting(true);
      startProcessing();
    }
  }, [
    status,
    isNew,
    isProcessing,
    requestId,
    actionId,
    prevActionId,
    isExecuting,
  ]);
 
  useEffect(() => {
    if (status === CHATBOT_STATUS.COMPLETE) {
      if (!requestId && actionId) {
        saveActionId?.('');
        savePrevActionId?.(actionId);
      }
 
      const shouldHandleCompletion =
        isExecuting ||
        processingStartedRef.current ||
        (Boolean(actionId) && Boolean(requestId) && actionId === requestId) ||
        // Always handle completion for no-requestId tools (e.g. CHANGE_TOTAL_MODE).
        // Idempotency is enforced by the messageId-based dedup in the parent hook.
        (!requestId && !result?.error) ||
        // useRenderToolCall re-registers the renderer on each parent render,
        // which can remount this component before the IN_PROGRESS effect's
        // processingStartedRef survives into COMPLETE. Trust the parent hook's
        // dedup to keep COMPLETE handling idempotent.
        (Boolean(requestId) && !result?.error);
 
      // Stop processing if started
      if (shouldHandleCompletion) {
        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;
        }
 
        // Some COMPLETE payloads do not carry requestId. In that case, release the
        // active actionId so the next request can start a fresh id flow.
        if (!requestId && actionId) {
          // CHANGE TOTAL MODE still needs to apply mode/totalMode once per completed action,
          // even if COMPLETE payload omits requestId.
          onChangeFilter?.(filter as FilterType);
          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
          ) {
            // CHANGE TOTAL MODE: still trigger handler so mode/totalMode mapping
            // derived in the hook gets applied on the first attempt.
            onChangeFilter?.(filter as FilterType);
            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,
          } as FilterType);
 
          saveActionId?.('');
          savePrevActionId?.(requestId || '');
          setTimeout(() => {
            stopProcessing();
          }, LOADING_OVERLAY_DELAY);
        } else {
          onChangeFilter?.(filter as FilterType);
          if (actionId && actionId === requestId) {
            saveActionId?.('');
            savePrevActionId?.(requestId || '');
          } else if (requestId) {
            // Effect 1 (isNew branch) and Effect 2 run in the same render snapshot,
            // so Effect 2 sees actionId='' even though Effect 1 queued saveActionId(requestId).
            // Set prevActionId here so the first effect's guard works on re-render/remount.
            savePrevActionId?.(requestId);
          }
          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}</>;
};