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 23 commits into
base: dev
Choose a base branch
from
Open
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
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 @@ -63,6 +63,8 @@ import {
UserRoute,
ResubmitSurveyResponseRequest,
ResubmitSurveyResponseRoute,
ExportSurveyResponseRequest,
ExportSurveyResponseRoute,
} from '../routes';
import { attachAccessPolicy } from './middleware';
import { API_CLIENT_PERMISSIONS } from '../constants';
Expand Down Expand Up @@ -115,6 +117,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,48 @@
/*
* 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;
},
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 } = 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);

return {
contents: buffer,
type: 'application/pdf',
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,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
Expand Up @@ -6,13 +6,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 @@ -21,16 +15,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 @@ -37,3 +37,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 @@ -20,3 +20,4 @@ export * from './useExportSurveyResponses';
export { useTupaiaRedirect } from './useTupaiaRedirect';
export { useCreateTask } from './useCreateTask';
export { useCreateTaskComment } from './useCreateTaskComment';
export { useExportSurveyResponse } from './useExportSurveyResponse';
35 changes: 35 additions & 0 deletions packages/datatrak-web/src/api/mutations/useExportSurveyResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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) => {
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,
},
});
},
{
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 @@ -33,6 +33,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 @@ -7,6 +7,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 @@ -92,7 +93,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 @@ -8,29 +8,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 @@ -55,15 +47,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 @@ -90,20 +99,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!);

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 @@ -22,6 +22,7 @@ import {
TasksDashboardPage,
TaskDetailsPage,
NotAuthorisedPage,
ExportSurveyResponsePage,
} from '../views';
import { useCurrentUserContext } from '../api';
import { ROUTES } from '../constants';
Expand Down Expand Up @@ -58,6 +59,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
22 changes: 13 additions & 9 deletions packages/datatrak-web/src/utils/date.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
/*
* Tupaia
* Copyright (c) 2017 - 2023 Beyond Essential Systems Pty Ltd
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/

import { format } from 'date-fns';

export const displayDate = (date?: Date | null) => {
export const displayDate = (date?: Date | 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 | 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
Loading