Skip to content

Commit

Permalink
Improve file name
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucieo committed Mar 5, 2024
1 parent 507dafe commit 0fe8c4a
Show file tree
Hide file tree
Showing 8 changed files with 160 additions and 93 deletions.
44 changes: 27 additions & 17 deletions back/api/application/controllers/application.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'use strict';
'use strict'

/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-controllers)
Expand All @@ -7,18 +7,29 @@

module.exports = {
async myApplications(ctx) {
const populateCommon = ['disponibility.espace', 'disponibility.espace.users_permissions_user', 'creation_file' ]
const { id, type } = ctx.state.user;
const {query: initialQuery}=ctx.request;
const query = type === "place" ? {...initialQuery, 'disponibility.espace.users_permissions_user.id':id} : {...initialQuery, company: id };
const populate = type==="place"? [...populateCommon,'company', ]:[...populateCommon,'place']
const populateCommon = [
'disponibility.espace',
'disponibility.espace.users_permissions_user',
'creation_file',
'campaign',
]
const { id, type } = ctx.state.user
const { query: initialQuery } = ctx.request
const query =
type === 'place'
? {
...initialQuery,
'disponibility.espace.users_permissions_user.id': id,
}
: { ...initialQuery, company: id }
const populate =
type === 'place'
? [...populateCommon, 'company']
: [...populateCommon, 'place']

return strapi
.query("application")
.find(
query,
populate
)
.query('application')
.find(query, populate)
.then((res) => {
return Promise.all(
res.map(async (application) => {
Expand All @@ -29,10 +40,9 @@ module.exports = {
type,
applicationId: application.id,
}),
};
})
);
});
}
}),
)
})
},

};
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"x-generation-date": "03/05/2024 5:57:47 PM"
"x-generation-date": "03/05/2024 7:21:13 PM"
},
"x-strapi-config": {
"path": "/documentation",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@ const ApplicationEditRightPanel = ({
}}
color="white"
height="auto!important"
// isDisabled={isLoading}
isLoading={isLoading}
loadingText={t('company.detail.saving')}
type="submit"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import DownloadApplication from 'public/assets/img/downloadApplication.svg'
import { useState } from 'react'
import useToast from '~hooks/useToast'
import { Application } from '~typings/api'
import { formatApplicationPdfName, handleApplicationDownload } from '~utils/pdf'

const ApplicationDownloadButton = ({
application,
Expand Down Expand Up @@ -32,20 +33,13 @@ const ApplicationDownloadButton = ({
onClick={async () => {
setIsLoading(true)
try {
const res = await fetch(`/api/pdfs/single/${application.id}`)
if (!res.ok) {
errorToast(t('error'))
}
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'file.pdf') // or any other extension
document.body.appendChild(link)
link.click()
link.parentNode?.removeChild(link)
await handleApplicationDownload({
application,
onError: () => errorToast(t('error')),
})
} catch (err) {
console.error(err)
console.log(err)
errorToast(t('error'))
} finally {
setIsLoading(false)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
Grid,
GridItem,
Box,
Text,
Skeleton,
} from '@chakra-ui/react'
import { useTranslation } from 'next-i18next'
import ApplicationDetailHeader from '~components/Account/Application/Place/DetailDrawer/ApplicationDetailHeader'
Expand All @@ -19,6 +21,7 @@ import { useState } from 'react'
import { Document, Page } from 'react-pdf'

import useToast from '~hooks/useToast'
import { handleApplicationDownload } from '~utils/pdf'

const ApplicationDetailDrawer = ({
isOpen,
Expand All @@ -34,28 +37,20 @@ const ApplicationDetailDrawer = ({
const { t } = useTranslation('application')
const { id } = application ?? {}
const [isDownloading, setIsDownloading] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [scales, setScales] = useState([])
const { errorToast } = useToast()
const [numPages, setNumPages] = useState(0)

const handleDownload = async () => {
setIsDownloading(true)
try {
const res = await fetch(`/api/pdfs/single/${application.id}`)
if (!res.ok) {
errorToast(t('error'))
}
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'file.pdf') // or any other extension
document.body.appendChild(link)
link.click()
link.parentNode?.removeChild(link)
await handleApplicationDownload({
application,
onError: () => errorToast(t('error')),
})
} catch (err) {
console.error(err)
console.log(err)
errorToast(t('error'))
} finally {
setIsDownloading(false)
}
Expand All @@ -78,44 +73,54 @@ const ApplicationDetailDrawer = ({
<ApplicationDetailHeader application={application} />
<Divider />

<Box paddingBottom={4}>
<Box paddingBottom={4} width="100%">
<Grid templateColumns={'repeat(3, 1fr)'} gap={4} width="100%">
<GridItem
colSpan={{ base: 3, md: 2 }}
overflowX="auto"
maxHeight="90vh"
overflowY="auto"
>
<Document
file={`/api/pdfs/single/${application.id}`}
onLoadSuccess={({ numPages }) => {
setNumPages(numPages)
}}
>
{Array.from(new Array(numPages), (el, index) => (
<Page
key={`page_${index + 1}`}
pageNumber={index + 1}
onRenderSuccess={(page) => {
const viewport = page.getViewport({ scale: 1 })
if (viewport) {
const orientation =
viewport.width > viewport.height
? 'landscape'
: 'portrait'
// Adjust the scale based on the orientation
const scale = orientation === 'landscape' ? 0.6 : 1.0
setScales((prevScales) => {
const newScales = [...prevScales]
newScales[index] = scale
return newScales
})
}
}}
scale={scales[index] || 1.0}
/>
))}
</Document>
<Box overflowX="auto">
<Document
file={`/api/pdfs/single/${application.id}`}
onLoadSuccess={({ numPages }) => {
setNumPages(numPages)
}}
loading={
<Skeleton
height="100vh"
width="100vw"
variant="rectangle"
/>
}
>
{Array.from(new Array(numPages), (el, index) => (
<Page
key={`page_${index + 1}`}
pageNumber={index + 1}
onRenderSuccess={(page) => {
const viewport = page.getViewport({ scale: 1 })
if (viewport) {
const orientation =
viewport.width > viewport.height
? 'landscape'
: 'portrait'
// Adjust the scale based on the orientation
const scale =
orientation === 'landscape' ? 0.7 : 1.0
setScales((prevScales) => {
const newScales = [...prevScales]
newScales[index] = scale
return newScales
})
}
}}
scale={scales[index] || 1.0}
/>
))}
</Document>
</Box>
</GridItem>

<GridItem
Expand Down
17 changes: 6 additions & 11 deletions web/pages/api/pdfs/single/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,8 @@ import { client } from '~api/client-api'
import ApplicationDocument from '~components/pdfs/ApplicationDocument'
import { getSession } from 'next-auth/client'
import PDFMerger from 'pdf-merger-js'
import { Stream } from 'stream'

function getBufferFromStream(stream: Stream): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: any[] = []
stream.on('data', (chunk) => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => resolve(Buffer.concat(chunks)))
})
}
import { formatApplicationPdfName, getBufferFromStream } from '~utils/pdf'
import { format } from 'path'

const SingleApplication = async (req, res) => {
const { id } = req.query
Expand Down Expand Up @@ -48,7 +40,10 @@ const SingleApplication = async (req, res) => {
finalPDF = await merger.saveAsBuffer()
}
res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Disposition', 'attachment; filename=merged.pdf')
res.setHeader(
'Content-Disposition',
'attachment; filename=' + formatApplicationPdfName(application?.[0]),
)
res.send(finalPDF)
}

Expand Down
26 changes: 21 additions & 5 deletions web/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
Expand All @@ -15,10 +19,22 @@
"jsx": "preserve",
"baseUrl": ".",
"paths": {
"~*": ["*"]
"~*": [
"*"
]
},
"typeRoots": ["@types", "./node_modules/@types"]
"typeRoots": [
"@types",
"./node_modules/@types"
],
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
48 changes: 48 additions & 0 deletions web/utils/pdf.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Stream } from 'stream'
import { Application } from '~typings/api'
import { format } from '~utils/date'

export const getBufferFromStream = (stream: Stream): Promise<Buffer> => {
return new Promise((resolve, reject) => {
const chunks: any[] = []
stream.on('data', (chunk) => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => resolve(Buffer.concat(chunks)))
})
}

export const formatApplicationPdfName = (application: Application) => {
//@ts-expect-error
return `${application?.disponibility?.espace?.name
?.split(' ')
.join('_')}_${format(
application?.disponibility?.start,
'dd-MM-yyyy',
)}_${format(application?.disponibility?.end, 'dd-MM-yyyy')}_Ref-${
application?.id
//@ts-expect-error
}_${application?.disponibility?.espace?.users_permissions_user?.structureName
?.split(' ')
.join('_')}_${application?.campaign?.title?.split(' ').join('_')}.pdf`
}

export const handleApplicationDownload = async ({
application,
onError,
}: {
application: Application
onError: () => void
}) => {
const res = await fetch(`/api/pdfs/single/${application.id}`)
if (!res.ok) {
onError()
}
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', formatApplicationPdfName(application))
document.body.appendChild(link)
link.click()
link.parentNode?.removeChild(link)
}

0 comments on commit 0fe8c4a

Please sign in to comment.