Saturday, 1 August 2020

ButtonClick


// JavaScript source code

var Report = window.Report || {};

var users = [];

var emails = [];

 

Report.OnFinalizeButtonClick = function (primaryControl) {

    Xrm.Utility.showProgressIndicator("Performing action .......");

    var formContext = primaryControl;

    if (formContext !== null) {

        //// Get CE Plan ID

        var planID;

        var cePlan = formContext.getAttribute("Field_ceplan").getValue();    //Field

        if (cePlan !== null) {

            planID = cePlan[0].id;

        }

        //// Get All Notes For CE Plan

        Report.FetchAllNotes(formContext, planID, 0, formContext.data.entity.getId());

    }

};

 

Report.OnPingForCeNotes = function (primaryControl) {

    Xrm.Utility.showProgressIndicator("Performing action .......");

    var formContext = primaryControl;

    if (formContext !== null) {

        //// Get CE Plan ID

        var planID;

        var cePlan = formContext.getAttribute("Field_ceplan").getValue();    //Field Value

        if (cePlan !== null) {

            planID = cePlan[0].id;

        }

        //// Get All Notes For CE Plan

        Report.FetchAllNotes(formContext, planID, 1, formContext.data.entity.getId());

    }

};

 

Report.FormReadOnly = function (formContext) {

    if (formContext !== null) {

        formContext.data.entity.attributes.forEach(function (attribute, index) {

            var control = formContext.getControl(attribute.getName());

            if (control) {

                control.setDisabled(true);

            }

        });

        formContext.getAttribute("field_readonly").setValue(true); //FieldValue

        var id = "Notification";

        var message = "record is set to read only mode".toUpperCase();

        var level = "INFO";

        formContext.ui.setFormNotification(message, level, id);

        //// formContext.data.entity.save();

    }

};

 

Report.FetchAllNotes = function (formContext, cePlanId, checkCondition, recordId) {

    if (formContext !== null) {

        var usersWhoSentNotes = [];

        var req = new XMLHttpRequest();

        req.open("GET", Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/yash_cenoteses?$select=_ownerid_value,yash_email,yash_owner&$filter=_yash_customerengagementnotesid_value eq " + recordId.replace('{', '').replace('}', ''), false);

        req.setRequestHeader("OData-MaxVersion", "4.0");

        req.setRequestHeader("OData-Version", "4.0");

        req.setRequestHeader("Accept", "application/json");

        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

        req.onreadystatechange = function () {

            if (this.readyState === 4) {

                req.onreadystatechange = null;

                if (this.status === 200) {

                    var results = JSON.parse(this.response);

                    for (var i = 0; i < results.value.length; i++) {

                        // alert(results.value[i]["yash_owner"]);

                       // usersWhoSentNotes.push(results.value[i]["yash_owner"]);

                       usersWhoSentNotes.push(results.value[i]["yash_email"]);

                    }

                    Report.FetchAllYashParticipants(formContext, cePlanId, usersWhoSentNotes, checkCondition);

 

                } else {

                    Alert(this.statusText);

                }

            }

        };

        req.send();

    }

};

 

Report.FetchAllYashParticipants = function (formContext, CEPlanID, usersWhoSentNotes, checkCondition) {

    if (formContext !== null) {

        if (emails.length > 0) {

            emails = [];

        }

        if (users.length > 0) { users = new Array(); }

        var ownerCEPlan = formContext.getAttribute("ownerid").getValue();

        var req = new XMLHttpRequest();

        req.open("GET", Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/yash_callplanningmechanism_yash_yashintset?$select=yash_callplanningmechanism_yash_yashintid,yash_callplanningmechanismid,yash_yashinternalparticipantsid&$filter=yash_callplanningmechanismid eq " + CEPlanID.replace('{', '').replace('}', ''), false);

        req.setRequestHeader("OData-MaxVersion", "4.0");

        req.setRequestHeader("OData-Version", "4.0");

        req.setRequestHeader("Accept", "application/json");

        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

        req.onreadystatechange = function () {

            if (this.readyState === 4) {

                req.onreadystatechange = null;

                if (this.status === 200) {

                    var results = JSON.parse(this.response);

                    for (var i = 0; i < results.value.length; i++) {

                        var yash_yashinternalparticipantsid = results.value[i]["yash_yashinternalparticipantsid"];

                        Report.pushUsers(yash_yashinternalparticipantsid, usersWhoSentNotes);

 

                    }

                    //// Check For Owner Of Record

                  if (ownerCEPlan !== null) {

                        var checkForOwner = usersWhoSentNotes.includes(ownerCEPlan[0].name);

                        if (!checkForOwner) {

                            if (!users.includes(ownerCEPlan[0].name)) { Report.GetUserName(ownerCEPlan[0].id, usersWhoSentNotes); }

                        }

                    }

                  

   

                    

                    if (users.length > 0) {

                        //// Show Confirmbox for Selection

                        Xrm.Utility.closeProgressIndicator();

                        var message = '';

                        users.forEach(x => { message += '\n' + x; });

                        var usersEmail = '';

                        if (checkCondition === 0) {

                            var confirmStrings = { text: " This CE Report hasn't got CE Notes from below users :\n" + message, confirmButtonLabel: "Publish", cancelButtonLabel: "Send Reminder For Notes", title: "Do you want to publish CE Report ?" };

                            var confirmOptions = { height: 300, width: 550 };

                            Xrm.Navigation.openConfirmDialog(confirmStrings, confirmOptions).then(

                                function (success) {

                                    if (success.confirmed) {

                                        // console.log("Dialog closed using OK button.");

                                        var summary = formContext.getAttribute("yash_executivesummary").getValue();

                                        if (summary !== null) {

                                            formContext.getAttribute("yash_cereportstatu").setValue(true);

                                            Report.FormReadOnly(formContext);

                                            formContext.data.entity.save();

                                        }

                                        else {

                                            /// alert

                                            var message = "Please Provide the Executive Summary Details before finalizing.";

                                            Report.ShowAlert(message);

                                        }

                                    }

                                    else {

                                        // console.log("Dialog closed using Cancel button or X.");

                                        //// Send Reminder Email For users.

                                        Report.SendNotification(formContext, usersEmail, message, CEPlanID);

                                    }

                                });

                        }

                        else {

                            //// Condition For Ping Button Click

                            Xrm.Utility.closeProgressIndicator();

                            Report.SendNotification(formContext, usersEmail, message, CEPlanID);

                        }

                    }

                    else {

                        Xrm.Utility.closeProgressIndicator();

                        formContext.getAttribute("yash_cereportstatu").setValue(true);

                        Report.FormReadOnly(formContext);

                    }

                } else {

                    Alert(this.statusText);

                }

            }

        };

        req.send();

    }

};

 

Report.ShowAlert = function (message) {

    var alertStrings = { confirmButtonLabel: "Close", text: message, title: "Need Executive Summary" };

    var alertOptions = { height: 200, width: 450 };

    Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(

        function success(result) {

            // console.log("Alert dialog closed");

        },

        function (error) {

            // console.log(error.message);

        }

    );

};

 

Report.GetUserName = function (id, usersWhoSentNotes) {

    var req = new XMLHttpRequest();

    req.open("GET", Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/systemusers?$select=fullname,internalemailaddress&$filter=systemuserid eq " + id, false);

    req.setRequestHeader("OData-MaxVersion", "4.0");

    req.setRequestHeader("OData-Version", "4.0");

    req.setRequestHeader("Accept", "application/json");

    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

    req.onreadystatechange = function () {

        if (this.readyState === 4) {

            req.onreadystatechange = null;

            if (this.status === 200) {

                var results = JSON.parse(this.response);

                for (var i = 0; i < results.value.length; i++) {

               

                    var systemuser = results.value[i]["fullname"];

                    var systemuseremail = results.value[i]["internalemailaddress"];

                    var systemCheck = usersWhoSentNotes.includes(systemuseremail);

                        if (!systemCheck) {

                            users.push(systemuser);

                            emails.push(systemuseremail);

                        }

                   

                }

            } else {

                Alert(this.statusText);

            }

        }

    };

    req.send();

};

 

Report.SendNotification = function (formContext, usersEmail, message, CEPlanID) {

    formContext.getAttribute("yash_sendremindernotification").setValue(true);

    emails.forEach(x => { usersEmail += x + ';'; });

    formContext.getAttribute("yash_reminderfortousers").setValue(usersEmail);

    /// Calling Flow For Sending Email Notification

    Report.CallFowForEmail(CEPlanID, formContext.data.entity.getId(), formContext);

 

    setTimeout(function () {

        formContext.ui.clearFormNotification();

    },

        10000

    );

};

 

Report.Onload = function (executionContext, attributeName, attributeQualificationDetails) {

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

        Report.ShowHideCEPlanDetails(formContext);

        var checkIsreadOnly = formContext.getAttribute(attributeName).getValue();

        var checkIsReOpened = formContext.getAttribute(attributeQualificationDetails).getValue();

        if (checkIsReOpened === 2 && checkIsreadOnly) {

            Report.FormReadOnly(formContext);

            formContext.getAttribute("yash_qualify").setRequiredLevel("none");

            var control = formContext.getControl("yash_executivesummary");

            if (control) {

                control.setDisabled(false);

            }

        }

        else if (checkIsreadOnly) {

            Report.FormReadOnly(formContext);

        }

    }

};

 

Report.LiteCEReport = function (executionContext) {

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

        formContext.getAttribute("yash_cereportstatu").setValue(true);

        formContext.getAttribute("yash_readonly").setValue(true);

 

    }

};

 

Report.ShowHideCEPlanDetails = function (formContext) {

    if (formContext !== null) {

        var checkValue = formContext.getAttribute("yash_ceplan").getValue();

        if (checkValue === null) {

            formContext.getControl("yash_ceplan").setVisible(false);

            // formContext.getControl("yash_dateandtime").setVisible(false);

            formContext.getControl("CENotes").setVisible(false);

            //formContext.getControl("yash_account").setVisible(false);

            //formContext.getControl("yash_opportunity").setVisible(false);

        }

        else {

            formContext.getControl("yash_engagementobjective").setVisible(false);

            formContext.getAttribute("yash_engagementobjective").setRequiredLevel("none");

        }

    }

};

 

function ExecutiveSummary(executionContext) {

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

        var checkValue = formContext.getAttribute("yash_ceplan").getValue();

        if (checkValue !== null) {

            var ID = "CE Notification";

            var message = "Ping for Notes or Complete the Executive Summary and hit “Publish Report”".toUpperCase();

            var level = "INFO";

            formContext.ui.setFormNotification(message, level, ID);

            setTimeout(function () {

                formContext.ui.clearFormNotification(ID);

            },

                50000

            );

        }

    }

}

 

function HideButtons(primaryControl) {

    var formContext = primaryControl;

    if (formContext !== null) {

        var checkValue = formContext.getAttribute("yash_ceplan").getValue();

        if (checkValue !== null) {

            return true;

        }

 

        return false;

    }

}

 

function ValidateDate(executionContext) {

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

        var today = new Date();

        var Startdate = formContext.getAttribute('yash_dateandtime').getValue();

        if (Startdate > today) {

            alert("Date and time cannot be future date");

            formContext.getAttribute('yash_dateandtime').setValue(null);

        }

        else {

            formContext.getAttribute('yash_dateandtime').setValue(Startdate);

        }

    }

}

 

// JavaScript source code

Report.ShowQylifyfield = function (executionContext) {

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

        /// get Logged in user role Id

        var userSettings = Xrm.Utility.getGlobalContext().userSettings;

 

        // Get Logged In User Security Roles

        var loggedInUsersecurityRolesGuidArray = userSettings.securityRoles;

        var totalSecurityRolesArray = new Array();

        //var arreyToCheck = [];

        if (loggedInUsersecurityRolesGuidArray.length > 0) {

            Xrm.WebApi.online.retrieveMultipleRecords("role", "?$select=name,roleid").then(

                function success(result) {

                    if (result.entities.length > 0) {

                        // Push Role Names and Role Ids to Array

                        for (var rolesCount = 0; rolesCount < result.entities.length; rolesCount++) {

                            totalSecurityRolesArray.push({ RoleName: result.entities[rolesCount].name, RoleId: result.entities[rolesCount].roleid });

                        }

 

                        // Compare the User Security Roles with Total Security Roles

                        for (var userSecurityRolesCounter = 0; userSecurityRolesCounter < loggedInUsersecurityRolesGuidArray.length; userSecurityRolesCounter++) {

                            for (var totalsecurityRolesCounter = 0; totalsecurityRolesCounter < totalSecurityRolesArray.length; totalsecurityRolesCounter++) {

                                if (totalSecurityRolesArray[totalsecurityRolesCounter].RoleId.toLowerCase() === loggedInUsersecurityRolesGuidArray[userSecurityRolesCounter].toLowerCase()) {

                                    if (totalSecurityRolesArray[totalsecurityRolesCounter].RoleName === 'System Administrator') {

 

                                        formContext.ui.controls.get("yash_qualify").setDisabled(false);

                                        formContext.ui.controls.get("yash_qualificationnotes").setDisabled(false);

                                        return;

                                    } else if (totalSecurityRolesArray[totalsecurityRolesCounter].RoleName === 'Vice President of Sales') {

 

                                        formContext.ui.controls.get("yash_qualify").setDisabled(false);

                                        formContext.ui.controls.get("yash_qualificationnotes").setDisabled(false);

                                        return;

                                    } else if (totalSecurityRolesArray[totalsecurityRolesCounter].RoleName === 'Sales Manager - BD Ops') {

 

                                        formContext.ui.controls.get("yash_qualify").setDisabled(false);

                                        formContext.ui.controls.get("yash_qualificationnotes").setDisabled(false);

                                        return;

                                    }

                                }

                                else {

 

                                    formContext.ui.controls.get("yash_qualify").setDisabled(true);

                                    formContext.ui.controls.get("yash_qualificationnotes").setDisabled(true);

                                }

                            }

                        }

                    }

 

                },

                function (error) {

                    // Show error

                    Alert(error.message, null);

                });

        }

    }

};

 

Report.AccountOnchange = function (executionContext) {

    var formContext = executionContext.getFormContext();

    var accountid = formContext.getAttribute("yash_account").getValue();

    if (formContext !== null && accountid !== null) {

        var lookupid = accountid[0].id.replace("{", "").replace("}", "");

        var req = new XMLHttpRequest();

        req.open("GET", Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/accounts?$select=accountid,new_accounttype&$filter=accountid eq " + lookupid + "", false);

        req.setRequestHeader("OData-MaxVersion", "4.0");

        req.setRequestHeader("OData-Version", "4.0");

        req.setRequestHeader("Accept", "application/json");

        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

        req.onreadystatechange = function () {

            if (this.readyState === 4) {

                req.onreadystatechange = null;

                if (this.status === 200) {

                    var results = JSON.parse(this.response);

                    for (var i = 0; i < results.value.length; i++) {

                        var new_accounttype = results.value[i]["new_accounttype"];

                        formContext.getAttribute("yash_accounttype").setValue(new_accounttype);

                        formContext.data.entity.save();

                    }

                } else {

                    Alert(this.statusText);

                }

            }

        };

        req.send();

 

    }

    else {

        formContext.getAttribute("yash_accounttype").setValue(null);

    }

};

 

Report.OnQualifySelect = function (executionContext) {

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

        var qualify = formContext.getAttribute("yash_qualify").getValue();

        var accountType = formContext.getAttribute("yash_accounttype").getValue();

        if (accountType === 100000002 && qualify === 3) {

            var message = "You can not qualify prospect type account as \"Half Credit\"";

            Report.ShowAlert(message);

            formContext.getAttribute("yash_qualify").setValue(null);

        }

    }

};

 

Report.AccountupOnchange = function (executionContext) {

    var formContext = executionContext.getFormContext();

    var globalcontext = Xrm.Utility.getGlobalContext();

    var Client = globalcontext.getClientUrl();

    var accountname = formContext.getAttribute("yash_accountup").getValue();

    if (formContext !== null && accountname !== null) {

        var req = new XMLHttpRequest();

        req.open("GET", Client + "/api/data/v9.1/accounts?$select=name,new_accounttype&$filter=name eq '" + accountname + "'", false);

        req.setRequestHeader("OData-MaxVersion", "4.0");

        req.setRequestHeader("OData-Version", "4.0");

        req.setRequestHeader("Accept", "application/json");

        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

        req.onreadystatechange = function () {

            if (this.readyState === 4) {

                req.onreadystatechange = null;

                if (this.status === 200) {

                    var results = JSON.parse(this.response);

                    for (var i = 0; i < results.value.length; i++) {

                        var name = results.value[i]["name"];

                        var new_accounttype = results.value[i]["new_accounttype"];

                        var new_accounttype_formatted = results.value[i]["new_accounttype@OData.Community.Display.V1.FormattedValue"];

                        formContext.getAttribute("yash_accounttype").setValue(new_accounttype);

                    }

                } else {

                    Alert(this.statusText);

                }

            }

        };

        req.send();

    }

    else {

        formContext.getAttribute("yash_accounttype").setValue(null);

    }

};

 

function Alert(message) {

    var alertStrings = { confirmButtonLabel: "Ok", text: message };

    var alertOptions = { height: 150, width: 400 };

    Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(

        function success(result) {

        },

        function (error) {

        }

    );

}

 

// JavaScript source code

 

function HideQulification(executionContext) {

 

    var formContext = executionContext.getFormContext();

    if (formContext !== null) {

 

        var CEReportstattus = formContext.getAttribute("yash_cereportstatu").getValue();

        if (CEReportstattus === true) {

            formContext.ui.tabs.get("QualificationInformation").setVisible(true);

        }

    }

}

 

Report.OnNotQualifiedStatus = function (executionContext) {

    var formContext = executionContext.getFormContext();

   if (formContext !== null) {

        if (formContext.getAttribute("yash_qualify").getValue() === 2) {

            var control = formContext.getControl("yash_executivesummary");

            if (control) {

                control.setDisabled(false);

            }

 

 

            formContext.getAttribute("yash_qualify").setRequiredLevel("none");

            formContext.getAttribute("yash_qualificationnotes").setRequiredLevel("none");

            formContext.getAttribute("yash_qualify").setValue(null);

            formContext.getAttribute("yash_qualificationdetails").setValue(2);

        }

        else if (formContext.getAttribute("yash_qualificationdetails").getValue() === 2 && formContext.getAttribute("yash_executivesummary").getIsDirty()) {

            var _control = formContext.getControl("yash_executivesummary");

            if (_control) {

                _control.setDisabled(true);

            }

 

            formContext.getAttribute("yash_qualificationdetails").setValue(3);

        }

    }

};

 

Report.pushUsers = function (recordId, usersWhoSentNotes) {

    if (recordId !== null) {

        //  var usersWhoSentNotes = [];

        var req = new XMLHttpRequest();

        req.open("GET", Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.1/yash_yashinternalparticipantses?$select=yash_name,yash_email&$filter=yash_yashinternalparticipantsid eq " + recordId.replace('{', '').replace('}', ''), false);

        req.setRequestHeader("OData-MaxVersion", "4.0");

        req.setRequestHeader("OData-Version", "4.0");

        req.setRequestHeader("Accept", "application/json");

        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

        req.onreadystatechange = function () {

            if (this.readyState === 4) {

                req.onreadystatechange = null;

                if (this.status === 200) {

                    var results = JSON.parse(this.response);

                    for (var i = 0; i < results.value.length; i++) {

                        var name = results.value[i]["yash_name"];

                        var email = results.value[i]["yash_email"];

                        var check = usersWhoSentNotes.includes(email);

                        if (!check) {

                            users.push(name);

                            emails.push(email);

                        }        

                        

                    }

                } else {

                    Alert(this.statusText);

                }

            }

        };

        req.send();

    }

};

 

అప్ట్= new XMLHttpRequest();

    req.open('POST', "https://prod-116.westus.logic.azure.com:443/workflows/24fe514ad1f34093a4c06521310b6c92/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=hawz3ux5c4sboNei7idTRW_T0n577cVtpXl5JZv1z-M");

    req.setRequestHeader("OData-MaxVersion", "4.0");

    req.setRequestHeader("OData-Version", "4.0");

    req.setRequestHeader("Accept", "*/*");

    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",return=representation");

    req.onreadystatechange = function () {

        if (this.readyState === 4) {

            req.onreadystatechange = null;

            if (this.status === 200) {

                formContext.data.save();

                formContext.ui.setFormNotification(this.response, "INFO", "PingForNotes");

 

            } else {

                formContext.data.save();

                formContext.ui.setFormNotification(this.response, "ERROR", "Error_PingForNotes");

            }

        }

    };

    req.send(JSON.stringify({

        "CePlan": ce_plan_id,

        "CeReport": Ce_Report_id

    }));

};