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

feat(datatrakWeb): RN-1407: PDF export of survey responses #5917

Open
wants to merge 30 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
04ac77c
Download button
alexd-bes Sep 18, 2024
a9a87f0
Heading
alexd-bes Sep 18, 2024
a2f9f8c
WIP
alexd-bes Sep 19, 2024
a6e29d8
Display styling
alexd-bes Sep 19, 2024
9e46baf
File tidy ups
alexd-bes Sep 19, 2024
3893d17
Styling
alexd-bes Sep 20, 2024
82ef603
Styling updates
alexd-bes Sep 23, 2024
227fec6
Geolocate questions
alexd-bes Sep 23, 2024
cae9b0d
Handle date formatting
alexd-bes Sep 23, 2024
4db8cc2
tweak layout
tcaiger Sep 30, 2024
70d2f3b
tweak styles
tcaiger Sep 30, 2024
b7bb152
Merge branch 'dev' into rn-1407-survey-response-pdf
tcaiger Oct 31, 2024
1fb6ffa
Merge pull request #5989 from beyondessential/dev
avaek Nov 4, 2024
27023f2
Merge pull request #5998 from beyondessential/dev
avaek Nov 10, 2024
bd9acdb
Merge branch 'dev' into rn-1407-survey-response-pdf
tcaiger Dec 10, 2024
1ba9ea1
refactor display questions
tcaiger Dec 10, 2024
fae4c4b
Update Question.tsx
tcaiger Dec 10, 2024
831ae50
fix file questions
tcaiger Dec 11, 2024
242da1a
Update Question.tsx
tcaiger Dec 12, 2024
d3724f0
Update Question.tsx
tcaiger Dec 12, 2024
9ef0bb8
Update SurveyQuestion.tsx
tcaiger Dec 12, 2024
0c38c8b
Update ExportSurveyResponsePage.tsx
tcaiger Dec 12, 2024
086280b
Update ExportSurveyResponsePage.tsx
tcaiger Dec 12, 2024
8afa0d2
Merge branch 'dev' into rn-1407-survey-response-pdf
tcaiger Jan 28, 2025
426f281
fix export date
tcaiger Jan 28, 2025
afed627
Update ExportSurveyResponsePage.tsx
tcaiger Jan 28, 2025
c7e8a63
fix tests
tcaiger Jan 29, 2025
ddddbf7
use survey response timezone
tcaiger Feb 4, 2025
5080462
useExportSurveyResponse
tcaiger Feb 4, 2025
8d49146
Update Question.tsx
tcaiger Feb 4, 2025
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
6 changes: 6 additions & 0 deletions packages/datatrak-web-server/src/app/createApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ import {
UserRoute,
ResubmitSurveyResponseRequest,
ResubmitSurveyResponseRoute,
ExportSurveyResponseRequest,
ExportSurveyResponseRoute,
} from '../routes';
import { attachAccessPolicy } from './middleware';
import { API_CLIENT_PERMISSIONS } from '../constants';
Expand Down Expand Up @@ -110,6 +112,10 @@ export async function createApp() {
handleWith(ResubmitSurveyResponseRoute),
)
.post<GenerateLoginTokenRequest>('generateLoginToken', handleWith(GenerateLoginTokenRoute))
.post<ExportSurveyResponseRequest>(
'export/:surveyResponseId',
handleWith(ExportSurveyResponseRoute),
)
// Forward auth requests to web-config
.use('signup', forwardRequest(WEB_CONFIG_API_URL, { authHandlerProvider }))
.use('resendEmail', forwardRequest(WEB_CONFIG_API_URL, { authHandlerProvider }))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*
*/

import { Request } from 'express';
import { Route } from '@tupaia/server-boilerplate';
import { downloadPageAsPDF } from '@tupaia/server-utils';

export type ExportSurveyResponseRequest = Request<
{
surveyResponseId: string;
},
{
contents: Buffer;
type: string;
},
{
baseUrl: string;
cookieDomain: string;
locale: string;
timezone: string;
},
Record<string, unknown>
>;

export class ExportSurveyResponseRoute extends Route<ExportSurveyResponseRequest> {
protected type = 'download' as const;

public async buildResponse() {
const { surveyResponseId } = this.req.params;
const { baseUrl, cookieDomain, locale, timezone } = this.req.body;
const { cookie } = this.req.headers;

if (!cookie) {
throw new Error(`Must have a valid session to export a dashboard`);
}

const pdfPageUrl = `${baseUrl}/export/${surveyResponseId}?locale=${locale}`;

const buffer = await downloadPageAsPDF(pdfPageUrl, cookie, cookieDomain, false, true, timezone);

return {
contents: buffer,
type: 'application/pdf',
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const DEFAULT_FIELDS = [
'assessor_name',
'country.name',
'data_time',
'end_time',
'entity.name',
'entity.id',
'id',
Expand Down
18 changes: 1 addition & 17 deletions packages/datatrak-web-server/src/routes/SurveyResponsesRoute.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import { Request } from 'express';
import camelcaseKeys from 'camelcase-keys';
import { Route } from '@tupaia/server-boilerplate';
import {
DatatrakWebSurveyResponsesRequest,
SurveyResponse,
Country,
Entity,
Survey,
} from '@tupaia/types';
import { DatatrakWebSurveyResponsesRequest } from '@tupaia/types';

export type SurveyResponsesRequest = Request<
DatatrakWebSurveyResponsesRequest.Params,
Expand All @@ -16,16 +10,6 @@ export type SurveyResponsesRequest = Request<
DatatrakWebSurveyResponsesRequest.ReqQuery
>;

type SurveyResponseT = Record<string, any> & {
assessor_name: SurveyResponse['assessor_name'];
'country.name': Country['name'];
data_time: Date;
'entity.name': Entity['name'];
id: SurveyResponse['id'];
'survey.name': Survey['name'];
'survey.project_id': Survey['project_id'];
};

const DEFAULT_FIELDS = [
'assessor_name',
'country.name',
Expand Down
4 changes: 4 additions & 0 deletions packages/datatrak-web-server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,7 @@ export {
PermissionGroupUsersRequest,
PermissionGroupUsersRoute,
} from './PermissionGroupUsersRoute';
export {
ExportSurveyResponseRequest,
ExportSurveyResponseRoute,
} from './ExportSurveyResponseRoute';
12 changes: 12 additions & 0 deletions packages/datatrak-web/public/tupaia-logo-dark.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions packages/datatrak-web/src/api/mutations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export * from './useExportSurveyResponses';
export { useTupaiaRedirect } from './useTupaiaRedirect';
export { useCreateTask } from './useCreateTask';
export { useCreateTaskComment } from './useCreateTaskComment';
export { useExportSurveyResponse } from './useExportSurveyResponse';
36 changes: 36 additions & 0 deletions packages/datatrak-web/src/api/mutations/useExportSurveyResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/
import { useMutation } from '@tanstack/react-query';
import download from 'downloadjs';
import { API_URL, post } from '../api';
import { successToast } from '../../utils';

// Requests a survey response PDF export from the server, and returns the response
export const useExportSurveyResponse = (surveyResponseId: string, timezone?: string | null) => {
return useMutation<any, Error, unknown, unknown>(
() => {
const baseUrl = `${window.location.protocol}//${window.location.host}`;

// Auth cookies are saved against this domain. Pass this to server, so that when it pretends to be us, it can do the same.
const cookieDomain = new URL(API_URL).hostname;

return post(`export/${surveyResponseId}`, {
responseType: 'blob',
data: {
cookieDomain,
baseUrl,
locale: window.navigator.language,
timezone: timezone,
},
});
},
{
onSuccess: data => {
download(data, `survey_response_${surveyResponseId}.pdf`);
successToast('Survey response downloaded');
},
},
);
};
1 change: 1 addition & 0 deletions packages/datatrak-web/src/constants/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const ROUTES = {
TASKS: '/tasks',
TASK_DETAILS: '/tasks/:taskId',
NOT_AUTHORISED: '/not-authorised',
EXPORT_SURVEY_RESPONSE: 'export/:surveyResponseId',
};

export const PASSWORD_RESET_TOKEN_PARAM = 'passwordResetToken';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React from 'react';
import styled from 'styled-components';
import { useFormContext, Controller } from 'react-hook-form';
import { FormHelperText } from '@material-ui/core';
import { stripTimezoneFromDate } from '@tupaia/utils';
import {
BinaryQuestion,
DateQuestion,
Expand Down Expand Up @@ -88,7 +89,9 @@ export const SurveyQuestion = ({
const getDefaultValue = () => {
if (formData[name] !== undefined) return formData[name];
// This is so that the default value gets carried through to the component, and dates that have a visible value of 'today' have that value recognised when validating
if (type?.includes('Date')) return isResubmit ? null : new Date();
if (type?.includes('Date')) {
return isResubmit ? null : stripTimezoneFromDate(new Date());
}
return undefined;
};

Expand Down
59 changes: 40 additions & 19 deletions packages/datatrak-web/src/features/SurveyResponseModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,21 @@ import { useForm, FormProvider } from 'react-hook-form';
import { useSearchParams } from 'react-router-dom';
import styled from 'styled-components';
import { Dialog, Typography } from '@material-ui/core';
import {
ModalContentProvider,
ModalFooter,
ModalHeader,
SpinningLoader,
} from '@tupaia/ui-components';
import { ModalContentProvider, ModalFooter, SpinningLoader } from '@tupaia/ui-components';
import { DatatrakWebSingleSurveyResponseRequest } from '@tupaia/types';
import { useSurveyResponse } from '../api/queries';
import { Button, SurveyTickIcon } from '../components';
import { Button, DownloadIcon, SurveyTickIcon } from '../components';
import { displayDate } from '../utils';
import { SurveyReviewSection, useSurveyResponseWithForm } from './Survey';
import { SurveyContext } from '.';
import { useExportSurveyResponse } from '../api';

const Header = styled.div`
display: flex;
align-items: center;
padding: 0.5rem;
justify-content: space-between;
padding: 1.5rem 1.8rem 1.2rem;
width: 100%;

.MuiSvgIcon-root {
font-size: 2.5em;
margin-right: 0.35em;
}
`;

const Heading = styled(Typography).attrs({
Expand All @@ -50,15 +42,32 @@ const SubHeading = styled(Typography)`
`;

const Loader = styled(SpinningLoader)`
width: 25rem;
padding-block: 3rem;
max-width: 100%;
`;

const Content = styled.div`
min-height: 10rem;
width: 62rem;
max-width: 100%;
`;

const Icon = styled(SurveyTickIcon)`
font-size: 2.5rem;
margin-right: 0.35rem;
`;

const DownloadButton = styled(Button).attrs({
variant: 'outlined',
})`
margin-left: auto;
&.Mui-disabled.MuiButtonBase-root {
opacity: 0.5;
color: ${({ theme }) => theme.palette.primary.main};
border-color: ${({ theme }) => theme.palette.primary.main};
}
`;

const getSubHeadingText = surveyResponse => {
if (!surveyResponse) {
return null;
Expand All @@ -85,20 +94,32 @@ const SurveyResponseModalContent = ({
const { surveyLoading } = useSurveyResponseWithForm(surveyResponse);
const subHeading = getSubHeadingText(surveyResponse);
const showLoading = isLoading || surveyLoading;
const [urlSearchParams] = useSearchParams();
const surveyResponseId = urlSearchParams.get('responseId');
const { mutate: downloadSurveyResponse, isLoading: isDownloadingSurveyResponse } =
useExportSurveyResponse(surveyResponseId!, surveyResponse?.timezone);

return (
<>
<ModalHeader onClose={onClose} title={error ? 'Error loading survey response' : ''}>
<Header>
{!showLoading && !error && (
<Header>
<SurveyTickIcon />
<>
<Icon />
<div>
<Heading>{surveyResponse?.surveyName}</Heading>
<SubHeading>{subHeading}</SubHeading>
</div>
</Header>
<DownloadButton
onClick={downloadSurveyResponse}
isLoading={isDownloadingSurveyResponse}
loadingText="Downloading"
startIcon={<DownloadIcon />}
>
Download
</DownloadButton>
</>
)}
</ModalHeader>
</Header>
<ModalContentProvider error={error as Error}>
<Content>
{showLoading && <Loader />}
Expand Down
2 changes: 2 additions & 0 deletions packages/datatrak-web/src/routes/Routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
TasksDashboardPage,
TaskDetailsPage,
NotAuthorisedPage,
ExportSurveyResponsePage,
} from '../views';
import { useCurrentUserContext } from '../api';
import { ROUTES } from '../constants';
Expand Down Expand Up @@ -53,6 +54,7 @@ const AuthViewLoggedInRedirect = ({ children }) => {
export const Routes = () => {
return (
<RouterRoutes>
<Route path={ROUTES.EXPORT_SURVEY_RESPONSE} element={<ExportSurveyResponsePage />} />
<Route path="/" element={<MainPageLayout />}>
{/* PRIVATE ROUTES */}
<Route path="/" element={<PrivateRoute />}>
Expand Down
20 changes: 12 additions & 8 deletions packages/datatrak-web/src/utils/date.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import { format } from 'date-fns';

export const displayDate = (date?: Date | null) => {
export const displayDate = (date?: Date | string | null, localeCode?: string) => {
if (!date) {
return '';
}
return new Date(date).toLocaleDateString();
return new Date(date).toLocaleDateString(localeCode);
};

export const displayDateTime = (date?: Date | null) => {
export const displayDateTime = (date?: Date | string | null, locale?: string) => {
if (!date) {
return '';
}

const dateDisplay = displayDate(date);
const timeDisplay = format(new Date(date), 'p');
return `${dateDisplay} ${timeDisplay}`;
return new Date(date)
.toLocaleString(locale, {
hour: '2-digit',
minute: '2-digit',
year: 'numeric',
month: 'numeric',
day: 'numeric',
})
.replace(',', ' ');
};
Loading