All files / src/components ConditionBuilder.vue

98.68% Statements 75/76
82.5% Branches 33/40
100% Functions 18/18
100% Lines 67/67

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  71x                     6x             4x                   6x 6x 6x                                                                                                                             22x       22x   22x     22x       22x   22x 22x     22x 24x   2x 2x 1x 1x       22x     40x 40x 40x         22x 63x                     2x 2x 2x 2x 2x 2x 2x     22x   2x 2x     1x     1x     1x               2x     1x 1x     29x 29x 29x 44x 41x       22x       22x 22x 22x     4x 3x 3x 3x 3x   1x         4x 4x   1x 1x   3x 4x 4x 1x 1x   2x 2x                      
<template>
  <div class="condition-builder" data-testid="condition-builder">
    <template v-if="!jsonMode">
      <ConditionGroup
        :group="root"
        :depth="1"
        :fields="usableFields"
        :translate="translate"
        :linked-entities="linkedEntities"
      />
      <div class="condition-preview small mt-2" data-testid="condition-preview">
        <font-awesome-icon icon="fa-solid fa-circle-info" class="me-1 text-muted" />
        <span class="text-muted">{{ t('workflow.conditionPreview') }}</span>
        {{ preview }}
      </div>
    </template>
 
    <template v-else>
      <textarea
        v-model="jsonText"
        class="form-control font-monospace small"
        rows="10"
        data-testid="condition-json"
        spellcheck="false"
        name="condition-json"
      ></textarea>
      <div v-if="jsonError" class="text-danger small mt-1">{{ jsonError }}</div>
    </template>
 
    <div class="d-flex justify-content-between align-items-center mt-2">
      <small class="text-muted">{{ t('workflow.conditionEvaluatedOnSave') }}</small>
      <div class="d-flex gap-2">
        <button
          v-if="jsonMode"
          type="button"
          class="btn btn-sm btn-primary"
          data-testid="condition-json-apply"
          @click="applyJson"
        >
          <font-awesome-icon icon="fa-solid fa-check" class="me-1" />
          {{ t('workflow.applyJson') }}
        </button>
        <button
          type="button"
          class="btn btn-sm btn-outline-secondary"
          data-testid="condition-json-toggle"
          @click="toggleJson"
        >
          <font-awesome-icon icon="fa-solid fa-code" class="me-1" />
          {{ jsonMode ? t('workflow.builderView') : t('workflow.jsonView') }}
        </button>
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-WORKFLOW-007.1, UC-WORKFLOW-008.1, UC-WORKFLOW-009.1
import { computed, provide, ref, watch } from 'vue'
import ConditionGroup from './ConditionGroup.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import type { WorkflowCondition, WorkflowConditionOperator } from '@/schemas/entity-schema'
import {
  conditionFields,
  defaultValueFor,
  describeCondition,
  validateCondition,
  OPERATORS_BY_KIND,
  leafKind,
  systemDateFields,
  type ConditionField,
  type LinkedEntities
} from '@/utils/workflowConditions'
import {
  findGroup,
  fromModel,
  newKey,
  removeNode,
  toModel,
  leaves,
  type GroupMode,
  type GroupModel,
  type NodeModel
} from '@/utils/conditionModel'
import { CONDITION_ACTIONS, type ConditionActions } from './conditionActions'
 
interface Props {
  modelValue?: WorkflowCondition
  fields: ConditionField[]
  translate: (value: string | Record<string, string> | undefined) => string
  /** targets of the item link fields, once loaded — for rows on linked items */
  linkedEntities?: LinkedEntities
}
 
const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  linkedEntities: undefined
})
const emit = defineEmits<{ (e: 'update:modelValue', value: WorkflowCondition | undefined): void }>()
 
const { t } = useUILanguage()
 
// The entity's fields plus its system dates (created, updated, entered a state)
const allFields = computed(() => [
  ...props.fields,
  ...systemDateFields(props.fields, t, props.translate)
])
const usableFields = computed(() => conditionFields(allFields.value))
 
const root = ref<GroupModel>(toModel(props.modelValue))
let lastEmitted = JSON.stringify(props.modelValue ?? null)
 
// Re-sync only on an external change (e.g. the panel opened another transition)
watch(
  () => props.modelValue,
  (value) => {
    const serialized = JSON.stringify(value ?? null)
    if (serialized === lastEmitted) return
    lastEmitted = serialized
    root.value = toModel(value)
  }
)
 
watch(
  root,
  (value) => {
    const condition = fromModel(value)
    lastEmitted = JSON.stringify(condition ?? null)
    emit('update:modelValue', condition)
  },
  { deep: true }
)
 
const preview = computed(() =>
  describeCondition(fromModel(root.value), {
    t,
    translate: props.translate,
    fields: allFields.value,
    linkedEntities: props.linkedEntities
  })
)
 
// ---- mutations, shared with ConditionGroup / ConditionRow ----
 
function firstRow(): NodeModel {
  const field = usableFields.value[0]
  const kind = leafKind(field?.type)
  const op: WorkflowConditionOperator = kind ? OPERATORS_BY_KIND[kind][0]! : 'isNotEmpty'
  const row: NodeModel = { key: newKey(), kind: 'row', field: field?.fieldId ?? '', op }
  const value = defaultValueFor(field, op)
  Eif (value !== undefined) row.value = value
  return row
}
 
const actions: ConditionActions = {
  setMode(groupKey: string, mode: GroupMode) {
    const group = findGroup(root.value, groupKey)
    Eif (group) group.mode = mode
  },
  addRow(groupKey: string) {
    findGroup(root.value, groupKey)?.children.push(firstRow())
  },
  addFormula(groupKey: string) {
    findGroup(root.value, groupKey)?.children.push({ key: newKey(), kind: 'formula', formula: '' })
  },
  addGroup(groupKey: string) {
    findGroup(root.value, groupKey)?.children.push({
      key: newKey(),
      kind: 'group',
      mode: 'any',
      children: [firstRow()]
    })
  },
  remove(key: string) {
    removeNode(root.value, key)
  },
  reorder(groupKey: string, children: NodeModel[]) {
    const group = findGroup(root.value, groupKey)
    Eif (group) group.children = children
  },
  updateRow(key: string, patch: Record<string, unknown>) {
    const row = leaves(root.value).find((leaf) => leaf.key === key)
    Iif (!row) return
    for (const [name, value] of Object.entries(patch)) {
      if (value === undefined) delete (row as unknown as Record<string, unknown>)[name]
      else (row as unknown as Record<string, unknown>)[name] = value
    }
  }
}
provide(CONDITION_ACTIONS, actions)
 
// ---- JSON view ----
 
const jsonMode = ref(false)
const jsonText = ref('')
const jsonError = ref('')
 
function toggleJson() {
  if (!jsonMode.value) {
    jsonText.value = JSON.stringify(fromModel(root.value) ?? null, null, 2)
    jsonError.value = ''
    jsonMode.value = true
    return
  }
  jsonMode.value = false
}
 
function applyJson() {
  let parsed: unknown
  try {
    parsed = JSON.parse(jsonText.value)
  } catch {
    jsonError.value = t('workflow.conditionErrors.INVALID_JSON')
    return
  }
  const condition = parsed === null ? undefined : (parsed as WorkflowCondition)
  const error = validateCondition(condition, usableFields.value, props.linkedEntities)
  if (error) {
    jsonError.value = `${error.path}: ${t(`workflow.conditionErrors.${error.code}`)}`
    return
  }
  root.value = toModel(condition)
  jsonMode.value = false
}
</script>
 
<style scoped>
.condition-preview {
  padding: 6px 8px;
  border-radius: 4px;
  background: var(--bw-surface-muted, #f8f9fa);
}
</style>