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

fix: [DHIS2-16994] Image and File DE and TEA not Displayed in Changelog #3837

Merged
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
02f2536
feat: temp
henrikmv Oct 9, 2024
1e14e25
fix: revert clienttolist changes
henrikmv Oct 9, 2024
6cd1a7d
fix: code clean up
henrikmv Oct 9, 2024
94d61f3
feat: temp
henrikmv Oct 9, 2024
1464867
fix: wrong else statement
henrikmv Oct 10, 2024
9a5dbda
feat: add link for image and file data element
henrikmv Oct 11, 2024
41b9ed1
fix: image and file for tea
henrikmv Oct 13, 2024
c546e9c
fix: show only latest image and file
henrikmv Oct 13, 2024
05a6059
fix: revert change
henrikmv Oct 13, 2024
6cfeb66
fix: update islatestvalue to check for fieldid
henrikmv Oct 14, 2024
72b9d50
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Oct 16, 2024
eceb19e
feat: temp
henrikmv Oct 18, 2024
8389805
fix: caching
henrikmv Oct 22, 2024
45b10e9
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Oct 22, 2024
5781035
fix: ensure text utilizes space without overflow
henrikmv Oct 23, 2024
56748b7
fix: add try catch to all query calls
henrikmv Oct 25, 2024
877d489
fix: use storagestatus to find latest value
henrikmv Oct 28, 2024
d8a92bf
fix: string improvement
henrikmv Oct 28, 2024
9a2c8c2
Revert "fix: string improvement"
henrikmv Oct 28, 2024
a849f28
Revert "fix: use storagestatus to find latest value"
henrikmv Nov 4, 2024
2b4cb96
feat: temp
henrikmv Nov 5, 2024
8217a68
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Nov 5, 2024
292ff79
feat: compare with event data to find latest value
henrikmv Nov 5, 2024
df7011f
feat: image and file for event and tracked entity
henrikmv Nov 6, 2024
4276fbf
fix: performance
henrikmv Nov 6, 2024
c80b635
fix: review comments
henrikmv Nov 7, 2024
94b3aca
fix: review comments
henrikmv Nov 11, 2024
879f45d
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Nov 11, 2024
04590c3
fix: latest value not shown
henrikmv Nov 12, 2024
dd12732
fix: missing question mark
henrikmv Nov 12, 2024
69f0075
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Nov 13, 2024
87b7387
Merge branch 'master' into hv/fix/DHIS2-16994_ImageAndFileDEAndTEANot…
henrikmv Nov 13, 2024
32adfb3
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Nov 14, 2024
9d54e47
Merge branch 'hv/fix/DHIS2-16994_ImageAndFileDEAndTEANotDisplayedInCh…
henrikmv Nov 14, 2024
94b5994
Merge branch 'master' of https://github.com/dhis2/capture-app into hv…
henrikmv Nov 18, 2024
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
@@ -1,22 +1,35 @@
// @flow
import { useState, useEffect, useMemo } from 'react';
import moment from 'moment';
import { v4 as uuid } from 'uuid';
import log from 'loglevel';
import { errorCreator } from 'capture-core-utils';
import { useMemo, useState } from 'react';
import { useTimeZoneConversion } from '@dhis2/app-runtime';
import { useTimeZoneConversion, useConfig, useDataEngine } from '@dhis2/app-runtime';
import { errorCreator, buildUrl } from 'capture-core-utils';
import { useApiDataQuery } from '../../../../utils/reactQueryHelpers';
import { CHANGELOG_ENTITY_TYPES, QUERY_KEYS_BY_ENTITY_TYPE } from '../Changelog/Changelog.constants';
import type { Change, ChangelogRecord, ItemDefinitions, SortDirection } from '../Changelog/Changelog.types';
import {
CHANGELOG_ENTITY_TYPES,
QUERY_KEYS_BY_ENTITY_TYPE,
} from '../Changelog/Changelog.constants';
import type {
Change,
ChangelogRecord,
ItemDefinitions,
SortDirection,
} from '../Changelog/Changelog.types';
import { convertServerToClient } from '../../../../converters';
import { convert } from '../../../../converters/clientToList';
import {
RECORD_TYPE,
subValueGetterByElementType,
} from '../utils/getSubValueForChangelogData';
import { makeQuerySingleResource } from '../../../../utils/api';

type Props = {
entityId: string,
programId?: string,
entityType: $Values<typeof CHANGELOG_ENTITY_TYPES>,
dataItemDefinitions: ItemDefinitions,
}
};

const DEFAULT_PAGE_SIZE = 10;
const DEFAULT_SORT_DIRECTION = 'default';
Expand All @@ -39,10 +52,20 @@ export const useChangelogData = ({
programId,
dataItemDefinitions,
}: Props) => {
const dataEngine = useDataEngine();
const { baseUrl, apiVersion } = useConfig();
const { fromServerDate } = useTimeZoneConversion();
const absoluteApiPath = buildUrl(baseUrl, `api/${apiVersion}`);

const [page, setPage] = useState<number>(1);
const [pageSize, setPageSize] = useState<number>(DEFAULT_PAGE_SIZE);
const [sortDirection, setSortDirection] = useState<SortDirection>(DEFAULT_SORT_DIRECTION);
const { fromServerDate } = useTimeZoneConversion();
const [records, setRecords] = useState<?Array<ChangelogRecord>>(undefined);

const querySingleResource = useMemo(
() => makeQuerySingleResource(dataEngine.query.bind(dataEngine)),
[dataEngine],
);

const handleChangePageSize = (newPageSize: number) => {
setPage(1);
Expand All @@ -67,54 +90,109 @@ export const useChangelogData = ({
},
);

const records: ?Array<ChangelogRecord> = useMemo(() => {
if (!data) return undefined;

return data.changeLogs.map((changelog) => {
const { change: apiChange, createdAt, createdBy } = changelog;
const elementKey = Object.keys(apiChange)[0];
const change = apiChange[elementKey];

const { metadataElement, fieldId } = getMetadataItemDefinition(
elementKey,
change,
dataItemDefinitions,
);

if (!metadataElement) {
log.error(errorCreator('Could not find metadata for element')({
...changelog,
}));
return null;
}

const { firstName, surname, username } = createdBy;
const { options } = metadataElement;

const previousValue = convert(
convertServerToClient(change.previousValue, metadataElement.type),
metadataElement.type,
options,
);

const currentValue = convert(
convertServerToClient(change.currentValue, metadataElement.type),
metadataElement.type,
options,
useEffect(() => {
henrikmv marked this conversation as resolved.
Show resolved Hide resolved
const fetchRecords = async () => {
if (!data) return;

const mostRecentCreatedAtByFieldId = data.changeLogs.reduce((acc, record) => {
const elementKey = Object.keys(record.change)[0];
const fieldId = record.change[elementKey]?.dataElement ?? record.change[elementKey]?.attribute;

if (!acc[fieldId] || moment(record.createdAt).isAfter(acc[fieldId])) {
acc[fieldId] = record.createdAt;
}
return acc;
}, {});

const fetchedRecords = await Promise.all(
data.changeLogs.map(async (changelog) => {
const { change: apiChange, createdAt, createdBy, type } = changelog;
const elementKey = Object.keys(apiChange)[0];
const change = apiChange[elementKey];

const { metadataElement, fieldId } = getMetadataItemDefinition(
elementKey,
change,
dataItemDefinitions,
);

if (!metadataElement) {
log.error(
errorCreator('Could not find metadata for element')({ ...changelog }),
);
return null;
}

const getSubValue =
subValueGetterByElementType[RECORD_TYPE[entityType]]?.[metadataElement.type];

const isLatestValue =
moment(createdAt).isSameOrAfter(mostRecentCreatedAtByFieldId[fieldId]);

const getValue = async (value, latestValue) => {
if (!getSubValue) {
return convertServerToClient(value, metadataElement.type);
}
if (entityType === RECORD_TYPE.trackedEntity) {
return getSubValue({
trackedEntity: { teiId: entityId, value },
programId,
attributeId: fieldId,
absoluteApiPath,
querySingleResource,
latestValue,
});
}
if (entityType === RECORD_TYPE.event) {
return getSubValue({
dataElement: { id: fieldId, value },
eventId: entityId,
absoluteApiPath,
querySingleResource,
latestValue,
});
}
return null;
};

const [previousValueRaw, currentValueRaw] = await Promise.all([
change.previousValue ? getValue(change.previousValue, false) : null,
getValue(change.currentValue, isLatestValue),
]);

const { firstName, surname, username } = createdBy;
const { options } = metadataElement;

const previousValue = convert(previousValueRaw, metadataElement.type, options);
const currentValue = convert(currentValueRaw, metadataElement.type, options);

return {
reactKey: uuid(),
date: moment(fromServerDate(createdAt)).format('YYYY-MM-DD HH:mm'),
henrikmv marked this conversation as resolved.
Show resolved Hide resolved
user: `${firstName} ${surname} (${username})`,
dataItemId: fieldId,
changeType: type,
dataItemLabel: metadataElement.name,
previousValue,
currentValue,
};
}),
);

return {
reactKey: uuid(),
date: moment(fromServerDate(createdAt)).format('YYYY-MM-DD HH:mm'),
user: `${firstName} ${surname} (${username})`,
dataItemId: fieldId,
changeType: changelog.type,
dataItemLabel: metadataElement.name,
previousValue,
currentValue,
};
}).filter(Boolean);
}, [data, dataItemDefinitions, fromServerDate]);
setRecords(fetchedRecords.filter(Boolean));
};

fetchRecords();
}, [
data,
dataItemDefinitions,
fromServerDate,
entityId,
entityType,
programId,
absoluteApiPath,
querySingleResource,
]);

return {
records,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// @flow
import { dataElementTypes } from '../../../../metaData';
import type { QuerySingleResource } from '../../../../utils/api';

type SubValueTEAProps = {
trackedEntity: Object,
attributeId: string,
programId: string,
absoluteApiPath: string,
querySingleResource: QuerySingleResource,
latestValue?: boolean,
};

type SubValuesDataElementProps = {
dataElement: Object,
querySingleResource: QuerySingleResource,
eventId: string,
absoluteApiPath: string,
latestValue?: boolean,
};

const buildTEAUrlByElementType: {|
[string]: Function,
|} = {
[dataElementTypes.FILE_RESOURCE]: async ({
trackedEntity,
attributeId,
programId,
absoluteApiPath,
querySingleResource,
latestValue,
}: SubValueTEAProps) => {
const { teiId, value } = trackedEntity;
if (!value) return null;
const { id, displayName: name } = await querySingleResource({ resource: `fileResources/${value}` });
henrikmv marked this conversation as resolved.
Show resolved Hide resolved

if (!latestValue) {
return name;
}

return {
id,
name,
url: `${absoluteApiPath}/tracker/trackedEntities/${teiId}/attributes/${attributeId}/file?program=${programId}`,
};
},
[dataElementTypes.IMAGE]: async ({
trackedEntity,
attributeId,
programId,
absoluteApiPath,
latestValue,
querySingleResource,
}: SubValueTEAProps) => {
const { teiId, value } = trackedEntity;
if (!value) return null;
const { id, displayName: name } = await querySingleResource({ resource: `fileResources/${value}` });

if (!latestValue) {
return name;
}

return {
id,
name,
url: `${absoluteApiPath}/tracker/trackedEntities/${teiId}/attributes/${attributeId}/image?program=${programId}`,
previewUrl: `${absoluteApiPath}/tracker/trackedEntities/${teiId}/attributes/${attributeId}/image?program=${programId}&dimension=small`,
};
},
};


const buildDataElementUrlByElementType: {|
[string]: Function,
|} = {
[dataElementTypes.FILE_RESOURCE]: async ({ dataElement, querySingleResource, eventId, absoluteApiPath, latestValue }: SubValuesDataElementProps) => {
const { id: dataElementId, value } = dataElement;
if (!value) return null;

const { id, displayName: name } = await querySingleResource({ resource: `fileResources/${value}` });

if (!latestValue) {
return name;
}

return {
id,
name,
url: `${absoluteApiPath}/tracker/events/${eventId}/dataValues/${dataElementId}/file`,
};
},
[dataElementTypes.IMAGE]: async ({ dataElement, querySingleResource, eventId, absoluteApiPath, latestValue }: SubValuesDataElementProps) => {
const { id: dataElementId, value } = dataElement;
if (!value) return null;

const { id, displayName: name } = await querySingleResource({ resource: `fileResources/${value}` });

if (!latestValue) {
return name;
}

return {
id,
name,
url: `${absoluteApiPath}/tracker/events/${eventId}/dataValues/${dataElementId}/image`,
previewUrl: `${absoluteApiPath}/tracker/events/${eventId}/dataValues/${dataElementId}/image?dimension=small`,
};
},
};

export const RECORD_TYPE = Object.freeze({
event: 'event',
trackedEntity: 'trackedEntity',
});

export const subValueGetterByElementType = Object.freeze({
[RECORD_TYPE.trackedEntity]: buildTEAUrlByElementType,
[RECORD_TYPE.event]: buildDataElementUrlByElementType,
});
Loading