All files / utils emailTemplates.js

100% Statements 97/97
98.9% Branches 90/91
100% Functions 16/16
100% Lines 77/77

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                      7x   7x 7x 7x 7x 7x 7x 7x     7x                                       26x       96x         32x 31x 31x 30x   28x                     173x 24x 23x 1x     60x 22x 22x 22x 22x 22x 2x   81x 1x   19x 18x 18x 1x     17x   17x   13x 25x 18x 18x 13x 1x         7x                     30x 19x 2x     17x 17x 62x   17x 17x 19x 19x 19x 1x   75x 2x   16x 16x 15x   11x 11x   11x   2x   9x 9x 2x   7x 1x   6x 1x     5x 2x 2x 1x 1x       2x     7x              
// @implements UC-WORKFLOW-010.1, UC-WORKFLOW-011.1
/**
 * Email templates of an entity, and the Email actions of its workflow
 * transitions (see docs/architecture/AUTOMATION.md "Email actions").
 *
 * A template is plain text — subject and body per language — with the item's
 * values inserted as `{fieldId}`; never HTML, never code. An Email action on a
 * transition picks a template and its recipients among the item's `user`
 * fields and its creator.
 */
 
const { validateCondition } = require('./expressions/condition')
 
const MAX_EMAIL_TEMPLATES = 20
const MAX_SUBJECT_LENGTH = 200
const MAX_BODY_LENGTH = 5000
const MAX_ACTIONS_PER_TRANSITION = 10
const TEMPLATE_KEYS = ['id', 'name', 'subject', 'body']
const ACTION_KEYS = ['id', 'type', 'templateId', 'recipients', 'when']
const RECIPIENT_KEYS = ['fields', 'creator']
 
/** Field types whose value can be inserted in an email */
const INSERTABLE_TYPES = [
  'text',
  'textarea',
  'email',
  'number',
  'date',
  'boolean',
  'select',
  'multiselect',
  'workflow',
  'user'
]
 
/**
 * The fieldIds a template text inserts (`{fieldId}`), in order.
 *
 * @param {string} text
 * @returns {string[]}
 */
function insertedFieldIds(text) {
  return [...String(text).matchAll(/\{([^{}]*)\}/g)].map((match) => match[1].trim())
}
 
function isPlainObject(value) {
  return !!value && typeof value === 'object' && !Array.isArray(value)
}
 
// A multilingual text: { lang: string }, each within `maxLength`
function checkLocalized(value, maxLength) {
  if (!isPlainObject(value) || Object.keys(value).length === 0) return 'INVALID_EMAIL_TEMPLATE'
  for (const text of Object.values(value)) {
    if (typeof text !== 'string') return 'INVALID_EMAIL_TEMPLATE'
    if (text.length > maxLength) return 'EMAIL_TEMPLATE_TOO_LONG'
  }
  return null
}
 
/**
 * Validates an entity's email templates against its fields.
 *
 * @param {unknown} templates - `entity.emailTemplates`
 * @param {object[]} fields - The entity's field definitions
 * @returns {{ valid: true } | { valid: false, code: string, templateId?: string, fieldId?: string }}
 */
function validateEmailTemplates(templates, fields) {
  if (templates === undefined || templates === null) return { valid: true }
  if (!Array.isArray(templates)) return { valid: false, code: 'INVALID_EMAIL_TEMPLATE' }
  if (templates.length > MAX_EMAIL_TEMPLATES) {
    return { valid: false, code: 'TOO_MANY_EMAIL_TEMPLATES' }
  }
 
  const fieldsById = new Map((fields || []).map((field) => [field.fieldId, field]))
  const ids = new Set()
  for (const template of templates) {
    const templateId = template?.id
    const fail = (code, extra = {}) => ({ valid: false, code, templateId, ...extra })
    if (!isPlainObject(template) || typeof templateId !== 'string' || templateId === '') {
      return { valid: false, code: 'INVALID_EMAIL_TEMPLATE' }
    }
    if (Object.keys(template).some((key) => !TEMPLATE_KEYS.includes(key))) {
      return fail('INVALID_EMAIL_TEMPLATE')
    }
    if (ids.has(templateId)) return fail('INVALID_EMAIL_TEMPLATE')
    ids.add(templateId)
    if (typeof template.name !== 'string' && !isPlainObject(template.name)) {
      return fail('INVALID_EMAIL_TEMPLATE')
    }
    const problem =
      checkLocalized(template.subject, MAX_SUBJECT_LENGTH) ||
      checkLocalized(template.body, MAX_BODY_LENGTH)
    if (problem) return fail(problem)
 
    for (const text of [...Object.values(template.subject), ...Object.values(template.body)]) {
      for (const fieldId of insertedFieldIds(text)) {
        const field = fieldsById.get(fieldId)
        if (!field) return fail('UNKNOWN_TEMPLATE_FIELD', { fieldId })
        if (!INSERTABLE_TYPES.includes(field.type)) {
          return fail('UNSUPPORTED_TEMPLATE_FIELD', { fieldId })
        }
      }
    }
  }
  return { valid: true }
}
 
/**
 * Validates the `actions` of one workflow transition.
 *
 * @param {unknown} actions - `transition.actions`
 * @param {{ fields: object[], emailTemplates?: object[], linkedEntities?: Map<string, object> }} context
 * @returns {{ valid: true } | { valid: false, code: string, actionId?: string, conditionCode?: string, path?: string, position?: number }}
 */
function validateTransitionActions(actions, { fields, emailTemplates, linkedEntities }) {
  if (actions === undefined || actions === null) return { valid: true }
  if (!Array.isArray(actions) || actions.length > MAX_ACTIONS_PER_TRANSITION) {
    return { valid: false, code: 'INVALID_ACTION' }
  }
 
  const templateIds = new Set((emailTemplates || []).map((template) => template?.id))
  const userFieldIds = new Set(
    (fields || []).filter((field) => field.type === 'user').map((field) => field.fieldId)
  )
  const ids = new Set()
  for (const action of actions) {
    const actionId = action?.id
    const fail = (code, extra = {}) => ({ valid: false, code, actionId, ...extra })
    if (!isPlainObject(action) || typeof actionId !== 'string' || actionId === '') {
      return { valid: false, code: 'INVALID_ACTION' }
    }
    if (Object.keys(action).some((key) => !ACTION_KEYS.includes(key)) || ids.has(actionId)) {
      return fail('INVALID_ACTION')
    }
    ids.add(actionId)
    if (action.type !== 'email') return fail('UNSUPPORTED_ACTION_TYPE')
    if (!templateIds.has(action.templateId)) return fail('UNKNOWN_EMAIL_TEMPLATE')
 
    const recipients = action.recipients
    if (
      !isPlainObject(recipients) ||
      Object.keys(recipients).some((key) => !RECIPIENT_KEYS.includes(key))
    ) {
      return fail('INVALID_RECIPIENTS')
    }
    const recipientFields = recipients.fields ?? []
    if (!Array.isArray(recipientFields) || !recipientFields.every((id) => userFieldIds.has(id))) {
      return fail('INVALID_RECIPIENTS')
    }
    if (recipients.creator !== undefined && typeof recipients.creator !== 'boolean') {
      return fail('INVALID_RECIPIENTS')
    }
    if (recipientFields.length === 0 && recipients.creator !== true) {
      return fail('NO_RECIPIENTS')
    }
 
    if (action.when !== undefined) {
      const result = validateCondition(action.when, fields, { linkedEntities })
      if (!result.valid) {
        const { code: conditionCode, ...where } = result.error
        return fail('INVALID_ACTION_CONDITION', { conditionCode, ...where })
      }
    }
  }
  return { valid: true }
}
 
module.exports = {
  INSERTABLE_TYPES,
  MAX_EMAIL_TEMPLATES,
  insertedFieldIds,
  validateEmailTemplates,
  validateTransitionActions
}