All files / items workflow-transitions.js

99.25% Statements 134/135
99.13% Branches 114/115
100% Functions 17/17
100% Lines 110/110

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                      10x 10x     10x                         10x     10x                           5x       134x                                   68x   68x 69x 31x   27x 27x   27x   22x 62x   22x 6x     16x   22x   13x 4x         9x 4x       58x                                                                                       122x 196x   122x 122x 122x 122x 122x 122x 122x   122x 122x       122x     122x 51x 51x 51x 51x   33x 33x   18x 18x 18x 18x 18x     122x 122x 122x 122x 155x 155x 86x 86x   83x 83x 412x 83x   147x         83x   34x 34x 34x 34x 34x 34x 34x 34x 34x 34x       122x 122x 1x           122x 122x 51x 20x       122x               122x 122x   122x 366x 122x 37x     122x 122x 28x 28x 27x 28x     122x 122x 122x   122x                           122x 122x 51x 97x 51x   18x 4x 4x 4x   14x 14x   122x     10x                
// @implements UC-WORKFLOW-005.1, UC-WORKFLOW-007.1, UC-WORKFLOW-008.1, UC-WORKFLOW-009.1, UC-WORKFLOW-011.1
/**
 * Workflow transitions on item writes.
 *
 * A workflow field's value may only move along a transition defined in its
 * workflowDefinition; a transition flagged `requiresPermission` may only be
 * fired by a caller holding its dedicated permission string (UC-WORKFLOW-005.1);
 * an automatic transition (`auto`) is fired by the system only, never by a
 * user (UC-WORKFLOW-007.1, see resolveAutomaticTransitions).
 */
 
const { evaluateCondition } = require('../utils/expressions/condition')
const { timerDueAt } = require('../utils/expressions/timers')
 
// System attributes maintained here, never accepted from a client
const WORKFLOW_SYSTEM_KEYS = [
  'workflowStateEnteredAt',
  'lastTransitionPath',
  'lastTransitionBy',
  // Who fired each step of `lastTransitionPath` (UC-WORKFLOW-011.1: an email
  // never goes to whoever fired its transition)
  'lastTransitionActors',
  // When each field's state timer is due, and the next wake-up (UC-WORKFLOW-009.1)
  'timerDueAt',
  'wakeUpAt'
]
 
// Automatic transitions fired by one write, all workflow fields included
const MAX_AUTOMATIC_TRANSITIONS = 10
 
// The actor recorded for a transition the system fired
const SYSTEM_ACTOR = 'system'
 
/**
 * The permission string guarding one transition of one workflow field.
 * Transitions have no id of their own: the editor forbids two transitions
 * between the same pair of states, so (fieldId, from, to) identifies one.
 *
 * @param {string} entityId
 * @param {string} fieldId
 * @param {string} fromStateId
 * @param {string} toStateId
 * @returns {string}
 */
function transitionPermission(entityId, fieldId, fromStateId, toStateId) {
  return `entities-${entityId}:items:transition:${fieldId}:${fromStateId}:${toStateId}`
}
 
function isEmpty(value) {
  return value === undefined || value === null || value === ''
}
 
/**
 * Checks every workflow field whose value changes in `data` against its
 * workflow definition.
 *
 * A field with no current state (item created before the field existed) or
 * whose current state no longer exists may be set to any state — mirroring the
 * item form, which then offers every state.
 *
 * @param {Array} fields - Entity field definitions
 * @param {object} previousItem - The stored item
 * @param {object} data - The (filtered) incoming changes
 * @param {string} entityId
 * @returns {{ valid: true, requiredPermissions: string[] } | { valid: false, error: string, fieldId: string }}
 */
function validateWorkflowTransitions(fields, previousItem, data, entityId) {
  const requiredPermissions = []
 
  for (const field of fields || []) {
    if (field.type !== 'workflow' || !field.workflowDefinition) continue
    if (!Object.prototype.hasOwnProperty.call(data, field.fieldId)) continue
 
    const from = previousItem?.[field.fieldId]
    const to = data[field.fieldId]
    // The edit form sends `null` for a workflow field the item never had
    if (from === to || (isEmpty(from) && isEmpty(to))) continue
 
    const { states = [], transitions = [] } = field.workflowDefinition
    const stateIds = new Set(states.map((s) => s.id))
 
    if (typeof to !== 'string' || !stateIds.has(to)) {
      return { valid: false, error: 'INVALID_WORKFLOW_STATE', fieldId: field.fieldId }
    }
 
    if (!from || !stateIds.has(from)) continue
 
    const transition = transitions.find((t) => t.from === from && t.to === to)
    // An automatic transition is fired by the system only
    if (!transition || transition.auto) {
      return { valid: false, error: 'INVALID_WORKFLOW_TRANSITION', fieldId: field.fieldId }
    }
 
    // Legacy definitions stored a free-text permission name: any truthy value
    // means the transition is protected.
    if (transition.requiresPermission) {
      requiredPermissions.push(transitionPermission(entityId, field.fieldId, from, to))
    }
  }
 
  return { valid: true, requiredPermissions }
}
 
/**
 * Applies the automatic transitions an item write triggers (UC-WORKFLOW-007.1),
 * be it a save or a timer's wake-up (UC-WORKFLOW-009.1).
 *
 * Starting from `after` (the item as it is about to be written), each
 * workflow field fires the first automatic transition leaving its current
 * state whose condition holds, then the same from the new state, and so on.
 * A field's chain stops right after entering a state it already went through
 * in this write (so `A → B → A` ends in `A`); the whole write stops after
 * MAX_AUTOMATIC_TRANSITIONS. Then the timers of the states reached are set
 * (see stateTimers). Pure: the caller writes the result once, and schedules
 * `wakeUpAt` when it changed.
 *
 * @param {object} params
 * @param {Array} params.fields - Entity field definitions
 * @param {object} params.before - The stored item ({} on create)
 * @param {object} params.after - The item with the caller's changes applied
 * @param {string} params.actor - Who made the write (userId)
 * @param {string} params.now - ISO timestamp of the write
 * @param {{ entities: Map, items: Map }} [params.linked] - Linked items the
 *   conditions may read (expressions/linkedItems.js loadLinkedItems)
 * @param {boolean} [params.wakeUp] - A timer's wake-up rather than a save
 * @returns {{
 *   changes: Record<string, string>,
 *   system: Record<string, unknown>,
 *   fired: number,
 *   limitReached: boolean,
 *   wakeUpAt: string | null
 * }} `changes`: workflow fields moved by automatic transitions; `system`:
 *   the workflow system attributes that changed (`wakeUpAt` among them when
 *   the next wake-up moved)
 */
function resolveAutomaticTransitions({
  fields,
  before,
  after,
  actor,
  now,
  linked,
  wakeUp = false
}) {
  const workflowFields = (fields || []).filter(
    (field) => field.type === 'workflow' && field.workflowDefinition
  )
  const nowMs = Date.parse(now)
  const working = { ...after }
  const paths = {}
  const actors = {}
  const stepActors = {}
  const visited = {}
  const stopped = new Set()
  // When each workflow field entered its state — visible to conditions as it changes
  const enteredAt = { ...(before?.workflowStateEnteredAt || {}) }
  working.workflowStateEnteredAt = enteredAt
  // A save is a modification: conditions on `updatedAt` see this one ("updated
  // more than 3 days ago" can't hold right after a save). A wake-up isn't,
  // until a transition fires.
  if (!wakeUp) working.updatedAt = now
 
  // A state set by the caller (manual transition, or the start state on create)
  for (const field of workflowFields) {
    const from = before?.[field.fieldId]
    const to = working[field.fieldId]
    visited[field.fieldId] = new Set([to])
    if (from === to || isEmpty(to)) {
      // An item from before this attribute existed: its stay counts from this write
      if (!isEmpty(to) && !enteredAt[field.fieldId]) enteredAt[field.fieldId] = now
      continue
    }
    if (!isEmpty(from)) visited[field.fieldId].add(from)
    paths[field.fieldId] = isEmpty(from) ? [to] : [from, to]
    stepActors[field.fieldId] = isEmpty(from) ? [] : [actor]
    actors[field.fieldId] = actor
    enteredAt[field.fieldId] = now
  }
 
  const compiled = new Map()
  let fired = 0
  let progress = true
  while (progress && fired < MAX_AUTOMATIC_TRANSITIONS) {
    progress = false
    for (const field of workflowFields) {
      Iif (fired >= MAX_AUTOMATIC_TRANSITIONS) break
      if (stopped.has(field.fieldId)) continue
 
      const current = working[field.fieldId]
      const { states = [], transitions = [] } = field.workflowDefinition
      const stateIds = new Set(states.map((state) => state.id))
      const next = transitions.find(
        (t) =>
          t.from === current &&
          t.auto &&
          stateIds.has(t.to) &&
          evaluateCondition(t.auto.when, working, fields, compiled, linked, nowMs)
      )
      if (!next) continue
 
      working[field.fieldId] = next.to
      paths[field.fieldId] = [...(paths[field.fieldId] || [current]), next.to]
      stepActors[field.fieldId] = [...(stepActors[field.fieldId] || []), SYSTEM_ACTOR]
      actors[field.fieldId] = SYSTEM_ACTOR
      enteredAt[field.fieldId] = now
      working.updatedAt = now
      if (visited[field.fieldId].has(next.to)) stopped.add(field.fieldId)
      visited[field.fieldId].add(next.to)
      fired++
      progress = true
    }
  }
 
  const limitReached = fired >= MAX_AUTOMATIC_TRANSITIONS
  if (limitReached) {
    console.error(
      `Automatic transitions stopped after ${MAX_AUTOMATIC_TRANSITIONS} in one write`,
      JSON.stringify(paths)
    )
  }
 
  const changes = {}
  for (const field of workflowFields) {
    if (working[field.fieldId] !== after[field.fieldId]) {
      changes[field.fieldId] = working[field.fieldId]
    }
  }
 
  const timerDue = stateTimers({
    workflowFields,
    item: working,
    previous: before?.timerDueAt || {},
    moved: new Set(Object.keys(paths)),
    wakeUp,
    nowMs
  })
  const due = Object.values(timerDue).filter((value) => value !== null)
  const wakeUpAt = due.length > 0 ? due.sort()[0] : null
 
  const system = {}
  const unchanged = (key, value) => JSON.stringify(before?.[key] ?? null) === JSON.stringify(value)
  if (!unchanged('workflowStateEnteredAt', enteredAt) && Object.keys(enteredAt).length > 0) {
    system.workflowStateEnteredAt = enteredAt
  }
  // Only real moves (two states or more) are a transition path
  const movedFieldIds = Object.keys(paths).filter((fieldId) => paths[fieldId].length > 1)
  if (movedFieldIds.length > 0) {
    system.lastTransitionPath = Object.fromEntries(movedFieldIds.map((id) => [id, paths[id]]))
    system.lastTransitionBy = Object.fromEntries(movedFieldIds.map((id) => [id, actors[id]]))
    system.lastTransitionActors = Object.fromEntries(
      movedFieldIds.map((id) => [id, stepActors[id]])
    )
  }
  const timerDueValue = Object.keys(timerDue).length > 0 ? timerDue : null
  if (!unchanged('timerDueAt', timerDueValue)) system.timerDueAt = timerDueValue
  if (!unchanged('wakeUpAt', wakeUpAt)) system.wakeUpAt = wakeUpAt
 
  return { changes, system, fired, limitReached, wakeUpAt }
}
 
/**
 * When the timer of each workflow field's current state is due
 * (UC-WORKFLOW-009.1), keyed by fieldId — only fields with a pending timer.
 *
 * A save starts every timer again (from now, or at its date); a wake-up starts
 * the timer of a state it moved into, ends the timers that were due, and
 * keeps the others.
 *
 * @returns {Record<string, string>} ISO timestamps
 */
function stateTimers({ workflowFields, item, previous, moved, wakeUp, nowMs }) {
  const result = {}
  for (const field of workflowFields) {
    const current = item[field.fieldId]
    const state = (field.workflowDefinition.states || []).find((s) => s.id === current)
    if (!state?.timer) continue
 
    if (wakeUp && !moved.has(field.fieldId)) {
      const pending = previous[field.fieldId]
      if (pending && Date.parse(pending) > nowMs) result[field.fieldId] = pending
      continue
    }
    const dueAt = timerDueAt(state.timer, item, nowMs)
    if (dueAt !== null && dueAt > nowMs) result[field.fieldId] = new Date(dueAt).toISOString()
  }
  return result
}
 
module.exports = {
  WORKFLOW_SYSTEM_KEYS,
  MAX_AUTOMATIC_TRANSITIONS,
  SYSTEM_ACTOR,
  transitionPermission,
  validateWorkflowTransitions,
  resolveAutomaticTransitions
}