All files / utils cascadeItemFieldValue.js

100% Statements 53/53
85.71% Branches 30/35
100% Functions 7/7
100% Lines 49/49

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 23810x 10x                                 15x                 15x 15x   15x 5x 5x 5x   3x               3x       15x                 55x 55x     55x 56x                   56x 56x     55x       17x 6x                   11x                                                         16x 16x 16x   16x 14x     14x 4x 3x   11x     14x                   16x                                 2x               2x 3x                   2x                               4x                 4x 4x   4x 5x 5x 7x 6x   4x               4x       4x     10x                
const { QueryCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
const { buildDeletedPlaceholder, shortId } = require('./deletedPlaceholder')
 
// Item Link (entity_ref) targets in a different flow are only reachable when the
// target entity is public, and an eager cross-flow cascade would require
// scanning the entire entities table. So the onDelete cascade below is scoped to
// same-flow references only; entities/update.js and entities/create.js forbid
// `mandatory: true` on a cross-flow entity_ref field so a stale cross-flow value
// never needs to satisfy a "must always have a value" guarantee — it's left to
// resolve lazily at read time (see lookup-form.js's `missingIds`).
async function cascadeItemDeletionReferences({
  docClient,
  entitiesTableName,
  itemsTableName,
  flowId,
  deletedEntityId,
  deletedItemId
}) {
  const entitiesResult = await docClient.send(
    new QueryCommand({
      TableName: entitiesTableName,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ExpressionAttributeValues: { ':flowId': flowId }
    })
  )
 
  const referencingEntities = entitiesResult.Items || []
  let updatedCount = 0
 
  for (const entity of referencingEntities) {
    const fields = Array.isArray(entity.fields) ? entity.fields : []
    for (const field of fields) {
      if (field.type !== 'entity_ref' || field.reference?.entityId !== deletedEntityId) continue
 
      const { updatedCount: fieldUpdatedCount } = await cascadeRemovedReferenceValue({
        docClient,
        itemsTableName,
        entityId: entity.id,
        field,
        matchValue: deletedItemId,
        placeholderLabel: `Deleted item (…${shortId(deletedItemId)})`
      })
      updatedCount += fieldUpdatedCount
    }
  }
 
  return { updatedCount }
}
 
// Queries every item of `entityId` whose `field.fieldId` matches `matchValue`
// (scalar equality, or array membership for multi-value reference fields),
// paginating across LastEvaluatedKey — same partition-key Query pattern already
// used for the uniqueness check in items/create.js and items/update.js, so this
// stays a bounded Query rather than a table Scan.
async function findMatchingItems({ docClient, itemsTableName, entityId, field, matchValue }) {
  const isMultiple = field.reference?.multiple === true
  const items = []
  let ExclusiveStartKey
 
  do {
    const result = await docClient.send(
      new QueryCommand({
        TableName: itemsTableName,
        KeyConditionExpression: 'entityId = :eid',
        FilterExpression: isMultiple ? 'contains(#f, :v)' : '#f = :v',
        ExpressionAttributeNames: { '#f': field.fieldId },
        ExpressionAttributeValues: { ':eid': entityId, ':v': matchValue },
        ExclusiveStartKey
      })
    )
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
 
  return items
}
 
async function setOrRemoveField({ docClient, itemsTableName, entityId, id, fieldId, newValue }) {
  if (newValue === undefined) {
    await docClient.send(
      new UpdateCommand({
        TableName: itemsTableName,
        Key: { entityId, id },
        UpdateExpression: 'REMOVE #f SET #updatedAt = :updatedAt',
        ExpressionAttributeNames: { '#f': fieldId, '#updatedAt': 'updatedAt' },
        ExpressionAttributeValues: { ':updatedAt': new Date().toISOString() }
      })
    )
  } else {
    await docClient.send(
      new UpdateCommand({
        TableName: itemsTableName,
        Key: { entityId, id },
        UpdateExpression: 'SET #f = :v, #updatedAt = :updatedAt',
        ExpressionAttributeNames: { '#f': fieldId, '#updatedAt': 'updatedAt' },
        ExpressionAttributeValues: { ':v': newValue, ':updatedAt': new Date().toISOString() }
      })
    )
  }
}
 
/**
 * onDelete strategy for a reference-style field (user / entity_ref / select)
 * whose target value (`matchValue`) has disappeared:
 *   - not mandatory -> SET_NULL (remove the attribute, or drop the id from a
 *     multi-value array)
 *   - mandatory -> replace with a short placeholder built from `placeholderLabel`
 *     (or, for a multi-value array that becomes empty, replace with a single
 *     placeholder entry so the field never ends up truly empty)
 */
async function cascadeRemovedReferenceValue({
  docClient,
  itemsTableName,
  entityId,
  field,
  matchValue,
  placeholderLabel
}) {
  const items = await findMatchingItems({ docClient, itemsTableName, entityId, field, matchValue })
  const isMultiple = field.reference?.multiple === true
  const placeholder = buildDeletedPlaceholder(placeholderLabel)
 
  for (const item of items) {
    const currentValue = item[field.fieldId]
    let newValue
 
    if (isMultiple && Array.isArray(currentValue)) {
      const filtered = currentValue.filter((v) => v !== matchValue)
      newValue = filtered.length === 0 && field.mandatory ? [placeholder] : filtered
    } else {
      newValue = field.mandatory ? placeholder : undefined
    }
 
    await setOrRemoveField({
      docClient,
      itemsTableName,
      entityId,
      id: item.id,
      fieldId: field.fieldId,
      newValue
    })
  }
 
  return { updatedCount: items.length }
}
 
/**
 * Migrates every item of `entityId` currently in workflow state `removedStateId`
 * (for `field.fieldId`) to `fallbackStateId`. Used when a workflow status is
 * deleted from the field's definition — the caller (entities/update.js) is
 * responsible for requiring the fallback to be chosen up front.
 */
async function cascadeWorkflowStateMigration({
  docClient,
  itemsTableName,
  entityId,
  field,
  removedStateId,
  fallbackStateId
}) {
  const items = await findMatchingItems({
    docClient,
    itemsTableName,
    entityId,
    field,
    matchValue: removedStateId
  })
 
  for (const item of items) {
    await setOrRemoveField({
      docClient,
      itemsTableName,
      entityId,
      id: item.id,
      fieldId: field.fieldId,
      newValue: fallbackStateId
    })
  }
 
  return { updatedCount: items.length }
}
 
// Public entities can never have a `user`-type field (enforced by
// validatePublicEntityFields.js), so a removed flow member only ever needs to be
// cascaded within that same flow's own entities. `keep` ({ entityId, fieldId })
// names one user field left as is: the member field of the membership entity,
// whose items keep the former member (UC-SPACE-006.1).
async function cascadeMemberRemovalReferences({
  docClient,
  entitiesTableName,
  itemsTableName,
  flowId,
  removedUserId,
  keep
}) {
  const entitiesResult = await docClient.send(
    new QueryCommand({
      TableName: entitiesTableName,
      IndexName: 'flowIndex',
      KeyConditionExpression: 'flowId = :flowId',
      ExpressionAttributeValues: { ':flowId': flowId }
    })
  )
 
  const flowEntities = entitiesResult.Items || []
  let updatedCount = 0
 
  for (const entity of flowEntities) {
    const fields = Array.isArray(entity.fields) ? entity.fields : []
    for (const field of fields) {
      if (field.type !== 'user') continue
      if (keep && entity.id === keep.entityId && field.fieldId === keep.fieldId) continue
 
      const { updatedCount: fieldUpdatedCount } = await cascadeRemovedReferenceValue({
        docClient,
        itemsTableName,
        entityId: entity.id,
        field,
        matchValue: removedUserId,
        placeholderLabel: `Removed member (…${shortId(removedUserId)})`
      })
      updatedCount += fieldUpdatedCount
    }
  }
 
  return { updatedCount }
}
 
module.exports = {
  findMatchingItems,
  cascadeRemovedReferenceValue,
  cascadeWorkflowStateMigration,
  cascadeItemDeletionReferences,
  cascadeMemberRemovalReferences,
  shortId
}