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

99.29% Statements 141/142
92.1% Branches 35/38
100% Functions 1/1
99.29% Lines 141/142

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 2191x     1x                   1x 1x 1x 1x     1x     1x           1x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x                                           58x 58x 58x 58x   58x 35x 35x 33x 31x 35x 14x   14x   35x 22x 10x 10x 6x 4x 2x 10x 1x 1x         10x   9x 10x 2x   10x 9x 9x 9x 9x 10x 22x   58x                           58x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x   52x 52x 48x 58x 24x 24x   28x 28x 27x 27x 27x 27x 18x 18x 16x 16x 16x 16x   16x 15x 15x 15x 15x 15x 15x   16x 16x 16x   16x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 2x 2x 2x   2x 18x   9x 9x 8x 8x 8x     27x 28x   1x 1x  
import { useEffect, useState } from 'react';
 
// Types
import {
  CHATBOT_GROUP_ACTIONS,
  CHATBOT_STATUS,
  FormattedLunchPlan,
  LunchPlansResponse,
} from '@/types';
import { ArgsType, MealType } from '@/hooks/chat/useChatbotActions';
import { FilterType } from '@/providers/statistic';
 
// Components
import { PlanResult } from './PlanResult';
import { MenuResult } from './MenuResult';
import { ProcessingIndicator } from '../ProcessingIndicator';
import { StatisticResult } from './StatisticResult';
 
// Constants
import { CHATBOT_MESSAGES } from '@shared/constants';
 
// Utils
import {
  filterPlansByOffice,
  formatLunchPlans,
  normalizeResponseResult,
} from '@/utils';
 
export const AwaitAndResponse = ({
  status,
  args,
  result,
  filter,
  onChangeFilter,
  onStopGeneration,
  isChangeTotalMode,
  setIsProcessing,
  actionId,
  saveActionId,
  prevActionId,
  savePrevActionId,
  isChatLoading,
  isNew,
}: {
  status: 'complete' | 'executing' | 'inProgress';
  args: ArgsType;
  filter: FilterType;
  result: {
    response?: string;
    result?: string;
    error?: string;
    time?: string;
    requestId?: string;
  } | null;
  onChangeFilter?: (filter: FilterType) => void;
  onStopGeneration?: () => void;
  isChangeTotalMode?: boolean;
  isProcessing?: boolean;
  isChatLoading?: boolean;
  setIsProcessing: (value: boolean) => void;
  isNew?: boolean;
  actionId?: string;
  saveActionId?: (value: string) => void;
  prevActionId?: string;
  savePrevActionId?: (value: string) => void;
}) => {
  const [isExecuting, saveIsExecuting] = useState(false);
  const groupAction = args?.group;
  const isNotStatsGroup = groupAction !== CHATBOT_GROUP_ACTIONS.STATISTIC;
 
  useEffect(() => {
    if (
      (isChatLoading && !isNotStatsGroup) ||
      status === CHATBOT_STATUS.IN_PROGRESS ||
      status === CHATBOT_STATUS.EXECUTING
    ) {
      saveIsExecuting(true);
      // setIsProcessing(true);
    }
 
    if (status === CHATBOT_STATUS.COMPLETE) {
      if (isExecuting) {
        if (
          result?.requestId &&
          isNew &&
          !actionId &&
          prevActionId !== result?.requestId
        ) {
          saveActionId?.(result?.requestId);
        }
 
        /**
         * Wait for updating comparison state before end executing
         */
        if (!isNotStatsGroup) return;
 
        if (
          (result?.response && isNotStatsGroup) ||
          !result?.response ||
          result?.error
        ) {
          saveIsExecuting(false);
          setIsProcessing(false);
        }
        onStopGeneration?.();
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status, result]);
 
  // useEffect(() => {
  //   if (isProcessing) {
  //     const timeout = setTimeout(() => {
  //       onStopGeneration?.();
  //       saveIsExecuting(false);
  //       setIsProcessing(false);
  //     }, LONG_RESPONSE_TIME); // Trigger after 60s of loading
 
  //     return () => clearTimeout(timeout);
  //   }
  // }, [isProcessing, onStopGeneration]);
 
  if (groupAction === CHATBOT_GROUP_ACTIONS.STATISTIC) {
    return (
      <StatisticResult
        setIsProcessing={setIsProcessing}
        isChatLoading={isChatLoading}
        args={args}
        time={result?.time || (args as ArgsType)?.time || ''}
        response={result?.response}
        filter={filter}
        onChangeFilter={onChangeFilter}
        isExecuting={isExecuting}
        onSaveExecuting={saveIsExecuting}
        status={status}
        onStopGeneration={onStopGeneration}
        actionId={actionId}
        saveActionId={saveActionId}
        savePrevActionId={savePrevActionId}
        requestId={result?.requestId}
      />
    );
  }
 
  if (
    status === CHATBOT_STATUS.IN_PROGRESS ||
    status === CHATBOT_STATUS.EXECUTING
  ) {
    return <ProcessingIndicator />;
  }
 
  if (status === CHATBOT_STATUS.COMPLETE) {
    if (!isChangeTotalMode) {
      const normalizedResult = normalizeResponseResult(
        result?.result || result?.error || '',
      );
      if (result?.response) {
        const response = JSON.parse(result.response);
        if (groupAction === CHATBOT_GROUP_ACTIONS.MENU) {
          return (
            <>
              <div className="relative py-2.5 px-[15px] rounded-lg w-fit max-w-cb-message-box text-3xs leading-5 border shadow-sm border-primary-700 text-primary-700 dark:text-background dark:bg-secondary-900 dark:border-secondary-900">
                <p className="mb-[15px]">{`${CHATBOT_MESSAGES.MENU_RESULT}:`}</p>
 
                {response.map((meal: MealType, index: number) => {
                  return (
                    <MenuResult
                      key={meal.date}
                      meal={meal}
                      hasBorder={index !== response.length - 1}
                    />
                  );
                })}
              </div>
            </>
          );
        }
 
        if (groupAction === CHATBOT_GROUP_ACTIONS.PLAN) {
          const formalizedPlan = formatLunchPlans(
            filterPlansByOffice(response, args.office) as LunchPlansResponse[],
          );
          return (
            <>
              <div className="relative py-2.5 px-[15px] rounded-lg w-fit max-w-cb-message-box text-3xs leading-5 border shadow-sm border-primary-700 text-primary-700 dark:text-background dark:bg-secondary-900 dark:border-secondary-900">
                <p className="mb-[15px]">{`${CHATBOT_MESSAGES.PLAN_RESULT}:`}</p>
                {formalizedPlan.map(
                  (statsItem: FormattedLunchPlan, index: number) => {
                    return (
                      <PlanResult
                        key={statsItem.date}
                        date={statsItem.date}
                        totalVeganMeals={statsItem.totalVeganMeals}
                        totalNormalMeals={statsItem.totalNormalMeals}
                        stats={statsItem.stats}
                        hasBorder={index !== response.length - 1}
                      />
                    );
                  },
                )}
              </div>
            </>
          );
        }
      }
 
      return (
        normalizedResult && (
          <div className="relative py-2.5 px-[15px] rounded-lg w-fit max-w-cb-message-box text-3xs leading-5 border shadow-sm border-primary-700 text-primary-700 dark:text-background dark:bg-secondary-900 dark:border-secondary-900">
            <ul dangerouslySetInnerHTML={{ __html: normalizedResult }} />
          </div>
        )
      );
    }
  }
 
  return <></>;
};