All files / src/flow/nodes split_by_airtime.ts

93.69% Statements 223/238
73.58% Branches 39/53
75% Functions 3/4
93.69% Lines 223/238

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 23998x 98x 98x 98x 98x 98x 98x 98x 98x 3x 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 98x 98x 98x 98x 9x         9x 9x 10x 10x 9x 9x 10x 9x 9x 3x 3x 6x 6x 6x 6x 6x 8x 8x 8x 8x 8x 8x 8x     8x 8x 8x 7x 6x 1x 1x 1x 1x 9x 9x 8x 8x 8x 3x 3x 3x 98x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 3x 1x 1x 3x 3x 1x 1x 3x 98x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 7x 7x 7x       7x 7x 7x 5x 5x 5x 5x 98x 98x 98x 98x 98x 98x 98x 98x 109x 109x 109x 109x 109x 108x 107x 109x 109x 107x 107x 107x 109x 107x 109x 97x 97x 97x 97x 97x 97x 97x 97x 107x 107x 107x 109x 107x 107x 107x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 101x 98x 98x 98x 98x 98x 98x 98x 98x  
import {
  ACTION_GROUPS,
  FormData,
  NodeConfig,
  FlowTypes,
  Features
} from '../types';
import { TransferAirtime, Node } from '../../store/flow-definition';
import { generateUUID, createSuccessFailureRouter } from '../../utils';
import { validateWith } from '../utils';
import { html } from 'lit';
import { CURRENCY_OPTIONS, CURRENCIES } from '../currencies';
import { resultNameField } from './shared';
 
export const split_by_airtime: NodeConfig = {
  type: 'split_by_airtime',
  name: 'Send Airtime',
  group: ACTION_GROUPS.services,
  flowTypes: [FlowTypes.VOICE, FlowTypes.MESSAGE, FlowTypes.BACKGROUND],
  features: [Features.AIRTIME],
  showAsAction: true,
  form: {
    amounts: {
      type: 'array',
      label: 'Airtime Amounts',
      helpText: 'Define the currencies and amounts to transfer',
      required: true,
      itemLabel: 'Amount',
      sortable: false,
      minItems: 1,
      maxItems: 10,
      isEmptyItem: (item: any) => {
        return !item.currency || !item.amount || item.amount.trim() === '';
      },
      itemConfig: {
        currency: {
          type: 'select',
          placeholder: 'Select a currency',
          required: true,
          options: CURRENCY_OPTIONS,
          searchable: true,
          multi: false,
          width: '200px'
        },
        amount: {
          type: 'text',
          placeholder: 'Amount',
          required: true
        }
      }
    },
    result_name: resultNameField
  },
  layout: ['amounts', 'result_name'],
  validate: validateWith((formData, errors) => {
    if (!formData.amounts || !Array.isArray(formData.amounts)) {
      errors.amounts = 'At least one currency and amount is required';
      return;
    }
 
    const validAmounts = formData.amounts.filter(
      (item: any) => item?.currency && item?.amount && item.amount.trim() !== ''
    );

    if (validAmounts.length === 0) {
      errors.amounts = 'At least one currency and amount is required';
      return;
    }
 
    const currencies = new Set();
    const duplicates: string[] = [];
 
    validAmounts.forEach((item: any) => {
      const currencyCode =
        Array.isArray(item.currency) && item.currency.length > 0
          ? item.currency[0].value
          : typeof item.currency === 'string'
            ? item.currency
            : item.currency?.value;
 
      if (currencies.has(currencyCode)) {
        duplicates.push(currencyCode);
      } else {
        currencies.add(currencyCode);
      }
    });
 
    if (duplicates.length > 0) {
      errors.amounts = `Duplicate currencies found: ${duplicates.join(', ')}`;
    }

    for (const item of validAmounts) {
      const amount = item.amount.trim();
      if (isNaN(Number(amount)) || Number(amount) <= 0) {
        errors.amounts = 'All amounts must be valid positive numbers';
        return;
      }
    }
  }),
  render: (node: Node) => {
    const transferAirtimeAction = node.actions?.find(
      (action) => action.type === 'transfer_airtime'
    ) as TransferAirtime;
 
    if (!transferAirtimeAction || !transferAirtimeAction.amounts) {
      return html`<div class="body">Configure airtime transfer</div>`;
    }
 
    const amounts = transferAirtimeAction.amounts;
    const currencies = Object.keys(amounts);
 
    if (currencies.length === 0) {
      return html`<div class="body">Configure airtime transfer</div>`;
    }
 
    // Display the first currency amount, with indicator if there are more
    const firstCurrency = currencies[0];
    const firstAmount = amounts[firstCurrency];
    const moreCount = currencies.length - 1;

    return html`
      <div class="body">
        ${firstCurrency}
        ${firstAmount}${moreCount > 0
          ? html` <span style="color: #999;">+${moreCount} more</span>`
          : ''}
      </div>
    `;
  },
  toFormData: (node: Node) => {
    // Extract data from the existing node structure
    const transferAirtimeAction = node.actions?.find(
      (action) => action.type === 'transfer_airtime'
    ) as TransferAirtime;
 
    const amounts: any[] = [];
    if (transferAirtimeAction && transferAirtimeAction.amounts) {
      Object.entries(transferAirtimeAction.amounts).forEach(
        ([currency, amount]) => {
          amounts.push({
            currency: [
              {
                value: currency,
                name: CURRENCIES[currency]?.name
                  ? `${CURRENCIES[currency].name} (${currency})`
                  : currency
              }
            ],
            amount: String(amount)
          });
        }
      );
    }
 
    return {
      uuid: node.uuid,
      amounts: amounts,
      result_name: node.router?.result_name || ''
    };
  },
  fromFormData: (formData: FormData, originalNode: Node): Node => {
    // Get user amounts and convert to amounts object
    const amountsObject: Record<string, number> = {};
 
    if (formData.amounts && Array.isArray(formData.amounts)) {
      formData.amounts.forEach((item: any) => {
        if (!item?.currency || !item?.amount || item.amount.trim() === '') {
          return;
        }

        // Extract currency code from selection (handle both array and object formats)
        let currencyCode: string;
        if (Array.isArray(item.currency) && item.currency.length > 0) {
          currencyCode = item.currency[0].value;
        } else if (typeof item.currency === 'string') {
          currencyCode = item.currency;
        } else if (item.currency?.value) {
          currencyCode = item.currency.value;
        } else {
          return;
        }
 
        const amount = parseFloat(item.amount.trim());
        if (!isNaN(amount) && amount > 0) {
          amountsObject[currencyCode] = amount;
        }
      });
    }
 
    // Find existing transfer_airtime action to preserve its UUID
    const existingTransferAirtimeAction = originalNode.actions?.find(
      (action) => action.type === 'transfer_airtime'
    );
    const transferAirtimeUuid =
      existingTransferAirtimeAction?.uuid || generateUUID();
 
    // Create transfer_airtime action
    const transferAirtimeAction: TransferAirtime = {
      type: 'transfer_airtime',
      uuid: transferAirtimeUuid,
      amounts: amountsObject
    };
 
    // Create categories and exits for Success and Failure
    const existingCategories = originalNode.router?.categories || [];
    const existingExits = originalNode.exits || [];
    const existingCases = originalNode.router?.cases || [];
 
    const { router, exits } = createSuccessFailureRouter(
      '@locals._new_transfer',
      {
        type: 'has_text',
        arguments: []
      },
      existingCategories,
      existingExits,
      existingCases
    );
 
    // Add result_name if provided
    const finalRouter: any = { ...router };
    if (formData.result_name && formData.result_name.trim() !== '') {
      finalRouter.result_name = formData.result_name.trim();
    }
 
    // Return the complete node
    return {
      uuid: originalNode.uuid,
      actions: [transferAirtimeAction],
      router: finalRouter,
      exits: exits
    };
  },
 
  // Localization support for categories
  localizable: 'categories',
  nonTranslatableCategories: 'all'
};