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: handle compulsory data element operands [DHIS2-17647] #426

Merged
merged 3 commits into from
Dec 10, 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
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: 2024-10-18T12:58:59.146Z\n"
"PO-Revision-Date: 2024-10-18T12:58:59.146Z\n"
"POT-Creation-Date: 2024-11-29T16:17:15.582Z\n"
"PO-Revision-Date: 2024-11-29T16:17:15.582Z\n"

msgid "Not authorized"
msgstr "Not authorized"
Expand Down Expand Up @@ -81,6 +81,9 @@ msgstr "Couldn't validate the form. This does not effect form completion!"
msgid "The form can't be completed while invalid"
msgstr "The form can't be completed while invalid"

msgid "Compulsory fields must be filled out before completing the form"
msgstr "Compulsory fields must be filled out before completing the form"

msgid "1 comment required"
msgstr "1 comment required"

Expand Down Expand Up @@ -213,6 +216,9 @@ msgstr "Warning, saved"
msgid "Locked, not editable"
msgstr "Locked, not editable"

msgid "Compulsory field"
msgstr "Compulsory field"

msgid "Help"
msgstr "Help"

Expand Down
220 changes: 220 additions & 0 deletions src/bottom-bar/complete-button.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import { waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import React from 'react'
import { useMetadata } from '../shared/metadata/use-metadata.js'
import { useDataSetId } from '../shared/use-context-selection/use-context-selection.js'
import { useDataValueSet } from '../shared/use-data-value-set/use-data-value-set.js'
import { useImperativeValidate } from '../shared/validation/use-imperative-validate.js'
import { render } from '../test-utils/render.js'
import CompleteButton from './complete-button.js'

const mockShow = jest.fn()
const mockSetFormCompletion = jest
.fn()
.mockImplementation(() => Promise.resolve())
const mockValidate = jest.fn().mockImplementation(() =>
Promise.resolve({
commentRequiredViolations: [],
validationRuleViolations: [],
})
)
const mockSetCompleteAttempted = jest.fn()
const mockIsComplete = jest.fn()

jest.mock('@dhis2/app-runtime', () => ({
...jest.requireActual('@dhis2/app-runtime'),
useAlert: jest.fn(() => ({
show: mockShow,
})),
}))

jest.mock('../shared/use-context-selection/use-context-selection.js', () => ({
...jest.requireActual(
'../shared/use-context-selection/use-context-selection.js'
),
useDataSetId: jest.fn(),
}))

jest.mock('../shared/metadata/use-metadata.js', () => ({
useMetadata: jest.fn(),
}))

jest.mock('../shared/validation/use-imperative-validate.js', () => ({
useImperativeValidate: jest.fn(),
}))

jest.mock('../shared/completion/use-set-form-completion-mutation.js', () => ({
...jest.requireActual(
'../shared/completion/use-set-form-completion-mutation.js'
),
useSetFormCompletionMutation: jest.fn(() => ({
mutateAsync: mockSetFormCompletion,
})),
}))

jest.mock('../shared/stores/entry-form-store.js', () => ({
...jest.requireActual('../shared/stores/entry-form-store.js'),
useEntryFormStore: jest.fn().mockImplementation((func) => {
const state = {
setCompleteAttempted: mockSetCompleteAttempted,
}
return func(state)
}),
}))

jest.mock('../shared/stores/data-value-store.js', () => ({
...jest.requireActual('../shared/stores/data-value-store.js'),
useValueStore: jest.fn().mockImplementation((func) => {
const state = {
isComplete: mockIsComplete,
}
return func(state)
}),
}))

jest.mock('../shared/use-data-value-set/use-data-value-set.js', () => ({
useDataValueSet: jest.fn(),
}))

const MOCK_METADATA = {
dataSets: {
data_set_id_1: {
id: 'data_set_id_1',
},
data_set_id_compulsory_validation_without_cdeo: {
id: 'data_set_id_compulsory_validation_without_cdeo',
compulsoryDataElementOperands: [],
compulsoryFieldsCompleteOnly: true,
},
data_set_id_compulsory_validation_with_cdeo: {
id: 'data_set_id_compulsory_validation_without_cdeo',
compulsoryDataElementOperands: [
{
dataElement: {
id: 'de-id-1',
},
categoryOptionCombo: {
id: 'coc-id-1',
},
},
{
dataElement: {
id: 'de-id-2',
},
categoryOptionCombo: {
id: 'coc-id-2',
},
},
],
compulsoryFieldsCompleteOnly: true,
},
},
}

const MOCK_DATA = {
dataValues: {
'de-id-1': {
'coc-id-1': {
value: '5',
},
},
'de-id-2': {
'coc-id-2': {
value: '10',
},
},
},
}

const MOCK_DATA_INCOMPLETE = {
dataValues: {
'de-id-1': {
'coc-id-1': {
value: '5',
},
},
},
}

describe('CompleteButton', () => {
beforeEach(() => {
jest.clearAllMocks()
useImperativeValidate.mockReturnValue(mockValidate)
})

it('validates form and completes when clicked', () => {
mockIsComplete.mockReturnValue(false)
useDataSetId.mockReturnValue(['data_set_id_1'])
useDataValueSet.mockReturnValue({ data: MOCK_DATA })
useMetadata.mockReturnValue({ data: MOCK_METADATA })
const { getByText } = render(<CompleteButton />)

userEvent.click(getByText('Mark complete'))
expect(mockValidate).toHaveBeenCalledOnce()
expect(mockSetFormCompletion).toHaveBeenCalledWith({ completed: true })
})

it('completes if the compulsoryFieldsCompleteOnly:true but there are no compulsory data element operands', () => {
mockIsComplete.mockReturnValue(false)
useDataSetId.mockReturnValue([
'data_set_id_compulsory_validation_without_cdeo',
])
useDataValueSet.mockReturnValue({ data: MOCK_DATA })
useMetadata.mockReturnValue({ data: MOCK_METADATA })
const { getByText } = render(<CompleteButton />)

userEvent.click(getByText('Mark complete'))
expect(mockValidate).toHaveBeenCalledOnce()
expect(mockSetFormCompletion).toHaveBeenCalledWith({ completed: true })
// completeAttempted only set if the complete is rejected due to compulsory data element operands
expect(mockSetCompleteAttempted).not.toHaveBeenCalled()
})

it('does not complete and shows error if the compulsoryFieldsCompleteOnly:true and there are compulsory data element operands without values', async () => {
mockIsComplete.mockReturnValue(false)
useDataSetId.mockReturnValue([
'data_set_id_compulsory_validation_with_cdeo',
])
useDataValueSet.mockReturnValue({ data: MOCK_DATA_INCOMPLETE })
useMetadata.mockReturnValue({ data: MOCK_METADATA })
const { getByText } = render(<CompleteButton />)

userEvent.click(getByText('Mark complete'))
expect(mockValidate).not.toHaveBeenCalled()
expect(mockSetFormCompletion).not.toHaveBeenCalled()
expect(mockSetCompleteAttempted).toHaveBeenCalledWith(true)
await waitFor(() =>
expect(mockShow).toHaveBeenCalledWith(
'Compulsory fields must be filled out before completing the form'
)
)
})

it('completes if the compulsoryFieldsCompleteOnly:true and there are compulsory data element operands but all have values', () => {
mockIsComplete.mockReturnValue(false)
useDataSetId.mockReturnValue([
'data_set_id_compulsory_validation_with_cdeo',
])
useDataValueSet.mockReturnValue({ data: MOCK_DATA })
useMetadata.mockReturnValue({ data: MOCK_METADATA })
const { getByText } = render(<CompleteButton />)

userEvent.click(getByText('Mark complete'))
expect(mockValidate).toHaveBeenCalledOnce()
expect(mockSetFormCompletion).toHaveBeenCalledWith({ completed: true })
// completeAttempted only set if the complete is rejected due to compulsory data element operands
expect(mockSetCompleteAttempted).not.toHaveBeenCalled()
})

it('marks form as incomplete if form is completed', () => {
mockIsComplete.mockReturnValue(true)
useDataSetId.mockReturnValue(['data_set_id_1'])
useDataValueSet.mockReturnValue({ data: MOCK_DATA })
useMetadata.mockReturnValue({ data: MOCK_METADATA })
const { getByText } = render(<CompleteButton />)

userEvent.click(getByText('Mark incomplete'))
expect(mockValidate).not.toHaveBeenCalledOnce()
expect(mockSetFormCompletion).toHaveBeenCalledWith({ completed: false })
})
})
23 changes: 21 additions & 2 deletions src/bottom-bar/use-on-complete-callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
useSetFormCompletionMutation,
useSetFormCompletionMutationKey,
validationResultsSidebarId,
useHasCompulsoryDataElementOperandsToFillOut,
useEntryFormStore,
} from '../shared/index.js'

const validationFailedMessage = i18n.t(
Expand Down Expand Up @@ -121,7 +123,9 @@ export default function useOnCompleteCallback() {
const { offline } = useConnectionStatus()
const { data: metadata } = useMetadata()
const [dataSetId] = useDataSetId()
const dataSet = selectors.getDataSetById(metadata, dataSetId)
const dataSet = dataSetId
? selectors.getDataSetById(metadata, dataSetId)
: {}
const { validCompleteOnly } = dataSet
const { show: showErrorAlert } = useAlert((message) => message, {
critical: true,
Expand All @@ -135,11 +139,26 @@ export default function useOnCompleteCallback() {
useOnCompleteWhenValidNotRequiredClick()
const onCompleteWithoutValidationClick =
useOnCompleteWithoutValidationClick()
const hasCompulsoryDataElementOperandsToFillOut =
useHasCompulsoryDataElementOperandsToFillOut()
const setCompleteAttempted = useEntryFormStore(
(state) => state.setCompleteAttempted
)

return () => {
let promise

if (isLoading && offline) {
if (hasCompulsoryDataElementOperandsToFillOut) {
setCompleteAttempted(true)
Copy link
Member Author

Choose a reason for hiding this comment

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

this is only set if there is a compulsory data element operand to fill out, so that invalid styling only gets applied if the compulsory data element operands need to be filled out (otherwise, they remain with just the *)

cancelCompletionMutation()
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 that doing completeStatus: { ...previousDataValueSet.completeStatus, complete: !completed, }, in cancelCompletionMutation messes up the complete status a bit. In you try to mark as complete successfully, then mark as incomplete successfully and then finally mark as complete unsuccessfully you will see the complete status = true even if the completion did fail. maybe we just want to set it as completeStatus: { ...previousDataValueSet.completeStatus, complete: false, }, ?

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks! Fixed this. I did't pay enough attention to what the cancelCompletionMutation function was doing before. I guess as it's used for cancelling incomplete functions as well, I've modified the hook to return a function to which you can pass the desired complete status (i.e. false here).

This works as far as I can tell though I have not gone through in total detail to review all of the logic with the completion.

promise = Promise.reject(
new Error(
i18n.t(
'Compulsory fields must be filled out before completing the form'
)
)
)
} else if (isLoading && offline) {
cancelCompletionMutation()
// No need to complete when the completion request
// hasn't been sent yet due to being offline.
Expand Down
3 changes: 3 additions & 0 deletions src/context-selection/contextual-help-sidebar/cell.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const Cell = ({ value, state }) => (
{state === 'SYNCED' && (
<div className={styles.topRightTriangle} />
)}
{state === 'COMPULSORY' && (
<div className={styles.topRightAsterisk}>*</div>
)}
</div>
<div className={styles.bottomRightIndicator}>
{state === 'HAS_COMMENT' && (
Expand Down
5 changes: 5 additions & 0 deletions src/context-selection/contextual-help-sidebar/cell.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
.input {
composes: densePadding from '../../data-workspace/inputs/inputs.module.css';
composes: alignToEnd from '../../data-workspace/inputs/inputs.module.css';
padding-inline-end: 16px;
outline: 1px solid var(--colors-grey400);
}

Expand Down Expand Up @@ -45,3 +46,7 @@
.bottomRightTriangle {
composes: bottomRightTriangle from '../../data-workspace/data-entry-cell/data-entry-cell.module.css';
}

.topRightAsterisk {
composes: topRightAsterisk from '../../data-workspace/data-entry-cell/data-entry-cell.module.css';
}
6 changes: 6 additions & 0 deletions src/context-selection/contextual-help-sidebar/cells-legend.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ export default function CellsLegend() {
name={i18n.t('Locked, not editable')}
state="LOCKED"
/>
<Divider />

<CellsLegendSymbol
name={i18n.t('Compulsory field')}
state="COMPULSORY"
/>
</ExpandableUnit>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,21 @@ import { Table } from '@dhis2/ui'
import { getAllByTestId, getByTestId, getByText } from '@testing-library/react'
import React from 'react'
import { useMetadata } from '../../shared/metadata/use-metadata.js'
import { useDataSetId } from '../../shared/use-context-selection/use-context-selection.js'
import { render } from '../../test-utils/index.js'
import { FinalFormWrapper } from '../final-form-wrapper.js'
import { CategoryComboTableBody } from './category-combo-table-body.js'

jest.mock(
'../../shared/use-context-selection/use-context-selection.js',
() => ({
...jest.requireActual(
'../../shared/use-context-selection/use-context-selection.js'
),
useDataSetId: jest.fn(),
})
)

jest.mock('../../shared/metadata/use-metadata.js', () => ({
useMetadata: jest.fn(),
}))
Expand Down Expand Up @@ -453,6 +464,7 @@ const metadata = {

describe('<CategoryComboTableBody />', () => {
useMetadata.mockReturnValue({ data: metadata })
useDataSetId.mockReturnValue(['dataSet1'])
Copy link
Member Author

Choose a reason for hiding this comment

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

(FYI: edit was necessary because of thenew call to the useIsCompulsoryDataElementOperand hook


it('should render rows and columns based on the data elements and categorycombo', () => {
const tableDataElements = [
Expand Down
5 changes: 5 additions & 0 deletions src/data-workspace/data-entry-cell/data-entry-cell.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@
border-inline-start: 3px solid transparent;
}

.topRightAsterisk {
color: var(--colors-grey600);
inline-size: 8px;
}

.locked {
background-color: var(--colors-grey050);
}
Expand Down
Loading
Loading