All files / src/utils emailTemplates.ts

98.85% Statements 86/87
97.97% Branches 97/99
100% Functions 33/33
100% Lines 69/69

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                            10x 10x 10x 10x     10x                             99x       2x       3x                   40x 40x 40x 4x   36x 51x 48x   1x   35x 98x 84x 58x 55x 4x       28x               23x 32x 23x                 111x 111x 47x 14x 14x     111x                           23x 1x   15x 16x 12x 1x   11x                       19x 14x 14x   13x 7x       14x       14x               15x 15x 14x                         19x 18x   19x   2x     5x   6x 8x   6x           2x 2x     4x 6x 5x       5x 5x                         4x 8x 19x 7x   4x              
// @implements UC-WORKFLOW-010.1, UC-WORKFLOW-011.1
// Client-side mirror of flows-api/infrastructure/lambda/utils/emailTemplates.js
// — keep the two in sync. A UX convenience, not a security boundary: the API
// validates again.
import type { EmailTemplate, WorkflowTransitionAction } from '@/schemas/entity-schema'
import type { EntityField } from '@/stores/entities'
import {
  describeCondition,
  validateCondition,
  type ConditionField,
  type DescribeContext,
  type LinkedEntities
} from './workflowConditions'
 
export const MAX_EMAIL_TEMPLATES = 20
export const MAX_SUBJECT_LENGTH = 200
export const MAX_BODY_LENGTH = 5000
export const MAX_ACTIONS_PER_TRANSITION = 10
 
/** Field types whose value can be inserted in an email */
export const INSERTABLE_TYPES = [
  'text',
  'textarea',
  'email',
  'number',
  'date',
  'boolean',
  'select',
  'multiselect',
  'workflow',
  'user'
]
 
/** The fieldIds a template text inserts (`{fieldId}`), in order */
export function insertedFieldIds(text: string): string[] {
  return [...String(text).matchAll(/\{([^{}]*)\}/g)].map((match) => match[1]!.trim())
}
 
export function newTemplateId(): string {
  return `tpl_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`
}
 
export function newActionId(): string {
  return `act_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`
}
 
/**
 * What is wrong with one template, as an API error code, or null.
 */
export function validateEmailTemplate(
  template: EmailTemplate,
  fields: Array<Pick<EntityField, 'fieldId' | 'type'>>
): { code: string; fieldId?: string } | null {
  const subjects = Object.values(template.subject || {})
  const bodies = Object.values(template.body || {})
  if (!subjects.some((text) => text.trim()) || !bodies.some((text) => text.trim())) {
    return { code: 'INVALID_EMAIL_TEMPLATE' }
  }
  if (
    subjects.some((text) => text.length > MAX_SUBJECT_LENGTH) ||
    bodies.some((text) => text.length > MAX_BODY_LENGTH)
  ) {
    return { code: 'EMAIL_TEMPLATE_TOO_LONG' }
  }
  for (const text of [...subjects, ...bodies]) {
    for (const fieldId of insertedFieldIds(text)) {
      const field = fields.find((f) => f.fieldId === fieldId)
      if (!field) return { code: 'UNKNOWN_TEMPLATE_FIELD', fieldId }
      if (!INSERTABLE_TYPES.includes(field.type ?? '')) {
        return { code: 'UNSUPPORTED_TEMPLATE_FIELD', fieldId }
      }
    }
  }
  return null
}
 
/**
 * Drops, from what is sent to the API, the languages a template leaves empty:
 * an empty subject or body is no translation at all.
 */
export function cleanEmailTemplates(templates: EmailTemplate[]): EmailTemplate[] {
  const filled = (texts: Record<string, string>) =>
    Object.fromEntries(Object.entries(texts || {}).filter(([, text]) => text.trim() !== ''))
  return templates.map((template) => ({
    ...template,
    subject: filled(template.subject),
    body: filled(template.body)
  }))
}
 
/** The ids of the templates the Email actions of the entity's workflows use */
export function usedTemplateIds(fields: EntityField[]): Set<string> {
  const ids = new Set<string>()
  for (const field of fields) {
    if (field.type !== 'workflow') continue
    for (const transition of field.workflowDefinition?.transitions ?? []) {
      for (const action of transition.actions ?? []) ids.add(action.templateId)
    }
  }
  return ids
}
 
/**
 * What is wrong with one Email action, as an API error code, or null.
 */
export function validateTransitionAction(
  action: WorkflowTransitionAction,
  {
    fields,
    templates,
    linkedEntities
  }: { fields: ConditionField[]; templates: EmailTemplate[]; linkedEntities?: LinkedEntities }
): string | null {
  if (!templates.some((template) => template.id === action.templateId)) {
    return 'UNKNOWN_EMAIL_TEMPLATE'
  }
  const recipientFields = action.recipients?.fields ?? []
  if (recipientFields.length === 0 && action.recipients?.creator !== true) return 'NO_RECIPIENTS'
  if (action.when !== undefined && validateCondition(action.when, fields, linkedEntities)) {
    return 'INVALID_ACTION_CONDITION'
  }
  return null
}
 
/**
 * An Email action in plain words: 'Email “Reminder” to Manager and the
 * creator, if Days > 2'.
 */
export function describeEmailAction(
  action: WorkflowTransitionAction,
  templates: EmailTemplate[],
  ctx: DescribeContext
): string {
  const template = templates.find((tpl) => tpl.id === action.templateId)
  const name = template ? ctx.translate(template.name) || template.id : '?'
  const recipients = [
    ...(action.recipients?.fields ?? []).map((fieldId) => {
      const field = ctx.fields.find((f) => f.fieldId === fieldId)
      return (field && ctx.translate(field.name)) || fieldId
    }),
    ...(action.recipients?.creator ? [ctx.t('workflow.emailActions.theCreator')] : [])
  ]
  const text = ctx
    .t('workflow.emailActions.summary')
    .replace('{template}', name)
    .replace('{recipients}', recipients.join(', ') || '?')
  return action.when
    ? `${text}${ctx.t('workflow.emailActions.summaryIf')}${describeCondition(action.when, ctx)}`
    : text
}
 
type Localized = string | Record<string, string> | undefined | null
 
function localized(value: Localized, lang: string): string {
  Iif (value === undefined || value === null) return ''
  if (typeof value !== 'object') return String(value)
  return value[lang] ?? Object.values(value)[0] ?? ''
}
 
/**
 * One field's value as the email shows it — mirrors formatValue in
 * flows-api/infrastructure/lambda/automation/emailRendering.js.
 */
export function formatEmailValue(
  field: EntityField,
  value: unknown,
  lang: string,
  { t, userName }: { t: (key: string) => string; userName: (userId: string) => string }
): string {
  if (value === undefined || value === null || value === '') return ''
  const values = Array.isArray(value) ? value : [value]
  // The wire format also has `multiselect`, which flows-ui's field type union lacks
  switch (field.type as string) {
    case 'boolean':
      return t(value === true ? 'common.yes' : 'common.no')
    case 'select':
    case 'multiselect':
      return values
        .map((v) => {
          const option = (field.options ?? []).find((o: any) =>
            o && typeof o === 'object' ? o.value === v : o === v
          ) as any
          return option && typeof option === 'object'
            ? localized(option.label ?? option.value, lang)
            : String(v)
        })
        .join(', ')
    case 'workflow': {
      const state = field.workflowDefinition?.states.find((s) => s.id === value)
      return state ? localized(state.label, lang) : String(value)
    }
    case 'user':
      return values
        .filter((v) => typeof v === 'string' && !v.startsWith('::deleted::'))
        .map((v) => userName(v as string))
        .filter(Boolean)
        .join(', ')
    default:
      return values
        .map((v) => (v && typeof v === 'object' ? localized(v as Localized, lang) : String(v)))
        .join(', ')
  }
}
 
/** A template filled with one item's values, in one language: the email's subject and text */
export function renderEmailPreview(
  template: EmailTemplate,
  lang: string,
  fields: EntityField[],
  item: Record<string, unknown>,
  context: { t: (key: string) => string; userName: (userId: string) => string }
): { subject: string; body: string } {
  const fill = (text: string) =>
    text.replace(/\{([^{}]*)\}/g, (match, rawId: string) => {
      const field = fields.find((f) => f.fieldId === rawId.trim())
      return field ? formatEmailValue(field, item[field.fieldId!], lang, context) : match
    })
  return {
    subject: fill(localized(template.subject, lang))
      .replace(/\s*[\r\n]+\s*/g, ' ')
      .trim(),
    body: fill(localized(template.body, lang))
  }
}