All files / entities create.js

94.91% Statements 112/118
82.17% Branches 83/101
100% Functions 2/2
96.42% Lines 108/112

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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 4561x 1x 1x 1x 1x 1x 1x 1x       1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x   1x 1x   1x 64x 64x     63x 63x   63x                     63x 3x                   60x             60x 1x                                   59x 1x                     58x 58x     58x 58x             58x 58x 58x 58x                   58x             58x       58x     58x 58x 1x 1x                     57x 57x       54x     54x     49x 49x       49x           49x       48x         48x 48x 4x                         44x           44x 1x                   43x     43x                         43x 1x                     42x 6x         6x       4x 2x             2x 1x                           39x 1x                         38x 38x     38x     38x 2x                           36x   36x                                                         36x                       36x       32x 32x 32x     32x                                         1x               32x 1x 6x   1x 1x 1x                     32x                 5x   5x 2x                   3x                       1x      
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
const { requirePermission } = require('../utils/requirePermission')
const { putEntityRecord } = require('./createEntityRecord')
const { buildRestrictedEntityCreationWrites } = require('../utils/restrictedEntityRoles')
const { batchWrite } = require('../utils/batchWrite')
const {
  getCatalogSearchTokens,
  buildCatalogSearchPutRequest
} = require('../utils/catalogSearchIndex')
const {
  RESERVED_ENTITY_IDS,
  VISIBILITY_LEVELS,
  MAX_ENTITY_FORMS,
  MAX_ENTITY_SIZE_BYTES
} = require('../utils/constants')
const { getCreditsBalance, debitCredits } = require('../utils/creditsLedger')
const { getPricingConfig } = require('../utils/pricingConfig')
const { getConsumedCapacity } = require('../shared/usage-tracking')
const { validateWorkflowFields } = require('../utils/validateWorkflowFields')
const { loadLinkedEntities } = require('../utils/expressions/linkedItems')
const { validateEmailTemplates } = require('../utils/emailTemplates')
const { validateFieldNames } = require('../utils/validateFieldNames')
const { validateFieldDefinitions } = require('../utils/validateFieldDefinitions')
const { validateDescription } = require('../utils/validateDescription')
const { validatePublicEntityFields } = require('../utils/validatePublicEntityFields')
const { validateMandatoryCrossFlowReferences } = require('../utils/entityFieldCascadeValidation')
const { resolveForms } = require('../utils/resolveEntityForms')
const { isValidUuid } = require('../utils/isValidUuid')
const {
  findEntityNameConflict,
  findPublicEntityNameConflictForOwner
} = require('../utils/nameUniqueness')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const createEntityHandler = async (event) => {
  try {
    const body = JSON.parse(event.body || '{}')
 
    // Extract flowId from JWT claims (Cognito authorizer)
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    Iif (!flowId) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing flow context' })
      }
    }
 
    if (!body.name || !body.fields) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing required fields: name, fields' })
      }
    }
 
    const entitySizeBytes = Buffer.byteLength(
      JSON.stringify({
        fields: body.fields,
        forms: body.forms,
        emailTemplates: body.emailTemplates
      })
    )
    if (entitySizeBytes > MAX_ENTITY_SIZE_BYTES) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: 'ENTITY_TOO_LARGE',
          maxBytes: MAX_ENTITY_SIZE_BYTES,
          actualBytes: entitySizeBytes
        })
      }
    }
 
    // Callers may supply the entity's id up front (generated client-side
    // before the first request), so image fields (picture/icon) uploaded
    // during creation can be keyed by the real id from the start instead of
    // a throwaway placeholder that would never get reconciled afterward.
    if (body.id !== undefined && !isValidUuid(body.id)) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Invalid id: must be a UUID' })
      }
    }
 
    // Fetch flow configuration for language defaults and ownership
    let flowDefaultLanguage = 'en'
    let flowEnabledLanguages = ['en', 'fr']
    let flowOwnerId
 
    try {
      const flowResult = await docClient.send(
        new GetCommand({
          TableName: process.env.FLOWS_TABLE_NAME,
          Key: { id: flowId }
        })
      )
 
      Eif (flowResult.Item) {
        flowDefaultLanguage = flowResult.Item.defaultLanguage || 'en'
        flowEnabledLanguages = flowResult.Item.enabledLanguages || ['en', 'fr']
        flowOwnerId = flowResult.Item.ownerId
      }
    } catch (error) {
      console.warn('Could not fetch flow configuration, using defaults:', error)
      // Continue with defaults if flow fetch fails
    }
 
    // Validate workflow fields: each workflow field must have a valid startStateId,
    // and each automatic transition a valid condition — rows on linked items
    // against their entity's fields (UC-WORKFLOW-008.1)
    const linkedEntities = await loadLinkedEntities({
      docClient,
      entitiesTableName: process.env.TABLE_NAME,
      fields: body.fields,
      entityId: body.id,
      flowId
    })
    const workflowValidation = validateWorkflowFields(body.fields, {
      linkedEntities,
      emailTemplates: body.emailTemplates
    })
    Iif (!workflowValidation.valid) return workflowValidation.errorResponse
 
    // Email templates: plain text with the item's values inserted (UC-WORKFLOW-010.1)
    const templatesValidation = validateEmailTemplates(body.emailTemplates, body.fields)
    if (!templatesValidation.valid) {
      const { valid, ...details } = templatesValidation // eslint-disable-line no-unused-vars
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'INVALID_EMAIL_TEMPLATE', ...details })
      }
    }
 
    // Validate field names: every field must have a non-empty name
    const fieldNameValidation = validateFieldNames(body.fields)
    if (!fieldNameValidation.valid) return fieldNameValidation.errorResponse
 
    // Validate field definitions: known type, well-formed select/multiselect
    // options, sound number min/max/step, positive length/maxLines
    const fieldDefinitionValidation = validateFieldDefinitions(body.fields, {
      defaultLanguage: body.defaultLanguage || flowDefaultLanguage
    })
    if (!fieldDefinitionValidation.valid) return fieldDefinitionValidation.errorResponse
 
    // Validate description: cannot exceed the maximum number of line breaks
    const descriptionValidation = validateDescription(body.description)
    Iif (!descriptionValidation.valid) return descriptionValidation.errorResponse
 
    // A mandatory Item Link field can't safely target a public entity owned by
    // another flow — see entityFieldCascadeValidation.js for why.
    const crossFlowValidation = await validateMandatoryCrossFlowReferences(
      body.fields,
      docClient,
      process.env.TABLE_NAME,
      flowId
    )
    if (!crossFlowValidation.valid) return crossFlowValidation.errorResponse
 
    // Extract entity name for validation (support both string and multilingual object)
    const entityName =
      typeof body.name === 'string'
        ? body.name
        : body.name.en || body.name.fr || Object.values(body.name)[0] || ''
 
    // Validate that entity name is not a reserved system ID
    const proposedId = entityName.toLowerCase().replace(/[^a-z0-9-]/g, '-')
    if (RESERVED_ENTITY_IDS.includes(proposedId)) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: `Entity name "${entityName}" conflicts with reserved system entity. Reserved names: ${RESERVED_ENTITY_IDS.join(', ')}`
        })
      }
    }
 
    // Verify entity name is unique within the flow
    const nameConflict = await findEntityNameConflict(docClient, {
      tableName: process.env.TABLE_NAME,
      flowId,
      name: body.name
    })
 
    if (nameConflict) {
      return {
        statusCode: 409,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'An entity with this name already exists in this flow' })
      }
    }
 
    const visibility = body.visibility ?? 'flow-members'
 
    // Validate visibility if provided
    Iif (!VISIBILITY_LEVELS.includes(visibility)) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: `Invalid visibility level. Must be one of: ${VISIBILITY_LEVELS.join(', ')}`
        })
      }
    }
 
    if (body.commentsEnabled !== undefined && typeof body.commentsEnabled !== 'boolean') {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'commentsEnabled must be a boolean' })
      }
    }
 
    // Public entities cannot expose user data or reference non-public entities
    if (visibility === 'public') {
      const publicFieldsValidation = await validatePublicEntityFields(
        body.fields,
        docClient,
        process.env.TABLE_NAME
      )
      if (!publicFieldsValidation.valid) return publicFieldsValidation.errorResponse
 
      // A user's public entity names must be unique across all of their own
      // flows, not just this one — see findPublicEntityNameConflictForOwner.
      if (flowOwnerId) {
        const publicNameConflict = await findPublicEntityNameConflictForOwner(docClient, {
          entitiesTableName: process.env.TABLE_NAME,
          flowsTableName: process.env.FLOWS_TABLE_NAME,
          ownerId: flowOwnerId,
          name: body.name
        })
 
        if (publicNameConflict) {
          return {
            statusCode: 409,
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify({
              error: 'A public entity with this name already exists in one of your other flows'
            })
          }
        }
      }
    }
 
    if (Array.isArray(body.forms) && body.forms.length > MAX_ENTITY_FORMS) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'TOO_MANY_FORMS', max: MAX_ENTITY_FORMS })
      }
    }
 
    // Storage-credit preflight — see docs/architecture/USAGE_METERING.md
    // "DynamoDB storage credits" (same model as items/create.js, extended to
    // entities/flows). Rates are admin-editable — see pricingConfig.js.
    const pricing = await getPricingConfig(docClient, process.env.PRICING_CONFIG_TABLE_NAME)
    const storageCreditEstimate = Math.ceil(
      (entitySizeBytes / 1024) * pricing.dynamodb_storage_credits_per_kb
    )
    const { balance: creditsBalance, isPlatformAdmin } = userId
      ? await getCreditsBalance(docClient, process.env.USERS_TABLE_NAME, userId)
      : { balance: 0, isPlatformAdmin: false }
    if (!userId || (!isPlatformAdmin && creditsBalance < storageCreditEstimate)) {
      return {
        statusCode: 402,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          error: 'INSUFFICIENT_CREDITS',
          required: storageCreditEstimate,
          balance: creditsBalance
        })
      }
    }
 
    const forms = resolveForms({ fields: body.fields, forms: body.forms })
 
    const entity = {
      id: body.id || randomUUID(),
      flowId,
      visibility: visibility,
      name: body.name,
      fields: body.fields,
      commentsEnabled: body.commentsEnabled ?? false,
      defaultLanguage: body.defaultLanguage || flowDefaultLanguage,
      enabledLanguages: body.enabledLanguages || flowEnabledLanguages,
      ...(body.picture && { picture: body.picture }),
      ...(body.icon && { icon: body.icon }),
      ...(body.description && { description: body.description }),
      ...(forms && { forms }),
      ...(Array.isArray(body.emailTemplates) &&
        body.emailTemplates.length > 0 && { emailTemplates: body.emailTemplates }),
      ...(body.publicPermissions &&
        visibility === 'public' && { publicPermissions: body.publicPermissions }),
      createdBy: userId,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      // Constant partition value for the platformStatsIndex GSI, letting the
      // platform-admin dashboard query "all entities by creation date" without a scan.
      gsiPk: 'ENTITY'
    }
 
    // A restricted entity comes with its own Reader/Contributor/Manager roles,
    // the creator holding Manager — written with the entity so it can never
    // exist without anyone able to reach it (UC-RBAC-008.1).
    const restrictedEntityWrites =
      visibility === 'restricted'
        ? await buildRestrictedEntityCreationWrites({
            docClient,
            rolesTableName: process.env.ROLES_TABLE_NAME,
            membershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
            flowId,
            entity,
            userId,
            now: entity.createdAt
          })
        : []
 
    await putEntityRecord(docClient, process.env.TABLE_NAME, entity, restrictedEntityWrites)
 
    // Best-effort from here: a failure doesn't unwind the write — see
    // items/create.js's identical reasoning.
    try {
      const { writeUnits } = getConsumedCapacity()
      const throughputCreditCost = Math.ceil(
        writeUnits * pricing.dynamodb_throughput_credits_per_wru
      )
      await debitCredits(docClient, {
        usersTableName: process.env.USERS_TABLE_NAME,
        creditsLedgerTableName: process.env.CREDITS_LEDGER_TABLE_NAME,
        userId,
        flowId,
        charges: [
          {
            pool: 'dynamodb_storage',
            operation: 'entity_create',
            costCredits: storageCreditEstimate,
            referenceId: entity.id
          },
          {
            pool: 'dynamodb_throughput',
            operation: 'entity_create',
            costCredits: throughputCreditCost,
            referenceId: entity.id
          }
        ]
      })
    } catch (creditError) {
      console.error('Failed to debit credits for entity create:', creditError)
    }
 
    // Catalog-search index rows are best-effort and non-transactional, same
    // reasoning as items/create.js's trigram flush: the entity itself is
    // already correctly written, and a failure here only delays its
    // discoverability in the Catalog, so it's logged and swallowed rather
    // than failing the create response.
    if (process.env.FIELD_VALUE_INDEX_TABLE_NAME) {
      const catalogSearchRequests = getCatalogSearchTokens(entity.name).map(({ kind, token }) =>
        buildCatalogSearchPutRequest(kind, token, entity.id)
      )
      Eif (catalogSearchRequests.length > 0) {
        try {
          await batchWrite(
            docClient,
            process.env.FIELD_VALUE_INDEX_TABLE_NAME,
            catalogSearchRequests
          )
        } catch (catalogSearchError) {
          console.error('Failed to write catalog-search index rows:', catalogSearchError)
        }
      }
    }
 
    return {
      statusCode: 201,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(entity)
    }
  } catch (error) {
    console.error('Error:', error)
 
    if (error.name === 'ConditionalCheckFailedException') {
      return {
        statusCode: 409,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'An entity with this id already exists' })
      }
    }
 
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to create entity' })
    }
  }
}
 
// Wrap with permission check: require 'entities:create' permission
exports.handler = requirePermission(createEntityHandler, {
  permission: 'entities:create'
})