User Story
As a: Sales Manager
I want to: generate a unique credit card number automatically for customers during the order creation process
So that: I can ensure that each order is associated with a valid and unique credit card number, improving efficiency and reducing manual errors.
Acceptance Criteria:
- A new Apex Action is created to generate a unique credit card number.
- The Apex Action is integrated into a Salesforce Flow.
- The Flow triggers the Apex Action when a new order is created.
- The generated credit card number is automatically populated in the "Credit Card Number" field of the order record.
- The credit card number follows a valid format and is unique for each order.
- The Flow provides an error message if the Apex Action fails to generate a credit card number.
Apex Class
public class CardNumberGenerator {
private static final String DIGITS = '0123456789';
private static String generatedCardNumber = '';
@InvocableMethod(Label='Generate Card Number')
public static List<String> createCardNumber() {
generatedCardNumber = ''; // Initialize or reset the card number for each call
for (Integer index = 0; index < 19; index++) {
if (index == 4 || index == 9 || index == 14) {
generatedCardNumber += ' ';
} else {
Integer randomDigitIndex = Math.mod(Math.round(Math.random() * 100), DIGITS.length());
generatedCardNumber += DIGITS.substring(randomDigitIndex, randomDigitIndex + 1);
}
}
System.debug(generatedCardNumber);
return new List<String>{ generatedCardNumber };
}
}
Apex Test Class
@IsTest
public class CardNumberGeneratorTest {
@IsTest
static void testCreateCardNumber() {
// Call the method to test
List<String> result = CardNumberGenerator.createCardNumber();
// Check that a result is returned
System.assert(result != null, 'The result should not be null');
System.assertEquals(1, result.size(), 'The result list should contain one item');
String cardNumber = result[0];
// Verify the format of the generated card number
System.assertEquals(19, cardNumber.length(), 'The generated card number should have 19 characters including spaces.');
// Check if spaces are at the correct positions
System.assertEquals(' ', cardNumber.substring(4, 5), 'There should be a space at position 4.');
System.assertEquals(' ', cardNumber.substring(9, 10), 'There should be a space at position 9.');
System.assertEquals(' ', cardNumber.substring(14, 15), 'There should be a space at position 14.');
// Check that only digits or spaces are present
for (Integer i = 0; i < cardNumber.length(); i++) {
if (i == 4 || i == 9 || i == 14) {
System.assertEquals(' ', cardNumber.substring(i, i + 1), 'There should be a space at positions 4, 9, 14.');
} else {
// Verify each character is a digit
String charAtPosition = cardNumber.substring(i, i + 1);
System.assert(charAtPosition >= '0' && charAtPosition <= '9', 'Only digits should be present except at positions 4, 9, 14.');
}
}
}
}