All files / src/flow/actions send_msg.ts

95.09% Statements 388/408
75.94% Branches 60/79
100% Functions 11/11
95.09% Lines 388/408

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 40998x 11x 11x 11x 11x 11x 11x 11x 11x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 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 60x 2x 2x 2x 138x 138x 292x 2x 2x 344x 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 363x 363x 363x 83x 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 71x 71x 71x 40x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 67x 67x 67x 67x 67x 98x 98x 98x 98x 98x 71x 71x 71x 71x 98x 98x 39x 39x 39x 4x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 8x 2x 2x 8x 39x 39x 39x 39x 39x 39x 39x 39x 60x 39x 39x 39x 39x 39x 39x 39x 39x 39x 98x 98x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 8x       8x 8x 8x 8x 8x 8x     98x 98x 1x 1x 98x 98x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 98x 98x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 6x 3x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 6x 6x 6x 6x 6x 6x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 101x 101x 101x 97x 97x 98x 101x 101x 98x 99x 99x 99x 99x 99x 98x 98x 98x 98x 98x 98x 98x 98x 98x  
import { html } from 'lit-html';
import {
  ActionConfig,
  ACTION_GROUPS,
  FormData,
  ValidationResult,
  FlowTypes
} from '../types';
import { Node, SendMsg } from '../../store/flow-definition';
import { titleCase } from '../../utils';
import { renderClamped, renderHighlightedText } from '../utils';
import { splitSMS } from '../../display/sms';
 
const ATTACHMENT_TYPE_NAMES: Record<string, string> = {
  image: 'Image',
  audio: 'Audio',
  video: 'Video',
  application: 'Document'
};
 
export const send_msg: ActionConfig = {
  name: 'Send Message',
  group: ACTION_GROUPS.send,
  flowTypes: [FlowTypes.VOICE, FlowTypes.MESSAGE, FlowTypes.BACKGROUND],
  hideFromActions: true,
  render: (_node: Node, action: SendMsg) => {
    const sms = splitSMS(action.text);
 
    return html`
      ${action.template
        ? html`<div
            style="border: 1px solid #7dc8bc;padding: 0.5em;margin-bottom: 0.5em;border-radius: 4px; display:flex;align-items: flex-start;background: #f0faf7;color: #128C7E;font-size: 0.85em;"
          >
            <temba-icon
              name="channel_wac"
              style="--icon-size: 14px;"
            ></temba-icon>
            <div style="margin-left:0.4em">${action.template.name}</div>
          </div>`
        : null}
      ${renderClamped(renderHighlightedText(action.text, true), action.text, 6)}
      ${sms.parts.length > 1
        ? html`<div style="text-align: right;">
            <temba-charcount
              .text="${action.text}"
              style="font-size: 1em; --temba-charcount-background: var(--color-overlay-light, rgba(0,0,0,0.05)); --temba-charcount-color: var(--color-overlay-light-text, #666);"
            ></temba-charcount>
          </div>`
        : null}
      ${(action.quick_replies || [])?.length > 0
        ? html`<div class="quick-replies">
            ${(action.quick_replies || []).map((reply) => {
              return html`<div class="quick-reply">${reply}</div>`;
            })}
          </div>`
        : null}
    `;
  },
  form: {
    text: {
      type: 'message-editor',
      label: 'Message',
      helpText:
        'Enter the message to send with optional attachments. You can use expressions like @contact.name',
      required: true,
      evaluated: true,
      placeholder: 'Type your message here...',
      maxLength: 10000,
      maxAttachments: 10,
      accept: '',
      endpoint: '/api/v2/media.json',
      counter: 'temba-charcount',
      gsm: true,
      autogrow: true
    },
    quick_replies: {
      type: 'select',
      options: [],
      multi: true,
      tags: true,
      searchable: true,
      placeholder: 'Add quick replies...',
      maxItems: 10,
      evaluated: true
    },
    template: {
      type: 'template-editor',
      endpoint: '/api/internal/templates.json'
    },
    runtime_attachments: {
      type: 'array',
      itemLabel: 'Attachment',
      sortable: true,
      maxItems: 10,
      isEmptyItem: (item: any) => {
        return !item.expression || item.expression.trim() === '';
      },
      itemConfig: {
        type: {
          type: 'select',
          width: '140px',
          options: [
            { value: 'image', name: 'Image' },
            { value: 'audio', name: 'Audio' },
            { value: 'video', name: 'Video' },
            { value: 'application', name: 'Document' }
          ],
          required: true,
          searchable: false
        },
        expression: {
          type: 'text',
          placeholder: 'Expression (e.g. @contact.photo)',
          required: true,
          evaluated: true
        }
      }
    }
  },
  layout: [
    'text',
    {
      type: 'accordion',
      sections: [
        {
          label: 'Quick Replies',
          collapsed: true,
          getValueCount: (formData: FormData) => {
            return formData.quick_replies?.length || 0;
          },
          items: ['quick_replies']
        },
        {
          label: 'WhatsApp Template',
          collapsed: true,
          localizable: false,
          getValueCount: (formData: FormData) => {
            return !!formData.template;
          },
          items: ['template']
        },
        {
          label: 'Runtime Attachments',
          collapsed: true,
          getValueCount: (formData: FormData) => {
            return (
              formData.runtime_attachments?.filter(
                (item: any) =>
                  item && item.expression && item.expression.trim() !== ''
              ).length || 0
            );
          },
          items: ['runtime_attachments']
        }
      ]
    }
  ],
  toFormData: (action: SendMsg) => {
    // Extract runtime attachments from the text field attachments
    const runtimeAttachments: {
      type: { name: string; value: string };
      expression: string;
    }[] = [];
    const staticAttachments: string[] = [];
 
    if (action.attachments && Array.isArray(action.attachments)) {
      action.attachments.forEach((attachment) => {
        if (typeof attachment === 'string' && attachment.includes(':')) {
          const colonIndex = attachment.indexOf(':');
          const contentType = attachment.substring(0, colonIndex);
          const value = attachment.substring(colonIndex + 1);
 
          if (!contentType.includes('/')) {
            runtimeAttachments.push({
              type: {
                name:
                  ATTACHMENT_TYPE_NAMES[contentType] || titleCase(contentType),
                value: contentType
              },
              expression: value
            });
          } else {
            staticAttachments.push(attachment);
          }
        }
      });
    }
 
    return {
      uuid: action.uuid,
      text: action.text || '',
      attachments: staticAttachments,
      runtime_attachments: runtimeAttachments,
      quick_replies: (action.quick_replies || []).map((reply) => ({
        name: reply,
        value: reply
      })),
      template: action.template || null,
      template_variables: action.template_variables || []
    };
  },
  fromFormData: (data: FormData) => {
    const result = {
      uuid: data.uuid,
      type: 'send_msg',
      text: data.text || '',
      attachments: [],
      quick_replies: (data.quick_replies || []).map((reply: any) =>
        typeof reply === 'string' ? reply : reply.value || reply.name || reply
      )
    };
 
    // Combine static attachments from text field with runtime attachments
    const staticAttachments = data.attachments || [];
    const runtimeAttachments = (data.runtime_attachments || [])
      .filter(
        (item: {
          type: [{ name: string; value: string }];
          expression: string;
        }) => item && item.type && item.expression
      ) // Filter out invalid items
      .map(
        (item: {
          type: [{ name: string; value: string }];
          expression: string;
        }) => `${item.type[0].value}:${item.expression}`
      );
 
    result.attachments = [...staticAttachments, ...runtimeAttachments];
 
    // Remove quick_replies if empty to match original format
    if (result.quick_replies.length === 0) {
      delete (result as any).quick_replies;
    }
 
    // Add template and template_variables if a template is selected
    if (data.template) {
      (result as any).template = data.template;
      (result as any).template_variables = data.template_variables || [];
    }
 
    return result as SendMsg;
  },
  sanitize: (formData: FormData): void => {
    if (formData.text && typeof formData.text === 'string') {
      formData.text = formData.text.trim();
    }
  },
  validate: (formData: FormData): ValidationResult => {
    const errors: { [key: string]: string } = {};

    // Check total attachment count (static + runtime should not exceed 10)
    const staticAttachments = formData.attachments || [];
    const runtimeAttachments = (formData.runtime_attachments || []).filter(
      (item: any) => item && item.expression && item.expression.trim() !== ''
    );
 
    const totalAttachments =
      staticAttachments.length + runtimeAttachments.length;
    if (totalAttachments > 10) {
      if (runtimeAttachments.length > 0) {
        errors.runtime_attachments =
          'Each message can only have up to 10 attachments';
      }
      if (staticAttachments.length > 0) {
        errors.text = 'Each message can only have up to 10 total attachments';
      }
    }
 
    return {
      valid: Object.keys(errors).length === 0,
      errors
    };
  },
  localizable: ['text', 'quick_replies', 'attachments'],
  toLocalizationFormData: (
    action: SendMsg,
    localization: Record<string, any>
  ) => {
    // Convert localized values to form data format
    // Localized values are stored as arrays even for single values
    const formData: FormData = {
      uuid: action.uuid
    };
 
    // Handle text (single value, but stored as array in localization)
    if (localization.text && Array.isArray(localization.text)) {
      formData.text = localization.text[0] || '';
    } else {
      // Fall back to empty string if no localization
      formData.text = '';
    }
 
    // Handle attachments (already an array)
    if (localization.attachments && Array.isArray(localization.attachments)) {
      formData.attachments = localization.attachments;
    }
 
    // Handle quick_replies (already an array)
    if (
      localization.quick_replies &&
      Array.isArray(localization.quick_replies)
    ) {
      formData.quick_replies = localization.quick_replies.map((reply) => ({
        name: reply,
        value: reply
      }));
    }
 
    // Extract runtime attachments from localized attachments
    const runtimeAttachments: {
      type: { name: string; value: string };
      expression: string;
    }[] = [];
    const staticAttachments: string[] = [];
 
    if (formData.attachments && Array.isArray(formData.attachments)) {
      formData.attachments.forEach((attachment) => {
        if (typeof attachment === 'string' && attachment.includes(':')) {
          const colonIndex = attachment.indexOf(':');
          const contentType = attachment.substring(0, colonIndex);
          const value = attachment.substring(colonIndex + 1);
 
          if (!contentType.includes('/')) {
            runtimeAttachments.push({
              type: {
                name:
                  ATTACHMENT_TYPE_NAMES[contentType] || titleCase(contentType),
                value: contentType
              },
              expression: value
            });
          } else {
            staticAttachments.push(attachment);
          }
        }
      });
    }
 
    formData.attachments = staticAttachments;
    formData.runtime_attachments = runtimeAttachments;
 
    return formData;
  },
  fromLocalizationFormData: (formData: FormData, action: SendMsg) => {
    // Convert form data to localization format
    // All values must be stored as arrays
    const localization: Record<string, any> = {};
 
    // Handle text (store as single-element array)
    // Only save if not empty and different from base action
    if (formData.text && formData.text.trim() !== '') {
      if (formData.text !== action.text) {
        localization.text = [formData.text];
      }
    }
 
    // Handle quick_replies (store as array)
    const quickReplies = (formData.quick_replies || [])
      .map((reply: any) =>
        typeof reply === 'string' ? reply : reply.value || reply.name || reply
      )
      .filter((reply: string) => reply && reply.trim() !== '');
 
    // Only save if there are quick replies and different from base action
    if (quickReplies.length > 0) {
      if (
        JSON.stringify(quickReplies) !==
        JSON.stringify(action.quick_replies || [])
      ) {
        localization.quick_replies = quickReplies;
      }
    }
 
    // Handle attachments (combine static and runtime attachments)
    const staticAttachments = (formData.attachments || []).filter(
      (att: string) => att && att.trim() !== ''
    );
    const runtimeAttachments = (formData.runtime_attachments || [])
      .filter(
        (item: {
          type: [{ name: string; value: string }];
          expression: string;
        }) =>
          item && item.type && item.expression && item.expression.trim() !== ''
      )
      .map(
        (item: {
          type: [{ name: string; value: string }];
          expression: string;
        }) => `${item.type[0].value}:${item.expression}`
      );
 
    const allAttachments = [...staticAttachments, ...runtimeAttachments];
 
    // Only save if there are attachments and different from base action
    if (allAttachments.length > 0) {
      if (
        JSON.stringify(allAttachments) !==
        JSON.stringify(action.attachments || [])
      ) {
        localization.attachments = allAttachments;
      }
    }
 
    return localization;
  }
};