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 fill primary entity questions for a survey #5853

Merged
merged 11 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 10 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 @@ -25,6 +25,8 @@ import {
EntitiesRoute,
EntityDescendantsRequest,
EntityDescendantsRoute,
EntityAncestorsRequest,
EntityAncestorsRoute,
GenerateLoginTokenRequest,
GenerateLoginTokenRoute,
LeaderboardRequest,
Expand Down Expand Up @@ -79,6 +81,10 @@ export async function createApp() {
.get<UserRequest>('getUser', handleWith(UserRoute))
.get<SingleEntityRequest>('entity/:entityCode', handleWith(SingleEntityRoute))
.get<EntityDescendantsRequest>('entityDescendants', handleWith(EntityDescendantsRoute))
.get<EntityAncestorsRequest>(
'entityAncestors/:projectCode/:rootEntityCode',
handleWith(EntityAncestorsRoute),
)
.get<EntitiesRequest>('entities', handleWith(EntitiesRoute))
.get<SurveysRequest>('surveys', handleWith(SurveysRoute))
.get<SurveyResponsesRequest>('surveyResponses', handleWith(SurveyResponsesRoute))
Expand Down
36 changes: 36 additions & 0 deletions packages/datatrak-web-server/src/routes/EntityAncestorsRoute.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 { Request } from 'express';
import { Route } from '@tupaia/server-boilerplate';
import { TupaiaWebEntitiesRequest, Entity } from '@tupaia/types';
import { camelcaseKeys } from '@tupaia/tsutils';

export type EntityAncestorsRequest = Request<
TupaiaWebEntitiesRequest.Params,
TupaiaWebEntitiesRequest.ResBody,
TupaiaWebEntitiesRequest.ReqBody,
TupaiaWebEntitiesRequest.ReqQuery
>;

const DEFAULT_FIELDS = ['id', 'parent_code', 'code', 'name', 'type'];

export class EntityAncestorsRoute extends Route<EntityAncestorsRequest> {
public async buildResponse() {
const { params, query, ctx } = this.req;
const { rootEntityCode, projectCode } = params;

const entities: Entity[] = await ctx.services.entity.getAncestorsOfEntity(
projectCode,
rootEntityCode,
{
fields: DEFAULT_FIELDS,
},
true,
);

return camelcaseKeys(entities, { deep: true });
}
}
1 change: 1 addition & 0 deletions packages/datatrak-web-server/src/routes/TasksRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const FIELDS = [
'survey.code',
'entity.country_code',
'entity.name',
'entity.code',
'assignee_name',
'assignee_id',
'task_status',
Expand Down
1 change: 1 addition & 0 deletions packages/datatrak-web-server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export { SurveyResponsesRequest, SurveyResponsesRoute } from './SurveyResponsesR
export { ProjectsRequest, ProjectsRoute } from './ProjectsRoute';
export { SingleEntityRequest, SingleEntityRoute } from './SingleEntityRoute';
export { EntityDescendantsRequest, EntityDescendantsRoute } from './EntityDescendantsRoute';
export { EntityAncestorsRequest, EntityAncestorsRoute } from './EntityAncestorsRoute';
export { ProjectRequest, ProjectRoute } from './ProjectRoute';
export {
SubmitSurveyResponseRequest,
Expand Down
3 changes: 3 additions & 0 deletions packages/datatrak-web-server/src/utils/formatTaskResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import camelcaseKeys from 'camelcase-keys';

export type TaskT = Omit<Task, 'created_at' | 'repeat_schedule'> & {
'entity.name': Entity['name'];
'entity.code': Entity['code'];
'entity.parent_name': Entity['name'];
'entity.country_code': Country['code'];
'survey.code': Survey['code'];
Expand All @@ -23,6 +24,7 @@ export const formatTaskResponse = (task: TaskT): FormattedTask => {
const {
entity_id: entityId,
'entity.name': entityName,
'entity.code': entityCode,
'entity.parent_name': entityParentName,
'entity.country_code': entityCountryCode,
'survey.code': surveyCode,
Expand All @@ -38,6 +40,7 @@ export const formatTaskResponse = (task: TaskT): FormattedTask => {
entity: {
id: entityId,
name: entityName,
code: entityCode,
countryCode: entityCountryCode,
parentName: entityParentName,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/
import { getEntityQuestionAncestorAnswers } from '../../../features/Survey/utils/usePrimaryEntityQuestionAutoFill';

describe('getEntityQuestionAncestorAnswers', () => {
it('should return an empty object if the answer is not found', () => {
const question = {
config: {
entity: {
filter: {
type: ['facility'],
},
},
},
};
const questionsById = {};
const ancestorsByType = {};
// @ts-ignore
expect(getEntityQuestionAncestorAnswers(question, questionsById, ancestorsByType)).toEqual({});
});

it('should return the answer id if there is no parent question', () => {
const question = {
id: 'questionId',
config: {
entity: {
filter: {
type: ['facility'],
},
},
},
};
const questionsById = {};
const ancestorsByType = {
facility: {
id: 'facilityId',
},
};
// @ts-ignore
expect(getEntityQuestionAncestorAnswers(question, questionsById, ancestorsByType)).toEqual({
questionId: 'facilityId',
});
});

it('should return the ancestor id and the parent question ancestor ids', () => {
const question = {
id: 'questionId',
config: {
entity: {
filter: {
parentId: { questionId: 'parentQuestionId' },
type: ['facility'],
},
},
},
};
const parentQuestion = {
id: 'parentQuestionId',
config: {
entity: {
filter: {
type: ['district'],
},
},
},
};
const questionsById = {
questionId: question,
parentQuestionId: parentQuestion,
};
const ancestorsByType = {
facility: {
id: 'facilityId',
},
district: {
id: 'districtId',
},
};

expect(
// @ts-ignore
getEntityQuestionAncestorAnswers(question, questionsById, ancestorsByType),
).toEqual({
questionId: 'facilityId',
parentQuestionId: 'districtId',
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,17 @@ export const useSurveyResponseData = () => {
};
};

export const useSubmitSurveyResponse = (fromLocation?: string | undefined) => {
interface LocationStateProps {
from?: string | undefined;
}

export const useSubmitSurveyResponse = ({ from }: LocationStateProps) => {
const queryClient = useQueryClient();
const navigate = useNavigate();
const params = useParams();
const { resetForm } = useSurveyForm();
const user = useCurrentUserContext();
const { data: survey } = useSurvey(params.surveyCode);

const surveyResponseData = useSurveyResponseData();

return useMutation<any, Error, AnswersT, unknown>(
Expand Down Expand Up @@ -87,7 +90,7 @@ export const useSubmitSurveyResponse = (fromLocation?: string | undefined) => {
// include the survey response data in the location state, so that we can use it to generate QR codes
navigate(generatePath(ROUTES.SURVEY_SUCCESS, params), {
state: {
...(fromLocation && { from: fromLocation }),
...(from && { from }),
surveyResponse: JSON.stringify(data),
},
});
Expand Down
1 change: 1 addition & 0 deletions packages/datatrak-web/src/api/queries/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Copyright (c) 2017 - 2023 Beyond Essential Systems Pty Ltd
*/

export { useEntityAncestors } from './useEntityAncestors';
export { useUser } from './useUser';
export { useProjects } from './useProjects';
export { useSurveys } from './useSurveys';
Expand Down
19 changes: 19 additions & 0 deletions packages/datatrak-web/src/api/queries/useEntityAncestors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/

import { useQuery } from 'react-query';
import { Project } from '@tupaia/types';
import { Entity } from '../../types';
import { get } from '../api';

export const useEntityAncestors = (projectCode?: Project['code'], entityCode?: Entity['code']) => {
return useQuery(
['entityAncestors', projectCode, entityCode],
(): Promise<Entity[]> => get(`entityAncestors/${projectCode}/${entityCode}`),
{
enabled: !!projectCode && !!entityCode,
},
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styled from 'styled-components';
import { To, Link as RouterLink } from 'react-router-dom';
import { useFormContext } from 'react-hook-form';
import { Drawer as BaseDrawer, ListItem, List, ButtonProps } from '@material-ui/core';
import { useFromLocation, useIsMobile } from '../../../../utils';
import { useFromLocation, useIsMobile, usePrimaryEntityLocation } from '../../../../utils';
import { getSurveyScreenNumber } from '../../utils';
import { useSurveyRouting } from '../../useSurveyRouting';
import { SideMenuButton } from './SideMenuButton';
Expand Down Expand Up @@ -98,6 +98,7 @@ const Header = styled.div`

export const SurveySideMenu = () => {
const { getValues } = useFormContext();
const primaryEntityCode = usePrimaryEntityLocation();
const from = useFromLocation();
const isMobile = useIsMobile();
const {
Expand Down Expand Up @@ -146,7 +147,10 @@ export const SurveySideMenu = () => {
return (
<li key={screen.id}>
<SurveyMenuItem
state={{ ...(from && { from }) }}
state={{
...(from && { from }),
...(primaryEntityCode && { primaryEntityCode }),
}}
to={getScreenPath(num)}
$active={screenNumber === num}
onClick={onChangeScreen}
Expand Down
Loading
Loading