All files / src/flow/nodes split_by_subflow.ts

84.3% Statements 247/293
81.39% Branches 70/86
57.14% Functions 4/7
84.3% Lines 247/293

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 29498x 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 2x 2x 2x 2x   2x     98x 98x 98x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 5x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 3x 3x 6x 98x 98x 98x 98x 98x 98x                                     98x 98x 98x 98x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x               1x 98x                                 98x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 7x 7x 7x 1x 7x 6x 6x 7x 7x 98x 98x 98x 98x 98x 98x 98x 98x 98x 102x 102x 98x 98x 98x 98x 98x 98x 98x 101x 101x 98x 98x 98x 104x 104x 104x 98x 98x 98x 98x 98x 103x 103x 103x 101x 101x 101x 101x 101x 101x 98x 98x 98x 98x 98x 98x 98x 98x 98x 101x 98x 101x 101x 101x 101x 98x 101x 101x 101x 101x 101x 98x 98x 98x 98x 101x 98x 98x 98x 98x 98x 98x 98x 98x 98x 101x 101x 98x 98x 98x 98x 98x 105x 98x 98x 101x 105x 105x 101x 101x 101x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 101x 101x 101x 98x 98x 98x 98x 98x 98x 98x  
import { ACTION_GROUPS, FormData, NodeConfig, FlowTypes } from '../types';
import { Node, SetRunResult } from '../../store/flow-definition';
import { generateUUID } from '../../utils';
import { html } from 'lit';
import { renderFlowLinks } from '../utils';
import { shouldExcludeFlow } from '../flow-utils';
 
export const split_by_subflow: NodeConfig = {
  type: 'split_by_subflow',
  name: 'Enter a Flow',
  group: ACTION_GROUPS.trigger,
  flowTypes: [FlowTypes.VOICE, FlowTypes.MESSAGE, FlowTypes.BACKGROUND],
  showAsAction: true,
  form: {
    flow: {
      type: 'select',
      required: true,
      searchable: true,
      placeholder: 'Select a flow...',
      helpText:
        'Once the subflow is complete or expires, the contact will return here',
      endpoint: '/api/v2/flows.json',
      valueKey: 'uuid',
      nameKey: 'name',
      shouldExclude: shouldExcludeFlow
    },
    params: {
      type: 'key-value',
      keyPlaceholder: 'Parameter name',
      valuePlaceholder: 'Value',
      minRows: 0,
      readOnlyKeys: true,
      dependsOn: ['flow'],
      conditions: {
        visible: (formData: Record<string, any>) => {
          const params = formData.params;
          if (Array.isArray(params)) return params.length > 0;
          if (params && typeof params === 'object')
            return Object.keys(params).length > 0;
          return false;
        }
      },
      computeValue: (values: Record<string, any>, currentValue: any) => {
        const flow =
          Array.isArray(values.flow) && values.flow.length > 0
            ? values.flow[0]
            : null;
        if (!flow?.parent_refs?.length) {
          // Clear params when selected flow has no parent_refs
          return [];
        }
 
        // Build a map of existing values
        const existingValues: Record<string, string> = {};
        if (Array.isArray(currentValue)) {
          currentValue.forEach((item: any) => {
            if (item.key) existingValues[item.key] = item.value || '';
          });
        } else if (currentValue && typeof currentValue === 'object') {
          Object.entries(currentValue).forEach(([k, v]) => {
            existingValues[k] = typeof v === 'string' ? (v as string) : '';
          });
        }
 
        // Create params from parent_refs, preserving existing values
        return flow.parent_refs.map((ref: string) => ({
          key: ref,
          value: existingValues[ref] || ''
        }));
      }
    }
  },
  layout: [
    'flow',
    {
      type: 'accordion',
      sections: [
        {
          label: 'Parameters',
          collapsed: false,
          getValueCount: (formData: FormData) => {
            const params = formData.params;
            if (Array.isArray(params)) {
              return params.filter((p: any) => p.value && p.value.trim() !== '')
                .length;
            }
            if (params && typeof params === 'object') {
              return Object.values(params).filter(
                (v) => typeof v === 'string' && v.trim() !== ''
              ).length;
            }
            return 0;
          },
          items: ['params']
        }
      ]
    }
  ],
  resolveFormData: async (formData: FormData) => {
    const flow =
      Array.isArray(formData.flow) && formData.flow.length > 0
        ? formData.flow[0]
        : null;
    if (!flow?.uuid) return formData;

    // Already have parent_refs (e.g. from a fresh selection)
    if (flow.parent_refs) return formData;
 
    try {
      const response = await fetch(`/api/v2/flows.json?uuid=${flow.uuid}`);
      const data = await response.json();
      const flowData = data.results?.[0];
      if (flowData?.parent_refs) {
        const updatedFlow = { ...flow, parent_refs: flowData.parent_refs };
        return { ...formData, flow: [updatedFlow] };
      }
    } catch {
      // Non-fatal; params just won't auto-populate
    }
 
    return formData;
  },
  render: (node: Node) => {
    const enterFlowAction = node.actions?.find(
      (action) => action.type === 'enter_flow'
    ) as any;
    return html`
      <div class="body">
        ${enterFlowAction?.flow
          ? renderFlowLinks([enterFlowAction.flow], 'flow')
          : null}
      </div>
    `;
  },
  toFormData: (node: Node) => {
    // Extract data from the existing node structure
    const enterFlowAction = node.actions?.find(
      (action) => action.type === 'enter_flow'
    ) as any;

    // Extract params from set_run_result actions
    const params: Record<string, string> = {};
    node.actions
      ?.filter((action) => action.type === 'set_run_result')
      .forEach((action) => {
        const setResult = action as SetRunResult;
        params[setResult.name] = setResult.value;
      });

    return {
      uuid: node.uuid,
      flow: enterFlowAction?.flow
        ? [{ uuid: enterFlowAction.flow.uuid, name: enterFlowAction.flow.name }]
        : [],
      params
    };
  },
  fromFormData: (formData: FormData, originalNode: Node): Node => {
    // Get flow selection
    const flowSelection =
      Array.isArray(formData.flow) && formData.flow.length > 0
        ? formData.flow[0]
        : null;
 
    // Find existing enter_flow action to preserve its UUID
    const existingEnterFlowAction = originalNode.actions?.find(
      (action) => action.type === 'enter_flow'
    );
    const enterFlowUuid = existingEnterFlowAction?.uuid || generateUUID();
 
    // Create enter_flow action
    const enterFlowAction: any = {
      type: 'enter_flow',
      uuid: enterFlowUuid,
      flow: flowSelection
        ? {
            uuid: flowSelection.uuid || flowSelection.value,
            name: flowSelection.name
          }
        : { uuid: '', name: '' }
    };
 
    // Create set_run_result actions for params
    const actions: any[] = [];
    const params = formData.params || {};
    Object.entries(params).forEach(([name, value]: [string, any]) => {
      if (typeof value === 'string' && value.trim() !== '') {
        actions.push({
          type: 'set_run_result',
          uuid: generateUUID(),
          name,
          value,
          category: ''
        });
      }
    });
 
    // enter_flow action goes last (after set_run_result actions)
    actions.push(enterFlowAction);
 
    // Create categories and exits for Complete and Expired
    const existingCategories = originalNode.router?.categories || [];
    const existingExits = originalNode.exits || [];
    const existingCases = originalNode.router?.cases || [];
 
    // Find existing Complete category
    const existingCompleteCategory = existingCategories.find(
      (cat) => cat.name === 'Complete'
    );
    const existingCompleteExit = existingCompleteCategory
      ? existingExits.find(
          (exit) => exit.uuid === existingCompleteCategory.exit_uuid
        )
      : null;
    const existingCompleteCase = existingCompleteCategory
      ? existingCases.find(
          (case_) => case_.category_uuid === existingCompleteCategory.uuid
        )
      : null;
 
    const completeCategoryUuid =
      existingCompleteCategory?.uuid || generateUUID();
    const completeExitUuid = existingCompleteExit?.uuid || generateUUID();
    const completeCaseUuid = existingCompleteCase?.uuid || generateUUID();
 
    // Find existing Expired category
    const existingExpiredCategory = existingCategories.find(
      (cat) => cat.name === 'Expired'
    );
    const existingExpiredExit = existingExpiredCategory
      ? existingExits.find(
          (exit) => exit.uuid === existingExpiredCategory.exit_uuid
        )
      : null;
 
    const expiredCategoryUuid = existingExpiredCategory?.uuid || generateUUID();
    const expiredExitUuid = existingExpiredExit?.uuid || generateUUID();
 
    const categories = [
      {
        uuid: completeCategoryUuid,
        name: 'Complete',
        exit_uuid: completeExitUuid
      },
      {
        uuid: expiredCategoryUuid,
        name: 'Expired',
        exit_uuid: expiredExitUuid
      }
    ];
 
    const exits = [
      {
        uuid: completeExitUuid,
        destination_uuid: existingCompleteExit?.destination_uuid || null
      },
      {
        uuid: expiredExitUuid,
        destination_uuid: existingExpiredExit?.destination_uuid || null
      }
    ];
 
    const cases = [
      {
        uuid: completeCaseUuid,
        type: 'has_only_text',
        arguments: ['completed'],
        category_uuid: completeCategoryUuid
      }
    ];
 
    // Create the router
    const router = {
      type: 'switch' as const,
      categories: categories,
      default_category_uuid: expiredCategoryUuid,
      operand: '@child.status',
      cases: cases
    };
 
    // Return the complete node
    return {
      uuid: originalNode.uuid,
      actions: actions,
      router: router,
      exits: exits
    };
  },
 
  // Localization support for categories
  localizable: 'categories',
  nonTranslatableCategories: 'all'
};