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); }
}
No comments:
Post a Comment