All files / utils membershipRequestEmails.js

100% Statements 71/71
78.78% Branches 26/33
100% Functions 16/16
100% Lines 61/61

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                      1x 1x 1x 1x   1x     15x   15x 19x 18x 18x   14x         8x         7x     12x 12x     8x                 8x 7x           7x 7x 16x 12x 8x     7x       6x 6x 6x 9x 6x 6x 6x 6x 6x     6x         7x 7x 10x 8x 8x 7x   1x           7x     7x             5x 7x 4x 3x 3x 3x 3x 5x     1x       1x                   5x 5x     4x 4x 4x   1x         1x       1x  
// @implements UC-SPACE-007.1
/**
 * Sends the membership request emails (docs/architecture/FLOW_SPACE.md
 * "Emails in the flow's colours"): to the approvers on a new request, to the
 * requester on a decision. Free (no credits): platform emails, like the API
 * key email, whose volume the flow's pending cap bounds.
 *
 * Best-effort: every failure is logged and swallowed, the request or the
 * decision is already written.
 */
 
const { QueryCommand, GetCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { sendEmail, pickEmailLanguage } = require('./email')
const { permissionChecker } = require('./PermissionChecker')
const { renderNewRequestEmail, renderDecisionEmail } = require('./emailTemplates/membershipRequest')
 
const APPROVE_PERMISSION = 'members:approve'
 
async function queryAll(docClient, input) {
  const items = []
  let ExclusiveStartKey
  do {
    const page = await docClient.send(new QueryCommand({ ...input, ExclusiveStartKey }))
    items.push(...(page.Items || []))
    ExclusiveStartKey = page.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return items
}
 
/** The flow's role ids whose permissions grant members:approve */
async function approverRoleIds(docClient, flowId) {
  const roles = await queryAll(docClient, {
    TableName: process.env.ROLES_TABLE_NAME,
    KeyConditionExpression: 'PK = :pk AND begins_with(SK, :sk)',
    ExpressionAttributeValues: { ':pk': `FLOW#${flowId}`, ':sk': 'ROLE#' }
  })
  return new Set(
    roles
      .filter((role) =>
        (role.permissions || []).some((granted) =>
          permissionChecker.matchesPermission(granted, APPROVE_PERMISSION)
        )
      )
      .map((role) => role.roleId || String(role.SK).slice('ROLE#'.length))
  )
}
 
/**
 * The ids of the flow's active members whose roles grant members:approve,
 * the owner always among them.
 */
async function findApproverIds(docClient, flow) {
  const roleIds = await approverRoleIds(docClient, flow.id)
  const memberships = await queryAll(docClient, {
    TableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
    IndexName: 'flowIndex',
    KeyConditionExpression: 'flowId = :flowId',
    ExpressionAttributeValues: { ':flowId': flow.id }
  })
  const ids = new Set(flow.ownerId ? [flow.ownerId] : [])
  for (const membership of memberships) {
    if (membership.status !== 'active') continue
    if ((membership.roleIds || []).some((roleId) => roleIds.has(roleId))) {
      ids.add(membership.userId)
    }
  }
  return [...ids]
}
 
async function getUsers(docClient, userIds) {
  const tableName = process.env.USERS_TABLE_NAME
  const users = []
  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 }))
      users.push(...(result.Responses?.[tableName] || []))
      const unprocessed = result.UnprocessedKeys
      request = unprocessed && Object.keys(unprocessed).length > 0 ? unprocessed : null
    }
  }
  return users
}
 
/** Sends one email per user that has an address; one failure does not stop the others */
async function sendToUsers(users, render) {
  let sent = 0
  for (const user of users) {
    if (!user?.email) continue
    try {
      await sendEmail({ to: user.email, ...render(pickEmailLanguage(user.languagePreferences)) })
      sent++
    } catch (error) {
      console.error('Failed to send a membership request email:', {
        userId: user.id,
        error: error.message
      })
    }
  }
  return sent
}
 
const appUrl = () => process.env.APP_URL || ''
 
/**
 * Tells the flow's approvers that `requesterId` asks to join.
 * @returns {Promise<number>} the emails sent
 */
async function emailApprovers({ docClient, flow, requesterId }) {
  try {
    const approverIds = (await findApproverIds(docClient, flow)).filter((id) => id !== requesterId)
    if (approverIds.length === 0) return 0
    const [requester] = await getUsers(docClient, [requesterId])
    const requesterName = requester?.name || requester?.nickname || ''
    const link = `${appUrl()}/flows/${encodeURIComponent(flow.slug)}/members?tab=requests`
    return await sendToUsers(await getUsers(docClient, approverIds), (lang) =>
      renderNewRequestEmail({ lang, flow, link, requesterName })
    )
  } catch (error) {
    console.error('Failed to email the approvers of a membership request:', {
      flowId: flow?.id,
      error: error.message
    })
    return 0
  }
}
 
/**
 * Tells the requester the decision on their request.
 * @param {{ docClient: object, flow: object, userId: string, decision: 'approved'|'refused' }} params
 * @returns {Promise<number>} the emails sent (0 or 1)
 */
async function emailDecision({ docClient, flow, userId, decision }) {
  try {
    const { Item: user } = await docClient.send(
      new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: userId } })
    )
    const slug = encodeURIComponent(flow.slug)
    const link = decision === 'approved' ? `${appUrl()}/flows/${slug}` : `${appUrl()}/space/${slug}`
    return await sendToUsers([user], (lang) => renderDecisionEmail(decision, { lang, flow, link }))
  } catch (error) {
    console.error('Failed to email a membership request decision:', {
      flowId: flow?.id,
      userId,
      error: error.message
    })
    return 0
  }
}
 
module.exports = { findApproverIds, emailApprovers, emailDecision }