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

[DHIS2-11878] feat: add program rules #2263

Merged
merged 1 commit into from
Nov 17, 2021
Merged
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
10 changes: 8 additions & 2 deletions i18n/en.pot
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ msgstr ""
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"POT-Creation-Date: 2021-11-04T12:22:50.798Z\n"
"PO-Revision-Date: 2021-11-04T12:22:50.798Z\n"
"POT-Creation-Date: 2021-11-16T08:56:46.802Z\n"
"PO-Revision-Date: 2021-11-16T08:56:46.802Z\n"

msgid "Choose one or more dates..."
msgstr ""
Expand Down Expand Up @@ -985,6 +985,12 @@ msgstr ""
msgid "Save changes"
msgstr ""

msgid "There are errors in this form"
msgstr ""

msgid "There are warnings in this form"
msgstr ""

msgid "Profile"
msgstr ""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ export {
export {
batchActionTypes as enrollmentBatchActionTypes,
runRulesOnUpdateFieldBatch,
updateFieldBatch as enrollmentUpdateFieldBatch,
updateDataEntryFieldBatch as enrollmentUpdateDataEntryFieldBatch,
} from './actions/enrollment.actionBatchs';
export { buildServerData } from './helpers/buildServerData';
export {
Expand Down
2 changes: 0 additions & 2 deletions src/core_modules/capture-core/components/DataEntries/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ export {
enrollmentBatchActionTypes,
runRulesOnEnrollmentFieldUpdateEpic,
runRulesOnEnrollmentDataEntryFieldUpdateEpic,
enrollmentUpdateFieldBatch,
enrollmentUpdateDataEntryFieldBatch,
} from './Enrollment';
export {
openDataEntryForNewTeiBatchAsync,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,45 @@ import { Modal, ModalTitle, ModalContent, ModalActions, ButtonStrip, Button } fr
import i18n from '@dhis2/d2-i18n';
import { useDispatch } from 'react-redux';
import { batchActions } from 'redux-batched-actions';
import { NoticeBoxes } from './NoticeBoxes.container';
import type { Props } from './dataEntry.types';
import { DataEntry } from '../../DataEntry';
import { getOpenDataEntryActions, getRulesActions } from './actions';
import { enrollmentUpdateFieldBatch, enrollmentUpdateDataEntryFieldBatch } from '../../DataEntries';
import { buildForm } from './buildForm';
import { useProgramRules } from './hooks';
import { updateFieldBatch, updateDataEntryFieldBatch } from './actions.batchs';
import { buildProgram } from './buildForm';

export const DataEntryProfile = ({ programAPI, orgUnitId, onCancel, toggleEditModal }: Props) => {
const { programRules, loading: loadingProgramRules } = useProgramRules(programAPI.id);

const dataEntryId = 'trackedEntityProfile';
const itemId = 'edit';
const dispatch = useDispatch();
const [enrollment, setEnrollment] = useState<any>({});
const [program, setProgram] = useState<any>({});
const [startUpdate, setStartUpdate] = useState(false);
const orgUnit: Object = useMemo(() => ({ id: orgUnitId }), [orgUnitId]);
const trackedEntityName = useMemo(() => programAPI?.trackedEntityType?.displayName || '', [programAPI]);

useEffect(() => {
if (Object.entries(enrollment).length === 0) {
buildForm(programAPI, setEnrollment);
if (!loadingProgramRules && Object.entries(program).length === 0) {
buildProgram({
programAPI,
setProgram,
programRules,
});
}
}, [programAPI, enrollment]);
}, [programAPI, program, loadingProgramRules, programRules]);

useEffect(() => {
if (enrollment && Object.entries(enrollment).length > 0) {
if (program && Object.entries(program).length > 0) {
dispatch(
batchActions([
...getOpenDataEntryActions(orgUnit, dataEntryId, itemId),
...getRulesActions(enrollment.enrollmentForm, orgUnit, dataEntryId, itemId),
...getRulesActions(program, orgUnit, dataEntryId, itemId),
]),
);
}
}, [dispatch, enrollment, orgUnit]);
}, [dispatch, program, orgUnit]);

return (
<div>
Expand All @@ -47,25 +56,25 @@ export const DataEntryProfile = ({ programAPI, orgUnitId, onCancel, toggleEditMo
)}
<DataEntry
id={dataEntryId}
formFoundation={enrollment?.enrollmentForm}
formFoundation={program.enrollment?.enrollmentForm}
onUpdateFormField={(...args: Array<any>) =>
dispatch(enrollmentUpdateFieldBatch(...args, programAPI.id, orgUnit))
dispatch(updateFieldBatch(...args, program, orgUnit))
}
onUpdateDataEntryField={(...args: Array<any>) =>
dispatch(enrollmentUpdateDataEntryFieldBatch(...args, programAPI.id, orgUnit))
dispatch(updateDataEntryFieldBatch(...args, program, orgUnit))
}
onUpdateFormFieldAsync={() => {}}
onGetValidationContext={() => {}}
saveAttempted={undefined}
/>
<NoticeBoxes dataEntryId={dataEntryId} itemId={itemId} onComplete={startUpdate} />
</ModalContent>
<ModalActions>
<ButtonStrip end>
<Button onClick={onCancel} secondary>
{i18n.t('Cancel without saving')}
</Button>
{/* TODO - https://jira.dhis2.org/browse/DHIS2-10950 */}
<Button onClick={() => {}} primary>
<Button onClick={() => setStartUpdate(true)} primary>
{i18n.t('Save changes')}
</Button>
</ButtonStrip>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// @flow
import React from 'react';
import uuid from 'uuid/v4';
import { NoticeBox } from '@dhis2/ui';
import i18n from '@dhis2/d2-i18n';
import { useSelector } from 'react-redux';

const prepareMessages = (rulesEffectsGeneral, rulesEffectsMessages, onComplete, type) => {
let messages = rulesEffectsGeneral && rulesEffectsGeneral[type] ? rulesEffectsGeneral[type] : [];
if (onComplete) {
messages =
rulesEffectsGeneral && rulesEffectsGeneral[`${type}OnComplete`]
? [...messages, ...rulesEffectsGeneral[`${type}OnComplete`]]
: messages;

messages =
rulesEffectsMessages &&
Object.values(rulesEffectsMessages).reduce(
(acc, rulesEffectsMessage: any) =>
(acc = rulesEffectsMessage[`${type}OnComplete`]
? [...acc, { message: rulesEffectsMessage[`${type}OnComplete`], id: uuid() }]
: acc),
messages,
);
}
return messages;
};

export const NoticeBoxes = ({
dataEntryId,
itemId,
onComplete,
}: {
dataEntryId: string,
itemId: string,
onComplete: boolean,
}) => {
const ruleId = `${dataEntryId}-${itemId}`;
const { rulesEffectsGeneralErrors, rulesEffectsGeneralWarnings, rulesEffectsMessages } = useSelector(store => ({
rulesEffectsGeneralErrors: store.rulesEffectsGeneralErrors && store.rulesEffectsGeneralErrors[ruleId],
rulesEffectsGeneralWarnings: store.rulesEffectsGeneralWarnings && store.rulesEffectsGeneralWarnings[ruleId],
rulesEffectsMessages: store.rulesEffectsMessages && store.rulesEffectsMessages[ruleId],
}));
const errors = prepareMessages(rulesEffectsGeneralErrors, rulesEffectsMessages, onComplete, 'error');
const warnings = prepareMessages(rulesEffectsGeneralWarnings, rulesEffectsMessages, onComplete, 'warning');

return (
<>
<br />
{errors && errors.length > 0 && (
<NoticeBox title={i18n.t('There are errors in this form')} error>
<ul>
{errors.map(error => (
<li key={error.id}> {error.message} </li>
))}
</ul>
</NoticeBox>
)}
<br />
{warnings && warnings.length > 0 && (
<NoticeBox title={i18n.t('There are warnings in this form')} warning>
<ul>
{warnings.map(warning => (
<li key={warning.id}> {warning.message} </li>
))}
</ul>
</NoticeBox>
)}
<br />
</>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// @flow
import uuid from 'uuid/v4';
import { batchActions } from 'redux-batched-actions';
import type { Enrollment, TEIValues } from 'capture-core-utils/rulesEngine';
import { getRulesActionsForTEI } from '../../../rules/actionsCreator';
import { rulesExecutedPostUpdateField } from '../../DataEntry/actions/dataEntry.actions';
import type { TrackerProgram, RenderFoundation } from '../../../metaData';
import { startRunRulesPostUpdateField } from '../../DataEntry';
import { startRunRulesOnUpdateForNewProfile } from './actions';

export const batchActionTypes = {
RULES_EXECUTED_POST_UPDATE_FIELD_FOR_PROFILE: 'RulesExecutedPostUpdateFieldForProfile',
UPDATE_FIELD_NEW_PROFILE_ACTION_BATCH: 'UpdateFieldNewProfileActionBatch',
UPDATE_DATA_ENTRY_FIELD_NEW_PROFILE_ACTION_BATCH: 'UpdateDataEntryFieldNewProfileActionBatch',
};

type Props = {
program: ?TrackerProgram,
foundation: ?RenderFoundation,
formId: string,
dataEntryId: string,
itemId: string,
orgUnit: Object,
currentEnrollmentValues: ?Enrollment,
currentTEIValues: ?TEIValues,
extraActions: Array<ReduxAction<any, any>>,
uid: string,
};

export const runRulesOnUpdateFieldBatch = ({
program,
foundation,
formId,
dataEntryId,
itemId,
orgUnit,
currentEnrollmentValues,
currentTEIValues,
extraActions = [],
uid,
}: Props) => {
let rulesActions = [];
if (program && foundation) {
rulesActions = getRulesActionsForTEI(
program,
foundation,
formId,
orgUnit,
currentEnrollmentValues,
currentTEIValues,
);
}
return batchActions(
[...rulesActions, rulesExecutedPostUpdateField(dataEntryId, itemId, uid), ...extraActions],
batchActionTypes.RULES_EXECUTED_POST_UPDATE_FIELD_FOR_PROFILE,
);
};

export const updateDataEntryFieldBatch = (innerAction: ReduxAction<any, any>, program: any, orgUnit: any) => {
const { dataEntryId, itemId } = innerAction.payload;
const uid = uuid();

return batchActions(
[
innerAction,
startRunRulesPostUpdateField(dataEntryId, itemId, uid),
startRunRulesOnUpdateForNewProfile(innerAction.payload, uid, orgUnit, program),
],
batchActionTypes.UPDATE_DATA_ENTRY_FIELD_NEW_PROFILE_ACTION_BATCH,
);
};

export const updateFieldBatch = (innerAction: ReduxAction<any, any>, program: any, orgUnit: any) => {
const { dataEntryId, itemId } = innerAction.payload;
const uid = uuid();

return batchActions(
[
innerAction,
startRunRulesPostUpdateField(dataEntryId, itemId, uid),
startRunRulesOnUpdateForNewProfile(innerAction.payload, uid, orgUnit, program),
],
batchActionTypes.UPDATE_FIELD_NEW_PROFILE_ACTION_BATCH,
);
};
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
// @flow

import { convertGeometryOut } from 'capture-core/components/DataEntries/converters';
import { actionCreator, actionPayloadAppender } from '../../../actions/actions.utils';
import { loadNewDataEntry } from '../../DataEntry/actions/dataEntryLoadNew.actions';
import { getDataEntryKey } from '../../DataEntry/common/getDataEntryKey';
import { getRulesActionsForEvent } from '../../../rules/actionsCreator';
import type { RenderFoundation } from '../../../metaData';

export const actionTypes = {
START_RUN_RULES_ON_UPDATE: 'StartRunRulesOnUpdateForNewProfile',
};

type DataEntryPropsToInclude = Array<Object>;

Expand All @@ -19,12 +22,19 @@ const dataEntryPropsToInclude: DataEntryPropsToInclude = [
},
];

export const getOpenDataEntryActions = (orgUnit: Object, dataEntryId: string, itemId: string) =>
export const startRunRulesOnUpdateForNewProfile = (payload: any, uid: string, orgUnit: any, program: any) =>
actionCreator(actionTypes.START_RUN_RULES_ON_UPDATE)({ innerPayload: payload, uid, orgUnit, program });

export const startAsyncUpdateFieldForNewProfile = (
innerAction: ReduxAction<any, any>,
onSuccess: Function,
onError: Function,
) => actionPayloadAppender(innerAction)({ onSuccess, onError });

export const getOpenDataEntryActions = (orgUnit: any, dataEntryId: string, itemId: string) =>
loadNewDataEntry(dataEntryId, itemId, dataEntryPropsToInclude);

export const getRulesActions = (foundation: RenderFoundation, orgUnit: Object, dataEntryId: string, itemId: string) => {
export const getRulesActions = (program: any, orgUnit: any, dataEntryId: string, itemId: string) => {
const formId = getDataEntryKey(dataEntryId, itemId);
// TODO DHIS2-11878 apply the programRules
// $FlowFixMe[incompatible-call]
return getRulesActionsForEvent({ programRules: [] }, foundation, formId, orgUnit);
return getRulesActionsForEvent(program, program.enrollment.foundation, formId, orgUnit);
};
Loading