Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Unanswered

Contracting unit based on Account Manager

(1) ShareShare
ReportReport
Posted on by
So we've had an issue with an script where it supposed to fill in the "Contracting Unit" based on the "Account Manager" that has created the Opportunity.
For a while now it has stopped working and is no longer selecting the Contracting Unit that is linked to the AM.
 
Below is, what i believe, the script that is supposed to handle this but this is not my expertise at all. Could anyone have a look at the script and maybe help me get this working again?
 
"use strict";
var customerIdField = "customerid";
var priceListField = "pricelevelid";
var currencyIdFieldName = "transactioncurrencyid";
var accountManagerFieldId = "msdyn_accountmanagerid";
var parentAccountIdField = "parentaccountid";
var priceListUnavailableWrnMsgId = "plwmgsid"; // pick an ID that is unlikely to be reused for other notifications.
var contractUnitFieldName = "msdyn_contractorganizationalunitid";
var resourceEntityName = "systemuser";
var requireConfigUrl = Xrm.Utility.getGlobalContext().getClientUrl() + "/WebResources/msdyn_/Common/RequireJSConfig/RequireJSConfig.js";
function setLookupValue(formContext, attributeName, id, name, entityType) {
    var attribute = formContext.getAttribute(attributeName);
    if (attribute) {
        var lookup = [
            {
                id: id,
                name: name,
                entityType: entityType
            }
        ];
        attribute.setValue(lookup);
    }
}
// Sets the default value of contracting org. unit
function initializeContractingOrganization(executionContext, isInitialization) {
    var formContext = executionContext.getFormContext();
    var contractingUnitAttr = formContext.getAttribute(contractUnitFieldName);
    var isCreateMode = formContext.data.entity.getId().length === 0;
    var isContractingUnitEmpty = contractingUnitAttr && !contractingUnitAttr.getValue();
    var isOnChangeTriggered = !isInitialization;
    // The Contracting Unit should be pre populated in case it is new entity creation(this entity wasn't saved yet)
    // And it is empty or Account Manager field was changed.
    if (isCreateMode && (isContractingUnitEmpty || isOnChangeTriggered)) {
        var accountManagerId = getAccountManagerId(formContext);
        if (accountManagerId) {
            setDefaultOrgUnit(formContext, accountManagerId);
        }
    }
}
function getAccountManagerId(formContext) {
    var accountManagerId = "";
    var accountManagerAttribute = formContext.getAttribute(accountManagerFieldId);
    if (accountManagerAttribute) {
        var accountManagerValues = accountManagerAttribute.getValue();
        if (accountManagerValues) {
            accountManagerId = accountManagerValues[0].id;
        }
    }
    return accountManagerId;
}
function setDefaultOrgUnit(formContext, accountManagerId) {
    require([requireConfigUrl], function () {
        require([
            "module!Common/Models/BookableResource",
            "module!Common/Models/OrganizationalUnit",
            "module!Common/Utils/EntityUtils"
        ], function (BookableResource, OrganizationalUnit, EntityUtils) {
            var options = BookableResource.getQueryOptionsForOrgUnit();
            var userIdGuid = EntityUtils.normalizeGuid(accountManagerId);
            options += "&$filter=_userid_value eq ".concat(userIdGuid, "&$top=1");
            Xrm.WebApi.retrieveMultipleRecords(BookableResource.EntityName, options).then(function (bookableResources) {
                if (bookableResources && bookableResources.entities.length > 0) {
                    var bookableResource = bookableResources.entities[0];
                    if (bookableResource._msdyn_organizationalunit_value) {
                        setLookupValue(formContext, contractUnitFieldName, bookableResource._msdyn_organizationalunit_value, bookableResource["_msdyn_organizationalunit_value@OData.Community.Display.V1.FormattedValue"], bookableResource["_msdyn_organizationalunit_value@Microsoft.Dynamics.CRM.lookuplogicalname"]);
                    }
                }
                else {
                    OrganizationalUnit.setDefaultOrgUnitFromParameters(formContext, contractUnitFieldName, requireConfigUrl);
                }
            }, function (error) {
                Xrm.Navigation.openErrorDialog({ message: error.message });
            });
        });
    });
}
// Sets the default value of the account manager
function initializeAccountManager(executionContext) {
    var formContext = executionContext.getFormContext();
    var accountManagerAttribute = formContext.getAttribute(accountManagerFieldId);
    // Initialize only if there's no value and a new document is being created.
    if (accountManagerAttribute && !accountManagerAttribute.getValue() && !formContext.data.entity.getId()) {
        var currentUserReference = {};
        currentUserReference.LogicalName = resourceEntityName;
        currentUserReference.Id = formContext.context.getUserId();
        currentUserReference.Name = formContext.context.getUserName();
        setLookupValue(formContext, accountManagerFieldId, currentUserReference.Id, currentUserReference.Name, currentUserReference.LogicalName);
        initializeContractingOrganization(executionContext, true);
    }
}
/// <summary>Normalizes a guid, making potential different implementations comparable.</summary>
function normalizeGuid(guid) {
    return guid ? guid.replace(/({|})/g, "").toLowerCase() : "";
}
// Changes the currency of the sales document if the provided currency is different
// than the current on the document.
function updateCurrencyIfDifferent(entity, formContext) {
    var newCurrencyId = entity["_transactioncurrencyid_value"];
    if (newCurrencyId) {
        var currentCurrencyId = void 0;
        var currentCurrencyArray = formContext.data.entity.attributes.get(currencyIdFieldName).getValue();
        if (currentCurrencyArray) {
            currentCurrencyId = currentCurrencyArray[0].id;
        }
        // Avoid change the currency unnecessarily; whenever the currency changes, the user is asked through a dialog to
        // verify all the amounts in the form.
        if (normalizeGuid(currentCurrencyId) !== normalizeGuid(newCurrencyId)) {
            setLookupValue(formContext, currencyIdFieldName, newCurrencyId, entity["_transactioncurrencyid_value@OData.Community.Display.V1.FormattedValue"], entity["_transactioncurrencyid_value@Microsoft.Dynamics.CRM.lookuplogicalname"]);
        }
    }
}
/// <summary>Process the event of the account being changed on the Opportunity main form.</summary>
function onAccountChange(executionContext) {
    var formContext = executionContext.getFormContext();
    var customersField = formContext.getAttribute(parentAccountIdField).getValue();
    if (customersField) {
        // If there was a price list defaulting message displayed before, clear it since it may
        // no longer be valid for the new customer.
        formContext.ui.clearFormNotification(priceListUnavailableWrnMsgId);
        var selectedCustomer = customersField[0];
        if (selectedCustomer.entityType === "account") {
            Xrm.WebApi.retrieveRecord("account", selectedCustomer.id, "?$select=_transactioncurrencyid_value,_defaultpricelevelid_value").then(function (account) {
                updateCurrencyIfDifferent(account, formContext);
                if (account._defaultpricelevelid_value) {
                    setLookupValue(formContext, priceListField, account._defaultpricelevelid_value, account["_defaultpricelevelid_value@OData.Community.Display.V1.FormattedValue"], account["_defaultpricelevelid_value@Microsoft.Dynamics.CRM.lookuplogicalname"]);
                }
                else {
                    setDefaultPriceList(formContext);
                }
            });
        }
    }
}
/// <summary>Gets the Default Price list from the projectParamter and sets it on the price list attribute</summary>
function setDefaultPriceList(formContext) {
    require([requireConfigUrl], function () {
        require([
            "module!ContractBilling/Model/OrganizationPriceList",
            "module!Common/Utils/EntityUtils",
            "module!Common/Models/OptionSets/Module",
            "module!Common/Utils/UIUtils"
        ], function (OrganizationPriceList, entityUtils, Module, uiUtils) {
            //get Currency
            var currencyId = uiUtils.getLookupValue(formContext, currencyIdFieldName);
            if (currencyId) {
                currencyId = entityUtils.normalizeGuid(currencyId);
            }
            if (currencyId) {
                var options = "?$select=msdyn_PriceList&$expand=msdyn_PriceList";
                Xrm.WebApi.retrieveMultipleRecords(OrganizationPriceList.LogicalName, options).then(function (retrievedRecords) {
                    for (var i = 0; i < retrievedRecords.entities.length; i++) {
                        var retrievedRecord = retrievedRecords.entities[i].msdyn_PriceList;
                        if (currencyId === retrievedRecord._transactioncurrencyid_value &&
                            Module.Sales === retrievedRecord.msdyn_module) {
                            setLookupValue(formContext, priceListField, retrievedRecord.pricelevelid, retrievedRecord.name, "pricelevel");
                            break;
                        }
                    }
                }, function (error) {
                    formContext.ui.setFormNotification(error.text, "ERROR" /* ERROR */, null);
                });
            }
        });
    });
}
/// Triggered by account change on Quote and Contract main form
function loadContactAddressAndPaymentTerms(executionContext) {
    var formContext = executionContext.getFormContext();
    try {
        var customersField = formContext.getAttribute(customerIdField).getValue();
        if (customersField === null) {
            return;
        }
        var selectedCustomer = customersField[0];
        if (selectedCustomer.entityType === "account" || selectedCustomer.entityType === "contact") {
            // If there was a price list defaulting message displayed before, clear it since it may
            // no longer be valid for the new customer.
            formContext.ui.clearFormNotification(priceListUnavailableWrnMsgId);
            if (selectedCustomer.entityType === "account") {
                var accountid = formContext.getAttribute("customerid").getValue()[0].id;
                Xrm.WebApi.retrieveRecord("account", accountid, null).then(function (account) {
                    copyCustomerAddressAndTerms(formContext, account);
                    updateCurrencyIfDifferent(account, formContext);
                    if (account._defaultpricelevelid_value) {
                        setLookupValue(formContext, priceListField, account._defaultpricelevelid_value, account["_defaultpricelevelid_value@OData.Community.Display.V1.FormattedValue"], account["_defaultpricelevelid_value@Microsoft.Dynamics.CRM.lookuplogicalname"]);
                    }
                }, function (error) {
                    Xrm.Navigation.openErrorDialog({ message: error.message });
                });
            }
            else if (selectedCustomer.entityType === "contact") {
                var contactid = formContext.getAttribute("customerid").getValue()[0].id;
                Xrm.WebApi.retrieveRecord("contact", contactid, null).then(function (contact) {
                    copyCustomerAddressAndTerms(formContext, contact);
                    updateCurrencyIfDifferent(contact, formContext);
                    if (contact._defaultpricelevelid_value) {
                        setLookupValue(formContext, priceListField, contact._defaultpricelevelid_value, contact["_defaultpricelevelid_value@OData.Community.Display.V1.FormattedValue"], contact["_defaultpricelevelid_value@Microsoft.Dynamics.CRM.lookuplogicalname"]);
                    }
                }, function (error) {
                    Xrm.Navigation.openErrorDialog({ message: error.message });
                });
            }
        }
    }
    catch (e) { }
}
function copyCustomerAddressAndTerms(formContext, customer) {
    var billToAddress1Attribute = formContext.getAttribute("billto_line1");
    if (billToAddress1Attribute) {
        billToAddress1Attribute.setValue(customer.address1_line1);
    }
    var billToAddress2Attribute = formContext.getAttribute("billto_line2");
    if (billToAddress2Attribute) {
        billToAddress2Attribute.setValue(customer.address1_line2);
    }
    var billToAddress3Attribute = formContext.getAttribute("billto_line3");
    if (billToAddress3Attribute) {
        billToAddress3Attribute.setValue(customer.address1_line3);
    }
    var billToCityAttribute = formContext.getAttribute("billto_city");
    if (billToCityAttribute) {
        billToCityAttribute.setValue(customer.address1_city);
    }
    var billToStateAttribute = formContext.getAttribute("billto_stateorprovince");
    if (billToStateAttribute) {
        billToStateAttribute.setValue(customer.address1_stateorprovince);
    }
    var billToPostalCodeAttribute = formContext.getAttribute("billto_postalcode");
    if (billToPostalCodeAttribute) {
        billToPostalCodeAttribute.setValue(customer.address1_postalcode);
    }
    var billToCountryAttribute = formContext.getAttribute("billto_country");
    if (billToCountryAttribute) {
        billToCountryAttribute.setValue(customer.address1_country);
    }
    var paymentTermsAttribute = formContext.getAttribute("paymenttermscode");
    if (paymentTermsAttribute) {
        paymentTermsAttribute.setValue(customer.paymenttermscode);
    }
}
//Clear the form notification if any
function onSave(executionContext) {
    var formContext = executionContext.getFormContext();
    if (formContext) {
        formContext.ui.clearFormNotification(priceListUnavailableWrnMsgId);
    }
}
 
Categories:
  • Suggested answer
    Tom_G Profile Picture
    Tom_G 69 on at
    Contracting unit based on Account Manager
    This is definitely the right script. I can interpret some of it, but somebody else might need to come along and see if they notice anything in particular that is causing the issue. Hopefully at least this helps you narrow it down. TLDR at the bottom for things you can check.

    Important definitions in your file to check on field values, to make sure those have not changed.
    • Account Manager = msdyn_accountmanagerid
    • Contracting Unit = msdyn_contractorganizationalunitid

    function initializeContractingOrganization(executionContext, isInitialization) {
        var formContext = executionContext.getFormContext();
        var contractingUnitAttr = formContext.getAttribute(contractUnitFieldName);
        var isCreateMode = formContext.data.entity.getId().length === 0;
        var isContractingUnitEmpty = contractingUnitAttr && !contractingUnitAttr.getValue();
        var isOnChangeTriggered = !isInitialization;
        // The Contracting Unit should be pre populated in case it is new entity creation(this entity wasn't saved yet)
        // And it is empty or Account Manager field was changed.
        if (isCreateMode && (isContractingUnitEmpty || isOnChangeTriggered)) {
            var accountManagerId = getAccountManagerId(formContext);
            if (accountManagerId) {
                setDefaultOrgUnit(formContext, accountManagerId);
            }
        }
    • This is your primary function that is doing the work. It is running and checking if the form is being created (has not been saved yet), if the Contracting Unit field is empty or a change has triggered this to run (like a change to the Account Manager)
    • It then gets the User ID for the Account manager, makes sure you have a value, and calls some other functions to set the default org unit

    function setDefaultOrgUnit(formContext, accountManagerId) {
        require([requireConfigUrl], function () {
            require([
                "module!Common/Models/BookableResource",
                "module!Common/Models/OrganizationalUnit",
                "module!Common/Utils/EntityUtils"
            ], function (BookableResource, OrganizationalUnit, EntityUtils) {
                var options = BookableResource.getQueryOptionsForOrgUnit();
                var userIdGuid = EntityUtils.normalizeGuid(accountManagerId);
                options += "&$filter=_userid_value eq ".concat(userIdGuid, "&$top=1");
                Xrm.WebApi.retrieveMultipleRecords(BookableResource.EntityName, options).then(function (bookableResources) {
                    if (bookableResources && bookableResources.entities.length > 0) {
                        var bookableResource = bookableResources.entities[0];
                        if (bookableResource._msdyn_organizationalunit_value) {
                            setLookupValue(formContext, contractUnitFieldName, bookableResource._msdyn_organizationalunit_value, bookableResource["_msdyn_organizationalunit_value@OData.Community.Display.V1.FormattedValue"], bookableResource["_msdyn_organizationalunit_value@Microsoft.Dynamics.CRM.lookuplogicalname"]);
                        }
                    }
                    else {
                        OrganizationalUnit.setDefaultOrgUnitFromParameters(formContext, contractUnitFieldName, requireConfigUrl);
                    }
                }, function (error) {
                    Xrm.Navigation.openErrorDialog({ message: error.message });
                });
            });
        });
    }
    • This is the function that sets the org unit. From what I can tell, it is reaching out to the Bookable Resource table and trying to find a resource record linked to the Account Manager. When it finds it, it then checks the [Organizational Unit] field on that resource and passes it back to the first function to update the Org Unit field

    Things you should check
    • Confirm that the user being selected as the Account Manager has a Bookable Resource listed for them. This should be a resource of type "User" and the user lookup field should be pointed to the same user selected on this record or it won't be able to find a match
    • Make sure that the above Bookable Resource record has an Organizational Unit selected. I think this is a required field, but it would be good to check anyway
     
    Hopefully this helps get you moving in the right direction. Let us know how it goes and if either of the above were the root cause of the issue.
     
     

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey Pt 2

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,861 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,540 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans