Skip to content

Commit

Permalink
fix: refine compulsory data element operands
Browse files Browse the repository at this point in the history
  • Loading branch information
tomzemp committed Nov 29, 2024
1 parent b43b81c commit fb52233
Show file tree
Hide file tree
Showing 15 changed files with 307 additions and 24 deletions.
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 })
})
})
24 changes: 16 additions & 8 deletions src/bottom-bar/use-on-complete-callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
useSetFormCompletionMutationKey,
validationResultsSidebarId,
useHasCompulsoryDataElementOperandsToFillOut,
useEntryFormStore,
} from '../shared/index.js'

const validationFailedMessage = i18n.t(
Expand Down Expand Up @@ -122,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 @@ -138,19 +141,24 @@ export default function useOnCompleteCallback() {
useOnCompleteWithoutValidationClick()
const hasCompulsoryDataElementOperandsToFillOut =
useHasCompulsoryDataElementOperandsToFillOut()
const setCompleteAttempted = useEntryFormStore(
(state) => state.setCompleteAttempted
)

return () => {
let promise
// showErrorAlert('Complete compulsory data element operands')
// return Promise.resolve()

if (hasCompulsoryDataElementOperandsToFillOut) {
setCompleteAttempted(true)
cancelCompletionMutation()
showErrorAlert(
'Compulsory fields must be filled out before completing form'
promise = Promise.reject(
new Error(
i18n.t(
'Compulsory fields must be filled out before completing the form'
)
)
)
return Promise.resolve()
}
if (isLoading && offline) {
} 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'])

it('should render rows and columns based on the data elements and categorycombo', () => {
const tableDataElements = [
Expand Down
Loading

0 comments on commit fb52233

Please sign in to comment.