Below is a getAllSubCustomers function designed to retrieve every sub-customer ID associated with a given parent customer ID. This function uses a queue-based method to explore each parent’s sub-customers recursively until all are found. Here’s the script in detail:
function getAllSubCustomers(clubCustomer) {
// Array to store subcustomer IDs
let allSubCustomerIds = [];
// Initial search queue for processing
let queue = [clubCustomer];
// Loop through the queue and fetch subcustomers for each parent
while (queue.length > 0) {
let parentCustomerId = queue.pop();
// Search for active subcustomers for the parent
let customerSearch = search.create({
type: search.Type.CUSTOMER,
filters: [
["parent", "anyof", parentCustomerId],
"AND",
["isinactive", "is", "F"],
],
columns: [search.createColumn({ name: "internalid" })],
});
// Run the search and process each result
customerSearch.run().each(function (result) {
let subCustomerId = result.getValue({ name: "internalid" });
// If subcustomer not already added, add to the array and queue
if (subCustomerId && !allSubCustomerIds.includes(subCustomerId)) {
allSubCustomerIds.push(subCustomerId);
queue.push(subCustomerId); // Add to queue for further processing
}
return true; // Continue to next result
});
}
// Remove clubCustomer from the result array if it somehow got included
allSubCustomerIds = allSubCustomerIds.filter(id => id !== clubCustomer);
return allSubCustomerIds;
}