All files / src/utils entityValidation.ts

98.03% Statements 50/51
96.05% Branches 73/76
100% Functions 6/6
97.82% Lines 45/46

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                      5x                                                 5x                                         18x     5x       134x   134x 2x 2x     132x 30x   30x       46x           30x     132x 8x 24x 8x     8x 1x   8x 1x         132x 33x 33x 3x   33x 33x         1x       132x 2x 2x 1x                   134x 134x 18x   18x 134x       45x 45x 52x 51x 51x 42x         1x     45x    
// Client-side mirror of flows-api/infrastructure/lambda/utils/schemas/field-definition-schema.js
// — keep the two in sync. Validates the shape of entity field *definitions*
// (as edited in SchemaBuilder.vue) before submit: known type, well-formed
// select options, sound number min/max/step, positive length/maxLines. This
// is a UX convenience, not a security boundary — the backend re-validates.
import { z } from 'zod'
import type { EntityField } from '@/stores/entities'
import { validateAutoTransitions, validateStateTimers } from './workflowConditions'
 
export type FieldErrorMap = Record<string, string>
 
export const ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY: Record<string, string> = {
  INVALID_FIELD_TYPE: 'entity.invalidFieldType',
  INVALID_SELECT_OPTIONS: 'entity.invalidSelectOptions',
  INVALID_NUMBER_CONSTRAINTS: 'entity.invalidNumberConstraints',
  INVALID_FILE_SET_CONSTRAINTS: 'entity.invalidFileSetConstraints',
  // Backend-only check (existing items scanned on update) — never produced by
  // the client-side schema above, but shares the same fieldId -> i18n key
  // consumption path in EntitiesPage.vue's update handler.
  UNIQUE_CONSTRAINT_VIOLATED_BY_EXISTING_ITEMS: 'entity.uniqueConstraintViolatedByExistingItems',
  // Backend-only too: two fields of an entity named alike in one language
  // (flows-api utils/fieldNameUniqueness.js)
  FIELD_NAME_TAKEN: 'entity.fieldNameTaken',
  // Automatic workflow transitions (UC-WORKFLOW-007.1) — also checked client-side
  // by validateEntityFields below, except formula syntax (API only)
  INVALID_WORKFLOW_CONDITION: 'workflow.invalidAutomaticTransition',
  INVALID_AUTO_TRANSITION: 'workflow.invalidAutomaticTransition',
  AUTO_TRANSITION_WITH_PERMISSION: 'workflow.invalidAutomaticTransition',
  INVALID_WORKFLOW_TIMER: 'workflow.invalidAutomaticTransition',
  // Email actions of transitions (UC-WORKFLOW-011.1)
  INVALID_TRANSITION_ACTION: 'workflow.emailActions.invalid'
}
 
// Canonical field type enum — mirrors EntityField.type in api-definition.yaml.
// This is the wire-format source of truth, not flows-ui's own EntityField type
// union (which only lists the types SchemaBuilder's palette can create).
const FIELD_TYPES = [
  'text',
  'textarea',
  'number',
  'email',
  'date',
  'boolean',
  'select',
  'multiselect',
  'image',
  'image_set',
  'file',
  'file_set',
  'geo_location',
  'workflow',
  'relation',
  'user',
  'entity_ref'
]
 
function addCustomIssue(ctx: z.RefinementCtx, path: (string | number)[], code: string) {
  ctx.addIssue({ code: z.ZodIssueCode.custom, path, params: { code } })
}
 
export const fieldDefinitionSchema = z
  .object({ type: z.string().optional() })
  .passthrough()
  .superRefine((field, ctx) => {
    const type = field.type as string | undefined
 
    if (type !== undefined && !FIELD_TYPES.includes(type)) {
      addCustomIssue(ctx, ['type'], 'INVALID_FIELD_TYPE')
      return
    }
 
    if (type === 'select' || type === 'multiselect') {
      const options = (field as { options?: unknown }).options
      const validShape =
        Array.isArray(options) &&
        options.length > 0 &&
        options.every(
          (opt) =>
            (typeof opt === 'string' && opt.trim().length > 0) ||
            (opt &&
              typeof opt === 'object' &&
              typeof (opt as { value?: unknown }).value === 'string' &&
              (opt as { value: string }).value.trim().length > 0)
        )
      if (!validShape) addCustomIssue(ctx, ['options'], 'INVALID_SELECT_OPTIONS')
    }
 
    if (type === 'number') {
      const { min, max, step } = field as { min?: unknown; max?: unknown; step?: unknown }
      const numericOrUndefined = (v: unknown) => v === undefined || typeof v === 'number'
      Iif (!numericOrUndefined(min) || !numericOrUndefined(max) || !numericOrUndefined(step)) {
        addCustomIssue(ctx, ['min'], 'INVALID_NUMBER_CONSTRAINTS')
      } else {
        if (typeof min === 'number' && typeof max === 'number' && min > max) {
          addCustomIssue(ctx, ['min'], 'INVALID_NUMBER_CONSTRAINTS')
        }
        if (typeof step === 'number' && step <= 0) {
          addCustomIssue(ctx, ['step'], 'INVALID_NUMBER_CONSTRAINTS')
        }
      }
    }
 
    if (type === 'text' || type === 'textarea' || type === 'email') {
      const length = (field as { length?: unknown }).length
      if (length !== undefined && (typeof length !== 'number' || length <= 0)) {
        addCustomIssue(ctx, ['length'], 'INVALID_NUMBER_CONSTRAINTS')
      }
      const maxLines = (field as { maxLines?: unknown }).maxLines
      if (
        type === 'textarea' &&
        maxLines !== undefined &&
        (typeof maxLines !== 'number' || maxLines <= 0)
      ) {
        addCustomIssue(ctx, ['maxLines'], 'INVALID_NUMBER_CONSTRAINTS')
      }
    }
 
    if (type === 'file_set') {
      const maxFiles = (field as { maxFiles?: unknown }).maxFiles
      if (maxFiles !== undefined && (typeof maxFiles !== 'number' || maxFiles <= 0)) {
        addCustomIssue(ctx, ['maxFiles'], 'INVALID_FILE_SET_CONSTRAINTS')
      }
    }
  })
 
// Validates a single field definition and returns the i18n key for its first
// violation, or undefined when valid. Exposed separately from
// validateEntityFields so components (e.g. SchemaBuilder.vue) can run it
// reactively per-field for live feedback while editing, not just at submit.
export function validateFieldDefinition(field: EntityField): string | undefined {
  const result = fieldDefinitionSchema.safeParse(field)
  if (result.success) return undefined
  const issue = result.error.issues[0]
  const code =
    issue.code === 'custom' ? (issue.params as { code?: string } | undefined)?.code : undefined
  return (code && ENTITY_FIELD_ERROR_CODE_TO_I18N_KEY[code]) || 'entity.invalidFieldType'
}
 
export function validateEntityFields(fields: EntityField[]): FieldErrorMap {
  const errors: FieldErrorMap = {}
  for (const field of fields) {
    if (!field.fieldId) continue
    const error = validateFieldDefinition(field)
    if (error) errors[field.fieldId] = error
    else if (
      field.type === 'workflow' &&
      (validateAutoTransitions(field.workflowDefinition, fields) ||
        validateStateTimers(field.workflowDefinition, fields))
    ) {
      errors[field.fieldId] = 'workflow.invalidAutomaticTransition'
    }
  }
  return errors
}