Automating Record Deactivation in Dynamics 365: A Guide to Sequential Deactivation of Related Records

 

Automating Record Deactivation in Dynamics 365: A Guide to Sequential Deactivation of Related Records

Introduction

In Dynamics 365, managing record states efficiently is crucial for maintaining data integrity and ensuring smooth business operations. This article demonstrates a common scenario where a series of related records need to be deactivated in a specific order: first the child records (appointment), followed by the parent record (recurringappointmentmaster). This approach ensures data consistency and aligns with typical business processes.

Scenario Overview

We have a requirement where, upon a certain trigger (like a button press on a form), all related appointment records of a recurringappointmentmaster record need to be deactivated. Once all the appointment records are successfully deactivated, the parent recurringappointmentmaster record should also be deactivated.

This process is beneficial in scenarios such as cancelling a series of appointments where the entire set (including the master appointment schedule) needs to be marked as inactive.

Solution Approach

The solution involves the following steps:

  1. A confirmation prompt to ensure the user's intent.
  2. Fetching and deactivating all related appointment records.
  3. Deactivating the parent recurringappointmentmaster record.

Implementation

Here is the Dynamics 365 JavaScript code that accomplishes the above steps:

Step 1: Confirmation Prompt

Before proceeding with the deactivation, we present a confirmation prompt to the user. This is a safeguard against accidental deactivation.

function deactivateSeries(primaryControl) {
    Xrm.Navigation.openConfirmDialog({ text: "Are you sure you want to deactivate these series and the parent record?" })
        .then(function (response) {
            if (response.confirmed) {
                performDeactivation(primaryControl);
            } else {
                console.log("Deactivation cancelled.");
            }
        });
}

Step 2: Deactivating appointment Records

We then retrieve and deactivate the related appointment records. This is done using a FetchXML query to select the appropriate records and updating their state.

function performDeactivation(primaryControl) {
    var formContext = primaryControl;
    // Extracting necessary values from the form
    var subject = formContext.data.entity.attributes.getByName("subject").getValue();
    // Note: Replace the following with actual attribute names
    var kcAppointmentTypeId = formContext.data.entity.attributes.getByName("kc_appointmenttypeid").getValue()[0].id;
    var kcBookingId = formContext.data.entity.attributes.getByName("kc_bookingid").getValue()[0].id;
    var kcSubjectId = formContext.data.entity.attributes.getByName("kc_subjectid").getValue()[0].id;
    var currentDate = new Date().toISOString();

    // Building the FetchXML query
    var fetchXml = "<fetch>...</fetch>"; // Complete FetchXML here

    // Fetch and deactivate appointments
    Xrm.WebApi.retrieveMultipleRecords("appointment", "?fetchXml=" + encodeURIComponent(fetchXml)).then(
        function success(result) {
            var promises = result.entities.map(function (entity) {
                return Xrm.WebApi.updateRecord("appointment", entity.activityid, { statecode: 2 });
            });

            Promise.all(promises).then(
                function() {
                    deactivateParentRecord(formContext);
                },
                function(error) {
                    console.log("Error in deactivating appointments: ", error.message);
                }
            );
        },
        function error(error) {
            console.log("Error in retrieving appointments: ", error.message);
        }
    );
}

Step 3: Deactivating the Parent recurringappointmentmaster Record

Finally, we deactivate the parent recurringappointmentmaster record. This step is only executed after the successful deactivation of all child appointment records.

function deactivateParentRecord(formContext) {
    var parentId = formContext.data.entity.getId();
    Xrm.WebApi.updateRecord("recurringappointmentmaster", parentId, { statecode: 2 }).then(
        function success(result) {
            console.log("Parent record deactivated successfully.");
        },
        function error(error) {
            console.log("Error deactivating parent record: ", error.message);
        }
    );
}


Conclusion

Sequential deactivation of records in Dynamics 365, as demonstrated in this scenario, is essential for maintaining the integrity and consistency of data. It aligns with business logic and ensures that dependent records are appropriately handled before making changes to primary records. This approach is adaptable and can be modified to fit various other scenarios in Dynamics 365.


No comments:

Post a Comment