ITroubleTicketManagementPOST Apex Interface

The ITroubleTicketManagementPOST interface enables customization of POST operations using Apex lifecycle hooks. Implementations can validate and enrich creation payloads, apply additional business logic, and modify the final response structure, ensuring that customer-creation workflows remain flexible maintaining TMF-compliant behavior.

This interface supports the following hooks.

note: These hooks are not used for the Trouble Ticket Management API. If implemented, the method may be invoked, but its return values are ignored.

  • configureDefaultValidations
  • customiseGraphQLQuery

Creation Lifecycle Use Cases and Hook Mapping

The following table lists common use cases for POST operation.

Use Case Hook(s) Description <div style="width:290px"></div> Example Scenarios <div style="width:290px"></div> Benefit <div style="width:290px"></div>
Enforce Business Rules applyCustomValidations Validates customer creation requests before processing to ensure they comply with business rules, data quality constraints, and organizational policies. Prevents invalid or duplicate customer records from entering the system. • Block creation of customers with duplicate names or identifiers• Reject requests with invalid customer types or lifecycle statuses• Enforce mandatory business validations (e.g., email/phone standards) Prevents invalid or low-quality customer records from being created, improving data integrity
Auto-Populate Fields customiseMutationPayload Automatically enriches or computes field values during customer creation. Ensures consistent and accurate population of derived or dependent fields before data is persisted. • Generate customer display name from first/last name• Auto-calculate classification, segment, or service level• Populate geo-encoding or internal routing codes Reduces manual data entry, enforces consistency, and improves data accuracy
Audit Trail handlePostOperation Adds audit metadata to newly created customer records after persistence, ensuring every creation event is traceable for security and compliance. • Stamp “createdBy”, “createdAt” values• Add system identifiers for correlation or traceability• Trigger downstream audit logging services Maintains a reliable and compliant audit trail across all customer creation events

transformRequest

This hook transforms the request context before processing any operation. It is invoked early in the request lifecycle, allowing implementers to adjust the context for subsequent extensibility hooks.

Hook Method

Map<String, Object> transformRequest(Map<String, Object> context)

Sample Apex Implementation

public Map<String, Object> transformRequest(Map<String, Object> context) {
    if (context == null) {
        return context;
    }

    Map<String, Object> requestBody = (Map<String, Object>) context.get('requestBody');
    if (requestBody == null) {
        return context;
    }

    // Add default values if not provided
    if (!requestBody.containsKey('status') || requestBody.get('status') == null) {
        requestBody.put('status', 'New');
    }

    if (!requestBody.containsKey('priority') || requestBody.get('priority') == null) {
        requestBody.put('priority', 'Medium');
    }

    // Add default origin if not provided
    if (!requestBody.containsKey('origin') || requestBody.get('origin') == null) {
        requestBody.put('origin', 'Web');
    }

    return context;
}

applyCustomValidations

This hook validates custom business logic before creating a customer record. If validation fails, rejects the request and returns an error response.

The handler processes return values as follows.

Success:

  • Return a map with validationStatus set to any value other than "fail" (case-insensitive).
  • The API request continues normally.
  • Other fields in the map are logged but not used.

Failure:

  • Return a map with validationStatus set to "fail" (case-insensitive).
  • The API request is terminated immediately.
  • Raise a ValidationException containing
    • message: value from validationMessage key (or "Validation failed" by default)
    • details: value from validationDetails key (optional)
  • The client receives an HTTP 400 error response.

Hook Method

Map<String, Object> applyCustomValidations(Map<String, Object> context)

Sample Apex Implementation

public Map<String, Object> applyCustomValidations(Map<String, Object> context) {
    // Input context:
    // {
    //   api: 'TroubleTicketManagement',
    //   version: '5.0',
    //   requestBody: {
    //     name: 'Network Issue',
    //     severity: 'InvalidSeverity',
    //     status: 'New'
    //   }
    // }

    Map<String, Object> requestBody = (Map<String, Object>) context.get('requestBody');

    if (requestBody == null) {
        return null;
    }

    String severity = (String) requestBody.get('severity');

    // If severity is not provided, validation passes (it's optional)
    if (severity == null || severity.trim().isEmpty()) {
        return null;
    }

    Map<String, Object> validationResult = new Map<String, Object>();

    // Validate severity is one of allowed values
    Set<String> allowedSeverities = new Set<String>{'Critical', 'Major', 'Minor', 'Warning', 'Informational'};

    if (!allowedSeverities.contains(severity)) {
        validationResult.put('validationStatus', 'FAIL');
        validationResult.put('validationMessage', 'Invalid severity value: ' + severity + '. Allowed values are: Critical, Major, Minor, Warning, Informational');
        validationResult.put('validationDetails', new Map<String, Object>{
            'denialReason' => 'INVALID_SEVERITY_VALUE',
            'providedValue' => severity,
            'allowedValues' => new List<String>(allowedSeverities)
        });
    } else {
        // Validation passes
        validationResult.put('validationStatus', 'PASS');
        validationResult.put('validationMessage', 'Severity validation passed');
    }

    return validationResult;
}



customiseGraphQLQuery

This hook modifies the GraphQL query before execution to add fields, filters, or transformations. Returns a map with a nodes key containing a list of QueryTransformationNode objects.

Hook Method

Map<String, Object> customiseGraphQLQuery(Map<String, Object> graphQLAsMap, Map<String, Object> context)

note: - When to use the hook: Use it when you need to fetch or customize related data before record creation, especially for complex business logic.

  • When not to use the hook: Avoid it for standard POST operations, simple payload changes (use customiseMutationPayload), or validations (use applyCustomValidations).

customiseMutationPayload

This hook modifies the mutation payload before creating a customer record. Use this to add computed fields, set defaults, or transform the payload based on business logic.

Hook Method

Map<String, Object> customiseMutationPayload(Map<String, Object> request, Map<String, Object> context)

Sample Apex Implementation

public Map<String, Object> customiseMutationPayload(
    Map<String, Object> mutationGraphQLPayload,
    Map<String, Object> context
) {
    // Create mutation transformation specification
    List<Map<String, Object>> transformationNodes = new List<Map<String, Object>>();

    // Node 1: Add custom input fields to the Case mutation
    // Path: troubleTicket (the Case mutation alias)
    Map<String, Object> modifyInputNode = new Map<String, Object>{
        'path' => 'troubleTicket',
        'modifyInput' => new Map<String, Object>{
            'addInputFields' => new Map<String, Object>{
                'Reason' => 'Created via POST API',
                'Origin' => 'Web',
                'Type' => 'Technical Issue'
            }
        }
    };
    transformationNodes.add(modifyInputNode);

    // Return transformation specification
    return new Map<String, Object>{
        'nodes' => transformationNodes
    };
}


handlePostOperation

This hook post-processes and transforms the API response after data is deleted.

Hook Method

Map<String, Object> handlePostOperation(Map<String, Object> graphQLQueryResultAsMap, Map<String, Object> constructedTMFResponse, Map<String, Object> context)

Sample Apex Implementation

public Map<String, Object> handlePostOperation(
    Map<String, Object> graphQLQueryResultAsMap,
    Map<String, Object> constructedTMFResponse,
    Map<String, Object> context
) {
    // Input TMF response:
    // {
    //   id: '00001027',
    //   name: 'Network connectivity issue',
    //   status: 'New',
    //   type: 'TroubleTicket'
    // }

    String ticketId = (String) constructedTMFResponse.get('id');

    if (ticketId != null) {
        // Fetch additional data for enrichment
        Case caseRecord = [SELECT Id, CaseNumber, CreatedDate, CreatedById FROM Case WHERE CaseNumber = :ticketId LIMIT 1];

        // Add audit information
        constructedTMFResponse.put('createdAt', caseRecord.CreatedDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''));
        constructedTMFResponse.put('createdBy', UserInfo.getName());

        // Add calculated fields
        constructedTMFResponse.put('ticketAge', 0); // New ticket, age is 0
        constructedTMFResponse.put('isNewTicket', true);
    }

    // Return enriched response
    return constructedTMFResponse;

    // Output response:
    // {
    //   id: '00001027',
    //   name: 'Network connectivity issue',
    //   status: 'New',
    //   type: 'TroubleTicket',
    //   createdAt: '2024-01-17T10:30:00Z',
    //   createdBy: 'John Smith',
    //   ticketAge: 0,
    //   isNewTicket: true
    // }
}


Full Implementation Example

/**
 * Complete Trouble Ticket Management POST API Extension
 * Demonstrates all applicable lifecycle hooks with business logic
 */
public class TroubleTicketManagementPOSTExtension implements comms_apex_ext.ITroubleTicketManagementPOST {

    /**
     * Hook 1: Transform request
     */
    public Map<String, Object> transformRequest(Map<String, Object> context) {
        if (context == null) {
            return context;
        }

        Map<String, Object> requestBody = (Map<String, Object>) context.get('requestBody');
        if (requestBody == null) {
            return context;
        }

        // Add default values if not provided
        if (!requestBody.containsKey('status') || requestBody.get('status') == null) {
            requestBody.put('status', 'New');
        }

        if (!requestBody.containsKey('priority') || requestBody.get('priority') == null) {
            requestBody.put('priority', 'Medium');
        }

        return context;
    }

    /**
     * Hook 2: Apply custom validations
     */
    public Map<String, Object> applyCustomValidations(Map<String, Object> context) {
        Map<String, Object> requestBody = (Map<String, Object>) context.get('requestBody');

        if (requestBody == null) {
            return null;
        }

        String severity = (String) requestBody.get('severity');

        if (severity == null || severity.trim().isEmpty()) {
            return null;
        }

        Set<String> allowedSeverities = new Set<String>{'Critical', 'Major', 'Minor', 'Warning', 'Informational'};

        if (!allowedSeverities.contains(severity)) {
            return new Map<String, Object>{
                'validationStatus' => 'FAIL',
                'validationMessage' => 'Invalid severity value: ' + severity,
                'validationDetails' => new Map<String, Object>{
                    'denialReason' => 'INVALID_SEVERITY_VALUE',
                    'providedValue' => severity,
                    'allowedValues' => new List<String>(allowedSeverities)
                }
            };
        }

        return null;
    }

    /**
     * Hook 3: Customize GraphQL query (optional, rarely used)
     */
    public Map<String, Object> customiseGraphQLQuery(
        Map<String, Object> graphQLAsMap,
        Map<String, Object> context
    ) {
        // Most POST operations don't need to customize the query
        return null;
    }

    /**
     * Hook 4: Customize mutation payload
     */
    public Map<String, Object> customiseMutationPayload(
        Map<String, Object> mutationGraphQLPayload,
        Map<String, Object> context
    ) {
        List<Map<String, Object>> transformationNodes = new List<Map<String, Object>>();

        // Add custom input fields
        Map<String, Object> modifyInput = new Map<String, Object>{
            'addInputFields' => new Map<String, Object>{
                'Reason' => 'Created via POST API',
                'Origin' => 'Web'
            }
        };

        transformationNodes.add(new Map<String, Object>{
            'path' => 'troubleTicket',
            'modifyInput' => modifyInput
        });

        return new Map<String, Object>{ 'nodes' => transformationNodes };
    }

    /**
     * Hook 5: Post-process response
     */
    public Map<String, Object> handlePostOperation(
        Map<String, Object> graphQLQueryResultAsMap,
        Map<String, Object> constructedTMFResponse,
        Map<String, Object> context
    ) {
        String ticketId = (String) constructedTMFResponse.get('id');

        if (ticketId != null) {
            try {
                Case caseRecord = [SELECT Id, CaseNumber, CreatedDate FROM Case WHERE CaseNumber = :ticketId LIMIT 1];

                constructedTMFResponse.put('createdAt', caseRecord.CreatedDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''));
                constructedTMFResponse.put('createdBy', UserInfo.getName());
                constructedTMFResponse.put('ticketAge', 0);
                constructedTMFResponse.put('isNewTicket', true);
            } catch (Exception e) {
                System.debug('Error enriching trouble ticket data: ' + e.getMessage());
            }
        }

        return constructedTMFResponse;
    }

    /**
     * NOT APPLICABLE: configureDefaultValidations is not used for Trouble Ticket Management API
     * If implemented, this method will be invoked but return values will be ignored.
     */
    public Map<String, Boolean> configureDefaultValidations(
        Map<String, Boolean> defaultValidationConfiguration,
        Map<String, Object> context
    ) {
        // This hook is not applicable for Trouble Ticket Management API
        // Return the configuration unchanged
        return defaultValidationConfiguration;
    }
}

GraphQL Mutation - Create Operations

Create mutations add new records and return the created record with the specified output fields.

Create Enhancements: Add Output Fields

Original Mutation (GraphQL):

mutation CreateCustomerAndRelatedEntities {
uiapi {
customerAccount: AccountCreate(input: {
Account: { Name: "Acme Corp" }
}) {
Record {
Id
Name { value }
}
}
}
}

Transformation Instructions (JSON):

{
"nodes": [{
"path": "customerAccount",
"addFields": {
"Industry": "Technology",
"Revenue": 5000000,
"Status": "Active"
}
}]
}

Result (GraphQL):

mutation CreateCustomerAndRelatedEntities {
uiapi {
customerAccount: AccountCreate(input: {
Account: { Name: "Acme Corp" }
}) {
Record {
Id
Name { value }
Industry
Revenue
Status
}
}
}
}

Create Enhancements: Modify Input Payload

Original Mutation (GraphQL):

mutation CreateCustomerAndRelatedEntities {
  uiapi {
    customerAccount: AccountCreate(input: {
      Account: { Name: "Acme Corp" }
    }) {
      Record {
        Id
        Name { value }
      }
    }
  }
}

Transformation Instructions (JSON - Modify Input):

{
  "nodes": [{
    "path": "customerAccount",
    "modifyInput": {
      "addInputFields": {
        "Industry": "Technology",
        "Status": "Active"
      }
    }
  }]
}

Result (GraphQL):

mutation CreateCustomerAndRelatedEntities {
  uiapi {
    customerAccount: AccountCreate(input: {
      Account: {
        Name: "Acme Corp",
        Industry: "Technology",
        Status: "Active"
      }
    }) {
      Record {
        Id
        Name { value }
      }
    }
  }
}

note: Using modifyInput with addInputFields adds new fields to the input payload. These fields are added to the Account object within the input wrapper and are sent to the mutation.

Create Enhancements: Modify Existing Input Fields

Original Mutation (GraphQL):

mutation CreateCustomerAndRelatedEntities {
  uiapi {
    customerAccount: AccountCreate(input: {
      Account: { Name: "Acme Corp" }
    }) {
      Record {
        Id
        Name { value }
      }
    }
  }
}

Transformation Instructions (JSON - Modify Existing Fields):

{
  "nodes": [{
    "path": "customerAccount",
    "modifyInput": {
      "inputModifications": {
        "Name": "Updated Company Name"
      }
    }
  }]
}

Result (GraphQL):

mutation CreateCustomerAndRelatedEntities {
  uiapi {
    customerAccount: AccountCreate(input: {
      Account: { Name: "Updated Company Name" }
    }) {
      Record {
        Id
        Name { value }
      }
    }
  }
}

note: The inputModifications replaces the values of existing input fields. The transformer identifies the wrapper key, for example Account and applies the changes at the correct nested level.