All files / src/flow/nodes wait_for_response.ts

98.54% Statements 405/411
70.58% Branches 48/68
80% Functions 4/5
98.54% Lines 405/411

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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 41298x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 19x 19x 19x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 16x 8x 8x 16x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 32x 32x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 4x 4x 98x 98x 29x 29x 29x 29x 29x 29x 29x 29x 14x 29x 29x 363x 363x 363x 29x 29x 17x 17x 29x 29x 29x 27x 10x 29x 29x 29x 29x 29x 29x 29x   98x 98x 98x           98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 106x 106x 106x 106x 106x 106x 102x 102x 102x 102x 102x 102x 102x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 102x 101x 101x 101x 101x 100x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 105x 105x 106x 106x 106x 102x 102x 102x 102x 97x 102x 102x 102x 97x 97x 97x 97x 97x 97x 97x 102x 102x 102x 102x 102x 102x 102x 97x 97x 97x 102x 97x 102x 97x 97x 97x 97x 102x 102x 102x 102x 102x 107x 102x 102x 102x 102x 102x 102x 102x 102x 102x 106x 106x 106x 106x 106x 107x 107x 107x 107x 107x 107x 107x 107x 98x 98x 98x 98x 98x 98x 98x 101x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 107x 107x 107x 107x 107x 107x 107x 107x 107x 98x 99x 99x 99x 99x 99x 99x 98x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 97x 97x 97x 99x 99x 99x 99x 99x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 99x 98x 98x 98x 98x 98x 98x 120x 120x 120x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x  
import { SPLIT_GROUPS, FormData, NodeConfig, FlowTypes } from '../types';
import { Node, Category, Exit, Case } from '../../store/flow-definition';
import { generateUUID, createRulesRouter } from '../../utils';
import {
  getWaitForResponseOperators,
  operatorsToSelectOptions,
  getOperatorConfig
} from '../operators';
import {
  resultNameField,
  localizeRulesField,
  localizeCategoriesField,
  nodeOptionsAccordion
} from './shared';
import {
  createRulesArrayConfig,
  extractUserRules,
  casesToFormRules
} from './shared-rules';
import { validateWith } from '../utils';
 
const TIMEOUT_OPTIONS = [
  { value: '60', name: '1 minute' },
  { value: '120', name: '2 minutes' },
  { value: '180', name: '3 minutes' },
  { value: '240', name: '4 minutes' },
  { value: '300', name: '5 minutes' },
  { value: '600', name: '10 minutes' },
  { value: '900', name: '15 minutes' },
  { value: '1800', name: '30 minutes' },
  { value: '3600', name: '1 hour' },
  { value: '7200', name: '2 hours' },
  { value: '10800', name: '3 hours' },
  { value: '21600', name: '6 hours' },
  { value: '43200', name: '12 hours' },
  { value: '64800', name: '18 hours' },
  { value: '86400', name: '1 day' },
  { value: '172800', name: '2 days' },
  { value: '259200', name: '3 days' },
  { value: '604800', name: '1 week' }
];
 
// Helper function to create a wait_for_response router with user rules
// This is a thin wrapper around createRulesRouter that adds the No Response category for timeouts
const createWaitForResponseRouter = (
  userRules: any[],
  existingCategories: Category[] = [],
  existingExits: Exit[] = [],
  existingCases: Case[] = []
) => {
  const { router, exits } = createRulesRouter(
    '@input.text',
    userRules,
    getOperatorConfig,
    existingCategories,
    existingExits,
    existingCases
  );
 
  // Add "No Response" category last (if it exists in the original)
  const existingNoResponseCategory = existingCategories.find(
    (cat) => cat.name === 'No Response' || cat.name === 'Timeout'
  );
 
  if (existingNoResponseCategory) {
    const existingNoResponseExit = existingExits.find(
      (exit) => exit.uuid === existingNoResponseCategory.exit_uuid
    );
 
    if (existingNoResponseExit) {
      router.categories.push(existingNoResponseCategory);
      exits.push({
        uuid: existingNoResponseExit.uuid,
        destination_uuid: existingNoResponseExit.destination_uuid || null
      });
    }
  }
 
  return { router, exits };
};
 
export const wait_for_response: NodeConfig = {
  type: 'wait_for_response',
  name: 'Wait for Response',
  group: SPLIT_GROUPS.wait,
  flowTypes: [FlowTypes.MESSAGE],
  hideFromSplits: true,
  dialogSize: 'large',
  form: {
    rules: createRulesArrayConfig(
      operatorsToSelectOptions(getWaitForResponseOperators()),
      'If the message from the contact...'
    ),
    timeout_enabled: {
      type: 'checkbox',
      label: (formData: Record<string, any>) => {
        return formData.timeout_enabled
          ? 'Continue when there is no response for'
          : 'Continue when there is no response..';
      },
      labelPadding: '4px 8px'
    },
    timeout_duration: {
      type: 'select',
      placeholder: '5 minutes',
      multi: false,
      maxWidth: '130px',
      flavor: 'xsmall',
      options: TIMEOUT_OPTIONS,
 
      conditions: {
        visible: (formData: Record<string, any>) => {
          return formData.timeout_enabled === true;
        }
      }
    },
    result_name: resultNameField,
    localizeRules: localizeRulesField,
    localizeCategories: localizeCategoriesField
  },
  layout: ['rules', nodeOptionsAccordion],
  gutter: [
    {
      type: 'row',
      items: ['timeout_enabled', 'timeout_duration'],
      gap: '0.5rem'
    }
  ],
  validate: validateWith(() => {
    // No validation needed - allow multiple rules to use same category name.
    // Rules with the same category name will be merged to use the same exit.
  }),
  toFormData: (node: Node, nodeUI?: any) => {
    // Extract rules from router cases using shared function
    const rules = casesToFormRules(node);
 
    // Extract timeout configuration
    const timeoutSeconds = node.router?.wait?.timeout?.seconds;
    let timeoutOption = TIMEOUT_OPTIONS.find(
      (opt) => opt.value === String(timeoutSeconds)
    );
 
    if (!timeoutOption) {
      timeoutOption = { value: '300', name: '5 minutes' };
    }
 
    return {
      uuid: node.uuid,
      rules: rules,
      timeout_enabled: !!timeoutSeconds,
      timeout_duration: timeoutOption,
      result_name: node.router?.result_name || '',
      localizeRules: nodeUI?.config?.localizeRules || false,
      localizeCategories: nodeUI?.config?.localizeCategories || false
    };
  },
  toUIConfig: (formData: FormData) => {
    const config: Record<string, any> = {};
    config.localizeRules = !!formData.localizeRules;
    config.localizeCategories = formData.result_name
      ? !!formData.localizeCategories
      : false;
    return config;
  },
  fromFormData: (formData: FormData, originalNode: Node): Node => {
    // Get user rules using shared extraction function
    const userRules = extractUserRules(formData);

    // If no user rules, clear cases but preserve other router config
    if (userRules.length === 0) {
      // Get existing router data for preservation
      let existingCategories = originalNode.router?.categories || [];
      const existingExits = [...(originalNode.exits || [])]; // Create a copy to avoid extensibility issues
 
      // Handle timeout: ensure "No Response" category exists if timeout is enabled,
      // or remove it if timeout is disabled
      if (formData.timeout_enabled) {
        let noResponseCategory = existingCategories.find(
          (cat: any) => cat.name === 'No Response'
        );
 
        if (!noResponseCategory) {
          // Create new "No Response" category and exit
          const noResponseExitUuid = generateUUID();
          noResponseCategory = {
            uuid: generateUUID(),
            name: 'No Response',
            exit_uuid: noResponseExitUuid
          };
 
          // Add to existing categories for processing
          existingCategories = [...existingCategories, noResponseCategory];
 
          // Add corresponding exit if it doesn't exist
          if (!existingExits.find((exit) => exit.uuid === noResponseExitUuid)) {
            existingExits.push({
              uuid: noResponseExitUuid,
              destination_uuid: null
            });
          }
        }
      } else {
        // If timeout is disabled, remove "No Response" category from existing categories
        existingCategories = existingCategories.filter(
          (cat: any) => cat.name !== 'No Response'
        );
      }
 
      // Create router with "All Responses" as default category
      // This will now properly handle the "No Response" category if it exists
      const { router: noRulesRouter, exits: noRulesExits } =
        createWaitForResponseRouter(
          [], // No user rules
          existingCategories,
          existingExits,
          [] // No cases
        );
 
      const router: any = {
        ...noRulesRouter,
        cases: [] // Clear all cases when no rules
      };
 
      // Only set result_name if provided
      if (formData.result_name && formData.result_name.trim() !== '') {
        router.result_name = formData.result_name.trim();
      }
 
      // Build wait configuration based on form data
      const waitConfig: any = {
        type: 'msg'
      };
 
      // Add timeout if enabled
      if (formData.timeout_enabled) {
        // Extract timeout value (handle both string and object formats)
        let timeoutSeconds;
 
        if (formData.timeout_duration) {
          if (
            Array.isArray(formData.timeout_duration) &&
            formData.timeout_duration.length > 0
          ) {
            // Handle array of selected options (multi-select behavior)
            timeoutSeconds = parseInt(formData.timeout_duration[0].value, 10);
          } else if (typeof formData.timeout_duration === 'string') {
            timeoutSeconds = parseInt(formData.timeout_duration, 10);
          } else if (
            formData.timeout_duration &&
            typeof formData.timeout_duration === 'object' &&
            formData.timeout_duration.value
          ) {
            timeoutSeconds = parseInt(formData.timeout_duration.value, 10);
          } else {
            timeoutSeconds = 300; // Default to 5 minutes
          }
        } else {
          // No duration selected, use default
          timeoutSeconds = 300; // Default to 5 minutes
        }
 
        // Validate that we got a valid number
        if (isNaN(timeoutSeconds) || timeoutSeconds <= 0) {
          timeoutSeconds = 300; // Default to 5 minutes
        }
 
        // Find the "No Response" category (should exist now)
        const noResponseCategory = router.categories.find(
          (cat: any) => cat.name === 'No Response'
        );
 
        if (noResponseCategory) {
          waitConfig.timeout = {
            seconds: timeoutSeconds,
            category_uuid: noResponseCategory.uuid
          };
        }
      }
 
      router.wait = waitConfig;
 
      return {
        ...originalNode,
        router,
        exits: noRulesExits
      };
    }
 
    // Get existing router data for preservation
    const existingCategories = originalNode.router?.categories || [];
    const existingExits = originalNode.exits || [];
    const existingCases = originalNode.router?.cases || [];
 
    // Create router and exits using existing data when possible
    const { router, exits } = createWaitForResponseRouter(
      userRules,
      existingCategories,
      existingExits,
      existingCases
    );
 
    // Build final router with wait configuration and result_name
    const finalRouter: any = {
      ...router
    };
 
    // Only set result_name if provided
    if (formData.result_name && formData.result_name.trim() !== '') {
      finalRouter.result_name = formData.result_name.trim();
    }
 
    // Build wait configuration based on form data
    const waitConfig: any = {
      type: 'msg'
    };
 
    try {
      // Handle timeout configuration
      if (formData.timeout_enabled) {
        // Extract timeout value (handle both string and object formats)
        let timeoutSeconds;
 
        if (formData.timeout_duration) {
          try {
            timeoutSeconds = parseInt(formData.timeout_duration[0].value, 10);
          } catch (e) {
            timeoutSeconds = 300; // Default to 5 minutes
          }
        }
 
        // Find or create the "No Response" category
        const existingNoResponseCategory =
          originalNode.router?.categories?.find(
            (cat: any) => cat.name === 'No Response'
          );
 
        const noResponseCategory = existingNoResponseCategory || {
          uuid: generateUUID(),
          name: 'No Response',
          exit_uuid: generateUUID()
        };
 
        waitConfig.timeout = {
          seconds: timeoutSeconds,
          category_uuid: noResponseCategory.uuid
        };
 
        // Ensure No Response category and exit exist
        if (
          !router.categories?.some((cat: any) => cat.name === 'No Response')
        ) {
          router.categories = router.categories || [];
          router.categories.push(noResponseCategory);
 
          // Add corresponding exit if it doesn't exist
          if (
            !exits.some(
              (exit: any) => exit.uuid === noResponseCategory.exit_uuid
            )
          ) {
            const noResponseExit = {
              uuid: noResponseCategory.exit_uuid,
              destination_uuid: existingNoResponseCategory?.exit_uuid
                ? originalNode.exits?.find(
                    (exit) => exit.uuid === existingNoResponseCategory.exit_uuid
                  )?.destination_uuid || null
                : null
            };
            exits.push(noResponseExit);
          }
        }
      } else {
        // Remove "No Response" category if timeout is disabled
        if (router.categories) {
          const noResponseCategoryIndex = router.categories.findIndex(
            (cat: any) => cat.name === 'No Response'
          );
          if (noResponseCategoryIndex !== -1) {
            const noResponseCategory =
              router.categories[noResponseCategoryIndex];
 
            // Remove the category
            router.categories.splice(noResponseCategoryIndex, 1);
 
            // Remove corresponding exit
            const exitIndex = exits.findIndex(
              (exit: any) => exit.uuid === noResponseCategory.exit_uuid
            );
            if (exitIndex !== -1) {
              exits.splice(exitIndex, 1);
            }
          }
        }
      }
    } catch (error) {
      console.error('Error processing timeout configuration:', error);
      // Continue without timeout in case of error
    }
 
    finalRouter.wait = waitConfig;
    return {
      ...originalNode,
      router: finalRouter,
      exits: exits
    };
  },
 
  // Localization support for categories
  localizable: 'categories',
  nonTranslatableCategories: ['Timeout']
};