All files / automation email-consumer.js

99.21% Statements 126/127
93.67% Branches 74/79
100% Functions 16/16
99.13% Lines 114/115

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                                          1x           1x 1x 1x 1x 1x 1x         1x 1x 1x   1x   1x           46x 46x       5x 5x   5x 14x 4x 4x 14x 4x 4x     5x       11x 10x       10x                       10x 10x   16x 20x     10x 8x   10x 10x                           10x 10x 18x 18x 27x     10x       10x 36x   10x 9x   10x 9x   10x 7x   10x       3x                         3x 2x                   13x       13x 13x 13x   10x 10x 7x   7x 7x 7x   6x 6x         6x 1x 1x     5x 5x 14x 5x     5x   5x 5x 5x 11x 2x 2x   9x 9x 2x 2x   7x 7x 7x 6x     4x   3x 3x 3x                                     4x 3x 3x   1x       4x               2x 2x   3x 1x 1x     2x 2x   1x 1x   1x 1x   1x 1x     2x     1x 1x 1x 1x  
// @implements UC-WORKFLOW-011.1
/**
 * Sends the emails of the Email actions queued by ./dispatcher.js (FIFO email
 * queue, one message per action of a fired transition). See
 * docs/architecture/AUTOMATION.md "Email actions".
 *
 * Everything is read again at send time — the item, its entity (the action and
 * its template may have changed or gone since), the flow — so an email never
 * shows stale values or outlives its definition.
 *
 * Recipients are the users in the action's `user` fields and/or the item's
 * creator, minus whoever fired the transition (nobody is emailed about their
 * own move), and only while active members of the flow. A recipient who can't
 * be reached (no longer a member, no account, no email address) is skipped,
 * and the flow owner hears about it through an in-app notification — also when
 * a mandatory `user` field only holds what's left of someone who left the flow.
 *
 * The flow owner pays `automation_email_credits` per email sent: nobody else
 * chose to send it. With a zero balance, nothing is sent.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  BatchGetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { sendEmail } = require('../utils/email')
const { referenceValues } = require('../utils/expressions/condition')
const { isDeletedPlaceholder } = require('../utils/deletedPlaceholder')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const {
  NOTIFICATION_TYPE,
  buildNotificationWrites,
  pushNotification
} = require('../utils/notifications')
const { pickItemLabel } = require('../utils/itemLabel')
const { pickTemplateLanguage, insertedUserIds, renderEmail } = require('./emailRendering')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const SKIP_REASON = {
  NOT_MEMBER: 'not-member',
  NO_EMAIL: 'no-email'
}
 
async function get(tableName, key) {
  const { Item } = await docClient.send(new GetCommand({ TableName: tableName, Key: key }))
  return Item
}
 
async function getUsers(userIds) {
  const users = new Map()
  const tableName = process.env.USERS_TABLE_NAME
  // A handful of recipients per action: one BatchGet (max 100 keys)
  for (let i = 0; i < userIds.length; i += 100) {
    let request = { [tableName]: { Keys: userIds.slice(i, i + 100).map((id) => ({ id })) } }
    for (let attempt = 0; attempt < 3 && request; attempt++) {
      const result = await docClient.send(new BatchGetCommand({ RequestItems: request }))
      for (const user of result.Responses?.[tableName] || []) users.set(user.id, user)
      const unprocessed = result.UnprocessedKeys
      request = unprocessed && Object.keys(unprocessed).length > 0 ? unprocessed : null
    }
  }
  return users
}
 
async function isActiveMember(userId, flow) {
  if (userId === flow.ownerId) return true
  const membership = await get(process.env.FLOW_MEMBERSHIPS_TABLE_NAME, {
    userId,
    flowId: flow.id
  })
  return membership?.status === 'active'
}
 
/**
 * The users an action emails, the actor excluded.
 *
 * @param {object} action
 * @param {object} item
 * @param {string} actor
 * @returns {string[]}
 */
function recipientIds(action, item, actor) {
  const ids = new Set()
  for (const fieldId of action.recipients?.fields || []) {
    // Without the deleted placeholders (see removedRecipients)
    for (const id of referenceValues(item[fieldId])) {
      Eif (typeof id === 'string') ids.add(id)
    }
  }
  if (action.recipients?.creator === true && typeof item.createdBy === 'string') {
    ids.add(item.createdBy)
  }
  ids.delete(actor)
  return [...ids]
}
 
/**
 * What the action's `user` fields still say about recipients who left: removing
 * a member turns a mandatory field's value into a deleted placeholder
 * (utils/cascadeItemFieldValue.js), and empties an optional one — an empty field
 * can't tell whether anyone was ever there, so it is not reported.
 *
 * @param {object} action
 * @param {object} item
 * @returns {string[]} the placeholders
 */
function removedRecipients(action, item) {
  const removed = new Set()
  for (const fieldId of action.recipients?.fields || []) {
    const values = Array.isArray(item[fieldId]) ? item[fieldId] : [item[fieldId]]
    for (const value of values) {
      if (isDeletedPlaceholder(value)) removed.add(value)
    }
  }
  return [...removed]
}
 
function findAction(entity, message) {
  const field = (entity.fields || []).find(
    (f) => f.fieldId === message.fieldId && f.type === 'workflow'
  )
  const transition = (field?.workflowDefinition?.transitions || []).find(
    (t) => t.from === message.from && t.to === message.to
  )
  const action = (Array.isArray(transition?.actions) ? transition.actions : []).find(
    (a) => a?.id === message.actionId && a.type === 'email'
  )
  const template = action
    ? (entity.emailTemplates || []).find((t) => t?.id === action.templateId)
    : undefined
  return action && template ? { action, template } : null
}
 
async function notifyOwnerOfSkipped(ownerId, { entity, item, template, skipped }) {
  const { notification, writes } = buildNotificationWrites(ownerId, {
    type: NOTIFICATION_TYPE.AUTOMATION_EMAIL_SKIPPED,
    data: {
      // The item's flow: the notification opens the entity there
      flowId: item.flowId,
      entityId: entity.id,
      entityName: entity.name,
      itemId: item.id,
      itemLabel: pickItemLabel(entity, item),
      templateName: template.name,
      recipients: skipped
    }
  })
  await docClient.send(new TransactWriteCommand({ TransactItems: writes }))
  await pushNotification(ownerId, notification)
}
 
/**
 * Sends the emails of one queued action.
 *
 * @param {object} message - The dispatcher's message body
 * @returns {Promise<{ status: string, sent?: number, skipped?: number }>}
 */
async function processMessage(message) {
  const item = await get(process.env.ITEMS_TABLE_NAME, {
    entityId: message.entityId,
    id: message.itemId
  })
  const entity = item ? await get(process.env.ENTITIES_TABLE_NAME, { id: message.entityId }) : null
  const flow = entity ? await get(process.env.FLOWS_TABLE_NAME, { id: item.flowId }) : null
  if (!item || !entity || !flow?.ownerId) return { status: 'orphan' }
 
  const found = findAction(entity, message)
  if (!found) return { status: 'removed' }
  const { action, template } = found
 
  const ids = recipientIds(action, item, message.actor)
  const removed = removedRecipients(action, item)
  if (ids.length === 0 && removed.length === 0) return { status: 'no-recipient', sent: 0 }
 
  const ownerId = flow.ownerId
  const { balance, isPlatformAdmin } = await getCreditsBalance(
    docClient,
    process.env.USERS_TABLE_NAME,
    ownerId
  )
  if (!isPlatformAdmin && balance <= 0) {
    console.error(`Email action skipped: flow owner ${ownerId} has no credits left`, item.id)
    return { status: 'no-credits' }
  }
 
  const fields = entity.fields || []
  const users = await getUsers([...new Set([...ids, ...insertedUserIds(template, fields, item)])])
  const userNames = new Map([...users].map(([id, user]) => [id, user.name || '']))
  const defaults = [entity.defaultLanguage, flow.defaultLanguage].filter(Boolean)
  // Opens the item itself, in its flow (the UI's flow pages live under
  // /flows/:slug; EntityItemsPage opens ?item)
  const link = `${process.env.APP_URL}/flows/${flow.slug}/entities/${entity.id}?item=${item.id}`
 
  const skipped = removed.map((userId) => ({ userId, reason: SKIP_REASON.NOT_MEMBER }))
  let sent = 0
  for (const userId of ids) {
    if (!(await isActiveMember(userId, flow))) {
      skipped.push({ userId, reason: SKIP_REASON.NOT_MEMBER })
      continue
    }
    const user = users.get(userId)
    if (!user?.email) {
      skipped.push({ userId, reason: SKIP_REASON.NO_EMAIL })
      continue
    }
    const lang = pickTemplateLanguage(template, user.languagePreferences, defaults)
    const email = renderEmail({ template, lang, fields, item, userNames, link })
    await sendEmail({ to: user.email, ...email })
    sent++
  }
 
  if (sent > 0) {
    // Best-effort, like every post-write debit (docs/architecture/USAGE_METERING.md)
    try {
      const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
      await debitCredits(docClient, {
        usersTableName: process.env.USERS_TABLE_NAME,
        creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
        userId: ownerId,
        flowId: item.flowId,
        charges: [
          {
            pool: 'lambda_compute',
            operation: 'email_action',
            costCredits: sent * pricing.automation_email_credits,
            referenceId: item.id
          }
        ]
      })
    } catch (error) {
      console.error('Failed to debit credits for email action:', error)
    }
  }
 
  if (skipped.length > 0) {
    try {
      await notifyOwnerOfSkipped(ownerId, { entity, item, template, skipped })
    } catch (error) {
      console.error('Failed to notify the flow owner of skipped recipients:', error)
    }
  }
 
  return { status: 'done', sent, skipped: skipped.length }
}
 
/**
 * @param {{ Records?: { messageId: string, body: string }[] }} event - SQS event
 * @returns {Promise<{ batchItemFailures: { itemIdentifier: string }[] }>}
 */
async function emailConsumerHandler(event) {
  const batchItemFailures = []
  for (const record of event?.Records || []) {
    // FIFO: once a message fails, the ones after it are retried with it, in order
    if (batchItemFailures.length > 0) {
      batchItemFailures.push({ itemIdentifier: record.messageId })
      continue
    }
    let message
    try {
      message = JSON.parse(record.body)
    } catch {
      console.error('Invalid email action message:', record.body)
      continue
    }
    try {
      await processMessage(message)
    } catch (error) {
      console.error('Email action failed:', error)
      batchItemFailures.push({ itemIdentifier: record.messageId })
    }
  }
  return { batchItemFailures }
}
 
exports.handler = emailConsumerHandler
exports.processMessage = processMessage
exports.recipientIds = recipientIds
exports.removedRecipients = removedRecipients