All files / src/features/targets/utils targetTransformers.js

93.75% Statements 210/224
83.02% Branches 269/324
88.09% Functions 37/42
93.53% Lines 188/201

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 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549      66x 36x 7x 6x   1x 1x           22x 14x     8x 6x 1x 1x           5x 5x 4x         1x       2x 2x                   21x   10x 10x   11x 10x 3x 71x 3x               20x   4x 4x       21x                   21x   8x 8x   8x   8x 3x 3x 5x 2x 2x 3x 3x 3x 6x 6x           3x     8x       22x             22x   8x 8x 2x 2x 1x 1x 1x 1x 1x 1x 1x   6x 3x 3x 3x 3x   3x 3x       8x       20x   7x 6x 6x 4x     1x       19x   11x                 19x 209x 33x     209x                   19x 17x   17x   13x 1x 12x 2x 10x 4x     13x       37x 35x   35x 29x   27x       19x         19x   6x 6x   6x           6x 3x   3x       6x       3x                                                         33x                   19x 2x     17x 17x 17x 17x   17x                                                         9x   9x         8x 12x 11x         9x         5x 5x 5x         9x       11x   11x 11x 11x   11x 5x             11x 1x 38x 2x       11x                   11x 5x   10x 10x 5x 5x         6x                 6x                             11x   11x 5x   11x 4x   11x 1x 10x         4x             11x                 11x 4x     11x   11x 4x     11x 5x     11x 4x                 11x 4x     11x 6x 57x 5x           6x 5x       11x 6x     11x 11x 4x 4x       4x       11x 4x       11x 11x 4x 4x               11x 4x       11x 11x   11x       5x                                  
import { US_STATES, USER_ATTRIBUTE_KEYS } from '../constants/targetConstants';
 
export function parseSetToArray(setOrArray) {
  if (!setOrArray) return [];
  if (Array.isArray(setOrArray)) return setOrArray;
  if (setOrArray instanceof Set) {
    return Array.from(setOrArray);
  }
  Eif (typeof setOrArray === 'object') {
    return Array.from(Object.values(setOrArray));
  }
  return [];
}
 
export function parseGeolocation(geolocation) {
  if (!geolocation) {
    return { latitude: null, longitude: null };
  }
 
  if (typeof geolocation === 'string') {
    if (geolocation.includes(',') && !geolocation.includes('{')) {
      const [lat, lon] = geolocation.split(',');
      return {
        latitude: lat ? parseFloat(lat).toString() : null,
        longitude: lon ? parseFloat(lon).toString() : null,
      };
    }
 
    try {
      const geo = JSON.parse(geolocation);
      return {
        latitude: geo.lat ?? geo.latitude ?? null,
        longitude: geo.lon ?? geo.longitude ?? null,
      };
    } catch {
      return { latitude: null, longitude: null };
    }
  }
 
  Eif (typeof geolocation === 'object') {
    return {
      latitude: geolocation.lat ?? geolocation.latitude ?? null,
      longitude: geolocation.lon ?? geolocation.longitude ?? null,
    };
  }
 
  return { latitude: null, longitude: null };
}
 
export function parseRegionsToStateCodes(regions) {
  if (!regions) return [];
 
  const regionsArray = parseSetToArray(regions);
  return regionsArray
    .map((r) => {
      if (!r) return null;
      if (r.stateCode) return r.stateCode;
      Eif (r.id) {
        const state = US_STATES.find((s) => s.regionId === String(r.id));
        return state?.value || null;
      }
      return null;
    })
    .filter(Boolean);
}
 
export function parseDmaToString(dma) {
  if (!dma) return '';
 
  const values = dma.value || dma.values || [];
  return Array.isArray(values) ? values.join(', ') : '';
}
 
export function parseZipData(zip) {
  const result = {
    zipType: null,
    zipMode: null,
    zipCode: '',
    zipStartRange: '',
    zipEndRange: '',
    zipRanges: [],
    zipCodes: [],
  };
 
  if (!zip) return result;
 
  const zipMode = zip.type;
  const zipValues = zip.value || zip.values || [];
 
  result.zipMode = zipMode;
 
  if (zipMode === 'list') {
    result.zipCode = Array.isArray(zipValues) ? zipValues.join(', ') : '';
    result.zipCodes = Array.isArray(zipValues) ? zipValues : [];
  } else if (zipMode === 'range' && zipValues.length >= 2) {
    result.zipStartRange = zipValues[0] || '';
    result.zipEndRange = zipValues[1] || '';
  } else Eif (zipMode === 'listRange' && zipValues.length > 0) {
    const ranges = [];
    for (let i = 0; i < zipValues.length; i += 2) {
      Eif (i + 1 < zipValues.length) {
        ranges.push({
          start: zipValues[i],
          end: zipValues[i + 1],
        });
      }
    }
    result.zipRanges = ranges;
  }
 
  return result;
}
 
export function parseDeviceSize(size) {
  const result = {
    sizeType: null,
    size: '',
    startSize: '',
    endSize: '',
  };
 
  if (!size) return result;
 
  Eif (typeof size === 'string') {
    if (size.includes(':')) {
      const [type, value] = size.split(':');
      if (type === 'single') {
        result.sizeType = 'list';
        result.size = value;
      } else Eif (type === 'range' && value.includes('-')) {
        const [start, end] = value.split('-');
        result.sizeType = 'range';
        result.startSize = start || '';
        result.endSize = end || '';
      }
    } else if (size.includes('-')) {
      const parts = size.split('-');
      result.sizeType = 'range';
      result.startSize = parts[0] || '';
      result.endSize = parts[1] || '';
    } else {
      result.sizeType = 'list';
      result.size = size;
    }
  }
 
  return result;
}
 
export function parsePreviousLocation(browserDetails) {
  if (!browserDetails) return '';
 
  if (browserDetails.previousLocation) {
    const prev = browserDetails.previousLocation;
    if (typeof prev === 'string') return prev;
    Eif (typeof prev === 'object') return prev.value || '';
  }
 
  return '';
}
 
export function parseTargetCookies(targetCookies) {
  if (!targetCookies || !Array.isArray(targetCookies)) return [];
 
  return targetCookies.map((cookie) => ({
    id: cookie?.id,
    name: cookie?.name || '',
    value: cookie?.value || '',
    operator: cookie?.operator || 'EQUALS',
  }));
}
 
export function parseUserAttributes(userAttributes) {
  return USER_ATTRIBUTE_KEYS.map((attrKey) => {
    const existingAttr = userAttributes && Array.isArray(userAttributes)
      ? userAttributes.find((a) => a && a.key === attrKey.key)
      : null;
 
    return {
      id: existingAttr?.id,
      key: attrKey.key,
      operator: existingAttr?.operator || null,
      value: existingAttr?.value || '',
    };
  });
}
 
export function convertRegexToUrl(regexPattern) {
  if (!regexPattern) return '';
  let url = regexPattern.trim();
 
  if (url === '/' || url === '.*') return url;
 
  if (url === '.*\\/') {
    url = url.substring(2);
  } else if (url.startsWith('.*') && url.length > 4) {
    url = url.substring(2, url.length - 2);
  } else if (url.endsWith('.*')) {
    url = url.substring(0, url.length - 2);
  }
 
  return url.replace(/\\\//g, '/');
}
 
export function convertUrlToRegex(url) {
  if (!url) return '';
  const trimmed = url.trim();
 
  if (trimmed === '' || trimmed === '/' || trimmed === '.*') return trimmed;
  if (trimmed.endsWith('.*')) return trimmed;
 
  return `${trimmed.replace(/\//g, '\\/')}.*`;
}
 
export function parseTargetUrls(targetUrls) {
  const result = {
    targetURLs: [],
    targetUrlsExc: [],
  };
 
  if (!targetUrls || !Array.isArray(targetUrls)) return result;
 
  targetUrls.forEach((urlItem) => {
    Iif (!urlItem) return;
 
    const urlObj = {
      id: urlItem.id,
      targetUrl: convertRegexToUrl(urlItem.targetUrl),
      qryParams: urlItem.qryParams || [],
    };
 
    if (urlItem.inclusive) {
      result.targetURLs.push(urlObj);
    } else {
      result.targetUrlsExc.push(urlObj);
    }
  });
 
  return result;
}
 
export function getEmptyFormData() {
  return {
    name: '',
    description: '',
    experimentIds: [],
    clients: [],
    targetURLs: [],
    targetUrlsExc: [],
    iShip: null,
    signedIn: null,
    userType: null,
    latitude: null,
    longitude: null,
    states: [],
    dmaValues: '',
    zipType: null,
    zipMode: null,
    zipCode: '',
    zipStartRange: '',
    zipEndRange: '',
    zipRanges: [],
    zipCodes: [],
    akamaiDevice: [],
    platform: [],
    sizeType: null,
    size: '',
    startSize: '',
    endSize: '',
    previousLocation: '',
    targetCookies: [],
    userAttributes: USER_ATTRIBUTE_KEYS.map((attr) => ({
      key: attr.key,
      operator: null,
      value: '',
    })),
    emailType: null,
  };
}
 
export function transformXAPIToForm(target) {
  if (!target) {
    return getEmptyFormData();
  }
 
  const userData = target.userData || target.user || target.userInfo || {};
  const deviceData = target.device;
  const browserData = target.browserDetails || target.browserInfo;
  const targetUrlsData = target.targetUrls || target.targetURLs;
 
  return {
    id: target.id,
    experimentIds: Array.isArray(target.experimentIds)
      ? target.experimentIds
      : [],
    name: target.name || '',
    description: target.description || '',
    clients: parseSetToArray(target.clients),
 
    iShip: userData.iship ?? userData.iShip ?? null,
    signedIn: userData.signedIn ?? null,
    userType: userData.userType ?? null,
    ...parseGeolocation(userData.geolocation || userData.geoLocation),
    states: parseRegionsToStateCodes(userData.regions),
    dmaValues: parseDmaToString(userData.dma),
    ...parseZipData(userData.zip || userData.zipInfo),
    akamaiDevice: parseSetToArray(deviceData?.akamaiValues),
    platform: parseSetToArray(deviceData?.platforms),
    ...parseDeviceSize(deviceData?.size),
    previousLocation: parsePreviousLocation(browserData),
    targetCookies: parseTargetCookies(target.targetCookies),
    userAttributes: parseUserAttributes(target.userAttributes),
    emailType:
      target.emailTemplate?.name || target.emailTemplate?.emailType || null,
    ...parseTargetUrls(targetUrlsData),
  };
}
 
export function generatePatterns(formData) {
  const urls = [];
 
  if (
    formData.targetURLs
    && Array.isArray(formData.targetURLs)
    && formData.targetURLs.length > 0
  ) {
    formData.targetURLs.forEach((item) => {
      if (item && item.targetUrl && item.targetUrl.trim()) {
        urls.push(convertUrlToRegex(item.targetUrl));
      }
    });
  }
 
  if (
    formData.targetUrlsExc
    && Array.isArray(formData.targetUrlsExc)
    && formData.targetUrlsExc.length > 0
  ) {
    formData.targetUrlsExc.forEach((item) => {
      Eif (item && item.targetUrl && item.targetUrl.trim()) {
        urls.push(convertUrlToRegex(item.targetUrl));
      }
    });
  }
 
  return urls;
}
 
export function transformFormToXAPI(formData) {
  const userInfo = {};
 
  userInfo.iShip = formData.iShip !== undefined ? formData.iShip : null;
  userInfo.signedIn = formData.signedIn !== undefined ? formData.signedIn : null;
  userInfo.userType = formData.userType !== undefined ? formData.userType : null;
 
  if (formData.latitude && formData.longitude) {
    userInfo.geoLocation = {
      type: 'GeoPointSingleValue',
      lat: parseFloat(formData.latitude),
      lon: parseFloat(formData.longitude),
    };
  }
 
  if (formData.states && formData.states.length > 0) {
    userInfo.regions = formData.states.map((stateCode) => {
      const state = US_STATES.find((s) => s.value === stateCode);
      return { id: state?.regionId || stateCode };
    });
  }
 
  Iif (formData.dmaValues && formData.dmaValues.trim()) {
    userInfo.dma = {
      type: 'dma',
      value: formData.dmaValues
        .split(',')
        .map((v) => v.trim())
        .filter((v) => v),
    };
  }
 
  if (formData.zipMode === 'list' && formData.zipCode) {
    const zipValues = formData.zipCode
      .split(',')
      .map((z) => z.trim())
      .filter((z) => z);
    Eif (zipValues.length > 0) {
      userInfo.zipInfo = {
        type: formData.zipMode,
        value: zipValues,
      };
    }
  } else Iif (
    formData.zipMode === 'range'
    && formData.zipStartRange
    && formData.zipEndRange
  ) {
    userInfo.zipInfo = {
      type: formData.zipMode,
      value: [formData.zipStartRange, formData.zipEndRange],
    };
  } else Iif (
    formData.zipMode === 'listRange'
    && formData.zipRanges.length > 0
  ) {
    const rangeValues = formData.zipRanges
      .flatMap((r) => [r.start, r.end])
      .filter((v) => v);
    if (rangeValues.length > 0) {
      userInfo.zipInfo = {
        type: formData.zipMode,
        value: rangeValues,
      };
    }
  }
 
  const devices = {};
 
  if (formData.akamaiDevice && formData.akamaiDevice.length > 0) {
    devices.akamaiDevice = { type: 'list', value: formData.akamaiDevice };
  }
  if (formData.platform && formData.platform.length > 0) {
    devices.platform = { type: 'list', value: formData.platform };
  }
  if (formData.sizeType === 'list' && formData.size) {
    devices.size = { type: 'single', value: parseInt(formData.size, 10) };
  } else if (
    formData.sizeType === 'range'
    && formData.startSize
    && formData.endSize
  ) {
    devices.size = {
      type: 'range',
      startSize: parseInt(formData.startSize, 10),
      endSize: parseInt(formData.endSize, 10),
    };
  }
 
  const payload = {
    name: formData.name,
    description: formData.description || null,
    clients: {
      type: 'list',
      value: formData.clients,
    },
  };
 
  if (formData.clients?.includes('SITE')) {
    payload.patterns = generatePatterns(formData);
  }
 
  payload.userInfo = userInfo;
 
  if (formData.zipType) {
    payload.zipType = formData.zipType;
  }
 
  if (Object.keys(devices).length > 0) {
    payload.devices = devices;
  }
 
  if (formData.previousLocation) {
    payload.browserInfo = {
      previousLocation: {
        type: 'single',
        value: formData.previousLocation,
      },
      browsingHistory: null,
    };
  }
 
  if (formData.targetCookies && formData.targetCookies.length > 0) {
    payload.targetCookies = formData.targetCookies;
  }
 
  if (formData.userAttributes && formData.userAttributes.length > 0) {
    const filledAttributes = formData.userAttributes
      .filter((attr) => attr.operator && attr.value && attr.value.trim())
      .map((attr) => ({
        key: attr.key,
        operator: attr.operator,
        value: attr.value,
      }));
 
    if (filledAttributes.length > 0) {
      payload.userAttributes = filledAttributes;
    }
  }
 
  if (formData.clients?.includes('EMAIL') && formData.emailType) {
    payload.targetEmailType = { emailType: formData.emailType };
  }
 
  Eif (formData.targetURLs && Array.isArray(formData.targetURLs)) {
    const validUrls = formData.targetURLs
      .filter((url) => url && url.targetUrl && url.targetUrl.trim())
      .map((url) => ({
        targetUrl: convertUrlToRegex(url.targetUrl),
        isInclusive: true,
        qryParams: (url.qryParams || []).filter(
          (p) => p && p.key && p.key.trim(),
        ),
      }));
 
    if (validUrls.length > 0) {
      payload.targetURLs = validUrls;
    }
  }
 
  Eif (formData.targetUrlsExc && Array.isArray(formData.targetUrlsExc)) {
    const validUrlsExc = formData.targetUrlsExc
      .filter((url) => url && url.targetUrl && url.targetUrl.trim())
      .map((url) => ({
        targetUrl: convertUrlToRegex(url.targetUrl),
        isInclusive: false,
        qryParams: (url.qryParams || []).filter(
          (p) => p && p.key && p.key.trim(),
        ),
      }));
 
    if (validUrlsExc.length > 0) {
      payload.targetUrlsExc = validUrlsExc;
    }
  }
 
  payload.isUrlTargetted = false;
  payload.isCacheable = false;
 
  return payload;
}
 
export function buildTemplateData(apiData) {
  return {
    name: null,
    clients: apiData.clients,
    targetURLs: apiData.targetURLs,
    targetUrlsExc: apiData.targetUrlsExc,
    userInfo: apiData.userInfo,
    devices: apiData.devices,
    patterns: apiData.patterns,
    zipType: apiData.zipType,
    browserInfo: apiData.browserInfo,
    targetCookies: apiData.targetCookies,
    userAttributes: apiData.userAttributes,
    targetEmailType: apiData.targetEmailType,
    isUrlTargetted: apiData.isUrlTargetted || false,
    isCacheable: apiData.isCacheable || false,
  };
}