Isses with assigning tasks created by rest api
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-26-2024 01:24 AM
I have the following rest api, but whatever I try i can't make it work in a way that task[sc_Task] records would be actually assigned to the corresponsive request item. could you help me?
// This function handles the incoming REST API request
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
try {
// Check if debug mode is enabled
var debug = gs.getProperty('enable.integration.debug.message', true); // Enable or Disable Debug statement in system Log
// Log processing message if debug mode is enabled
if (debug) {
gs.info('Tester Processing incoming integration message...');
}
// Extract request body from the incoming request
var requestBody = request.body.data;
// Check if request body is empty
if (!requestBody) {
throw new Error('Tester Request body is empty.');
}
// Extract JSON data from the request body
var json = requestBody;
// Check if JSON data contains the necessary structure
if (!json || !json.Rows || !Array.isArray(json.Rows)) {
throw new Error('Tester Invalid JSON structure. Expected "Rows" array.');
}
// Check for required fields in the header
var missingFields = [];
if (!json.Header || !json.Header.TransactionID) missingFields.push('TransactionID');
if (!json.Header || !json.Header.CurrencyCode) missingFields.push('CurrencyCode');
if (!json.Header || !json.Header.CustomerPurchaser) missingFields.push('CustomerPurchaser');
if (!json.Header || !json.Header.CustomerReference) missingFields.push('CustomerReference');
if (!json.Header || !json.Header.ShipTo || !json.Header.ShipTo.ID) missingFields.push('ShipTo.ID');
if (!json.Header || !json.Header.BillTo || !json.Header.BillTo.ID) missingFields.push('BillTo.ID');
// If any required fields are missing, throw an error
if (missingFields.length > 0) {
throw new Error('Tester Missing required fields in the header: ' + missingFields.join(', '));
}
// Process the JSON data to create request items and tasks
var requestNumber = processJson(json);
// Return success response along with the newly created request number
return {
"status": "success",
"message": "Request items and tasks created successfully.",
"request_number": requestNumber
};
} catch (ex) {
// Log error if an exception occurs during processing
gs.error('Tester Error processing integration message: ' + ex.message);
// Return error response with error message
return {
"status": "error",
"message": 'Tester ' + ex.message
};
}
})(request, response);
// Function to process JSON data and create request items and tasks
function processJson(json) {
try {
// Define catalog item sys_id
var catalogItem = 'sys_id_if_cat_item'; // catalog item sys_id
// Generate a cart ID
var cartId = GlideGuid.generate(null);
// Create a new cart object with the generated cart ID
var cart = new Cart(cartId);
// Extract buyer information from the JSON header
var buyer = json.Header.CustomerPurchaser;
var soldTo = json.Header.SoldTo;
var buyerInfo = JSON.stringify(soldTo); // Convert soldTo object to a JSON string
cart.setVariable(buyerInfo, 'buyerInfo', soldTo);
// Iterate over each row in the JSON data
for (var i = 0; i < json.Rows.length; i++) {
var row = json.Rows[i];
// Log the processing of each row
gs.info('Tester Processing row ' + (i + 1) + ': ' + JSON.stringify(row));
// Add item to the cart
var item = cart.addItem(catalogItem, 1);
// Set variables for the item in the cart
cart.setVariable(item, 'CustomerLineNumber', row.CustomerLineNumber);
cart.setVariable(item, 'SKU', row.SKU);
cart.setVariable(item, 'Description', row.Description);
// Set other variables as needed
// Set the "note" variable with corresponding row information
var note = 'Row ' + (i + 1) + ': ' + JSON.stringify(row);
note = note.replace(/,/g, '\n').replace(/: {"/g, ':\n{').replace(/"/g, '').replace(/{|}/g, ''); // Replace commas with line breaks, ': {"' with a line break, and remove double quotes and curly braces
cart.setVariable(item, 'note', note);
// Create a task for the request item
var task = new GlideRecord('sc_task');
task.initialize();
task.short_description = 'Hardware Delivery';
task.assignment_group = 'sys_id_of group';
//task.request_item.setDisplayValue(item);
task.description = note;
task.priority = 3;
task.insert();
// Check if the row contains IMACD and create tasks accordingly
if (row.IMACD && Array.isArray(row.IMACD)) {
for (var j = 0; j < row.IMACD.length; j++) {
var imacd = row.IMACD[j];
var imacdTask = new GlideRecord('sc_task');
imacdTask.initialize();
imacdTask.short_description = imacd.Operation;
imacdTask.description = JSON.stringify(imacd);
//imacdTask.request_item.setDisplayValue(item);
imacdTask.priority = 3;
imacdTask.insert();
}
}
}
// Run additional code after main processing
runAssociateTask();
// Set the "buyer" and "buyer_info" variables for the cart
cart.setVariable('buyer', buyer);
cart.setVariable('buyer_info', buyerInfo);
// Place the order and get the response
var rc = cart.placeOrder();
// Log request number if order placement is successful
if (rc && rc.number) {
gs.info('Tester Request Number is: ' + rc.number);
//--------------------------
// Update the description field of the newly created sc_request record
var requestGr = new GlideRecord('sc_request');
if (requestGr.get('number', rc.number)) {
requestGr.description = JSON.stringify(json);
requestGr.update();
gs.info('Tester Updated sc_request record with new description.');
} else {
gs.error('Tester No sc_request record found for request number ' + rc.number);
}
//--------------------------
return rc.number;
} else {
// Log error message if order placement fails
var errorMsg = 'Tester Failed to retrieve request number.';
if (rc && rc.error_message) {
errorMsg += ' ' + rc.error_message;
}
gs.error(errorMsg);
gs.error('Tester Cart details: ' + JSON.stringify(cart)); // Log cart details for debugging
return '';
}
} catch (ex) {
// Log error if an exception occurs during processing JSON data
gs.error('Tester Error processing JSON data: ' + ex.message);
throw new Error('Error processing JSON data: ' + ex.message);
}
}
// Function to associate created tasks
function runAssociateTask() {
var assignTask = new GlideRecord('sc_task');
assignTask.addEncodedQuery('short_description=Hardware Delivery^request_item=NULL^assignment_group=34ccc608db08ca107f710578f496190b');
assignTask.query();
while (assignTask.next()) {
var assignTaskDescription = assignTask.description;
var findReqItem = new GlideRecord('sc_req_item');
findReqItem.addEncodedQuery('variables.c9734b2047eb31503553cd84f26d4380LIKE' + assignTaskDescription);
findReqItem.query();
while (findReqItem.next()) {
assignTask.request_item = findReqItem.number;
gs.info(assignTask.number + " " + findReqItem.number);
assignTask.update();
}
}
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-26-2024 01:43 AM
Hi @Wasd123,
So you are trying to create and relate the Catalog Tasks to the Requested Item within the script?
I think you should create a Flow/Workflow for your catalog time and generate the SCTASKs from there.
Cheers
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-26-2024 06:16 AM - edited ‎02-26-2024 06:17 AM
sure, but I may ened only 1 catalog task to be generated or I may need 10 or 50. that depends on the incoming message (json), and because of that it seems much easier to generate the tasks here. As the loop in the script works perfectly, but "only" got issues with assigning the request items to the tasks.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-26-2024 10:53 AM
I would still recommend creating only the Request/RITM via REST API and using its workflow to create the subsequent Catalog tasks. If not, you might run into issues where Request/RITM are not closed properly, it's more difficult to maintain, and not scalable (e.g. you can't add approval in the future).
But if you insist on using the method above, you might be able to query the RITM using the Request. Something like below;
var rc = cart.placeOrder();
var ritmGr = new GlideRecord('sc_req_item');
ritmGr.get('request', rc); //assuming there will only be one RITM in the Request
if(ritmGr.isValidRecord()){
//use the ritmGr value to set SCTASK's value
}
Cheers
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-26-2024 12:58 PM
yep that is the issue, as it will always generate a single request, and based on the content o the message it generates x amount of request items which ones are assigned to the request record and y amount of tasks what depends again on the content. everything is being generated correctly when it comes to the amount, but can;t link the tasks to the items.