All files / src/utils workflowConditions.ts

99.63% Statements 274/275
98.38% Branches 305/310
100% Functions 60/60
100% Lines 212/212

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 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652                            15x 15x 15x 15x         15x                     15x     15x               15x                                                               399x       30x   130x     86x   27x     60x   2x     37x   27x                   22x             230x         97x 4x         94x 73x                     17x 14x 13x 11x   1x   5x     4x   1x         16x 6x 6x 4x 4x 4x                     120x 55x 4x   51x 51x 7x 2x   8x   44x     4x   10x   16x   3x   11x                                     148x 12x 10x   136x 108x 11x 1x   10x   9x 8x 8x 7x   125x             375x 132x 123x 123x 122x 120x                 20x 18x     84x 84x 1x   83x 82x 82x 159x 9x 9x 2x   7x 59x 59x   4x     73x   66x 66x 66x 65x 65x     18x               18x 18x 19x 19x 6x 1x     5x       15x 5x     5x 5x   16x               14x 14x 30x                         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                 13x 13x     42x 13x 21x 17x     13x 17x 17x 17x 25x 25x 21x 21x 21x   13x     13x 13x 21x   13x                             49x 44x 37x 34x 34x 22x                 65x 65x 43x       139x 64x   86x 9x   79x 76x 11x 23x 10x     65x   48x 5x     6x 5x 5x 5x   150x 60x 139x       73x 73x 73x               72x 63x       15x                                                                                                           7x     7x                           34x 8x 4x 13x 8x   4x 8x                       15x 15x 15x     78x                     32x               10x 10x 8x 8x 10x                             28x       201x 7x                                     20x 18x 11x 8x 8x   20x 7x 6x 5x               15x 27x 2x 2x   14x                       23x 4x 4x 4x    
// Client-side mirror of flows-api/infrastructure/lambda/utils/expressions/condition.js
// and of the automatic-transition checks of utils/validateWorkflowFields.js — keep
// them in sync (UC-WORKFLOW-007.1). A UX convenience for live feedback in the
// condition builder, not a security boundary: the API re-validates everything,
// formulas included (their syntax is only checked by the API).
// @implements UC-WORKFLOW-007.1
import type {
  WorkflowCondition,
  WorkflowConditionOperator,
  WorkflowDefinition,
  WorkflowTransition
} from '@/schemas/entity-schema'
import { formulaForDisplay } from './conditionModel'
 
export const MAX_CONDITION_DEPTH = 5
export const MAX_CONDITION_LEAVES = 50
export const MAX_FORMULA_LENGTH = 1000
const MAX_VALUE_LIST_LENGTH = 100
 
export type LeafKind =
  'text' | 'number' | 'date' | 'boolean' | 'choice' | 'multiselect' | 'reference'
 
export const OPERATORS_BY_KIND: Record<LeafKind, WorkflowConditionOperator[]> = {
  text: ['eq', 'neq', 'contains', 'startsWith', 'isEmpty', 'isNotEmpty'],
  number: ['eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'isEmpty', 'isNotEmpty'],
  date: ['eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'isEmpty', 'isNotEmpty'],
  boolean: ['eq'],
  choice: ['eq', 'neq', 'in', 'notIn', 'isEmpty', 'isNotEmpty'],
  multiselect: ['contains', 'containsAll', 'containsAny', 'isEmpty', 'isNotEmpty'],
  reference: ['eq', 'contains', 'isEmpty', 'isNotEmpty', 'countLt', 'countGt', 'countEq']
}
 
/** Operators taking no value */
export const UNARY_OPERATORS: WorkflowConditionOperator[] = ['isEmpty', 'isNotEmpty']
 
/** Operators taking a list of options/states */
export const LIST_OPERATORS: WorkflowConditionOperator[] = [
  'in',
  'notIn',
  'containsAll',
  'containsAny'
]
 
/** Operators taking a whole number */
export const COUNT_OPERATORS: WorkflowConditionOperator[] = ['countLt', 'countGt', 'countEq']
 
/** The subset of an entity field a condition needs */
export interface ConditionField {
  fieldId?: string
  name: string | Record<string, string>
  type?: string
  options?: Array<string | { value: string; label?: string | Record<string, string> }>
  workflowDefinition?: WorkflowDefinition
  reference?: { entityId?: string; multiple?: boolean; maxValues?: number }
}
 
/** The entities targeted by item link fields, by id — for rows on linked items */
export type LinkedEntities = Record<
  string,
  { name: string | Record<string, string>; fields: ConditionField[] }
>
 
export interface ConditionChoice {
  value: string
  label: string | Record<string, string>
}
 
export interface ConditionError {
  /** i18n key under `workflow.conditionErrors` */
  code: string
  /** path of the faulty node, as the API reports it (e.g. "all[1].any[0]") */
  path: string
}
 
/** How a field type behaves in a condition row, or null when it can't be used */
export function leafKind(type: string | undefined): LeafKind | null {
  switch (type) {
    case 'text':
    case 'textarea':
    case 'email':
      return 'text'
    case 'number':
      return 'number'
    case 'date':
    case 'datetime':
      return 'date'
    case 'boolean':
      return 'boolean'
    case 'select':
    case 'workflow':
      return 'choice'
    case 'multiselect':
      return 'multiselect'
    case 'user':
    case 'entity_ref':
      return 'reference'
    default:
      return null
  }
}
 
/**
 * Whether an item link field can be used to look at the linked item: a single
 * link (one item at most) to an entity. Multiple links can't be used in a
 * condition (UC-WORKFLOW-008.1).
 */
export function isLinkableReference(field: ConditionField | undefined): boolean {
  return (
    field?.type === 'entity_ref' && !!field.reference?.entityId && field.reference.multiple !== true
  )
}
 
/** The fields a condition row can use (those with an id and a supported type) */
export function conditionFields<T extends ConditionField>(fields: T[]): T[] {
  return fields.filter((field) => !!field.fieldId && leafKind(field.type) !== null)
}
 
/** The options of a select/multiselect field, or the states of a workflow field */
export function fieldChoices(field: ConditionField): ConditionChoice[] {
  if (field.type === 'workflow') {
    return (field.workflowDefinition?.states ?? []).map((state) => ({
      value: state.id,
      label: state.label
    }))
  }
  return (field.options ?? []).map((option) =>
    typeof option === 'string'
      ? { value: option, label: option }
      : { value: option.value, label: option.label ?? option.value }
  )
}
 
/** A sensible starting value when a row's field or operator changes */
export function defaultValueFor(
  field: ConditionField | undefined,
  op: WorkflowConditionOperator
): unknown {
  if (!field || UNARY_OPERATORS.includes(op)) return undefined
  if (COUNT_OPERATORS.includes(op)) return 0
  if (LIST_OPERATORS.includes(op)) return []
  switch (leafKind(field.type)) {
    case 'boolean':
      return true
    case 'number':
      return 0
    case 'choice':
    case 'multiselect':
      return fieldChoices(field)[0]?.value ?? ''
    default:
      return ''
  }
}
 
function isValidDateString(value: unknown): boolean {
  if (typeof value !== 'string') return false
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
  if (!match) return false
  const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]
  const date = new Date(Date.UTC(year, month - 1, day))
  return (
    date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
  )
}
 
function checkValue(
  field: ConditionField,
  kind: LeafKind,
  op: WorkflowConditionOperator,
  value: unknown
): string | null {
  if (UNARY_OPERATORS.includes(op)) return value === undefined ? null : 'invalidValue'
  if (COUNT_OPERATORS.includes(op)) {
    return Number.isInteger(value) && (value as number) >= 0 ? null : 'expectedWholeNumber'
  }
  const choices = fieldChoices(field).map((choice) => choice.value)
  if (LIST_OPERATORS.includes(op)) {
    if (!Array.isArray(value) || value.length === 0 || value.length > MAX_VALUE_LIST_LENGTH) {
      return 'expectedList'
    }
    return value.every((entry) => choices.includes(entry)) ? null : 'unknownChoice'
  }
  switch (kind) {
    case 'text':
    case 'reference':
      return typeof value === 'string' && value !== '' ? null : 'expectedText'
    case 'number':
      return typeof value === 'number' && Number.isFinite(value) ? null : 'expectedNumber'
    case 'date':
      return isValidDateString(value) || isRelativeDate(value) ? null : 'expectedDate'
    case 'boolean':
      return typeof value === 'boolean' ? null : 'invalidValue'
    default:
      return typeof value === 'string' && choices.includes(value) ? null : 'unknownChoice'
  }
}
 
/**
 * Checks one row (field row or formula row) — undefined when valid, else the
 * i18n key (under `workflow.conditionErrors`) of the problem.
 */
export function validateRow(
  row: {
    field?: string
    op?: WorkflowConditionOperator
    value?: unknown
    formula?: string
    via?: string
  },
  fields: ConditionField[],
  linkedEntities?: LinkedEntities
): string | undefined {
  if ('formula' in row) {
    if (typeof row.formula !== 'string' || row.formula.trim() === '') return 'EMPTY_FORMULA'
    return row.formula.length > MAX_FORMULA_LENGTH ? 'FORMULA_TOO_LONG' : undefined
  }
  if (row.via !== undefined) {
    const viaField = fields.find((f) => f.fieldId === row.via)
    if (viaField?.type !== 'entity_ref' || !viaField.reference?.entityId) {
      return 'INVALID_LINKED_REFERENCE'
    }
    if (!isLinkableReference(viaField)) return 'LINKED_REFERENCE_MULTIPLE'
    // Without the linked entities (e.g. before they are loaded), only the shape is checked
    if (!linkedEntities) return undefined
    const target = linkedEntities[viaField.reference.entityId]
    if (!target) return 'UNKNOWN_LINKED_ENTITY'
    return validateRowOn(row, target.fields)
  }
  return validateRowOn(row, fields)
}
 
function validateRowOn(
  row: { field?: string; op?: WorkflowConditionOperator; value?: unknown },
  fields: ConditionField[]
): string | undefined {
  const field = fields.find((f) => f.fieldId === row.field)
  if (!field) return 'UNKNOWN_CONDITION_FIELD'
  const kind = leafKind(field.type)
  if (!kind) return 'UNSUPPORTED_CONDITION_FIELD'
  if (!row.op || !OPERATORS_BY_KIND[kind].includes(row.op)) return 'INVALID_CONDITION_OPERATOR'
  return checkValue(field, kind, row.op, row.value) ?? undefined
}
 
/** Validates a whole condition tree; null when valid */
export function validateCondition(
  condition: WorkflowCondition | undefined,
  fields: ConditionField[],
  linkedEntities?: LinkedEntities
): ConditionError | null {
  if (condition === undefined) return null
  const state = { leaves: 0 }
 
  function visit(node: unknown, path: string, depth: number): ConditionError | null {
    const here = path || 'when'
    if (!node || typeof node !== 'object' || Array.isArray(node)) {
      return { code: 'INVALID_CONDITION_NODE', path: here }
    }
    if (depth > MAX_CONDITION_DEPTH) return { code: 'CONDITION_TOO_DEEP', path: here }
    const record = node as Record<string, unknown>
    for (const kind of ['all', 'any'] as const) {
      if (kind in record) {
        const children = record[kind]
        if (!Array.isArray(children) || children.length === 0) {
          return { code: 'INVALID_CONDITION_NODE', path: here }
        }
        for (let i = 0; i < children.length; i++) {
          const error = visit(children[i], `${path ? `${path}.` : ''}${kind}[${i}]`, depth + 1)
          if (error) return error
        }
        return null
      }
    }
    if ('not' in record) return visit(record.not, `${path ? `${path}.` : ''}not`, depth + 1)
 
    state.leaves++
    if (state.leaves > MAX_CONDITION_LEAVES)
      return { code: 'CONDITION_TOO_MANY_LEAVES', path: here }
    const code = validateRow(record, fields, linkedEntities)
    return code ? { code, path: here } : null
  }
 
  return visit(condition, '', 1)
}
 
/** Validates every automatic transition of a workflow; null when all are valid */
export function validateAutoTransitions(
  definition: WorkflowDefinition | undefined,
  fields: ConditionField[]
): (ConditionError & { transitionIndex: number }) | null {
  const transitions = definition?.transitions ?? []
  for (let i = 0; i < transitions.length; i++) {
    const transition = transitions[i]!
    if (!transition.auto) continue
    if (transition.requiresPermission) {
      return { code: 'AUTO_TRANSITION_WITH_PERMISSION', path: 'when', transitionIndex: i }
    }
    // System dates are valid row fields too (names don't matter to validation)
    const withSystemDates = [
      ...fields,
      ...systemDateFields(
        fields,
        (key) => key,
        () => ''
      )
    ]
    const error = validateCondition(transition.auto.when, withSystemDates)
    if (error) return { ...error, transitionIndex: i }
  }
  return null
}
 
/**
 * Indices of the automatic transitions leaving the same state as
 * `transitions[index]`, in evaluation order (the order of `transitions`).
 */
export function automaticSiblings(transitions: WorkflowTransition[], index: number): number[] {
  const from = transitions[index]?.from
  return transitions.flatMap((transition, i) =>
    transition.auto && transition.from === from ? [i] : []
  )
}
 
/**
 * Swaps two transitions — and their canvas positions, keyed by index
 * (`t{index}`) — so the evaluation order changes but the layout doesn't.
 */
export function swapTransitions(
  definition: WorkflowDefinition,
  a: number,
  b: number
): WorkflowDefinition {
  const transitions = [...definition.transitions]
  ;[transitions[a], transitions[b]] = [transitions[b]!, transitions[a]!]
  const positions = { ...(definition.positions ?? {}) }
  const positionA = positions[`t${a}`]
  const positionB = positions[`t${b}`]
  delete positions[`t${a}`]
  delete positions[`t${b}`]
  if (positionB) positions[`t${a}`] = positionB
  if (positionA) positions[`t${b}`] = positionA
  return { ...definition, transitions, positions }
}
 
/**
 * Indices of the automatic transitions that belong to a cycle of automatic
 * transitions without condition: such a cycle runs on every save (the API
 * stops it after one turn), which is rarely intended.
 */
export function automaticCycleTransitions(definition: WorkflowDefinition | undefined): Set<number> {
  const transitions = definition?.transitions ?? []
  const edges = new Map<string, string[]>()
  // Only transitions without a condition always fire: a loop with a condition
  // (e.g. a periodic reminder on "updated more than 3 days ago") is intended
  const instant = (t: WorkflowTransition) => !!t.auto && !t.auto.when
  transitions.forEach((t) => {
    if (!instant(t)) return
    edges.set(t.from, [...(edges.get(t.from) ?? []), t.to])
  })
 
  const reaches = (start: string, target: string): boolean => {
    const seen = new Set<string>()
    const stack = [start]
    while (stack.length) {
      const state = stack.pop()!
      if (state === target) return true
      Iif (seen.has(state)) continue
      seen.add(state)
      stack.push(...(edges.get(state) ?? []))
    }
    return false
  }
 
  const result = new Set<number>()
  transitions.forEach((t, i) => {
    if (instant(t) && reaches(t.to, t.from)) result.add(i)
  })
  return result
}
 
// ---------------------------------------------------------------------------
// Plain-language description
// ---------------------------------------------------------------------------
 
export interface DescribeContext {
  t: (key: string) => string
  translate: (value: string | Record<string, string> | undefined) => string
  fields: ConditionField[]
  linkedEntities?: LinkedEntities
}
 
function describeValue(field: ConditionField, value: unknown, ctx: DescribeContext): string {
  if (Array.isArray(value)) return value.map((v) => describeValue(field, v, ctx)).join(', ')
  if (isRelativeDate(value)) return describeRelativeDate(value.now, ctx.t)
  if (typeof value === 'boolean') return ctx.t(value ? 'common.yes' : 'common.no')
  const choice = fieldChoices(field).find((c) => c.value === value)
  if (choice) return ctx.translate(choice.label) || choice.value
  return String(value ?? '')
}
 
function describeRow(
  node: { field: string; op: WorkflowConditionOperator; value?: unknown },
  name: string,
  field: ConditionField | undefined,
  ctx: DescribeContext
): string {
  const op = ctx.t(`workflow.operators.${node.op}`)
  if (UNARY_OPERATORS.includes(node.op) || !field) return `${name} ${op}`
  return `${name} ${op} ${describeValue(field, node.value, ctx)}`
}
 
function describeNode(node: WorkflowCondition, ctx: DescribeContext): string {
  if ('all' in node) {
    return node.all.map((child) => describeNested(child, ctx)).join(` ${ctx.t('workflow.and')} `)
  }
  if ('any' in node) {
    return node.any.map((child) => describeNested(child, ctx)).join(` ${ctx.t('workflow.or')} `)
  }
  if ('not' in node) return `${ctx.t('workflow.not')} (${describeNode(node.not, ctx)})`
  if ('formula' in node) {
    return formulaForDisplay(node.formula, (fieldId) => {
      const field = ctx.fields.find((f) => f.fieldId === fieldId)
      return field ? ctx.translate(field.name) || undefined : undefined
    })
  }
  if ('via' in node) {
    // "Employee › Contract is Permanent"
    const viaField = ctx.fields.find((f) => f.fieldId === node.via)
    const target = viaField?.reference?.entityId
      ? ctx.linkedEntities?.[viaField.reference.entityId]
      : undefined
    const field = target?.fields.find((f) => f.fieldId === node.field)
    const viaName = viaField ? ctx.translate(viaField.name) || node.via : node.via
    const name = `${viaName} › ${field ? ctx.translate(field.name) || node.field : node.field}`
    return describeRow(node, name, field, ctx)
  }
  const field = ctx.fields.find((f) => f.fieldId === node.field)
  const name = field ? ctx.translate(field.name) || node.field : node.field
  return describeRow(node, name, field, ctx)
}
 
function describeNested(node: WorkflowCondition, ctx: DescribeContext): string {
  const text = describeNode(node, ctx)
  const isGroup = ('all' in node && node.all.length > 1) || ('any' in node && node.any.length > 1)
  return isGroup ? `(${text})` : text
}
 
/** "Type is RTT and Days ≤ 2" — the condition in the user's language */
export function describeCondition(
  condition: WorkflowCondition | undefined,
  ctx: DescribeContext
): string {
  if (!condition) return ctx.t('workflow.alwaysTrue')
  return describeNode(condition, ctx)
}
 
/** Every code with a message under `workflow.conditionErrors` */
export const CONDITION_ERROR_CODES = [
  // client-side row checks
  'invalidValue',
  'expectedWholeNumber',
  'expectedList',
  'unknownChoice',
  'expectedText',
  'expectedNumber',
  'expectedDate',
  'INVALID_JSON',
  // API condition checks (utils/expressions/condition.js)
  'INVALID_CONDITION_NODE',
  'CONDITION_TOO_DEEP',
  'CONDITION_TOO_MANY_LEAVES',
  'FORMULA_NOT_BOOLEAN',
  'INVALID_LINKED_REFERENCE',
  'LINKED_REFERENCE_MULTIPLE',
  'UNKNOWN_LINKED_ENTITY',
  'UNKNOWN_CONDITION_FIELD',
  'UNSUPPORTED_CONDITION_FIELD',
  'INVALID_CONDITION_OPERATOR',
  'INVALID_CONDITION_VALUE',
  'AUTO_TRANSITION_WITH_PERMISSION',
  // API timer checks (utils/expressions/timers.js)
  'INVALID_TIMER',
  'TIMER_TOO_SHORT',
  'INVALID_TIMER_DATE_FIELD',
  // API formula checks (utils/expressions/formula.js)
  'EMPTY_FORMULA',
  'FORMULA_TOO_LONG',
  'FORMULA_TOO_COMPLEX',
  'UNTERMINATED_STRING',
  'UNTERMINATED_FIELD',
  'EMPTY_FIELD_REFERENCE',
  'UNEXPECTED_CHARACTER',
  'UNEXPECTED_TOKEN',
  'UNEXPECTED_END',
  'UNKNOWN_FIELD',
  'UNSUPPORTED_FIELD_TYPE',
  'UNKNOWN_FUNCTION',
  'WRONG_ARGUMENT_COUNT',
  'TYPE_MISMATCH'
]
 
/**
 * The message of a condition error, in the user's language — with the
 * character it points at for a formula error the API reports.
 */
export function conditionErrorText(
  code: string | undefined,
  position: number | undefined,
  t: (key: string) => string
): string {
  const message =
    code && CONDITION_ERROR_CODES.includes(code)
      ? t(`workflow.conditionErrors.${code}`)
      : t('workflow.conditionErrors.generic')
  return position === undefined
    ? message
    : `${message} (${t('workflow.atCharacter').replace('{position}', String(position + 1))})`
}
 
/**
 * "Status: Draft → Review" — names the transition an API error points at
 * (`fieldId`, `from`, `to`), or '' when it can't be found anymore.
 */
export function describeTransitionRef(
  fields: ConditionField[],
  ref: { fieldId?: string; from?: string; to?: string },
  translate: (value: string | Record<string, string> | undefined) => string
): string {
  const field = fields.find((f) => f.fieldId === ref.fieldId)
  if (!field || !ref.from || !ref.to) return ''
  const stateName = (stateId: string) => {
    const state = field.workflowDefinition?.states?.find((s) => s.id === stateId)
    return (state && translate(state.label)) || stateId
  }
  const fieldName = translate(field.name) || ref.fieldId
  return `${fieldName}: ${stateName(ref.from)} → ${stateName(ref.to)}`
}
 
// ---------------------------------------------------------------------------
// Dates and timers (UC-WORKFLOW-009.1)
// ---------------------------------------------------------------------------
 
/** A date relative to when the condition is evaluated: { now: "-3d" } */
export interface RelativeDate {
  now: string
}
 
const RELATIVE_DATE_PATTERN = /^[+-]?\d+[hd]$/
const AFTER_PATTERN = /^\d+[hd]$/
const OFFSET_PATTERN = /^[+-]\d+[hd]$/
 
export function isRelativeDate(value: unknown): value is RelativeDate {
  return (
    !!value &&
    typeof value === 'object' &&
    Object.keys(value).length === 1 &&
    typeof (value as RelativeDate).now === 'string' &&
    RELATIVE_DATE_PATTERN.test((value as RelativeDate).now)
  )
}
 
/** A duration ("3d", "-12h", "+1d") as a signed amount and its unit */
export function parseDuration(duration: string): { amount: number; unit: 'h' | 'd' } {
  return {
    amount: parseInt(duration.slice(0, -1), 10),
    unit: duration.endsWith('h') ? 'h' : 'd'
  }
}
 
/** "today", "3 days ago", "in 2 hours" */
export function describeRelativeDate(now: string, t: (key: string) => string): string {
  const { amount, unit } = parseDuration(now)
  if (amount === 0) return t('workflow.relative.today')
  const count = String(Math.abs(amount))
  const unitText = t(unit === 'h' ? 'workflow.relative.hours' : 'workflow.relative.days')
  return t(amount < 0 ? 'workflow.relative.ago' : 'workflow.relative.in')
    .replace('{n}', count)
    .replace('{unit}', unitText)
}
 
/**
 * The item's system dates a condition can use like fields: created, updated,
 * and when each workflow field entered its current state. Mirrors
 * flows-api's expressions/condition.js systemDateFields.
 */
export function systemDateFields(
  fields: ConditionField[],
  t: (key: string) => string,
  translate: (value: string | Record<string, string> | undefined) => string
): ConditionField[] {
  return [
    { fieldId: 'createdAt', name: t('workflow.systemDates.createdAt'), type: 'datetime' },
    { fieldId: 'updatedAt', name: t('workflow.systemDates.updatedAt'), type: 'datetime' },
    ...fields
      .filter((field) => field.type === 'workflow' && field.fieldId)
      .map((field) => ({
        fieldId: `workflowStateEnteredAt.${field.fieldId}`,
        name: t('workflow.systemDates.enteredAt').replace(
          '{field}',
          translate(field.name) || field.fieldId!
        ),
        type: 'datetime'
      }))
  ]
}
 
/**
 * Checks a transition's timer — undefined when valid, else its error code.
 * Mirrors flows-api's expressions/timers.js validateTimer.
 */
export function validateTimer(
  timer: { after?: string; at?: string; offset?: string },
  fields: ConditionField[]
): string | undefined {
  if ((timer.after === undefined) === (timer.at === undefined)) return 'INVALID_TIMER'
  if (timer.after !== undefined) {
    if (timer.offset !== undefined || !AFTER_PATTERN.test(timer.after)) return 'INVALID_TIMER'
    const { amount, unit } = parseDuration(timer.after)
    return amount * (unit === 'd' ? 24 : 1) < 1 ? 'TIMER_TOO_SHORT' : undefined
  }
  const atField = fields.find((field) => field.fieldId === timer.at)
  if (timer.at !== 'createdAt' && atField?.type !== 'date') return 'INVALID_TIMER_DATE_FIELD'
  if (timer.offset !== undefined && !OFFSET_PATTERN.test(timer.offset)) return 'INVALID_TIMER'
  return undefined
}
 
/** Validates the timers of a workflow's states; null when all are valid */
export function validateStateTimers(
  definition: WorkflowDefinition | undefined,
  fields: ConditionField[]
): { code: string; stateId: string } | null {
  for (const state of definition?.states ?? []) {
    if (!state.timer) continue
    const code = validateTimer(state.timer, fields)
    if (code) return { code, stateId: state.id }
  }
  return null
}
 
/**
 * "Status: Submitted" — names the state an API error points at (`fieldId`,
 * `stateId`), or '' when it can't be found anymore.
 */
export function describeStateRef(
  fields: ConditionField[],
  ref: { fieldId?: string; stateId?: string },
  translate: (value: string | Record<string, string> | undefined) => string
): string {
  const field = fields.find((f) => f.fieldId === ref.fieldId)
  if (!field || !ref.stateId) return ''
  const state = field.workflowDefinition?.states?.find((s) => s.id === ref.stateId)
  return `${translate(field.name) || ref.fieldId}: ${(state && translate(state.label)) || ref.stateId}`
}