Auto creation- of project when demand is Completed

Aishwarya Pulas
Tera Contributor

Hi , 

So I have a requirement of auto creating a project from a demand when demand moves to Completed state. For now I am trying to replicate the Create Project UI action code into a BR or client script on demand form that triggers once demand moves to completed state , but no much success. 

Note: the Create Project UI action is present on create project related link on demand form 

Has any1 had the same requirement , or can guide me achieving this.Please consider that I am quite new to servicenow while answering.

 

2 REPLIES 2

Aishwarya Pulas
Tera Contributor

The UI action condition :

GlidePluginManager.isActive('com.snc.project_management_v3') && gs.hasRole('demand_manager') && (current.type == 'project' && current.project.nil())

 

UI Code :

var gDialog;

function convertDemandToProject() {
    if (g_form.modified) {
        return g_form.addErrorMessage(getMessage('You have not saved all your changes, save the demand record before creating project'));
    } if(g_form.getValue('type') == 'project'&& g_form.getElement("calculation_type") && !g_form.getValue('calculation_type')) {
        return g_form.addErrorMessage(getMessage('Please select a project calculation type under preferences.'));
    }
    var ga = new GlideAjax("AjaxCreateRelatedEntityFromDemand");
    ga.addParam("sysparm_name""checkPmoUpgrade");
    ga.addParam("sysparm_source_table", g_form.getTableName());
    ga.getXML(function(response) {
        var result = response.responseXML.getElementsByTagName("result");
        var isUpdrading = result[0].getAttribute("isUpgrading");
        var isProjectCurrencyEnabled = result[0].getAttribute("isProjectCurrencyEnabled");
        var isMoreThanOneProjectClassExists = result[0].getAttribute("isMultipleProjectClassExists");
        var defaultProjectTable = result[0].getAttribute("defaultProjectTable");
        if (isUpdrading === "true") {
            g_form.addErrorMessage(getMessage("Financial Planning Upgrade Job Running. Cannot create Project."));
        } else if (isProjectCurrencyEnabled == "true" || isMoreThanOneProjectClassExists == "true") {
            gDialog = new GlideModal('demand_to_project');
            gDialog.setPreference('sysparm_task_id', g_form.getUniqueValue());
            gDialog.setPreference('sysparm_projTable', defaultProjectTable);
            gDialog.setPreference('sysparm_isProjectCurrencyEnabled', isProjectCurrencyEnabled);
            gDialog.setPreference('sysparm_isMoreThanOneProjectTableExists', isMoreThanOneProjectClassExists);
            gDialog.setPreference('on_submit', onSubmit);
            gDialog.setPreference('on_cancel', onCancel);
            gDialog.setTitle(new GwtMessage().getMessage('Create project'));
            gDialog.render();
        } else
            onSubmit(defaultProjectTable);
    });
}
if (typeof window == 'undefined')
    redirect();

function redirect() {
    action.setRedirectURL(current);
}

function onCancel() {
    if (gDialog)
        gDialog.destroy();
    return false;
}

function onSubmit(projName) {
    var createProjectAjax = new GlideAjax("AjaxCreateRelatedEntityFromDemand");
    createProjectAjax.addParam("sysparm_name""createProjectAjax");
    createProjectAjax.addParam("sysparm_sys_id", g_form.getUniqueValue());
    createProjectAjax.addParam("sysparm_projName", projName);
    createProjectAjax.getXML();

    if (gDialog)
        gDialog.destroy();
    g_form.save();

    return false;
}
I have tried replicating it in After update Business Rule with conditions:
state changes to Completed 
Type is project 
Project field is empty 
role required: demand_manager
 
BR code :
(function executeRule(current, previous /*null when async*/) {
    var shouldContinue = true// Initialize a flag to control rule execution

    // Check if any update or insert operation was performed
    if (!current.update() && !current.insert()) {
        gs.addErrorMessage('You have not saved any changes. Save the demand record before creating a project.');
        shouldContinue = false// Set the flag to false to stop rule execution
    }

    // Check if the demand is of type 'project' and if 'calculation_type' is not selected
    if (current.type == 'project' && !current.calculation_type) {
        gs.addErrorMessage('Please select a project calculation type under preferences.');
        shouldContinue = false// Set the flag to false to stop rule execution
    }

    if (shouldContinue) {
        // Check for PMO upgrade and other conditions using GlideAjax
        var ga = new GlideAjax("AjaxCreateRelatedEntityFromDemand");
        ga.addParam("sysparm_name""checkPmoUpgrade");
        ga.addParam("sysparm_source_table", current.getTableName());
        ga.getXMLWait(); // Wait for the response

        var response = ga.getAnswer();
        var result = new XMLResponse(response).getRootElement();
        var isUpgrading = result.getAttribute("isUpgrading");
        var isProjectCurrencyEnabled = result.getAttribute("isProjectCurrencyEnabled");
        var isMoreThanOneProjectClassExists = result.getAttribute("isMultipleProjectClassExists");
        var defaultProjectTable = result.getAttribute("defaultProjectTable");

        if (isUpgrading === "true") {
            gs.addErrorMessage('Financial Planning Upgrade Job Running. Cannot create Project.');
        } else if (isProjectCurrencyEnabled == "true" || isMoreThanOneProjectClassExists == "true") {
            // At least show a message here
            gs.addInfoMessage('Not sure how to handle this');
        } else {
            // Handle the project creation logic here (similar to the onSubmit function).
            var createProjectAjax = new GlideAjax("AjaxCreateRelatedEntityFromDemand");
            createProjectAjax.addParam("sysparm_name""createProjectAjax");
            createProjectAjax.addParam("sysparm_sys_id", current.sys_id);
            createProjectAjax.addParam("sysparm_projName", defaultProjectTable);
            createProjectAjax.getXMLWait();

            // After the project creation is complete
            gs.addInfoMessage('Project created successfully.');
        }
    }
})(current, previous);

Aishwarya Pulas
Tera Contributor

This is the latest status , code: 

It directly gives me error{0} from the createProjectAjax function when I move demand to complete state (adding createProjectAjax function) at end 

(function executeRule(current, previous /*null when async*/) {

    gs.log("Business Rule Project creation triggerd");

    var shouldContinue = true// Initialize a flag to control rule execution

    // Check if any update or insert operation was performed
    if (!current.update() && !current.insert()) {
        gs.addErrorMessage('You have not saved any changes. Save the demand record before creating a project.');
        gs.log("Value of Should Continue1: " + shouldContinue);
        shouldContinue = false// Set the flag to false to stop rule execution
    }

    // Check if the demand is of type 'project' and if 'calculation_type' is not selected
    if (current.type == 'project' && !current.calculation_type) {
        gs.addErrorMessage('Please select a project calculation type under preferences.');
        gs.log("Value of Should Continue2: " + shouldContinue);
        shouldContinue = false// Set the flag to false to stop rule execution
    }

    if (shouldContinue) {
    gs.log("Value of Should Continue3: " + shouldContinue);

    // Create an instance of the script include
    var scriptInclude = new AjaxCreateRelatedEntityFromDemand();

    // Call the function to check PMO upgrade and other conditions
    var response = scriptInclude.checkPmoUpgrade();
    var isUpgrading = response.isUpgrading;
    var isProjectCurrencyEnabled = response.isProjectCurrencyEnabled;
    var isMoreThanOneProjectClassExists = response.isMultipleProjectClassExists;
    var defaultProjectTable = response.defaultProjectTable;

    if (isUpgrading === "true") {
        gs.addErrorMessage('Financial Planning Upgrade Job Running. Cannot create Project.');
    } else if (isProjectCurrencyEnabled == "true" || isMoreThanOneProjectClassExists == "true") {
        // At least show a message here
        gs.addInfoMessage('Not sure how to handle this');
    } else {
        // Handle the project creation logic here (similar to the onSubmit function).
        scriptInclude.createProjectAjax(current.sys_id, defaultProjectTable);
        
    }
}
})(current, previous);
 
 
 
 
createProjectAjax: function() {
            var sys_id = this.getParameter('sysparm_sys_id');
            var tablename = this.getParameter('sysparm_table_name');
            var projectTable = this.getParameter('sysparm_projName') || 'pm_project';
            var result = (new DemandToProjectCreationHelper()).createProject(sys_id, projectTable);

            var invst;
            if (new GlidePluginManager().isActive('com.snc.investment_funding')) {
                invst = new sn_invst_pln.InvstDemandConversion(this._getDemand(sys_id), this._getRecord(projectTable, result.sys_id));
                invst.updateExsistingInvestMentWhenDemandIsConverted();
            } else if (new GlidePluginManager().isActive('com.snc.investment_planning_pmo')) {
                invst = new InvstDemandConversion(this._getDemand(sys_id), this._getRecord(projectTable, result.sys_id));
                invst.updateExsistingInvestMentWhenDemandIsConverted();
            }
            //if(GlidePluginManager.isActive('com.snc.project_management_v3'))
            //  projectTable = SNC.PPMConfig.getProjectTable(tablename);
            var link = ' <a href ="/' + projectTable + '.do?sysparm_query=number%3D' + result.number + '">' + result.number + '</a>';
            var message;
            var prjGr = new GlideRecord(projectTable);
            if (result.sys_id && prjGr.get(result.sys_id)) {
                message = gs.getMessage("{0} {1} has been created.", [result.label, link]);
                gs.addInfoMessage(message);
            } else {
                message = gs.getMessage("Error creating {0}", result.label);
                gs.addErrorMessage(message);
            }
            return result.sys_id && prjGr.get(result.sys_id);
        },