All files / src/composables useEntityFormErrors.ts

97.43% Statements 38/39
88.23% Branches 45/51
100% Functions 9/9
97.22% Lines 35/36

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                            3x                       232x 232x                                   7x 2x   1x     1x       6x 2x 2x       2x     2x   4x 1x   3x     7x     7x     7x                 5x 5x 5x 10x 5x       5x       32x 9x 9x 2x     30x         353x     353x     222x   2x   351x     232x    
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { isReservedEntityName, getReservedNameError } from '@/utils/constants'
import type { EntityField } from '@/stores/entities'
import {
  conditionErrorText,
  describeStateRef,
  describeTransitionRef,
  type ConditionField
} from '@/utils/workflowConditions'
import { validateEmailTemplate } from '@/utils/emailTemplates'
import type { EmailTemplate } from '@/schemas/entity-schema'
 
// API errors on an automatic transition (UC-WORKFLOW-007.1)
const AUTO_TRANSITION_ERRORS = [
  'INVALID_WORKFLOW_CONDITION',
  'INVALID_AUTO_TRANSITION',
  'AUTO_TRANSITION_WITH_PERMISSION',
  'INVALID_WORKFLOW_TIMER'
]
 
/**
 * The messages the entity form shows for a rejected definition — shared by
 * creating (Entities page) and editing (EntityEditSidebar).
 */
export function useEntityFormErrors() {
  const { getTranslation } = useLanguage()
  const { t } = useUILanguage()
 
  // An automatic transition the API rejected names the transition and says why
  // (and where in a formula); other field errors keep the generic message.
  function fieldErrorMessage(
    errData: {
      error?: string
      fieldId?: string
      from?: string
      to?: string
      stateId?: string
      code?: string
      conditionCode?: string
      position?: number
      language?: string
    },
    fields: ConditionField[]
  ) {
    if (errData.error === 'FIELD_NAME_TAKEN') {
      const field = fields.find((f) => f.fieldId === errData.fieldId)
      const name =
        typeof field?.name === 'string'
          ? field.name
          : (errData.language && field?.name?.[errData.language]) || getTranslation(field?.name)
      return t('entity.fieldNameTakenIn')
        .replace('{name}', (name || errData.fieldId || '').trim())
        .replace('{language}', (errData.language || '').toUpperCase())
    }
    if (errData.error === 'INVALID_TRANSITION_ACTION') {
      const transition = describeTransitionRef(fields, errData, getTranslation)
      const title = transition
        ? `${t('workflow.emailActions.invalid')} (${transition})`
        : t('workflow.emailActions.invalid')
      const reason =
        errData.code === 'INVALID_ACTION_CONDITION'
          ? conditionErrorText(errData.conditionCode, errData.position, t)
          : t(`workflow.emailActions.errors.${errData.code}`)
      return `${title}: ${reason}`
    }
    if (!errData.error || !AUTO_TRANSITION_ERRORS.includes(errData.error)) {
      return t('entity.fixFieldErrors')
    }
    const code = ['INVALID_WORKFLOW_CONDITION', 'INVALID_WORKFLOW_TIMER'].includes(errData.error)
      ? errData.code
      : errData.error
    const transition = errData.stateId
      ? describeStateRef(fields, errData, getTranslation)
      : describeTransitionRef(fields, errData, getTranslation)
    const title = transition
      ? `${t('workflow.invalidAutomaticTransition')} (${transition})`
      : t('workflow.invalidAutomaticTransition')
    return `${title}: ${conditionErrorText(code, errData.position, t)}`
  }
 
  // An email template the API (or the pre-submit check) rejected, named
  function emailTemplateErrorText(
    error: { code?: string; templateId?: string; fieldId?: string },
    templates: EmailTemplate[] | undefined,
    fields: EntityField[]
  ) {
    const template = templates?.find((tpl) => tpl.id === error.templateId)
    const name = template ? getTranslation(template.name) : ''
    const title = name ? `${t('emailTemplates.invalid')} (${name})` : t('emailTemplates.invalid')
    const field = fields.find((f) => f.fieldId === error.fieldId)
    const reason = t(`emailTemplates.errors.${error.code ?? 'INVALID_EMAIL_TEMPLATE'}`).replace(
      '{field}',
      (field && getTranslation(field.name)) || error.fieldId || ''
    )
    return `${title}: ${reason}`
  }
 
  function emailTemplatesError(templates: EmailTemplate[] | undefined, fields: EntityField[]) {
    for (const template of templates ?? []) {
      const error = validateEmailTemplate(template, fields)
      if (error) {
        return emailTemplateErrorText({ ...error, templateId: template.id }, templates, fields)
      }
    }
    return null
  }
 
  /** Why the entity name can't be used (reserved for system entities), if it can't */
  function nameError(name: string | Record<string, string> | undefined): string | undefined {
    Iif (typeof name === 'string' && isReservedEntityName(name)) {
      return getReservedNameError(name)
    }
    if (
      name &&
      typeof name === 'object' &&
      Object.values(name).some((val: any) => isReservedEntityName(val))
    ) {
      return 'This name is reserved for system entities'
    }
    return undefined
  }
 
  return { fieldErrorMessage, emailTemplateErrorText, emailTemplatesError, nameError }
}