Untitled

mail@pastecode.io avatar
unknown
plain_text
22 days ago
23 kB
1
Indexable
Never
const fieldPreFilertingUserLookup = [
    {
        "Field": "ipro_dataentryuser",
        "Association": "DRO-Data Entry User",
        "ViewId": generate_uuidv4()
    },
    {
        "Field": "ipro_managementuser",
        "Association": "DRO-Management User",
        "ViewId": generate_uuidv4()
    }
]
function generate_uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
    function(c) {
       var uuid = Math.random() * 16 | 0, v = c == 'x' ? uuid : (uuid & 0x3 | 0x8);
       return uuid.toString(16);
    });
 }
var Petronas = Petronas || {};
Petronas.CRM = Petronas.CRM || {};
Petronas.CRM.DRO = Petronas.CRM.DRO || {};
Petronas.CRM.DRO.Form = {
    _privateMembers: {
        initialize: function (executionContext) {
            formContext = executionContext.getFormContext();
        
            OilForm = formContext.getAttribute("ipro_oildistance");
            GasForm = formContext.getAttribute("ipro_gasdistance");
            ARPRYear = formContext.getAttribute("ipro_arprstudyyear").getValue();
            ARPRYearAttr = formContext.getAttribute("ipro_arprstudyyear");
            oilFacilityCtrl = formContext.getControl("ipro_oilnearestfacility");
            gasFacilityCtrl = formContext.getControl("ipro_gasnearestfacility");
            droDetailSubGridCtrl = formContext.getControl('Subgrid_droDetail');
            collectorsSubGridCtrl = formContext.getControl('GridCollectors');
            processorsSubGridCtrl = formContext.getControl('GridProcessors');
            assignedHubSubGridCtrl = formContext.getControl('GridAssignedHub');
            stoiipMMBOESubGridCtrl = formContext.getControl('STOIIPMMBOE');
            gasCR2CBCFSubGridCtrl = formContext.getControl('GASCR2CBCF');
            giipMMBOESubGridCtrl = formContext.getControl('GIIPMMBOE');
            oilCR2CMMBOESubGridCtrl = formContext.getControl('OILCR2CMMBOE');
            giipBCFSubGridCtrl = formContext.getControl('GIIPBCF');

            let entityId = formContext.data.entity.getId();
            oilFacilityFetchFilter =
                `<filter type='and'><condition attribute='ipro_dro' operator='eq' value='${entityId}' /><condition attribute='ipro_arprstudyyear' operator='eq' value='${ARPRYear}' /> <condition attribute='ipro_fluidtype' operator='eq' value='0' /></filter>`

            gasFacilityFetchFilter =
                `<filter type='and'><condition attribute='ipro_dro' operator='eq' value='${entityId}' /><condition attribute='ipro_arprstudyyear' operator='eq' value='${ARPRYear}' /> <condition attribute='ipro_fluidtype' operator='eq' value='1' /></filter>`

        },
    },
    onLoad: function onLoad(executionContext) {
        Petronas.CRM.DRO.Form._privateMembers.initialize(executionContext);
        Petronas.CRM.DRO.Form.FilertingUserLookup();

        oilFacilityCtrl.addPreSearch(() => {
            oilFacilityCtrl.addCustomFilter(oilFacilityFetchFilter);
        });
        gasFacilityCtrl.addPreSearch(() => {
            gasFacilityCtrl.addCustomFilter(gasFacilityFetchFilter);
        });
        let FormType = formContext.ui.getFormType();
        if (FormType == 2) {
            var tabObj = formContext.ui.tabs.get("tab_NearestFacility");
            tabObj.setVisible(true);
        }
        else {
            var tabObj = formContext.ui.tabs.get("tab_NearestFacility");
            tabObj.setVisible(false);
        }
        let currentTab = Xrm.Page.ui.tabs.get().find(it => it.getDisplayState() == 'expanded')?.name;
if(!currentTab){
            return;
        }
        Petronas.CRM.DRO.Form.OnTabChange(executionContext, currentTab)
        let currentYear = new Date().getFullYear().toString();
        ARPRYearAttr.setValue(currentYear);
        ARPRYearAttr.fireOnChange();
        
    },
    autoSelectNearestFacility: function autoSelectNearestFacility(executionContext){
        let formContext = executionContext.getFormContext();
        let id = formContext.data.entity.getId().replace("{", "").replace("}", "");
        if (!id)
            return;
        Xrm.WebApi.retrieveMultipleRecords("ipro_nearestfacility", "?$select=ipro_distance,ipro_name&$filter=_ipro_dro_value eq '" + id + "' and ipro_fluidtype eq 0 ").then(
            function success(result) {
                if (result.entities.length > 0) {
                    var minOilRecord = result.entities[0]; // Initialize with the first record
                    var minOilDistance = minOilRecord?.["ipro_distance"]; // Assuming attribute1 holds numeric values
        
                    // Loop through the records to find the one with the minimum value
                    result.entities.forEach(function(oilRecord) {
                        var currentDistance = oilRecord?.["ipro_distance"];
                        if (currentDistance < minOilDistance || minOilDistance == null) {
                            minOilDistance = currentDistance;
                            minOilRecord = oilRecord;
                        }
                    });
                    var lookupOilRecord = [];
                    lookupOilRecord[0] = {};
                    lookupOilRecord[0].id = minOilRecord?.["ipro_nearestfacilityid"];
                    lookupOilRecord[0].entityType = "ipro_nearestfacility";
                    lookupOilRecord[0].name =  minOilRecord?.["ipro_name"];
                
                    formContext.getAttribute("ipro_oilnearestfacility").setValue(lookupOilRecord);
                    formContext.getAttribute("ipro_oilnearestfacility").fireOnChange();
                }
            },
                function (error) {
                    console.log(error.message);
                    // handle error conditions
                }
            );
   
            Xrm.WebApi.retrieveMultipleRecords("ipro_nearestfacility", "?$select=ipro_distance,ipro_name&$filter=_ipro_dro_value eq '" + id + "' and ipro_fluidtype eq 1 ").then(
                function success(result) {
                    if (result.entities.length > 0) {
                        var minGasRecord = result.entities[0]; // Initialize with the first record
                        var minGasDistance = minGasRecord?.["ipro_distance"]; // Assuming attribute1 holds numeric values
            
                        // Loop through the records to find the one with the minimum value
                        result.entities.forEach(function(gasRecord) {
                            var currentDistance = gasRecord?.["ipro_distance"];
                            if (currentDistance < minGasDistance || minGasDistance == null) {
                                minGasDistance = currentDistance;
                                minGasRecord = gasRecord;
                            }
                        });
                        var lookupGasRecord = [];
                        lookupGasRecord[0] = {};
                        lookupGasRecord[0].id = minGasRecord?.["ipro_nearestfacilityid"];
                        lookupGasRecord[0].entityType = "ipro_nearestfacility";
                        lookupGasRecord[0].name = minGasRecord?.["ipro_name"];
                    
                        formContext.getAttribute("ipro_gasnearestfacility").setValue(lookupGasRecord);
                        formContext.getAttribute("ipro_gasnearestfacility").fireOnChange();
                    }
                },
                    function (error) {
                        console.log(error.message);
                        // handle error conditions
                    }
                );
    },
    SetOilDistance_onChange: function SetOilDistance_onChange(executionContext) {
        var Oil = formContext.getAttribute("ipro_oilnearestfacility").getValue();
        if (Oil == null) {
            OilForm.setValue(null);
        }
        else {
            var OilId = Oil[0].id;
            if (OilId != null) {
                Xrm.WebApi.retrieveRecord("ipro_nearestfacility", OilId, "?$select=ipro_distance").then(
                    function success(result) {
                        OilForm.setValue(result.ipro_distance);
                    },
                    function (error) {
                        console.log(error);
                    });
            }
        }

    },

 
    SetGasDistance_onChange: function SetGasDistance_onChange(executionContext) {
        var Gas = formContext.getAttribute("ipro_gasnearestfacility").getValue();
        if (Gas == null) {
            GasForm.setValue(null);
        }
        else {
            var GasId = Gas[0].id;
            if (GasId != null) {
                Xrm.WebApi.retrieveRecord("ipro_nearestfacility", GasId, "?$select=ipro_distance").then(
                    function success(result) {
                        
                        GasForm.setValue(result.ipro_distance);
                    },
                    function (error) {
                        console.log(error);
                    });
            }
        }
    },
    DroProbabilities: function DroProbabilities(executionContext) {
        const probabilityTypes = { STOIIPMMBOE: 0, GIIPBCF: 1, OILCR2CMMBOE: 2,GASCR2CBCF:3,GIIPMMBOE:4 }

        let config = [

            { "RefName": "ipro_probabilitytype", "GridName": "STOIIPMMBOE",Type: probabilityTypes.STOIIPMMBOE},
            { "RefName": "ipro_probabilitytype", "GridName": "OILCR2CMMBOE",Type: probabilityTypes.OILCR2CMMBOE },
            { "RefName": "ipro_probabilitytype", "GridName": "GIIPMMBOE" ,Type: probabilityTypes.GIIPMMBOE},
            { "RefName": "ipro_probabilitytype", "GridName": "GIIPBCF",Type: probabilityTypes.GIIPBCF },
            { "RefName": "ipro_probabilitytype", "GridName": "GASCR2CBCF" ,Type: probabilityTypes.GASCR2CBCF},

        ];
        let anyRecord = config.find(it => it.GridName == executionContext.name);
        if (!anyRecord)
            return;
        var entityFormOptions = {};
        entityFormOptions["entityName"] = "ipro_droprobability";
        var formParameters = {};
        Dro = [{
            name: executionContext.formContext.getAttribute("ipro_name").getValue(),
            id: executionContext.formContext.data.entity.getId(),
            entityType: executionContext.formContext.data.entity.getEntityName()
        }];
        Petronas.CRM.DRO.Form.NearestFacilityOpenForm(executionContext, entityFormOptions, formParameters,'ipro_probabilitytype', anyRecord.Type, Dro);
    },
    NearestFacility: function NearestFacility(executionContext) {
        const hubTypes = { AssignedHub: 0, Processors: 1, Collectors: 2 }

        let config = [
            {  "GridName": "GridAssignedHub",type: hubTypes.AssignedHub},
            { "GridName": "GridProcessors",type: hubTypes.Processors },
            { "GridName": "GridCollectors" ,type: hubTypes.Collectors},
        ];
        

        let anyRecord = config.find(it => it.GridName == executionContext.name);
        if (!anyRecord)
            return;
        var entityFormOptions = {};
        entityFormOptions["entityName"] = "ipro_nearestfacility";
        var formParameters = {};
        Dro = [{
            name: executionContext.formContext.getAttribute("ipro_name").getValue(),
            id: executionContext.formContext.data.entity.getId(),
            entityType: executionContext.formContext.data.entity.getEntityName()
        }];
        Petronas.CRM.DRO.Form.NearestFacilityOpenForm(executionContext, entityFormOptions, formParameters, "ipro_hubtypes", anyRecord.type, Dro);
       
    },
    NearestFacilityOpenForm: function NearestFacilityOpenForm(executionContext, entityFormOptions, formParameters, RefName, setValue, DroLookUp) {
        formParameters[RefName] = setValue;
        formParameters["ipro_dro"] = DroLookUp;
        formParameters["ipro_fieldname"] = executionContext.formContext.getAttribute("ipro_name").getValue();
        // Open the form.
        Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
            function (success) {
                console.log(success);
            },
            function (error) {
                console.log(error);
            });
    },
    OnChangeOfARPRYear: function OnChangeOfARPRYear(executionContext) {
        let formContext = executionContext.getFormContext();
        let id = formContext.data.entity.getId().replace("{", "").replace("}", "");
        if (!id)
            return;
        let arprYearValue = ARPRYearAttr.getValue();
        if (arprYearValue == null || arprYearValue.length !== 4)
            return;
        Xrm.WebApi.retrieveMultipleRecords("ipro_dro", "?$filter=_ipro_parentdro_value eq '" + id + "' and ipro_arprstudyyear eq '" + arprYearValue + "'").then(
            function success(relatedDro) {
                console.log(relatedDro);
                let recordByYear = relatedDro.entities?.[0];

                let arr = ["ipro_fieldstatus", "ipro_operatershipstatus", "ipro_region", "ipro_discoveryyear", "ipro_blockname", "ipro_noofwellsea", "ipro_noofwellsproducing",
                     "ipro_oildrocount", "ipro_nagdrocount", "ipro_dropriotizationnag", "ipro_dropriotizationoil", "ipro_waterdepttype", "ipro_highco2observed",
                "ipro_cr2coilmmstb","ipro_oilprice","ipro_oilcost","ipro_cr2cgasbscf","ipro_gasprice","ipro_gascost",
                "ipro_category","ipro_startingdate","ipro_finisheddate","ipro_company","ipro_plan","ipro_activityyear","ipro_clusterfield","ipro_remark","ipro_promotiondate","ipro_resultstatus","ipro_promotionstatus"
                ,"ipro_gpsalegasbscf","ipro_npsaleoilmmstb","ipro_gpnonsalegasbscf","ipro_npnonsaleoilmmstb","ipro_gasdistance","ipro_oildistance","ipro_fluidtype","ipro_discoveryyear"];
                arr.forEach(it => {
                   let attribute = formContext.getAttribute(it)
                   if(attribute)
                   attribute.setValue(recordByYear?.[it]);
                });
                let lookUpArr = ["ipro_psc","ipro_oilnearestfacility","ipro_gasnearestfacility","ipro_operator"];
                lookUpArr.forEach(it => {
                   if(it == "ipro_psc"){
                        var id = recordByYear?.["_ipro_psc_value"];
                        if(id == null){
                            formContext.getAttribute(it).setValue(null);  
                        }
                        else {
                        var lookupValue = new Array();
                        lookupValue[0] = new Object();
                        lookupValue[0].id = recordByYear?.["_ipro_psc_value"];
                        lookupValue[0].name = recordByYear?.["_ipro_psc_value@OData.Community.Display.V1.FormattedValue"];
                        lookupValue[0].entityType = recordByYear?.["_ipro_psc_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                        formContext.getAttribute(it).setValue(lookupValue);
                        }
                    }
                else if(it == "ipro_oilnearestfacility"){
                    var id = recordByYear?.["_ipro_oilnearestfacility_value"];
                    if(id == null){
                        formContext.getAttribute(it).setValue(null);
                        formContext.getAttribute("ipro_oildistance").setValue(null);  
                    }
                    else {
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();
                    lookupValue[0].id = recordByYear?.["_ipro_oilnearestfacility_value"];
                    lookupValue[0].name = recordByYear?.["_ipro_oilnearestfacility_value@OData.Community.Display.V1.FormattedValue"];
                    lookupValue[0].entityType = recordByYear?.["_ipro_oilnearestfacility_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                    formContext.getAttribute(it).setValue(lookupValue);
                    formContext.getAttribute("ipro_oildistance").setValue(recordByYear?.["ipro_oildistance"]);
                    }
                }
                else if(it == "ipro_gasnearestfacility"){
                    var id = recordByYear?.["_ipro_gasnearestfacility_value"];
                    if(id == null){
                        formContext.getAttribute(it).setValue(null);
                        formContext.getAttribute("ipro_gasdistance").setValue(null);  
                    }
                    else {
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();
                    lookupValue[0].id = recordByYear?.["_ipro_gasnearestfacility_value"];
                    lookupValue[0].name = recordByYear?.["_ipro_gasnearestfacility_value@OData.Community.Display.V1.FormattedValue"];
                    lookupValue[0].entityType = recordByYear?.["_ipro_gasnearestfacility_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
                    formContext.getAttribute(it).setValue(lookupValue);
                    formContext.getAttribute("ipro_gasdistance").setValue(recordByYear?.["ipro_gasdistance"]);
                    }
                }

                else if(it == "ipro_operator"){
                    var id = recordByYear?.["_ipro_operator_value"];
                    if(id == null){
                        formContext.getAttribute(it).setValue(null);
                    }
                    else {
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();
                    lookupValue[0].id = recordByYear?.["_ipro_operator_value"];
                    lookupValue[0].name = recordByYear?.["_ipro_operator_value@OData.Community.Display.V1.FormattedValue"];
                    lookupValue[0].entityType = "ipro_operator";
                    formContext.getAttribute(it).setValue(lookupValue);
                    }
                }
                   
                });


            },
            function (error) {
                console.log(error.message);
                // handle error conditions
            }
        );

    },
    FilertingUserLookup: function FilertingUserLookup() {

        fieldPreFilertingUserLookup.forEach(it => {
            if (formContext.getAttribute(it.Field) != null) {
                Petronas.CRM.DRO.Form.createViewForBilling(it.Field, it.Association, it.ViewId);
            }
        });
    },
    createViewForBilling: function createViewForBilling(field, association, viewId) {

        var _viewId = viewId;
        var _entityName = 'systemuser';
        var _viewDisplayName = association;
        var fetchXML = `<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
    <entity name="systemuser">
      <attribute name="fullname" />
      <attribute name="businessunitid" />
      <attribute name="title" />
      <attribute name="address1_telephone1" />
      <attribute name="positionid" />
      <attribute name="systemuserid" />
      <order attribute="fullname" descending="false" />
      <link-entity name="ipro_userassociation_systemuser" from="systemuserid" to="systemuserid" visible="false" intersect="true">
        <link-entity name="ipro_userassociation" from="ipro_userassociationid" to="ipro_userassociationid" alias="ag">
          <filter type="and">
            <condition attribute="ipro_associationname" operator="eq" value="${association}" />
          </filter>
        </link-entity>
      </link-entity>
    </entity>
  </fetch>`;

        var layoutXML = "<grid name='resultset' object='1' jump='name' select='1' icon='1' preview='1'>" +
            "<row name='result' id='accountid'>" +
            "<cell name='fullname' width='150' />" +
            "<cell name='internalemailaddress' width='150' />" +
            "</row>" +
            "</grid>";
        var lookupControl = Xrm.Page.ui.controls.get(field);
        //in this call, true sets the custom view to the default view.
        lookupControl.addCustomView(_viewId, _entityName, _viewDisplayName, fetchXML, layoutXML, true);
    }
    ,
    OnTabChange: function (executionContext,tabName) {
        let formContext = executionContext.getFormContext();
        let valueOfYear = ARPRYearAttr.getValue();
        let currentTabName = "";
        if (tabName) {
            currentTabName = tabName;
        }else
          currentTabName = executionContext.getEventSource().name;
        if (valueOfYear) {
            if (currentTabName == 'tab_DRODetail') {

                let filterForDroGrid = '<filter type="and"><condition attribute="statecode" operator="eq" value="0" /><condition attribute="ipro_arprstudyyear" operator="eq" value="' + valueOfYear + '" /></filter>';
                droDetailSubGridCtrl.setFilterXml(filterForDroGrid);
                droDetailSubGridCtrl.refresh();
            }
            else if (currentTabName == 'tab_ARPR') {

                let filterFordroProbabilityGrid = '<filter type="and"><condition attribute="statecode" operator="eq" value="0" /><condition attribute="ipro_arprstudyyear" operator="eq" value="' + valueOfYear + '" /></filter>';
                giipBCFSubGridCtrl.setFilterXml(filterFordroProbabilityGrid);
                giipBCFSubGridCtrl.refresh();
                oilCR2CMMBOESubGridCtrl.setFilterXml(filterFordroProbabilityGrid);
                oilCR2CMMBOESubGridCtrl.refresh();
                giipMMBOESubGridCtrl.setFilterXml(filterFordroProbabilityGrid);
                giipMMBOESubGridCtrl.refresh();
                gasCR2CBCFSubGridCtrl.setFilterXml(filterFordroProbabilityGrid);
                gasCR2CBCFSubGridCtrl.refresh();
                stoiipMMBOESubGridCtrl .setFilterXml(filterFordroProbabilityGrid);
                stoiipMMBOESubGridCtrl .refresh();

            }
            else if (currentTabName == 'tab_NearestFacility') {

                let filterForNearestFacilityGrid = '<filter type="and"><condition attribute="statecode" operator="eq" value="0" /><condition attribute="ipro_arprstudyyear" operator="eq" value="' + valueOfYear + '" /></filter>';
                processorsSubGridCtrl.setFilterXml(filterForNearestFacilityGrid);
                processorsSubGridCtrl.refresh();
                collectorsSubGridCtrl.setFilterXml(filterForNearestFacilityGrid);
                collectorsSubGridCtrl.refresh();
                assignedHubSubGridCtrl.setFilterXml(filterForNearestFacilityGrid);
                assignedHubSubGridCtrl.refresh();
        Petronas.CRM.DRO.Form.autoSelectNearestFacility(executionContext);
            }
            else {
                return;
            }
        }
    }
}
Leave a Comment