Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********************************************************************************
- Copyright 2016 Lexmark International, Inc. All Rights Reserved.
- Reproduction and distribution of the contents of this work are prohibited without express and prior
- written consent of Lexmark International. Use of this work without an active iScript license is prohibited.
- Name: SendEmailWorkflow.js
- Author: Lexmark International, Inc
- Created: 02/12/2014-RG
- Last Updated: 02/15/2017-JJM
- For Version: 6.7+, 7.x
- Script Version: $Id$
- --------------------------------------------------------------------------------
- Summary:
- - This script is designed to be used in multiple workflow queues and send an email when a workflow object enters a queue.
- - Each queue is defined in a single JSON file.
- - The config file (SendEmailWorkflow_config.js) is designed to support the following:
- NOTE: each of the settings below are 'per queue' and can be different per queue
- ------------------------------------------------------------------------
- - HTML emails or ASCII text emails (true/false; not case sensitive)
- - Attachments or no attachment (true/false; not case sensitive)
- - email address can be a LITERAL, custom property value, or an ImageNow index value
- (LITERAL VALUES: field1, field2, field3, field4, field5)
- - emailFrom is a literal and can be unique per queue
- - Error queue workflow can be turned on or off (leave blank to turn off)
- - Success queue workflow can be turned on or off (leave blank to turn off)
- - emailSubject and emailBody can include parameters to be populated from a document
- or workflow property. See the emailTextToReplace configuration. Does not support
- composite custom properties.
- - emailBody
- - The customer can use the same script in multiple queues or a single queue.
- Mod Summary:
- 02/12/2014-RKG: First version.
- 10/22/2014-ADD: Added ATTACHMENT_PAGE_NUM to QUEUE.
- 11/21/2014-EDW: Added option to send to all users on a queue.
- 06/09/2015-KBO: Added ability to use index keys and custom properties as parameters
- in the email subject and body.
- 10/02/2015-KW: Updated copyright
- 12/31/2015-EDW: Converted config file to JSON config, now using getValueFromComplexArray, supports
- multiple to address types.
- 01/28/2016-WMT: Updated iScriptDebug and added stats object
- 05/12/2016-EDW: Updated script to do eForm value extraction (no line items), and support for full dry run
- mode.
- 01/04/2017-MFC: Addition of getINEmailAddressForUser STL function to use as a massage func when the
- doc contains only a username value
- 01/25/2017-WJF: Exposed useCDO & useUtility options for email config - Defaults to useCDO
- 02/15/2017-JJM: Updated to pass any parameter to iEmail configuration and allow for any emailConfig
- parameter to use a complex array configuration.
- Business Use:
- This script is designed to be run as inbound on a workflow queue.
- Installation Instructions :
- All configuration options can be found in the JSON configuration file whose path can be configured
- in the #includes. It is (by default) located in inserver6\etc\config\SendEmailWorkflow_config.js.
- *************************************************************************/
- // ********************* Include additional libraries *******************
- //Linked Libraries
- #link "inxml" //XML parser
- #link "secomobj" //COM object
- #if defined(imagenowDir6)
- // 6.7.0.2717+, including Active-Active support
- #include "$IMAGENOWDIR6$/script/STL/packages/Date/convertToDateStr.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Date/convertToDateObj.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Document/exportDocPhsOb.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Document/isValidIndexKey.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Document/setDocNotes.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Email/iEmail.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/File/doesFileExist.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Form/FormManager.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Logging/iScriptDebug.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Logging/StatsObject.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Object/getValueFromComplexArray.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Object/hashKeysToUpperCase.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Properties/PropertyManager.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/String/escapeForRegExp.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/User/getEmailsFromUsers.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/User/getINEmailAddressForUser.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Workflow/createOrRouteItem.js"
- #include "$IMAGENOWDIR6$/script/STL/packages/Workflow/routeItem.js"
- #include "$IMAGENOWDIR6$/script/SendEmailWorkflow_config.js" // <-- path to config file
- #else
- // pre-6.7.0.2717, no Active-Active support
- #include "../script/STL/packages/Date/convertToDateStr.js"
- #include "../script/STL/packages/Date/convertToDateObj.js"
- #include "../script/STL/packages/Document/exportDocPhsOb.js"
- #include "../script/STL/packages/Document/isValidIndexKey.js"
- #include "../script/STL/packages/Document/setDocNotes.js"
- #include "../script/STL/packages/Email/iEmail.js"
- #include "../script/STL/packages/File/doesFileExist.js"
- #include "../script/STL/packages/Form/FormManager.js"
- #include "../script/STL/packages/Logging/iScriptDebug.js"
- #include "../script/STL/packages/Logging/StatsObject.js"
- #include "../script/STL/packages/Object/getValueFromComplexArray.js"
- #include "../script/STL/packages/Object/hashKeysToUpperCase.js"
- #include "../script/STL/packages/Properties/PropertyManager.js"
- #include "../script/STL/packages/String/escapeForRegExp.js"
- #include "../script/STL/packages/User/getEmailsFromUsers.js"
- #include "../script/STL/packages/User/getINEmailAddressForUser.js"
- #include "../script/STL/packages/Workflow/createOrRouteItem.js"
- #include "../script/STL/packages/Workflow/routeItem.js"
- #include "../script/SendEmailWorkflow_config.js" // <-- path to config file
- #endif
- // ********************* Configuration **************************
- var CONFIG_VERIFIED = true; // set to true when configuration values have been verified
- //Document Error Notes Mode
- var RESET_DOC_NOTES = false; // true - reset document notes on success, false - do nothing
- var DOC_NOTE_MODE = -1; // -1=Do Nothing, 0=overwrite, 1=append, 2=prepend
- // Logging
- var LOG_TO_FILE = true; // false - log to stdout if ran by intool, true - log to inserverXX/log/ directory
- var DEBUG_LEVEL = 5; // 0 - 5. 0 least output, 5 most verbose
- var SPLIT_LOG_BY_THREAD = false; // set to true in high volume scripts when multiple worker threads are used (workflow, external message agent, etc)
- var MAX_LOG_FILE_SIZE = 100; // Maximum size of log file (in MB) before a new one will be created
- var DRY_RUN = true; //If true, the script will simulate the script execution without making any updates
- var UNDEFINED_VALUE = "[undefined]"; // default value used in email subject or body when parameter cannot be populated.
- // ********************* End Configuration *******************
- // ********************* Initialize global variables ********************
- var EXECUTION_METHODS = ["WORKFLOW"]; //Allowed script execution methods: WORKFLOW, INTOOL, TASK, EFORM, EMA
- var DOC_NOTE_DELIMITER = "\n";
- var debug, stats, formData, form = false;
- /** ****************************************************************************
- * Main body of script.
- *
- * @param {none} None
- * @returns {void} None
- *****************************************************************************/
- function main ()
- {
- try
- {
- // Logging and verification
- debug = new iScriptDebug("USE SCRIPT FILE NAME", LOG_TO_FILE, DEBUG_LEVEL, undefined, {splitLogByThreadID:SPLIT_LOG_BY_THREAD, maxLogFileSize:MAX_LOG_FILE_SIZE});
- debug.showINowInfo("INFO");
- debug.logAlways("INFO", "Script Version: $Id$\n");
- debug.logAlways("INFO", "Script Name: %s\n", _argv[0]);
- stats = new StatsObject();
- if (!CONFIG_VERIFIED)
- {
- var errorStr = "\nConfiguration not verified. Please verify \n" +
- "the defines in the *** Configuration *** section at the top \n" +
- "of this script and set CONFIG_VERIFIED to true. Aborting.\n\n";
- debug.log('CRITICAL', errorStr);
- printf(errorStr);
- return false;
- }
- // Check script execution
- if (!debug.checkExecution(EXECUTION_METHODS))
- {
- debug.log('CRITICAL', "This iScript is running as [%s] and is designed to run from [%s]\n", debug.getExecutionMethod(), EXECUTION_METHODS);
- return false;
- }
- if(DRY_RUN)
- {
- debug.logAlways("INFO", "**************** DRY RUN MODE ****************\n");
- }
- var wfItem = new INWfItem(currentWfItem.id);
- if(!wfItem.id || !wfItem.getInfo())
- {
- debug.log('ERROR', "Couldn't get wfItem info [%s]: [%s]\n", currentWfItem.id, getErrMsg());
- return false;
- }
- hashKeysToUpperCase(EMAIL_CONFIG);
- var currentQueueToUpper = ToString(wfItem.queueName).toUpperCase(), curCfg = false;
- if(!(currentQueueToUpper in EMAIL_CONFIG))
- {
- debug.log('ERROR', "Queue [%s] does not exist in config; sending to error queue.\n", wfItem.queueName);
- routeToQueue(wfItem, ERROR_QUEUE, "", Clib.rsprintf("Queue [%s] is not set up for email functionality; check XML file", wfItem.queueName));
- return false;
- }
- else
- {
- debug.log("DEBUG", "Current Queue for configuration: [%s]\n", wfItem.queueName);
- curCfg = EMAIL_CONFIG[currentQueueToUpper];
- }
- if (wfItem.type !== WfItemType.Document)
- {
- debug.log("CRITICAL", "This script is designed to process document items of type [%s], received type [%s], item id [%s]\n", WfItemType.Document, wfItem.type, wfItem.id);
- routeToQueue(wfItem, curCfg.queueError, "", "This is not a document");
- return false;
- }
- var wfDoc = new INDocument(wfItem.objectId);
- if(!wfDoc.id || !wfDoc.getInfo())
- {
- debug.log('ERROR', "Couldn't get doc info [%s]: [%s]\n", wfItem.objectId, getErrMsg());
- routeToQueue(wfItem, curCfg.queueError, "", "Form data requested but no form name provided");
- return false;
- }
- debug.log("INFO","Processing document [%s] (Item id: [%s])\n", wfDoc, wfItem.id);
- if(RESET_DOC_NOTES) updateDocNotes(wfDoc, "");
- if(!curCfg.emailConfig)
- {
- debug.log("ERROR", "No emailConfig in the configuration for queue [%s]\n", wfItem.queueName);
- updateDocNotes(wfDoc, Clib.rsprintf("ERROR: No emailConfig in the configuration for queue [%s]", wfItem.queueName));
- routeToQueue(wfItem, curCfg.queueError, "", "No emailConfig in the configuration for queue [" + wfItem.queueName + "]");
- return false;
- }
- var emailReplacementText = new Array();
- if(curCfg.emailTextToReplace)
- {
- for(var pattern in curCfg.emailTextToReplace)
- {
- var currentProp = curCfg.emailTextToReplace[pattern];
- if(!currentProp) continue;
- if(typeof(currentProp) == "boolean")
- {
- currentProp = ToString(currentProp);
- }
- var currentVal = getComplexValue(currentProp, pattern, wfDoc, wfItem, curCfg);
- if(currentVal === false)
- {
- debug.log("ERROR", "Failed to get data for property [%s]\n", pattern);
- updateDocNotes(wfDoc, Clib.rsprintf("ERROR: Failed to get data for property [%s]. Please refer to the log file for further details\n", pattern));
- routeToQueue(wfItem, curCfg.queueError, "", Clib.rsprintf("Failed to get data for property [%s]\n", pattern));
- return false;
- }
- if(UNDEFINED_VALUE && currentVal == "")
- {
- currentVal = UNDEFINED_VALUE;
- }
- var safePattern = new RegExp(escapeForRegExp(pattern), 'ig');
- emailReplacementText.push({regex: safePattern, value: ToString(currentVal)});
- }
- }
- var emailConfig = new Object();
- for(var emailProperty in curCfg.emailConfig)
- {
- var currentEmailPropertyValue = curCfg.emailConfig[emailProperty];
- if(currentEmailPropertyValue === undefined) continue;
- var arrayEmailPropertyValues = new Array();
- if(!(currentEmailPropertyValue instanceof Array)) currentEmailPropertyValue = [currentEmailPropertyValue];
- for(var i = 0; i < currentEmailPropertyValue.length; i++)
- {
- if(currentEmailPropertyValue[i] === undefined) continue;
- var arrayEmailPropertyValue = currentEmailPropertyValue[i];
- if(typeof(currentEmailPropertyValue[i]) !== "boolean")
- {
- arrayEmailPropertyValue = getComplexValue(currentEmailPropertyValue[i], emailProperty, wfDoc, wfItem, curCfg);
- if(arrayEmailPropertyValue === false)
- {
- //Logging and routing handled in the getComplexValue function
- return false;
- }
- }
- arrayEmailPropertyValues.push(arrayEmailPropertyValue);
- }
- var useEmailPropertyValue = (arrayEmailPropertyValues.length > 1) ? arrayEmailPropertyValues.join(",") : arrayEmailPropertyValues[0];
- if(typeof(useEmailPropertyValue) == "string" && useEmailPropertyValue)
- {
- debug.log("DEBUG", "Before replacement: [%s] => [%s]\n", emailProperty, useEmailPropertyValue);
- for(var r=0; r<emailReplacementText.length; r++)
- {
- useEmailPropertyValue = useEmailPropertyValue.replace(emailReplacementText[r].regex, emailReplacementText[r].value);
- }
- //debug.log("DEBUG", "After replacement: [%s] => [%s]\n", emailProperty, useEmailPropertyValue);
- }
- emailConfig[emailProperty] = useEmailPropertyValue;
- }
- //debug.logObject("DEBUG", emailConfig, 10, "-- emailConfig --");
- if(!emailConfig.to)
- {
- debug.log("ERROR", "Missing the TO email address.\n");
- updateDocNotes(wfDoc, "ERROR: Missing the TO email address.");
- routeToQueue(wfItem, curCfg.queueError, "", "Missing the TO email address");
- return false;
- }
- var attachmentPageNo = curCfg.attachmentPageNum != undefined ? curCfg.attachmentPageNum.toUpperCase() : "";
- var attachmentFlag = (attachmentPageNo && attachmentPageNo !== "NONE");
- if(attachmentFlag && !emailConfig.useUtility && !emailConfig.useCDO && !emailConfig.UnixSendmail)
- {
- debug.log("ERROR", "The configuration has attachments enabled (i.e. attachmentPageNum is not \"NONE\"), but the emailConfig needs to enable useUtility, useCDO or UnixSendmail in order to send attachments\n");
- updateDocNotes(wfDoc, "ERROR: The configuration has attachments enabled (i.e. attachmentPageNum is not \"NONE\"), but the emailConfig needs to enable useUtility, useCDO or UnixSendmail in order to send attachments");
- routeToQueue(wfItem, curCfg.queueError, "", "The configuration has attachments enabled but emailConfig does not");
- return false;
- }
- var pagesToattach = false;
- var emailToArr = (curCfg.emailSplit) ? ToString(emailConfig.to).split(",") : [emailConfig.to];
- for(var m = 0; m < emailToArr.length; m++)
- {
- debug.setIndent(0);
- debug.log("INFO", "Processing email [%s/%s] [%s]...\n", (m+1), emailToArr.length, emailToArr[m]);
- debug.setIndent(1);
- emailConfig.to = emailToArr[m]; //Update to the individual/group email address
- var email = new iEmail("", emailConfig);
- // Only add attachments to the email, if the HTML_FLAG is true AND the ATTACHMENT_FLAG is true
- if (attachmentFlag)
- {
- if(!pagesToattach)
- {
- var pagesToExport = attachmentPageNo ? attachmentPageNo : "ALL";
- if (pagesToExport != "LAST" && pagesToExport != "ALL")
- {
- pagesToExport = ToNumber(pagesToExport);
- if (isNaN(pagesToExport))
- {
- debug.log("ERROR", "[%s] is not a valid page number.\n", curCfg.attachmentPageNum);
- updateDocNotes(wfDoc, "ERROR: The attachmentPageNum is configured to an invalid page number for queue [" + wfItem.queueName + "]. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "attachmentPageNum is configured to an invalid page number");
- return false;
- }
- }
- pagesToattach = exportDocPhsOb(wfDoc, curCfg.attachmentTempDir, pagesToExport, "", true);
- if(!pagesToattach || pagesToattach.length == 0)
- {
- debug.log("ERROR", "Failed to export document to attach to email\n");
- updateDocNotes(wfDoc, "ERROR: Failed to export document to attach to email. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to export document to attach to email");
- return false;
- }
- if(!(pagesToattach instanceof Array)) pagesToattach = [pagesToattach];
- }
- //ADD ATTACHMENTS TO THE EMAIL
- for(var f = 0; f < pagesToattach.length; f++)
- {
- debug.log("DEBUG", "Adding attachment [%s]\n", pagesToattach[f]);
- email.addAttachment(pagesToattach[f]);
- }
- }
- // Send email
- if(!DRY_RUN)
- {
- if (!email.send())
- {
- debug.log("ERROR","Failed to send email. Error: [%s]\n", email.error);
- updateDocNotes(wfDoc, "ERROR: Failed to send email. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to send email");
- return false;
- }
- else
- {
- debug.log("INFO", "Sent email notification to: [%s]\n", email.to);
- }
- }
- else
- {
- debug.log("INFO", "Would have sent email to [%s]\n", email.to);
- //debug.logObject("INFO", emailConfig, 5, "Would send email");
- }
- }
- debug.setIndent(0);
- debug.log("NOTIFY","Email(s) sent successfully\n");
- if(RESET_DOC_NOTES) updateDocNotes(wfDoc, "");
- routeToQueue(wfItem, curCfg.queueSuccess, curCfg.queueError, "Emails sent");
- }
- catch(e)
- {
- if (!debug)
- {
- printf("\n\nFATAL iSCRIPT ERROR: %s\n\n", e.toString());
- }
- else
- {
- debug.setIndent(0);
- debug.log("CRITICAL", "***********************************************\n");
- debug.log("CRITICAL", "***********************************************\n");
- debug.log("CRITICAL", "** **\n");
- debug.log("CRITICAL", "** *** Fatal iScript Error! *** **\n");
- debug.log("CRITICAL", "** **\n");
- debug.log("CRITICAL", "***********************************************\n");
- debug.log("CRITICAL", "***********************************************\n");
- debug.log("CRITICAL", "\n\n\n%s\n\n\n", e.toString());
- debug.log("CRITICAL", "\n\nThis script has failed in an unexpected way. Please\ncontact Lexmark Enterprise Software Customer Support at 800-941-7460 ext. 2\nAlternatively, you may wish to email es_support@lexmark.com\nPlease attach:\n - This log file\n - The associated script [%s]\n - Any supporting files that might be specific to this script\n\n", _argv[0]);
- debug.log("CRITICAL", "***********************************************\n");
- debug.log("CRITICAL", "***********************************************\n");
- if (DEBUG_LEVEL < 3 && typeof(debug.getLogHistory) === "function")
- {
- debug.popLogHistory(11);
- debug.log("CRITICAL", "Log History:\n\n%s\n\n", debug.getLogHistory());
- }
- if(typeof(wfDoc) != "undefined" && wfDoc)
- {
- updateDocNotes(wfDoc, "ERROR: Fatal iScript Error. Please refer to the log file for further details");
- }
- //Fatal error routing
- if(typeof(wfItem) != "undefined" && wfItem && typeof(curCfg) != "undefined" && curCfg)
- {
- routeToQueue(wfItem, curCfg.queueError, "", "Fatal iScript Error");
- }
- }
- }
- finally
- {
- if (debug) debug.setIndent(0);
- if(typeof(pagesToattach) != "undefined" && pagesToattach)
- {
- //clean up temp directory (if needed)
- if(!(pagesToattach instanceof Array)) pagesToattach = [pagesToattach];
- for(var rf = 0; rf < pagesToattach.length; rf++)
- {
- debug.log("DEBUG", "Deleting file [%s/%s] [%s]\n", (rf+1), pagesToattach.length, pagesToattach[rf]);
- if(Clib.remove(pagesToattach[rf]) != 0)
- {
- debug.log("WARNING", "Error deleting file [%s]: [%s]\n", pagesToattach[rf], Clib.strerror(Clib.errno));
- }
- }
- }
- if (typeof(stats) == "object" && stats)
- {
- if (stats.isEmpty()) stats.inc("Stats successfully generated.");
- if (debug) debug.logAlways("NOTIFY", "Done:\n\n%s\n", stats.getSortedStats());
- else printf("Done:\n\n%s\n", stats.getSortedStats());
- }
- if (debug && (typeof(debug.finish) === "function"))
- {
- debug.finish();
- }
- }
- }
- // ********************* Function Definitions **********************************
- /**
- * The function will convert a date string to a different date format in a complex array
- *
- * @param {String} date - date to format
- * @param {Object} fieldMap - current field map
- * @return {String} formatted date
- */
- function convertToDateStrUsingComplexArray(date, fieldMap)
- {
- //debug.log("DEBUG", "convertToDateStrUsingCA: Date [%s]\n", date);
- if(!date) return ""; //No need to convert blank string
- var newDate;
- if(typeof(date) == "number")
- {
- newDate = new Date(date * 1000);
- }
- else
- {
- newDate = convertToDateObj(date, oFieldMap);
- if(newDate === false)
- {
- //Logging in the convertToDateObj function
- return false;
- }
- }
- return (newDate) ? convertToDateStr(newDate, oFieldMap.format) : "";
- }
- /**
- * Gets all the complex value for the given property configuration
- *
- * @method getEmailsFromQueue
- * @param {String} queue Queue name to get users from.
- * @return {String/Boolean} List of email addresses joined by a ',' on success, false on error.
- */
- function getComplexValue(currentPropCfg, property, wfDoc, wfItem, curCfg)
- {
- var currentVal = undefined;
- if(currentPropCfg && currentPropCfg instanceof Array)
- {
- //Check if their are any nested arrays
- var arrayValues = new Array();
- for (var ai=0; ai<currentPropCfg.length; ai++)
- {
- var arrayValue = getComplexValue(currentPropCfg[ai], property, wfDoc, wfItem, curCfg);
- if(arrayValue === false)
- {
- debug.log("ERROR", "getComplexValue: Failed to get array data for property [%s]\n", property);
- updateDocNotes(wfDoc, "ERROR: The script failed to get array data for property [" + property + "]. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to get array data for property "+property);
- return false;
- }
- arrayValues.push(arrayValue);
- }
- currentVal = (arrayValues.length > 1) ? arrayValues.join(",") : arrayValues[0];
- }
- else if(currentPropCfg && currentPropCfg.type !== undefined && currentPropCfg.source !== undefined)
- {
- //Check for a complex array configuration
- var newComplexArrayCfg = currentPropCfg;
- switch(currentPropCfg.type)
- {
- case "COMPLEX":
- var complexValues = new Array();
- for (var ci=0; ci<currentPropCfg.source.length; ci++)
- {
- var complexValue = getComplexValue(currentPropCfg.source[ci], property, wfDoc, wfItem, curCfg);
- if(complexValue === false)
- {
- debug.log("ERROR", "getComplexValue: Failed to get complex data for property [%s]\n", property);
- updateDocNotes(wfDoc, "ERROR: The script failed to get complex data for property [" + property + "]. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to get complex data for property "+property);
- return false;
- }
- complexValues.push(complexValue);
- }
- currentVal = (complexValues.length > 1) ? complexValues.join("") : complexValues[0];
- break;
- case "DICTIONARY":
- case "FORM":
- if(!form)
- {
- //Initialize the form data for the first time (if needed)
- if(!curCfg.formName)
- {
- debug.logln("ERROR","getComplexValue: Form data requested but no form name provided.");
- updateDocNotes(wfDoc, "ERROR: No form name configured and form data required");
- routeToQueue(wfItem, curCfg.queueError, "", "No form name configured and form data required.");
- return false;
- }
- else if(form === false)
- {
- form = new FormManager(curCfg.formName);
- if(!form || form.error)
- {
- debug.log("ERROR","getComplexValue: Failed to initialize FormManager for Form %s\n",curCfg.formName);
- updateDocNotes(wfDoc, "ERROR: Failed to find form [" + curCfg.formName + "]. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to initialize FormManager for Form " + curCfg.formName);
- return false;
- }
- }
- }
- if(!formData) formData = new Object();
- if(!formData[currentPropCfg.source])
- {
- var formFieldData = form.getDataFromForm(wfDoc, [currentPropCfg.source]);
- if(!formFieldData)
- {
- debug.log("ERROR","getComplexValue: Failed to get form data for node [%s]\n", currentPropCfg.source);
- updateDocNotes(wfDoc, "ERROR: The script failed to get form data for node [" + currentPropCfg.source + "]. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to get data from form for node [" + currentPropCfg.source + "]");
- return false;
- }
- formData[currentPropCfg.source] = formFieldData[currentPropCfg.source];
- }
- break;
- case "DOCUMENT_PROPERTY":
- if(currentPropCfg.source === "NOTES")
- {
- //Pass value to complex array in order to fulfill any additional properties (i.e. func, required)
- newComplexArrayCfg.type = "LITERAL";
- newComplexArrayCfg.source = wfDoc.getNotes();
- }
- break;
- case "QUEUE":
- currentVal = getEmailsFromQueue(currentPropCfg.source);
- //Pass value to complex array in order to fulfill any additional properties (i.e. func, required)
- newComplexArrayCfg.type = "LITERAL";
- newComplexArrayCfg.source = currentVal;
- break;
- }
- currentVal = getValueFromComplexArray(newComplexArrayCfg, wfDoc, wfItem, false, false, formData);
- if(currentVal === false)
- {
- debug.log("ERROR", "getComplexValue: Failed to get data for property [%s]\n", property);
- updateDocNotes(wfDoc, "ERROR: The script failed to get data for property [" + property + "]. Please refer to the log file for further details");
- routeToQueue(wfItem, curCfg.queueError, "", "Failed to get data for property "+property);
- return false;
- }
- }
- else
- {
- currentVal = currentPropCfg;
- }
- //debug.log("DEBUG", "getComplexValue: Returning [%s] (%s)\n", currentVal, typeof(currentVal));
- return currentVal;
- }
- /**
- * <div class="rev">$</div>
- * Gets all the email addresses for users with permissions on the passed in queue.
- * @requires routeItem, getEmailsFromUsers
- */
- /**
- * Gets all the email addresses for users with permissions on the passed in queue.
- * @method getEmailsFromQueue
- * @param {String} queueName Queue name to get users from.
- * @return {String/Boolean} List of email addresses joined by a ',' on success, false on error.
- */
- function getEmailsFromQueue(queueName)
- {
- debug.log("DEBUG", "getEmailsFromQueue: using queue name: %s\n", queueName);
- var queue = new INWfQueue();
- queue.name = queueName;
- var userList = queue.getAccessUserList();
- if(!userList || userList.length < 1)
- {
- debug.log("INFO", "getEmailsFromQueue: Queue [%s] has no members\n", queueName);
- return ""; //empty string for no users
- }
- var userIDArr = [];
- for(var m = 0; m < userList.length; m++)
- {
- userIDArr.push(userList[m].userId);
- }
- var emailArr = getEmailsFromUsers(userIDArr);
- if(!emailArr)
- {
- debug.logln("ERROR", "getEmailsFromQueue: Failed to get emails from users on queue [%s]", queue);
- return false;
- }
- return emailArr.join(",");
- }
- /**
- * The function only sets document notes if a document is passed in
- * and a valid document notes mode is specified.
- *
- * @param {String} str String to escape
- * @return {String} Escaped string
- */
- function updateDocNotes(doc, note, docNoteMode, docNoteDelimiter)
- {
- if(doc && doc instanceof INDocument && DOC_NOTE_MODE >= 0)
- {
- docNoteMode = (docNoteMode!==undefined) ? docNoteMode : DOC_NOTE_MODE;
- docNoteDelimiter = (docNoteDelimiter!==undefined) ? docNoteDelimiter : DOC_NOTE_DELIMITER;
- if(DRY_RUN)
- {
- debug.log("INFO", "updateDocNotes: Would have set document notes with [%s] option [%s]\n", note, docNoteMode);
- }
- else
- {
- return setDocNotes(doc, note, docNoteMode, docNoteDelimiter);
- }
- }
- return true;
- }
- /**
- * route document/item to specified workflow queue
- *
- * @param {INDocument|INWfItem} itemOrDoc workflow item/document
- * @param {String} queueOrRoute - queue name to route to
- * @param {String} errorQueueOrRoute - error queue name to route to (if queueOrRouter route fails, blank if not needed)
- * @param {String} reason - reason to route item/document
- * @return {Boolean} true on success, false otherwise
- */
- function routeToQueue(itemOrDoc, queueOrRoute, errorQueueOrRoute, reason)
- {
- if(itemOrDoc && queueOrRoute && queueOrRoute != "")
- {
- var routeFunc;
- if(itemOrDoc instanceof INWfItem)
- {
- routeFunc = routeItem;
- }
- else
- {
- routeFunc = createOrRouteItem;
- }
- if(DRY_RUN)
- {
- debug.log("INFO", "routeToQueue: Would have routed document to [%s] queue\n", queueOrRoute);
- }
- else if(routeFunc(itemOrDoc, queueOrRoute, reason))
- {
- debug.log("INFO", "routeToQueue: Successfully routed document to [%s] queue\n", queueOrRoute);
- }
- else
- {
- debug.log("ERROR", "routeToQueue: Failed to route document to [%s] queue\n", queueOrRoute);
- if(itemOrDoc instanceof INDocument)
- {
- updateDocNotes(itemOrDoc, "ERROR: Failed to route document to [" + queueOrRoute + "] queue");
- }
- routeToQueue(itemOrDoc, errorQueueOrRoute, "", "Failed to route document to [" + queueOrRoute + "] queue");
- return false;
- }
- }
- return true;
- }
- // Required Comment - DO NOT REMOVE
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement