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(datatrak): RN-1314: Auto populate entity question #5793

Merged
merged 3 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const DEFAULT_FIELDS = [
'country.name',
'data_time',
'entity.name',
'entity.id',
'id',
'survey.name',
'survey.code',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/

import React, { createContext, Dispatch, useContext, useEffect, useReducer } from 'react';
import React, { createContext, Dispatch, useContext, useReducer, useState } from 'react';
import { useMatch, useParams } from 'react-router-dom';
import { QuestionType } from '@tupaia/types';
import { ROUTES } from '../../../constants';
import { SurveyParams } from '../../../types';
import { useSurvey } from '../../../api';
Expand All @@ -17,6 +18,7 @@ import {
} from './utils';
import { SurveyFormContextType, surveyReducer } from './reducer';
import { ACTION_TYPES, SurveyFormAction } from './actions';
import { usePrimaryEntityLocation } from '../../../utils';

const defaultContext = {
startTime: new Date().toISOString(),
Expand All @@ -31,13 +33,16 @@ const defaultContext = {
displayQuestions: [],
sideMenuOpen: false,
cancelModalOpen: false,
primaryEntityQuestion: null,
} as SurveyFormContextType;

const SurveyFormContext = createContext(defaultContext);

export const SurveyFormDispatchContext = createContext<Dispatch<SurveyFormAction> | null>(null);

export const SurveyContext = ({ children }) => {
const [prevSurveyCode, setPrevSurveyCode] = useState<string | null>(null);
const primaryEntity = usePrimaryEntityLocation();
const [state, dispatch] = useReducer(surveyReducer, defaultContext);
const { surveyCode, ...params } = useParams<SurveyParams>();
const screenNumber = params.screenNumber ? parseInt(params.screenNumber!, 10) : null;
Expand All @@ -62,27 +67,36 @@ export const SurveyContext = ({ children }) => {
.filter(screen => screen.surveyScreenComponents.length > 0);

const activeScreen = visibleScreens?.[screenNumber! - 1]?.surveyScreenComponents || [];
const primaryEntityQuestion = flattenedScreenComponents.find(
question => question.type === QuestionType.PrimaryEntity,
);

useEffect(() => {
const initialiseFormData = () => {
if (!surveyCode || isResponseScreen) return;
// if we are on the response screen, we don't want to initialise the form data, because we want to show the user's saved answers
const initialFormData = generateCodeForCodeGeneratorQuestions(
flattenedScreenComponents,
formData,
);
dispatch({ type: ACTION_TYPES.SET_FORM_DATA, payload: initialFormData });
// update the start time when a survey is started, so that it can be passed on when submitting the survey

const currentDate = new Date();
dispatch({
type: ACTION_TYPES.SET_SURVEY_START_TIME,
payload: currentDate.toISOString(),
});
};
const initialiseFormData = () => {
if (!surveyCode || isResponseScreen) return;
// if we are on the response screen, we don't want to initialise the form data, because we want to show the user's saved answers
let initialFormData = generateCodeForCodeGeneratorQuestions(
flattenedScreenComponents,
formData,
);

if (primaryEntity && primaryEntityQuestion) {
initialFormData[primaryEntityQuestion.id as string] = primaryEntity;
}
dispatch({ type: ACTION_TYPES.SET_FORM_DATA, payload: initialFormData });
// update the start time when a survey is started, so that it can be passed on when submitting the survey

const currentDate = new Date();
dispatch({
type: ACTION_TYPES.SET_SURVEY_START_TIME,
payload: currentDate.toISOString(),
});
};

// @see https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
if (surveyCode !== prevSurveyCode) {
setPrevSurveyCode(surveyCode as string);
initialiseFormData();
}, [surveyCode]);
}

const displayQuestions = getDisplayQuestions(activeScreen, flattenedScreenComponents);
const screenHeader = activeScreen?.[0]?.text;
Expand All @@ -100,6 +114,7 @@ export const SurveyContext = ({ children }) => {
screenHeader,
screenDetail,
visibleScreens,
primaryEntityQuestion,
}}
>
<SurveyFormDispatchContext.Provider value={dispatch}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type SurveyFormContextType = {
surveyStartTime?: string;
isSuccessScreen?: boolean;
cancelModalOpen: boolean;
primaryEntityQuestion?: SurveyScreenComponent | null;
};

export const surveyReducer = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export const ActionButton = ({ task }: ActionButtonProps) => {
variant="contained"
state={{
from: location.pathname,
primaryEntity: entity.id,
}}
>
Complete task
Expand Down
1 change: 1 addition & 0 deletions packages/datatrak-web/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export {
getTaskFilterSetting,
removeTaskFilterSetting,
} from './taskFilterSettings';
export { usePrimaryEntityLocation } from './usePrimaryEntityLocation';
18 changes: 18 additions & 0 deletions packages/datatrak-web/src/utils/usePrimaryEntityLocation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Tupaia
* Copyright (c) 2017 - 2023 Beyond Essential Systems Pty Ltd
*/

import { useLocation } from 'react-router-dom';

function hasPrimaryEntity(state: unknown): state is { primaryEntity: string } {
if (state !== null && typeof state === 'object' && 'primaryEntity' in state) {
return typeof state.primaryEntity === 'string';
}
return false;
}

export function usePrimaryEntityLocation() {
const location = useLocation();
return hasPrimaryEntity(location.state) ? location.state.primaryEntity : undefined;
}
8 changes: 6 additions & 2 deletions packages/datatrak-web/src/views/SurveyResponsePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,20 +80,24 @@ const getSubHeadingText = surveyResponse => {

export const SurveyResponsePage = () => {
const { surveyResponseId } = useParams();
const { setFormData } = useSurveyForm();
const { setFormData, primaryEntityQuestion } = useSurveyForm();
const formContext = useFormContext();
const { data: surveyResponse } = useSurveyResponse(surveyResponseId);
const answers = surveyResponse?.answers || {};
const primaryEntityId = surveyResponse?.entityId;
const subHeading = getSubHeadingText(surveyResponse);

useEffect(() => {
if (answers) {
// Format the answers to be compatible with the form, i.e. parse stringified objects
const formattedAnswers = Object.entries(answers).reduce((acc, [key, value]) => {
let formattedAnswers = Object.entries(answers).reduce((acc, [key, value]) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can still be a const

// If the value is a stringified object, parse it
const isStringifiedObject = typeof value === 'string' && value.startsWith('{');
return { ...acc, [key]: isStringifiedObject ? JSON.parse(value) : value };
}, {});
if (primaryEntityQuestion) {
formattedAnswers[primaryEntityQuestion.id as string] = primaryEntityId;
}
formContext.reset(formattedAnswers);
setFormData(formattedAnswers);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface ResBody extends KeysToCamelCase<SurveyResponse> {
answers: Record<string, string>;
countryName: Country['name'];
entityName: Entity['name'];
entityId: Entity['id'];
surveyName: Survey['name'];
surveyCode: Survey['code'];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export type SurveyScreenComponent = CamelCasedComponent &
label?: BaseSurveyScreenComponent['question_label'];
options?: Option[] | null;
screenId?: string;
id?: string;
};

type CamelCasedSurveyScreen = KeysToCamelCase<Pick<BaseSurveyScreen, 'id' | 'screen_number'>>;
Expand Down
Loading