Wednesday, February 28, 2024

Batch file Download - Trigger power automate on Button click, Generate word document and Download file

How to Trigger power automate on Button click, Generate word document & Batch Download file

PART- 2

In our previous blog post, we showed how to create a "Print Case" button using Workbench for cloud flow and map Dynamics 365 case data to a Word document in developer mode. We then used Power Automate to convert the document to PDF and integrate it with SharePoint Online. Downloading the generated document involved clicking a "Print Case" button which triggered Power Automate multiple times for each selected case 

Upon document generation, we retrieved it by clicking a designated "Print Case" button. Previously, clicking this button triggered the execution of the Power Automate flow multiple times for various selected cases.

This blog post introduces a new approach: selecting multiple cases and downloading their associated documents using a single, iterating through the case records within the flow. We demonstrate how to print documents from the selected case records with a single button click in the same flow. Importantly, the flow execution occurs only once, regardless of the number of records selected.

For a more comprehensive understanding and implementation details, please refer to the video above. Additionally, you can access the code by clicking on the provided link.

Link to download code - Batch Print Cases

Javascript code logic below_

function generateSelectedItems(selectedItems, selectedControlSelectedItemIds, env_name, fileName, IDName) {
  try {
    console.log(selectedItems);
    const guids = selectedItems.map(item => item);
    getEnvironmentVariable(
      env_name,
      function (url) {
        if (!fileName) { fileName = 'document.docx'; }

        const userSettings = Xrm.Utility.getGlobalContext().userSettings;
        const userId = userSettings.userId.replace("{", "").replace("}", "");

        const data = {
          "UserID": userId,
          "Guids": guids, // Assuming your flow expects an array of Guids
        };

        Xrm.Utility.showProgressIndicator("Generating documents...please wait...");

        fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
        }).then(response => {
          Xrm.Utility.closeProgressIndicator();
          if (response.status == 200) {
            response.json().then(bulkResponseArray => {  // Adjust variable name to match your Flow
              console.log("Response from Flow:", bulkResponseArray);
              downloadFiles(bulkResponseArray, fileName);
              closePopups(selectedControlSelectedItemIds);
            });
          } else {
            response.text().then(body => {
              handleError(body);
            });
          }
        }).catch(function (error) {
          handleError(error);
        });
      },
      function (error) {
        handleError(error);
      }
    );

  } catch (error) {
    Xrm.Utility.closeProgressIndicator();
    showMessageDialog("Error", error.message);
  }
}

// cr146a_InvoiceReceiptUrl, Invoice.docx, caseEntityID
// cr146a_RegPaymentReceiptUrl, Receipt, 
function callHTTPFlow(primaryControl, env_name, fileName, IDName) {
try {
"use strict";
debugger;
console.log(primaryControl, env_name, fileName, IDName);
Xrm.Utility.showProgressIndicator("Generating document...please wait...");
getEnvironmentVariable(env_name,
function (url) {
callHTTPFlowInternal(url, primaryControl, fileName, IDName);
},
function (error) {
handleError(error);
}
);
} catch (error) { console.error(error); }
}

function handleError(error) {
try {
Xrm.Utility.closeProgressIndicator();
showMessageDialog("Error", error);
} catch (error) { console.error(error); }
}

function callHTTPFlowInternal(url, primaryControl, fileName, IDName) {
  try {
    "use strict";
    // var fileName = "Summary.docx";
    if (!fileName) { fileName = 'document.docx'; }

    var guid = primaryControl.data.entity.getId();
    var userSettings = Xrm.Utility.getGlobalContext().userSettings;
    var currentuserid = userSettings.userId;
    var userId = currentuserid.replace("{", "").replace("}", "");
    primaryControl.data.save().then(function () {

      guid = guid.replace("{", "").replace("}", "");
      // url = url + "&id=" + documentId;
      var data = {};
      data["UserID"] = userId;

      if (IDName) { data[IDName] = guid; }
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      }).then(response => {
        Xrm.Utility.closeProgressIndicator();
        if (response.status == 200) {
          if (response.headers.get("content-type") === "application/json") {
            response.json().then((data) => {
              if (data && data.SiteAddress && data.ETag) {
                const EncodeURIEtag = encodeURI(JSON.parse(data.ETag).split(',')[0]);
                const onlineDocLink = data.SiteAddress + "/_layouts/15/Doc.aspx?sourcedoc=" + EncodeURIEtag;
                window.open(onlineDocLink, "_blank");
              }
              else {
                throw new Error("Unable to find document");
              }
            })
          }
          else {
            response.blob().then(blob => {
              downloadFile(blob, fileName);
              closePopups(primaryControl);
            });
          }

        } else {
          response.text().then(body => {
            handleError(body);
          });
        }
      }).then(data => console.log(data))
        .catch(function (error) {
          handleError(error);
        });
    },
      function (error) {
        Xrm.Utility.closeProgressIndicator();
        showMessageDialog("Error", error.message);
      });
  } catch (error) { console.error(error); }
}


function closePopups(formContext) {
try {
formContext.data.refresh(false);
Xrm.Utility.closeProgressIndicator();
} catch (error) { console.error(error); }
}

function downloadFiles(bulkResponseArray, fileName) {
  try {
    bulkResponseArray.forEach(responseItem => {
      const contentType = responseItem["$content-type"];
      const content = responseItem["$content"];
      const blob = base64toBlob(content, contentType);
      downloadFile(blob, fileName);
    });
  } catch (error) {
    console.error(error);
  }
}

// Helper function to convert base64 to Blob
function base64toBlob(base64, contentType) {
  const binary = atob(base64);
  const array = [];
  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], { type: contentType });
}
function downloadFile(blob, fileName) {
try {
debugger;
var blobType = blob.type;
var name = fileName.split('.')[0];
// const fileOpen = new Blob([blob], {type: blob.type });
// const fileUrl = URL.createObjectURL(fileOpen);
// window.open(fileUrl);
if (blobType.includes('officedocument')) { // Set Docx file name
fileName = name + '.docx';
} else if (blobType.includes('application/pdf')) { // Set pdf file name
fileName = name + '.pdf';
}
console.log(fileName);
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
} catch (error) { console.error(error); }
}

function showMessageDialog(messageTitle, message) {
try {
var alertStrings = {
confirmButtonLabel: "OK",
text: message,
title: messageTitle
};
var alertOptions = {
height: 120,
width: 260
};
Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);
} catch (error) { console.error(error); }
}


function getEnvironmentVariable(varName, onSuccess, onError) {
try {
"use strict";
Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", "?$select=defaultvalue,displayname&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$filter=schemaname eq '" + varName + "'").then(
function success(result) {
var varValue = null;
for (var i = 0; i < result.entities.length; i++) {

if (typeof (result.entities[i]["environmentvariabledefinition_environmentvariablevalue"]) != "undefined"
&& result.entities[i]["environmentvariabledefinition_environmentvariablevalue"].length > 0) {
varValue = result.entities[i]["environmentvariabledefinition_environmentvariablevalue"][0].value;
}
else if (typeof (result.entities[i].defaultvalue) != "undefined") {
varValue = result.entities[i].defaultvalue;
}
else {
varValue = null;
}
}
onSuccess(varValue);
},
function (error) {
console.log(error.message);
onError(error);
}
);
} catch (error) { console.error(error); }
}

Previous blog (link here), we explored the following topics:
- Creating a custom button (e.g., Print Case) using Ribbon Work Bench
- Triggering a cloud flow upon clicking the Print Case button
- Enabling Developer mode and mapping Dynamics 365 case record fields in Microsoft Word
- Converting MS Word documents to PDF in Power Automate
- Integrating SharePoint with Dynamics 365
- Storing converted PDFs to both the case record and SharePoint
- Downloading the generated PDF document to the local system upon clicking the Print Case button

Followers

Power Dynamix YouTube Videos