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);
}
}