Skip to main content
Microsoft Dynamics CRM forum
Unanswered

TS webresource business process flow code executing mulitple times on stage change

editSubscribe (0) ShareShare
ReportReport
Posted on by
I have Business process flow and on stage change from 2nd to last stage it fires fulfillorder method and when requirements are not met for the bpf to be completed it fails and prevent going to the last stage and opens dialog with error message with details what is missing. However somewhow my code is executing multiple times and when i try to do multiple fails in a row the code doubles everytime so i get mulitple dialogs doubling with errors opening and breaking ui. (fulfillorder method basically sets status of the bpf to finished and completes the whole process- depending if field acceptedbyphone is yes or no it fires either fullfillorderbyphone or fullfillorder - the difference between those 2 is statuscode it sets).
 
export default class Form {    public static async onLoad(context: IExecutionContext): Promise<void> {        try {            console.log(/BPF Helper init./)            const formContext = context.getFormContext() as IFormContext;            const process = formContext.data.process;            if (!process) {                console.log(/BPF Helper exiting - could not get formContext.data.process./);                return;            }            try {                const configurationJSON = await Form.getConfigurationJSON();                if (!configurationJSON) {                    console.log(/BPF Helper exiting - no configuration./);                    return;                }                const configuration = JSON.parse(configurationJSON);                if (!configuration) {                    console.log(/BPF Helper exiting - cannot parse configuration./);                    return;                }                const currentBpf = process.getActiveProcess();                if (!currentBpf) {                    console.log(/BPF Helper exiting - cannot getActiveProcess()./);                    return;                }                const currentBpfId = currentBpf?.getId();                if (!currentBpfId) {                    console.log(/BPF Helper exiting - cannot getActiveProcess().getId()./);                    return;                }                Form.setFocusOnTabByBPFStage(formContext, configuration);                process.addOnPreStageChange((e: any) => {                    const isDirty = Xrm.Page.data.entity.getIsDirty()                    var bpfArgs = e.getEventArgs();                    if (!isDirty) {                        process.addOnStageChange(async (e: any) => {                            console.log(/BPF addOnStageChange init/);                            try {                                var bpfArgs = e.getEventArgs();                                const process = formContext.data.process;                                const stage = process.getActiveStage();                                const activeStageId = stage?.getId();                                console.log(/BPF status == / + process.getStatus());                                console.log(/BPF activeStageId: / + activeStageId);                                if (activeStageId != /5146fde3-f300-48cf-879c-0aebccfec26d/) {                                    Form.SetFocusOnTabByBPFStageOnStageChange(formContext, configuration);                                    return;                                }                                try {                                    console.log(/BPF automation finishes the process/);                                    await Form.FinalizeOrder(formContext);                                } catch (e) {                                    bpfArgs.preventDefault();                                    var alertStrings = { confirmButtonLabel: /OK/, text: e, title: /finalizing order failed/ };                                    var alertOptions = { height: 120, width: 260 };                                    Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);                                }                            } catch (e) {                                throw new Error(/Error in addOnStageChange: / + e);                            }                            console.log(/BPF addOnStageChange exit/);                        });                    } else {                        bpfArgs.preventDefault();                        var alertStrings = { confirmButtonLabel: /OK/, text: /save before proceeding to nest stage/, title: /error./ };                        var alertOptions = { height: 120, width: 260 };                        Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);                    }                })                if (currentBpfId == /1ce1b75d-c15f-4aaf-aca8-a25aha7f4f34/ || currentBpfId == /a3892452-d574-ed11-81ab-000d3aaa07b6/) {                    // prevent finishing of BPF - BPF finished by processing requests in the background                    process.addOnPreProcessStatusChange(async (e: any) => {                        try {                                                        const bpfArgs = e.getEventArgs();                            try {                                if (bpfArgs.getStatus() == /Finished/) {                                    bpfArgs.preventDefault();                                    var alertStrings = { confirmButtonLabel: /OK/, text: /order cant be closed manually./, title: /operation not supported/ };                                    var alertOptions = { height: 120, width: 260 };                                    Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);                                }                            } catch (error) {                                bpfArgs.preventDefault();                                alertStrings = { confirmButtonLabel: /OK/, text: error, title: error };                                alertOptions = { height: 120, width: 260 };                                Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);                            }                        } catch (error) {                            throw new Error(/Error in addOnPreProcessStatusChange: / + error.message);                        }                    })                }                else if (currentBpfId == /e2111dcc-1122-ed11-p83d-000d3abfb6c9/) {                 }            } catch (e) {                console.log(/BPF Helper failed and exiting - error: / + e);            }            console.log(/BPF Helper successful exit./)        } catch (e) {            throw new Error(/Error retrieving connfiguration / + e.message);        }    }    public static async FinalizeOrder(formContext: IFormContext): Promise<void> {        console.log(/BPF FinalizeOrder begin/);        try {            const process = formContext.data.process;            const stage = process.getActiveStage();            const activeStageId = stage?.getId();            if (activeStageId === /5846fde2-f300-48cf-879c-0aebccfec26d/) {                const acceptedByPhoneAttr = formContext.getAttribute(/acceptedbyphone/);                if (acceptedByPhoneAttr && acceptedByPhoneAttr.getValue()) {                    Form.FulfillOrderByPhone(formContext).then(() => {                        formContext.data.process.setStatus(/finished/);                    }).catch((e) => {                        var alertStrings = { confirmButtonLabel: /OK/, text: e, title: /finalization failed/ };                        var alertOptions = { height: 120, width: 260 };                        //formContext.data.process.setStatus(/active/);                                               formContext.data.process.setActiveStage(/d889215f-c8db-4d93-8eeb-643e7d7deb52/);                        Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);                    });                } else {                    Form.FulfillOrder(formContext).then(() => {                        formContext.data.process.setStatus(/finished/);                    }).catch((e) => {                        var alertStrings = { confirmButtonLabel: /OK/, text: e, title: /finalization failed/ };                        var alertOptions = { height: 120, width: 260 };                        //formContext.data.process.setStatus(/active/);                        formContext.data.process.setActiveStage(/d889615f-c8db-4d93-8eeb-643e7d7deb52/);                        Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);                    });                }            }        } catch (e) {            //throw new Error(/finalization failed: / + e);            var alertStrings = { confirmButtonLabel: /OK/, text: e, title: /finalization failed with error/ };            var alertOptions = { height: 120, width: 260 };            Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(() => {                console.log(/BPF error confirmed, changing status/);                formContext.data.process.setStatus(/active/);            });        }    }    static async FulfillOrderByPhone(form: IFormContext) {        console.log(/BPF: FulfillOrder/);        var orderId = form.data.entity.getId().replace(/}/, //).replace(/{/, //);        var orderClose: IOrderClose = {            subject: /Salesorder Fulfilled by user: /,            description: /This is code for thursday/,            actualend: new Date(),            /salesorderid@odata.bind/: //salesorders(/ + orderId + /)/        };        var execute_FulfillSalesOrder_Request: IFulfillSalesOrderRequest = {            // Parameters            getMetadata: function () {                return {                    boundParameter: /entityset/,                    parameterTypes: {                        entityset: { typeName: /mscrm.salesorder/, structuralProperty: 4 },                        OrderClose: { typeName: /mscrm.orderclose/, structuralProperty: 5 },                        Status: { typeName: /Edm.Int32/, structuralProperty: 2 }                    },                    operationType: 0, operationName: /FulfillSalesOrder/                };            },            Status: 865480000,            OrderClose: orderClose        }        console.log(/BPF: / + JSON.stringify(execute_FulfillSalesOrder_Request));        console.log(/BPF: calling fulfill/);        try {            //Xrm.Utility.showProgressIndicator(/loading, please wait/);            Xrm.Utility.showProgressIndicator(/sending requests./);            var response = await (new MsdWebApi()).execute(/salesorders/Microsoft.Dynamics.CRM.FulfillSalesOrder/, execute_FulfillSalesOrder_Request);            Xrm.Utility.showProgressIndicator(/sending data./);            console.log(/BPF: Not Waiting for 3 seconds/);            //await setTimeout(async function () {            //console.log(/BPF: Done waiting for 3 seconds./);            console.log(/BPF: creating integration command/);            var integrationcommand: IIntegrationCommand = {                entityid: form.data.entity.getId(),                entityname: form.data.entity.getEntityName(),                integrationtype: /price-making-factors-request/,                name: /price-making-factors-request / + new Date()            };            console.log(/BPF: / + JSON.stringify(integrationcommand));            console.log(/BPF: creating integraiton command/);            var x = await (new MsdWebApi()).createRecord(/integrationcommand/, integrationcommand);            Xrm.Utility.closeProgressIndicator();            //console.log(/BPF: / + JSON.stringify(x));            //console.log(/BPF finishing BPF/);            //form.data.process.setStatus(/finished/);            // }, 3000);        } catch (e) {            Xrm.Utility.closeProgressIndicator();            throw new Error(e);        }    }    static async FulfillOrder(form: IFormContext) {        console.log(/BPF: FulfillOrder/);        try {            var orderId = form.data.entity.getId().replace(/}/, //).replace(/{/, //);            var orderClose: IOrderClose = {                subject: /Salesorder Fulfilled by user: /,                description: / /,                actualend: new Date(),                /salesorderid@odata.bind/: //salesorders(/ + orderId + /)/            };            var execute_FulfillSalesOrder_Request: IFulfillSalesOrderRequest = {                // Parameters                getMetadata: function () {                    return {                        boundParameter: /entityset/,                        parameterTypes: {                            entityset: { typeName: /mscrm.salesorder/, structuralProperty: 4 },                            OrderClose: { typeName: /mscrm.orderclose/, structuralProperty: 5 },                            Status: { typeName: /Edm.Int32/, structuralProperty: 2 }                        },                        operationType: 0, operationName: /FulfillSalesOrder/                    };                },                Status: 100001,                OrderClose: orderClose            }            console.log(/BPF: / + JSON.stringify(execute_FulfillSalesOrder_Request));        } catch (e) {            console.log(/BPF: FulfillOrder: / + e);            throw new Error(/BPF: FulfillOrder: / + e);        }        console.log(/BPF: calling fulfill/);        try {            Xrm.Utility.showProgressIndicator(/sending requests./);            var response = await (new MsdWebApi()).execute(/salesorders/Microsoft.Dynamics.CRM.FulfillSalesOrder/, execute_FulfillSalesOrder_Request);            Xrm.Utility.showProgressIndicator(/sending data./);            console.log(/BPF: Not Waiting for 3 seconds/);            //await setTimeout(async function () {            //console.log(/SalesOrderFormScript: Done waiting for 3 seconds./);            console.log(/SalesOrderFormScript: creating integration command/);            var integrationcommand: IIntegrationCommand = {                entityid: form.data.entity.getId(),                entityname: form.data.entity.getEntityName(),                integrationtype: /price-making-factors-request/,                name: /price-making-factors-request / + new Date()            };            console.log(/SalesOrderFormScript: / + JSON.stringify(integrationcommand));            console.log(/SalesOrderFormScript: creating integraiton command/);            var x = await (new MsdWebApi()).createRecord(/integrationcommand/, integrationcommand);            Xrm.Utility.closeProgressIndicator();            //console.log(/BPF: / + JSON.stringify(x));            //console.log(/BPF finishing BPF/);            //await form.data.refresh();            //form.data.process.setStatus(/finished/);            //}, 3000);        } catch (e) {            Xrm.Utility.closeProgressIndicator();            throw new Error(e);        }    }
Categories:

Helpful resources

Quick Links

What Motivates a Super User?

We know many of you visit the Dynamics 365 Community and Power Platform…

Demystifying Copilot with Sundar…

Industry experts answer burning questions directly from our amazing Community…

Enabling Copilot Case and Conversation…

Agents can easily recap an ongoing chat, transcribe a voice conversation…

Leaderboard

#1
Andre Arnaud de Calavon Profile Picture

Andre Arnaud de Cal... 283,030 Super User

#2
Martin Dráb Profile Picture

Martin Dráb 222,562 Super User

#3
nmaenpaa Profile Picture

nmaenpaa 101,138

Product updates

Dynamics 365 release plans