67 lines
1.7 KiB
TypeScript
67 lines
1.7 KiB
TypeScript
// imports
|
|
|
|
import { API_ENDPOINTS } from "~/constants";
|
|
import { useQuery } from "@tanstack/vue-query";
|
|
import { useToast } from "~/composables/global/useToast";
|
|
|
|
const useDownloadInvoice = (transactionId: string) => {
|
|
// state
|
|
|
|
const { addToast } = useToast();
|
|
|
|
const { $queryClient: queryClient, $axios: axios } = useNuxtApp();
|
|
|
|
const enabled = ref(false);
|
|
|
|
// methods
|
|
|
|
const download = () => {
|
|
if (!enabled.value) enabled.value = true;
|
|
queryClient.invalidateQueries({
|
|
queryKey: ["download-invoice", transactionId],
|
|
});
|
|
};
|
|
|
|
// query
|
|
|
|
const handleDownloadInvoice = async () => {
|
|
const { data } = await axios.get<Blob>(`${API_ENDPOINTS.orders.cart.download_invoice}/${transactionId}`, {
|
|
responseType: "blob",
|
|
});
|
|
return data;
|
|
};
|
|
|
|
const { data: file, isLoading } = useQuery({
|
|
queryKey: ["download-invoice", transactionId],
|
|
queryFn: () => handleDownloadInvoice(),
|
|
enabled,
|
|
refetchOnWindowFocus: false,
|
|
retry: 0,
|
|
throwOnError(error) {
|
|
addToast({ message: "خطایی در دانلود فاکتور رخ داد", options: { status: "error" } });
|
|
},
|
|
});
|
|
|
|
// watch
|
|
|
|
whenever(file, () => {
|
|
if (!!file.value) {
|
|
const url = URL.createObjectURL(file.value);
|
|
const link = document.createElement("a");
|
|
link.href = url;
|
|
link.download = "invoice.pdf";
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
|
|
enabled.value = false;
|
|
}
|
|
});
|
|
|
|
return {
|
|
downloadIsLoading: isLoading,
|
|
downloadFn: download,
|
|
};
|
|
};
|
|
|
|
export default useDownloadInvoice;
|