Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

download filename fixes #693

Merged
merged 3 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { useTranslation } from "react-i18next";
import { DocumentIcon } from "./DocumentIcon";
import XlsPreview from "./XlsPreview";
import { XlsxFile } from "./icons/XlsxFile";
import { downloadExcelWithCustomName } from "../utils";

function CampaignDocumentsPreview({ documents = [], svgStyles = {}, isUserGenerate = false }) {
const { t } = useTranslation();
const tenantId = Digit.ULBService.getCurrentTenantId();
const [filesArray, setFilesArray] = useState(null);
const [pdfFiles, setPdfFiles] = useState({});
const [showPreview, setShowPreview] = useState(false);

useEffect(() => {
let acc = documents?.map((i) => (i?.id ? i?.id : i?.filestoreId));
setFilesArray(acc);
Expand All @@ -23,8 +25,9 @@ function CampaignDocumentsPreview({ documents = [], svgStyles = {}, isUserGenera
}
}, [filesArray]);

const handleFileDownload = (a, b) => {
window.open(b, "_blank");
const handleFileDownload = ({ id, name }) => {
const fileNameWithoutExtension = name?.split(/\.(xlsx|xls)/)?.[0];
downloadExcelWithCustomName({ fileStoreId: id, customName: fileNameWithoutExtension });
};
return (
<div>
Expand All @@ -48,8 +51,16 @@ function CampaignDocumentsPreview({ documents = [], svgStyles = {}, isUserGenera
</div>
{showPreview && (
<XlsPreview
file={{ url: pdfFiles[document?.id ? document?.id : document?.filestoreId] }}
onDownload={() => handleFileDownload(null, pdfFiles[document?.id ? document?.id : document?.filestoreId])}
file={{
url: pdfFiles[document?.id ? document?.id : document?.filestoreId],
filename: isUserGenerate ? document?.type : document?.filename,
}}
onDownload={() =>
handleFileDownload({
id: document?.id ? document?.id : document?.filestoreId,
name: isUserGenerate ? document?.type : document?.filename,
})
}
onBack={() => setShowPreview(false)}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function CampaignResourceDocuments({ resources = [], svgStyles = {}, isUserGener
const temp = resourceData.map((i) => {
return {
id: i?.processedFilestoreId,
type: i?.type,
type: "userCredential",
};
});
setProcessData(temp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useHistory } from "react-router-dom";
import { Button, EditIcon, Header, Loader, ViewComposer } from "@egovernments/digit-ui-react-components";
import { Toast } from "@egovernments/digit-ui-components";
import { DownloadIcon } from "@egovernments/digit-ui-react-components";
import { PRIMARY_COLOR } from "../utils";
import { PRIMARY_COLOR, downloadExcelWithCustomName } from "../utils";

function mergeObjects(item) {
const arr = item;
Expand Down Expand Up @@ -380,7 +380,7 @@ const CampaignSummary = () => {
}, [data]);

const downloadUserCred = async () => {
window.location.href = userCredential;
downloadExcelWithCustomName(userCredential);
};

useEffect(() => {
Expand All @@ -398,11 +398,9 @@ const CampaignSummary = () => {

const response = responseTemp?.ResourceDetails?.map((i) => i?.processedFilestoreId);

const fileUrl = await Digit.UploadServices.Filefetch(response, Digit.ULBService.getCurrentTenantId()).then((res) => {
return res?.data?.[response];
});
setUserCredential(fileUrl);
return;
if (response?.[0]) {
setUserCredential({ fileStoreId: response?.[0], customName: "userCredential" });
}
};
fetchUser();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { InfoCard, Toast } from "@egovernments/digit-ui-components";
import { schemaConfig } from "../configs/schemaConfig";
import { headerConfig } from "../configs/headerConfig";
import { PRIMARY_COLOR } from "../utils";

import { downloadExcelWithCustomName } from "../utils";
/**
* The `UploadData` function in JavaScript handles the uploading, validation, and management of files
* for different types of data in a web application.
Expand Down Expand Up @@ -543,10 +543,9 @@ const UploadData = ({ formData, onSelect, ...props }) => {

const onFileDownload = (file) => {
if (file && file?.url) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use optional chaining consistently to ensure robustness.

- const fileNameWithoutExtension = file?.filename.split(/\.(xlsx|xls)/)[0];
+ const fileNameWithoutExtension = file?.filename?.split(/\.(xlsx|xls)/)[0];
- downloadExcelWithCustomName({ fileStoreId: fileData?.[0]?.id, customName: fileData?.[0]?.filename });
+ downloadExcelWithCustomName({ fileStoreId: fileData?.[0]?.id, customName: fileData?.[0]?.filename });

Also applies to: 727-727


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if (file && file?.url) {
if (file && file?.url) {
const fileNameWithoutExtension = file?.filename?.split(/\.(xlsx|xls)/)[0];
downloadExcelWithCustomName({ fileStoreId: fileData?.[0]?.id, customName: fileData?.[0]?.filename });
}

window.location.href = file?.url;
// Splitting filename before .xlsx or .xls
// const fileNameWithoutExtension = file?.filename.split(/\.(xlsx|xls)/)[0];
// downloadExcel(new Blob([file], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), fileNameWithoutExtension);
const fileNameWithoutExtension = file?.filename.split(/\.(xlsx|xls)/)[0];
downloadExcelWithCustomName({ fileStoreId: file?.filestoreId, customName: fileNameWithoutExtension });
}
};
useEffect(() => {
Expand Down Expand Up @@ -727,13 +726,9 @@ const UploadData = ({ formData, onSelect, ...props }) => {

if (fileData && fileData?.[0]?.url) {
setDownloadError(false);
// downloadExcel(fileData[0].blob, fileData[0].fileName);
window.location.href = fileData?.[0]?.url;
// handleFileDownload(fileData?.[0]);
// downloadExcel(
// new Blob([fileData], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }),
// fileData?.[0]?.filename
// );
if (fileData?.[0]?.id) {
downloadExcelWithCustomName({ fileStoreId: fileData?.[0]?.id, customName: fileData?.[0]?.filename });
}
} else {
setDownloadError(true);
setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT") });
Expand All @@ -747,39 +742,6 @@ const UploadData = ({ formData, onSelect, ...props }) => {
);
};

// const downloadExcel = (blob, fileName) => {
// console.log("fileName", fileName);
// const link = document.createElement("a");
// link.href = URL.createObjectURL(blob);
// link.download = fileName + ".xlsx";
// document.body.append(link);
// link.click();
// link.remove();
// // document.body.removeChild(link);
// setTimeout(() => URL.revokeObjectURL(link.href), 7000);
// };

const downloadExcel = (blob, fileName) => {
if (window.mSewaApp && window.mSewaApp.isMsewaApp() && window.mSewaApp.downloadBase64File) {
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
var base64data = reader.result;
// Adjust MIME type and file extension if necessary
window.mSewaApp.downloadBase64File(base64data, fileName + ".xlsx");
};
} else {
const link = document.createElement("a");
// Adjust MIME type to Excel format
link.href = URL.createObjectURL(blob);
link.download = fileName + ".xlsx"; // Adjust file extension
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
}
};

return (
<>
<Card>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function XlsPreview({ file, ...props }) {
? [
{
fileType: "xlsx",
fileName: file?.fileName,
fileName: file?.filename,
uri: file?.url,
},
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import axios from "axios";

/* Fetching sheet as json object from the API , converting them into blob and downloading it.
* Way to use the function. Just import the funtion downloadExcelWithCustomName and pass the filestoreid and customName you want to download the file.
* Rest this function will take care for you and download it in your system.
*
* Eg. ->
* const handleDownload = (id, name) => {
* downloadExcelWithCustomName({fileStoreId: id, customName: name});
* }
*
*/

export const downloadExcelWithCustomName = ({ fileStoreId = null, customName = null }) => {
const downloadExcel = (blob, fileName) => {
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = fileName + ".xlsx";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use template literals for better readability in string concatenation.

- link.download = fileName + ".xlsx";
+ link.download = `${fileName}.xlsx`;

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
link.download = fileName + ".xlsx";
link.download = `${fileName}.xlsx`;

document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
};

if (fileStoreId) {
axios
.get("/filestore/v1/files/id", {
responseType: "arraybuffer",
headers: {
"Content-Type": "application/json",
Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"auth-token": Digit.UserService.getUser()?.["access_token"],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify the access token retrieval.

- "auth-token": Digit.UserService.getUser()?.["access_token"],
+ "auth-token": Digit.UserService.getUser()?.accessToken,

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"auth-token": Digit.UserService.getUser()?.["access_token"],
"auth-token": Digit.UserService.getUser()?.accessToken,

},
params: {
tenantId: Digit.ULBService.getCurrentTenantId(),
fileStoreId: fileStoreId,
},
})
.then(async (res) => {
downloadExcel(
new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }),
customName ? customName : "download"
);
});
}
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import _ from "lodash";
import { downloadExcelWithCustomName } from "./downloadExcel";

export default {};

export const PRIMARY_COLOR="#C84C0E";
export { downloadExcelWithCustomName };
export const PRIMARY_COLOR = "#C84C0E";
Loading