All files / src/flow/nodes split_by_contact_field.ts

94.78% Statements 200/211
48.83% Branches 21/43
75% Functions 3/4
94.78% Lines 200/211

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 21299x 99x 99x       99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 5x 1x 1x 1x 1x 1x 1x 5x 5x 1x 5x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 396x 99x 99x 99x 99x 99x 99x 99x 99x 99x 1485x 1485x 1485x 1485x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 2x 2x 2x 2x 2x 2x 2x 99x 99x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x       4x 4x 4x 4x 4x 4x 4x 4x 99x 99x 99x 99x 5x 5x 5x 5x 5x 5x       5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 5x 5x 5x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x  
import { SPLIT_GROUPS, FormData, NodeConfig, FlowTypes } from '../types';
import { Node } from '../../store/flow-definition';
import { createRulesRouter } from '../../utils';
import {
  getWaitForResponseOperators,
  operatorsToSelectOptions,
  getOperatorConfig
} from '../operators';
import {
  resultNameField,
  localizeRulesField,
  localizeCategoriesField,
  nodeOptionsAccordion
} from './shared';
import {
  createRulesArrayConfig,
  extractUserRules,
  casesToFormRules
} from './shared-rules';
import { SCHEMES, validateWith } from '../utils';
import { html } from 'lit';
 
// System contact properties that can be split on
export const CONTACT_PROPERTIES = {
  name: { id: 'name', name: 'Name', type: 'property' },
  language: { id: 'language', name: 'Language', type: 'property' },
  status: { id: 'status', name: 'Status', type: 'property' },
  channel: { id: 'channel', name: 'Channel', type: 'property' }
};
 
// Helper to get operand for the selected field
const getOperandForField = (field: any): string => {
  // For URN schemes, split on the URN path (the actual ID value like Facebook ID)
  // Note: This is different from split_by_scheme which splits on the scheme type itself
  if (field.type === 'scheme') {
    // field.id or field.value will be the scheme name like 'facebook', 'whatsapp', etc
    const schemeId = field.id || field.value;
    return `@(default(urn_parts(urns.${schemeId}).path, ""))`;
  }
  // For system properties, use the id
  if (field.type === 'property') {
    return `@contact.${field.id || field.value}`;
  }
  // For custom fields, use key with fallbacks
  return `@fields.${field.key || field.id || field.value}`;
};
 
export const split_by_contact_field: NodeConfig = {
  type: 'split_by_contact_field',
  name: 'Split by Contact Field',
  group: SPLIT_GROUPS.split,
  flowTypes: [FlowTypes.VOICE, FlowTypes.MESSAGE, FlowTypes.BACKGROUND],
  dialogSize: 'large',
  form: {
    field: {
      type: 'select',
      required: true,
      searchable: true,
      clearable: false,
      endpoint: '/api/v2/fields.json',
      valueKey: 'key',
      nameKey: 'name',
      placeholder: 'Select a field...',
      // Provide system properties as fixed options at the top
      options: [
        ...Object.values(CONTACT_PROPERTIES).map((prop) => ({
          value: prop.id,
          name: prop.name,
          type: prop.type
        })),
        // Add all URN scheme options (they represent splitting on the URN value, like Facebook ID)
        ...SCHEMES.filter((scheme) => !scheme.excludeFromSplit).map(
          (scheme) => ({
            value: scheme.scheme,
            name: scheme.path,
            type: 'scheme'
          })
        )
      ]
    },
    rules: createRulesArrayConfig(
      operatorsToSelectOptions(getWaitForResponseOperators()),
      ''
    ),
    result_name: resultNameField,
    localizeRules: localizeRulesField,
    localizeCategories: localizeCategoriesField
  },
  layout: ['field', 'rules', nodeOptionsAccordion],
  validate: validateWith((formData, errors) => {
    if (!formData.field || formData.field.length === 0) {
      errors.field = 'A field is required';
    }
  }),
  toFormData: (node: Node, nodeUI?: any) => {
    // Get the field from the UI config operand (source of truth)
    const operand = nodeUI?.config?.operand || CONTACT_PROPERTIES.name;
 
    // Normalize the field object to include properties expected by
    // the Select component (valueKey: 'key') and getOperandForField.
    // toUIConfig saves only { id, name, type }, so we need to add
    // 'key' for custom fields and 'value' for static option matching.
    const field = { ...operand };
    if (field.type === 'field') {
      if (!field.key) field.key = field.id;
    } else {
      if (!field.value) field.value = field.id;
    }
 
    // Extract rules from router cases using shared function
    const rules = casesToFormRules(node);
 
    return {
      uuid: node.uuid,
      field: [field],
      rules: rules,
      result_name: node.router?.result_name || '',
      localizeRules: nodeUI?.config?.localizeRules || false,
      localizeCategories: nodeUI?.config?.localizeCategories || false
    };
  },
  fromFormData: (formData: FormData, originalNode: Node): Node => {
    // Get selected field (it's an array from the select component)
    const selectedField = formData.field?.[0];
 
    if (!selectedField) {
      return originalNode;
    }

    // Get operand for the selected field
    const operand = getOperandForField(selectedField);
 
    // Get user rules using shared extraction function
    const userRules = extractUserRules(formData);
 
    // 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 } = createRulesRouter(
      operand,
      userRules,
      getOperatorConfig,
      existingCategories,
      existingExits,
      existingCases
    );

    // Build final router with 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();
    }
 
    return {
      ...originalNode,
      router: finalRouter,
      exits: exits
    };
  },
  toUIConfig: (formData: FormData) => {
    // Get selected field (it's an array from the select component)
    const selectedField = formData.field?.[0];
 
    if (!selectedField) {
      return {};
    }
 
    // For scheme types, the id should be the scheme name (facebook, whatsapp, etc)
    // For custom fields, the id should be the field key
    // For system properties, the id should be the property id
    let operandId =
      selectedField.id || selectedField.value || selectedField.key;
 
    // If this is a scheme type, ensure we use the scheme name as the id
    if (selectedField.type === 'scheme') {
      operandId = selectedField.value || selectedField.id;
    }
 
    let type = selectedField.type;
    if (type !== 'property' && type !== 'scheme') {
      type = 'field';
    }
 
    // Return UI config with operand information for persistence
    const config: Record<string, any> = {
      operand: {
        id: operandId,
        name: selectedField.name || selectedField.label,
        type
      }
    };
    config.localizeRules = !!formData.localizeRules;
    config.localizeCategories = formData.result_name
      ? !!formData.localizeCategories
      : false;
    return config;
  },
  renderTitle: (node: Node, nodeUI?: any) => {
    return html`<div>Split by ${nodeUI.config.operand.name}</div>`;
  },
 
  // Localization support for categories
  localizable: 'categories'
};