This commit is contained in:
David Arranz 2024-08-22 19:23:12 +02:00
parent 51d1c3bbc8
commit cbc1b1b2c3
11 changed files with 183 additions and 106 deletions

View File

@ -11,6 +11,7 @@ module.exports = {
parser: "@typescript-eslint/parser", parser: "@typescript-eslint/parser",
plugins: ["react-refresh"], plugins: ["react-refresh"],
rules: { rules: {
"@typescript-eslint/no-require-imports": "none",
"@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/no-explicit-any": "warn",
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }], "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"react/no-unescaped-entities": "off", "react/no-unescaped-entities": "off",

View File

@ -68,7 +68,9 @@
"react-secure-storage": "^1.3.2", "react-secure-storage": "^1.3.2",
"react-toastify": "^10.0.5", "react-toastify": "^10.0.5",
"react-wrap-balancer": "^1.1.1", "react-wrap-balancer": "^1.1.1",
"recharts": "^2.12.7" "recharts": "^2.12.7",
"slugify": "^1.6.6",
"use-debounce": "^10.0.3"
}, },
"devDependencies": { "devDependencies": {
"@tanstack/react-query-devtools": "^5.51.23", "@tanstack/react-query-devtools": "^5.51.23",
@ -82,6 +84,7 @@
"@typescript-eslint/eslint-plugin": "^7.2.0", "@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0", "@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"@welldone-software/why-did-you-render": "^8.0.3",
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"eslint": "^8.57.0", "eslint": "^8.57.0",

View File

@ -11,7 +11,7 @@ import {
Progress, Progress,
} from "@/ui"; } from "@/ui";
import { t } from "i18next"; import { t } from "i18next";
import { useEffect } from "react"; import { useEffect, useId } from "react";
import { UseDownloader } from "react-use-downloader/dist/types"; import { UseDownloader } from "react-use-downloader/dist/types";
type DownloadQuoteDialogProps = Omit<UseDownloader, "download"> & { type DownloadQuoteDialogProps = Omit<UseDownloader, "download"> & {
@ -20,6 +20,7 @@ type DownloadQuoteDialogProps = Omit<UseDownloader, "download"> & {
export const DownloadQuoteDialog = (props: DownloadQuoteDialogProps) => { export const DownloadQuoteDialog = (props: DownloadQuoteDialogProps) => {
const { percentage, cancel, error, isInProgress, onFinishDownload } = props; const { percentage, cancel, error, isInProgress, onFinishDownload } = props;
const panelId = useId();
useEffect(() => { useEffect(() => {
if (!isInProgress && !error && percentage === 100) { if (!isInProgress && !error && percentage === 100) {
@ -36,7 +37,7 @@ export const DownloadQuoteDialog = (props: DownloadQuoteDialogProps) => {
<DialogTitle>{t("quotes.downloading_dialog.title")}</DialogTitle> <DialogTitle>{t("quotes.downloading_dialog.title")}</DialogTitle>
<DialogDescription>{t("quotes.downloading_dialog.description")}</DialogDescription> <DialogDescription>{t("quotes.downloading_dialog.description")}</DialogDescription>
</DialogHeader> </DialogHeader>
<div className='mb-4 space-y-2'> <div className='mb-4 space-y-2' id={panelId}>
<Label> <Label>
{t("quotes.downloading_dialog.progress.label", { {t("quotes.downloading_dialog.progress.label", {
status: t( status: t(

View File

@ -18,13 +18,12 @@ import { useToast } from "@/ui/use-toast";
import { IListQuotes_Response_DTO } from "@shared/contexts"; import { IListQuotes_Response_DTO } from "@shared/contexts";
import { t } from "i18next"; import { t } from "i18next";
import { DownloadIcon, MoreVerticalIcon } from "lucide-react"; import { DownloadIcon, MoreVerticalIcon } from "lucide-react";
import { useCallback, useMemo } from "react"; import { useCallback, useEffect, useState } from "react";
import { Trans } from "react-i18next"; import { Trans } from "react-i18next";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useQuotes } from "../hooks"; import { useQuotes } from "../hooks";
import { DownloadQuoteDialog } from "./DownloadQuoteDialog";
export const QuotePDFPreview = ({ const QuotePDFPreview = ({
quote, quote,
className, className,
}: { }: {
@ -34,24 +33,42 @@ export const QuotePDFPreview = ({
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const { useReport, getQuotePDFFilename, useDownloader } = useQuotes(); const { useReport, getQuotePDFFilename, useDownloader } = useQuotes();
const { download, ...downloadProps } = useDownloader(); //const { download: downloadPDFFile } = useDownloader();
const { report, download, isInProgress } = useReport();
const { const [URLReport, setURLReport] = useState<string | undefined>(undefined);
data: reportData,
isLoading: reportIsLoading,
isPending: reportIsPending,
isFetching: reportIsFetching,
} = useReport(quote?.id);
const file = useMemo(() => (reportData ? { data: reportData.data } : undefined), [reportData]);
const handleFinishDownload = useCallback(() => { const handleFinishDownload = useCallback(() => {
console.log("Download success!!");
toast({ toast({
description: t("quotes.downloading_dialog.toast_success"), description: t("quotes.downloading_dialog.toast_success"),
}); });
}, [toast]); }, [toast]);
useEffect(() => {
const timer = setTimeout(() => {
if (!isInProgress && quote && quote.id) {
download(quote.id);
}
}, 200);
return () => clearTimeout(timer);
}, [quote]);
useEffect(() => {
if (!isInProgress && report) {
const blobURL =
window.URL && window.URL.createObjectURL
? window.URL.createObjectURL(report)
: window.webkitURL.createObjectURL(report);
setURLReport(blobURL);
return () => {
setURLReport(undefined);
window.URL.revokeObjectURL(blobURL);
};
}
}, [report, isInProgress]);
if (!quote) { if (!quote) {
return ( return (
<Card className={cn("overflow-hidden", className)}> <Card className={cn("overflow-hidden", className)}>
@ -62,7 +79,7 @@ export const QuotePDFPreview = ({
); );
} }
if (reportIsLoading || reportIsPending || reportIsFetching) { if (isInProgress) {
return ( return (
<Card className={cn("overflow-hidden flex flex-col", className)}> <Card className={cn("overflow-hidden flex flex-col", className)}>
<CardHeader> <CardHeader>
@ -108,7 +125,7 @@ export const QuotePDFPreview = ({
variant='outline' variant='outline'
className='h-8 gap-1' className='h-8 gap-1'
onClick={() => { onClick={() => {
download(quote.id, getQuotePDFFilename(quote)); //downloadPDFFile(quote.id, getQuotePDFFilename(quote));
}} }}
> >
<DownloadIcon className='h-3.5 w-3.5' /> <DownloadIcon className='h-3.5 w-3.5' />
@ -145,16 +162,22 @@ export const QuotePDFPreview = ({
</DropdownMenu> </DropdownMenu>
</div> </div>
</CardTitle> </CardTitle>
<CardDescription className='grid grid-cols-1 gap-2 space-y-2'> {false && (
{quote?.reference} <CardDescription className='grid grid-cols-1 gap-2 space-y-2'>
{quote?.date.toString()} {quote?.reference}
</CardDescription> {quote?.date.toString()}
</CardDescription>
)}
</CardHeader> </CardHeader>
<CardContent className='py-4'> <CardContent className='py-4'>
<PDFViewer file={file} className='object-contain' /> <PDFViewer file={URLReport} className='object-contain' />
</CardContent> </CardContent>
</Card> </Card>
<DownloadQuoteDialog {...downloadProps} onFinishDownload={handleFinishDownload} /> {/*<DownloadQuoteDialog {...downloadProps} onFinishDownload={handleFinishDownload} />*/}
</> </>
); );
}; };
QuotePDFPreview.whyDidYouRender = true;
export { QuotePDFPreview };

View File

@ -28,7 +28,7 @@ import { IListQuotes_Response_DTO, MoneyValue, UTCDateValue } from "@shared/cont
import { ColumnDef, Row } from "@tanstack/react-table"; import { ColumnDef, Row } from "@tanstack/react-table";
import { t } from "i18next"; import { t } from "i18next";
import { FilePenLineIcon, MoreVerticalIcon } from "lucide-react"; import { FilePenLineIcon, MoreVerticalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useId, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useQuotes } from "../hooks"; import { useQuotes } from "../hooks";
import { DownloadQuoteDialog } from "./DownloadQuoteDialog"; import { DownloadQuoteDialog } from "./DownloadQuoteDialog";
@ -43,6 +43,10 @@ export const QuotesDataTable = ({
}) => { }) => {
const navigate = useNavigate(); const navigate = useNavigate();
const { toast } = useToast(); const { toast } = useToast();
const tableId = useId();
const previewId = useId();
const { pagination, globalFilter, isFiltered } = useDataTableContext(); const { pagination, globalFilter, isFiltered } = useDataTableContext();
const [activeRow, setActiveRow] = useState<Row<IListQuotes_Response_DTO> | undefined>(undefined); const [activeRow, setActiveRow] = useState<Row<IListQuotes_Response_DTO> | undefined>(undefined);
@ -246,7 +250,12 @@ export const QuotesDataTable = ({
return ( return (
<> <>
<ResizablePanelGroup direction='horizontal' className='flex items-stretch flex-1 gap-4'> <ResizablePanelGroup direction='horizontal' className='flex items-stretch flex-1 gap-4'>
<ResizablePanel defaultSize={preview ? 66 : 100} className='flex items-stretch flex-1'> <ResizablePanel
id={tableId}
order={0}
defaultSize={preview ? 65 : 100}
className='flex items-stretch flex-1'
>
<DataTable <DataTable
table={table} table={table}
paginationOptions={{ visible: true }} paginationOptions={{ visible: true }}
@ -259,7 +268,12 @@ export const QuotesDataTable = ({
</ResizablePanel> </ResizablePanel>
{preview && <ResizableHandle withHandle />} {preview && <ResizableHandle withHandle />}
{preview && ( {preview && (
<ResizablePanel defaultSize={33} className='flex items-stretch flex-1'> <ResizablePanel
id={previewId}
order={1}
defaultSize={35}
className='flex items-stretch flex-1'
>
<QuotePDFPreview quote={activeRow?.original} className='flex-1' /> <QuotePDFPreview quote={activeRow?.original} className='flex-1' />
</ResizablePanel> </ResizablePanel>
)} )}

View File

@ -1,5 +1,5 @@
import { useDownloader } from "@/lib/hooks"; import { useDownloader } from "@/lib/hooks";
import { UseListQueryResult, useCustom, useList, useOne, useSave } from "@/lib/hooks/useDataSource"; import { UseListQueryResult, useList, useOne, useSave } from "@/lib/hooks/useDataSource";
import { import {
IFilterItemDataProviderParam, IFilterItemDataProviderParam,
IGetListDataProviderParams, IGetListDataProviderParams,
@ -13,13 +13,12 @@ import {
IGetQuote_Response_DTO, IGetQuote_Response_DTO,
IListQuotes_Response_DTO, IListQuotes_Response_DTO,
IListResponse_DTO, IListResponse_DTO,
IReportQuote_Response_DTO,
IUpdateQuote_Request_DTO, IUpdateQuote_Request_DTO,
IUpdateQuote_Response_DTO, IUpdateQuote_Response_DTO,
UniqueID, UniqueID,
} from "@shared/contexts"; } from "@shared/contexts";
import { useQueryClient } from "@tanstack/react-query"; import { useCallback, useState } from "react";
import { useCallback, useMemo, useState } from "react"; import slugify from "slugify";
export type UseQuotesListParams = Omit<IGetListDataProviderParams, "filters" | "resource"> & { export type UseQuotesListParams = Omit<IGetListDataProviderParams, "filters" | "resource"> & {
status?: string; status?: string;
@ -64,6 +63,23 @@ export const useQuotes = () => {
const dataSource = useDataSource(); const dataSource = useDataSource();
const keys = useQueryKey(); const keys = useQueryKey();
const getQuotePDFDownloadURL = useCallback(
(id: string) => `${dataSource.getApiUrl()}/quotes/${id}/report`,
[dataSource]
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const getQuotePDFFilename = useCallback(
(quote: IListQuotes_Response_DTO | IGetQuote_Response_DTO) =>
`quote-${slugify(quote.reference, {
lower: true, // Convierte a minúsculas
strict: true, // Elimina caracteres que no son letras o números
locale: "en", // Establece la localización para la conversión
trim: true, // Elimina espacios en blanco al principio y al final
})}.pdf`,
[]
);
const actions = { const actions = {
useList: (params: UseQuotesListParams): UseQuotesListResponse => { useList: (params: UseQuotesListParams): UseQuotesListResponse => {
const dataSource = useDataSource(); const dataSource = useDataSource();
@ -142,7 +158,7 @@ export const useQuotes = () => {
...params, ...params,
}), }),
useReport2: (id?: string, params?: UseQuotesReportParamsType) => { /*useReport2: (id?: string, params?: UseQuotesReportParamsType) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const queryKey = useMemo( const queryKey = useMemo(
() => keys().data().resource("quotes").action("report").id(id).params().get(), () => keys().data().resource("quotes").action("report").id(id).params().get(),
@ -172,12 +188,11 @@ export const useQuotes = () => {
}), }),
cancelQuery: () => queryClient.cancelQueries({ queryKey }), cancelQuery: () => queryClient.cancelQueries({ queryKey }),
}; };
}, },*/
getQuotePDFDownloadURL: (id: string) => `${dataSource.getApiUrl()}/quotes/${id}/report`, getQuotePDFDownloadURL,
getQuotePDFFilename: (quote: IListQuotes_Response_DTO | IGetQuote_Response_DTO) => getQuotePDFFilename,
`filename-quote.pdf`,
/*useDownload2: (id?: string, params?: UseQuotesReportParamsType) => { /*useDownload2: (id?: string, params?: UseQuotesReportParamsType) => {
const queryKey = useMemo( const queryKey = useMemo(
@ -223,32 +238,36 @@ export const useQuotes = () => {
useReport: () => { useReport: () => {
const auth = dataSource.getApiAuthorization(); const auth = dataSource.getApiAuthorization();
const [reportBlob, setReportBlob] = useState<Blob>(); const [report, setReport] = useState<Blob | undefined>(undefined);
const downloader = useDownloader({ const downloader = useDownloader({
headers: { headers: {
Authorization: auth, Authorization: auth,
}, },
customHandleDownload: (data: Blob) => { customHandleDownload: useCallback(
const blobData = [data]; (data: Blob) => {
const blob = new Blob(blobData, { const blobData = [data];
type: "application/pdf", const blob = new Blob(blobData, {
}); type: "application/octet-stream",
setReportBlob(blob); });
setReport(blob);
return true; return true;
}, },
[setReport]
),
}); });
const download = (id: string) => { const download = useCallback(
const url = actions.getQuotePDFDownloadURL(id); (id: string) => {
downloader.download(url, ""); return downloader.download(actions.getQuotePDFDownloadURL(id), "");
return reportBlob; },
}; [downloader]
);
return { return {
...downloader, ...downloader,
download, download,
report,
}; };
}, },

View File

@ -10,23 +10,22 @@ import { LoadingSpinner } from "../LoadingSpinner";
import "react-pdf/dist/esm/Page/AnnotationLayer.css"; import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import "react-pdf/dist/esm/Page/TextLayer.css"; import "react-pdf/dist/esm/Page/TextLayer.css";
pdfjs.GlobalWorkerOptions.workerSrc = new URL( /*pdfjs.GlobalWorkerOptions.workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.min.mjs", "pdfjs-dist/build/pdf.worker.min.mjs",
import.meta.url import.meta.url
).toString(); ).toString();*/
const options = { pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
cMapUrl: "/cmaps/",
standardFontDataUrl: "/standard_fonts/",
};
const maxWidth = 800; const maxWidth = 800;
const resizeObserverOptions = {}; const resizeObserverOptions = {};
export interface PDFViewerProps { export interface PDFViewerProps {
file?: { file?:
data: Uint8Array; | string
}; | {
data: Uint8Array;
};
className?: string; className?: string;
} }
@ -67,7 +66,9 @@ export const PDFViewer = ({ file, className }: PDFViewerProps): JSX.Element => {
const goToNextPage = useCallback(() => changePage(1), [changePage]); const goToNextPage = useCallback(() => changePage(1), [changePage]);
const goToPrevPage = useCallback(() => changePage(-1), [changePage]); const goToPrevPage = useCallback(() => changePage(-1), [changePage]);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const goToFirstPage = useCallback(() => setPageNumber(1), [setPageNumber]); const goToFirstPage = useCallback(() => setPageNumber(1), [setPageNumber]);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const goToLastPage = useCallback(() => setPageNumber(numPages), [setPageNumber, numPages]); const goToLastPage = useCallback(() => setPageNumber(numPages), [setPageNumber, numPages]);
const isLoading = useMemo( const isLoading = useMemo(
@ -75,13 +76,20 @@ export const PDFViewer = ({ file, className }: PDFViewerProps): JSX.Element => {
[renderedPageNumber, pageNumber] [renderedPageNumber, pageNumber]
); );
const options = useMemo(
() => ({
cMapUrl: "/cmaps/",
standardFontDataUrl: "/standard_fonts/",
}),
[]
);
return ( return (
<div <div
className={cn("flex flex-col cursor-default text-center", className)} className={cn("flex flex-col cursor-default text-center", className)}
ref={setContainerRef} ref={setContainerRef}
> >
<Document <Document
renderMode='canvas'
file={file} file={file}
onLoadSuccess={onDocumentLoadSuccess} onLoadSuccess={onDocumentLoadSuccess}
loading={<LoadingSpinner className='w-full mx-auto mt-32' />} loading={<LoadingSpinner className='w-full mx-auto mt-32' />}

View File

@ -214,39 +214,37 @@ export default function useDownloader({
// Use the custom handle download function if available // Use the custom handle download function if available
const _customHandleDownload = customHandleDownload || jsDownload; const _customHandleDownload = customHandleDownload || jsDownload;
return fetch(downloadUrl, { try {
method: "GET", const response = await fetch(downloadUrl, {
...options, method: "GET",
...overrideOptions, ...options,
signal: fetchController.signal, ...overrideOptions,
}) signal: fetchController.signal,
.then(resolverWithProgress)
.then((data) => {
return data.blob();
})
.then((response) => _customHandleDownload(response, filename))
.then(() => {
clearAllStateCallback();
return clearInterval(intervalId);
})
.catch((err) => {
clearAllStateCallback();
setError((prevValue) => {
const { message } = err;
if (message !== "Failed to fetch") {
return {
errorMessage: err.message,
};
}
return prevValue;
});
clearTimeout(timeoutId);
return clearInterval(intervalId);
}); });
const data = resolverWithProgress(response);
const blob = await data.blob();
_customHandleDownload(blob, filename);
clearAllStateCallback();
} catch (err: unknown) {
clearAllStateCallback();
setError((prevValue) => {
const { message } = err as Error;
if (message !== "Failed to fetch") {
return {
errorMessage: message,
};
}
return prevValue;
});
clearTimeout(timeoutId);
} finally {
clearInterval(intervalId);
}
}, },
[ [
isInProgress, isInProgress,

View File

@ -1,3 +1,6 @@
// eslint-disable-next-line import/order
import "./wdyr"; // <--- always first import
import React from "react"; import React from "react";
import ReactDOM from "react-dom/client"; import ReactDOM from "react-dom/client";
import App from "./App.tsx"; import App from "./App.tsx";

13
client/src/wdyr.ts Normal file
View File

@ -0,0 +1,13 @@
/// <reference types="@welldone-software/why-did-you-render" />
import * as React from "react";
if (import.meta.env.DEV && import.meta.env.VITE_ENABLE_WHY_DID_YOU_RENDER === "true") {
const { default: wdyr } = await import("@welldone-software/why-did-you-render");
wdyr(React, {
include: [/.*/],
exclude: [/^BrowserRouter/, /^Link/, /^Route/],
trackHooks: true,
trackAllPureComponents: true,
});
}

View File

@ -8,20 +8,10 @@ const require = createRequire(import.meta.url);
const pdfjsDistPath = path.dirname(require.resolve("pdfjs-dist/package.json")); const pdfjsDistPath = path.dirname(require.resolve("pdfjs-dist/package.json"));
const cMapsDir = normalizePath(path.join(pdfjsDistPath, "cmaps")); const cMapsDir = normalizePath(path.join(pdfjsDistPath, "cmaps"));
//const require = createRequire(import.meta.url);
/*const cMapsDir = normalizePath(
path.join(path.dirname(require.resolve("pdfjs-dist/package.json")), "cmaps")
);
const standardFontsDir = normalizePath( const standardFontsDir = normalizePath(
path.join( path.join(path.dirname(require.resolve("pdfjs-dist/package.json")), "standard_fonts")
path.dirname(require.resolve("pdfjs-dist/package.json")), );
"standard_fonts"
)
);*/
// https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
react(), react(),
@ -31,6 +21,10 @@ export default defineConfig({
src: cMapsDir, src: cMapsDir,
dest: "", dest: "",
}, },
{
src: standardFontsDir,
dest: "",
},
], ],
}), }),
], ],