All files / modules/75-cf/pages/target-group-detail/components/EditTargetGroupCriteria getInstructions.ts

100% Statements 27/27
90% Branches 9/10
100% Functions 12/12
100% Lines 22/22

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              3x     3x   3x           8x 24x   8x 22x       8x 2x     8x 2x     8x     3x 20x   10x   6x 19x   10x     6x 4x 1x   1x        
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import { isEqual, omit } from 'lodash-es'
import type { SelectOption } from '@wings-software/uicore'
import type { Clause, Target } from 'services/cf'
import patch, { getDiff, Instruction } from '@cf/utils/instructions'
 
export function getTargetInstructions(
  existing: Target[],
  selections: SelectOption[],
  addFn: (targets: string[]) => Instruction,
  removeFn: (targets: string[]) => Instruction
): Instruction[] {
  const instructions: Instruction[] = []
  const selectionIds = selections.map(({ value }) => value as string)
 
  const [newTargets, removedTargets] = getDiff<string, string>(
    existing.map(({ identifier }) => identifier),
    selectionIds
  )
 
  if (newTargets.length) {
    instructions.push(addFn(newTargets))
  }
 
  if (removedTargets.length) {
    instructions.push(removeFn(removedTargets))
  }
 
  return instructions
}
 
export function getRulesInstructions(existing: Clause[], rules: Clause[]): Instruction[] {
  const removedRules = existing.filter(({ id: existingId }) => !rules.find(({ id }) => id === existingId))
 
  const newRules = rules.filter(rule => !rule?.id)
 
  const editedRules = rules.filter(rule => {
    const existingRule = existing.find(({ id }) => id === rule.id)
 
    return !!existingRule && !isEqual(rule, existingRule)
  })
 
  return [
    ...removedRules.map(({ id }) => patch.creators.removeClauseOnSegment(id as string)),
    ...newRules.map(rule => patch.creators.addClauseToSegment(omit(rule, ['id']))),
    ...editedRules.map(rule =>
      patch.creators.updateClauseOnSegment({ ...omit(rule, ['id', 'negate']), clauseID: rule.id as string })
    )
  ]
}