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(attributes): prepare attributes fetching & state management #67

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
"react-router-dom": "^5.0.0",
"react-scripts": "3.0.1",
"redux": "^4.0.1",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"typeface-roboto": "^0.0.54",
"url-join": "^4.0.1"
Expand Down
6 changes: 4 additions & 2 deletions src/components/Form/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export * from './constants'

export class Form extends React.Component {
fields() {
const { fields, fieldValues } = this.props
const { fields, fieldValues, fieldValuesOverride } = this.props
const { _context: context, _meta: formMeta } = fieldValues

return fields.map(field => {
Expand All @@ -41,7 +41,9 @@ export class Form extends React.Component {
const props = { name, label, className, required, formMeta }

if (type === TYPE_RADIO) {
props['values'] = fieldValues[name]['values']
props['values'] = fieldValuesOverride[name]
? fieldValuesOverride[name]
: fieldValues[name]['values']
props['selected'] = fieldValues[name]['selected']

return (
Expand Down
1 change: 1 addition & 0 deletions src/components/FormBase/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export class FormBase extends React.Component {
onChange={this.onChange}
changeContext={this.changeContext}
submitLabel={this.submitLabel}
fieldValuesOverride={this.fieldValuesOverride || {}}
onSubmit={this.onBeforeSubmit}
/>
)
Expand Down
36 changes: 36 additions & 0 deletions src/helpers/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const ATTRIBUTES_ENDPOINT = 'attributes.json'

let d2
let api

/**
* Sets d2 and the api
*/
export const initApi = d2Instance => {
d2 = d2Instance
api = d2.Api.getApi()
}

export const getAttributes = ({
filter = [],
paging = false,
unique = true,
}) => {
const params = [
`paging=${paging}`,
`fields=${['id', 'displayName'].join(',')}`,
...[...filter, `unique:eq:${unique}`].map(f => `filter=${f}`),
Mohammer5 marked this conversation as resolved.
Show resolved Hide resolved
]

return api.get(`${ATTRIBUTES_ENDPOINT}?${params.join('&')}`)
}

export const getUniqueDataElementAttributes = () =>
getAttributes({ filter: ['dataElementAttribute:eq:true'] })
.then(({ attributes }) => attributes)
.catch(() => [])

export const getUniqueOrganisationUnitAttributes = () =>
getAttributes({ filter: ['organisationUnitAttribute:eq:true'] })
.then(({ attributes }) => attributes)
.catch(() => [])
3 changes: 1 addition & 2 deletions src/helpers/values.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const calculated = {
format: getFormat,
}

const values = {
export const values = {
upload: {
selected: null,
},
Expand All @@ -77,7 +77,6 @@ const values = {
['UID', i18n.t('UID')],
['CODE', i18n.t('Code')],
['NAME', i18n.t('Name')],
['ATTRIBUTE:UKNKz1H10EE', i18n.t('HR identifier')],
]),
},

Expand Down
56 changes: 27 additions & 29 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import './locales'
import './index.css'
import App from './App'
import { store } from './store'
import { initApi } from './helpers/api'
import * as serviceWorker from './serviceWorker'

/**
Expand All @@ -20,36 +21,33 @@ const { REACT_APP_DHIS2_BASE_URL } = process.env

init({
Mohammer5 marked this conversation as resolved.
Show resolved Hide resolved
baseUrl: `${REACT_APP_DHIS2_BASE_URL}/api/`,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
headers: { 'X-Requested-With': 'XMLHttpRequest' },
})

/**
* Initialize material ui theme
*/

lightBaseTheme.palette.primary1Color = '#4c708c'
lightBaseTheme.palette.primary2Color = '#4c708c'
lightBaseTheme.palette.primary3Color = '#4c708c'
lightBaseTheme.palette.pickerHeaderColor = '#4c708c'

const muiTheme = getMuiTheme(lightBaseTheme)

/**
* Mount app
*/

ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider muiTheme={muiTheme}>
<HashRouter>
<App />
</HashRouter>
</MuiThemeProvider>
</Provider>,
document.getElementById('root')
)
.then(initApi)
.then(() => {
/**
* Initialize material ui theme
*/

lightBaseTheme.palette.primary1Color = '#4c708c'
lightBaseTheme.palette.primary2Color = '#4c708c'
lightBaseTheme.palette.primary3Color = '#4c708c'
lightBaseTheme.palette.pickerHeaderColor = '#4c708c'

return getMuiTheme(lightBaseTheme)
})
.then(muiTheme => {
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider muiTheme={muiTheme}>
<HashRouter>
<App />
</HashRouter>
</MuiThemeProvider>
</Provider>,
document.getElementById('root')
)
})

/**
* If you want your app to work offline and load faster, you can change
Expand Down
172 changes: 137 additions & 35 deletions src/pages/export/Data.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { connect } from 'react-redux'
import { getInstance } from 'd2/lib/d2'
import JSZip from 'jszip'
import PropTypes from 'prop-types'
Expand All @@ -14,10 +15,16 @@ import {
getFormFieldMoreOptions,
getFormValues,
getParamsFromFormState,
values,
} from '../../helpers'
import {
fetchUniqueDataElementAttributes,
fetchUniqueOrgUnitAttributes,
} from '../../reducers/attributes/thunks'
import { isProduction } from '../../helpers/env'
import s from '../../components/Form/styles.module.css'

export class DataExport extends FormBase {
class DataExport extends FormBase {
static path = '/export/data'

static order = 7
Expand All @@ -36,46 +43,101 @@ export class DataExport extends FormBase {
formWidth = 800
formTitle = i18n.t('Data Export')
submitLabel = i18n.t('Export')
fields = []
state = {
_meta: {
submitted: false,
valid: false,
processing: false,
error: null,
},
}

fields = [
...getFormFields([
'orgUnit',
'children',
'selectedDataSets',
'startDate',
'endDate',
'format',
'compression',
]),

getFormFieldMoreOptions(),

...getFormFields([
'includeDeleted',
'dataElementIdScheme',
'orgUnitIdScheme',
'categoryOptionComboIdScheme',
]),
]

state = getFormValues([
'orgUnit',
'children',
'selectedDataSets',
'startDate',
'endDate',
'format:.json:json,xml,csv',
'compression',
'includeDeleted',
'dataElementIdScheme',
'orgUnitIdScheme',
'categoryOptionComboIdScheme',
])
setFormValues() {
this.setState({
...getFormValues([
'orgUnit',
'children',
'selectedDataSets',
'startDate',
'endDate',
'format:.json:json,xml,csv',
'compression',
'includeDeleted',
'dataElementIdScheme',
'orgUnitIdScheme',
'categoryOptionComboIdScheme',
]),
})
}

async componentDidMount() {
this.props.fetchDataElementAttributes()
this.props.fetchOrganisationUnitAttributes()
await this.fetch()
}

initializeFormValues(fieldValuesOverride) {
Mohammer5 marked this conversation as resolved.
Show resolved Hide resolved
this.fieldValuesOverride = fieldValuesOverride

this.fields = [
...getFormFields([
'orgUnit',
'children',
'selectedDataSets',
'startDate',
'endDate',
'format',
'compression',
]),

getFormFieldMoreOptions(),

...getFormFields([
'includeDeleted',
'dataElementIdScheme',
'orgUnitIdScheme',
'categoryOptionComboIdScheme',
]),
]

this.setFormValues()
}

componentDidUpdate(prevProps) {
if (
prevProps.dataElementAttributes.length !==
this.props.dataElementAttributes.length ||
prevProps.orgUnitAttributes.length !==
this.props.orgUnitAttributes.length
) {
const dataElementIdScheme = [
...values.dataElementIdScheme.values,
...this.props.dataElementAttributes.map(
({ id, displayName: label }) => ({
value: `ATTRIBUTE:${id}`,
label,
})
),
]

const orgUnitIdScheme = [
...values.orgUnitIdScheme.values,
...this.props.orgUnitAttributes.map(
({ id, displayName: label }) => ({
value: `ATTRIBUTE:${id}`,
label,
})
),
]

this.initializeFormValues({
dataElementIdScheme,
orgUnitIdScheme,
})
}
}

async fetch() {
try {
const d2 = await getInstance()
Expand Down Expand Up @@ -178,4 +240,44 @@ export class DataExport extends FormBase {
!isProduction && console.log('Data Export error', e, '\n')
}
}

render() {
const form = super.render()

if (this.props.loadingAttributes) {
return (
<div className={s.wrapper}>
<div
className={s.form}
style={{
padding: '14px 20px',
width: 800,
boxSizing: 'border-box',
margin: '60px auto',
}}
>
{i18n.t('Loading options...')}
</div>
</div>
)
}

return form
}
}

const ConnectedDataExport = connect(
state => ({
loadingAttributes: state.attributes.loading,
dataElementAttributes: state.attributes.dataElement,
orgUnitAttributes: state.attributes.organisationUnit,
}),
dispatch => ({
fetchDataElementAttributes: () =>
dispatch(fetchUniqueDataElementAttributes()),
fetchOrganisationUnitAttributes: () =>
dispatch(fetchUniqueOrgUnitAttributes()),
})
)(DataExport)

export { ConnectedDataExport as DataExport }
17 changes: 17 additions & 0 deletions src/reducers/attributes/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const LOADING_ATTRIBUTES_START = 'LOADING_ATTRIBUTES_START'
export const LOADING_ATTRIBUTES_ERROR = 'LOADING_ATTRIBUTES_ERROR'
export const SET_ATTRIBUTES = 'SET_ATTRIBUTES'

export const loadingAttributesStart = () => ({
type: LOADING_ATTRIBUTES_START,
})

export const loadingAttributesError = error => ({
type: LOADING_ATTRIBUTES_ERROR,
payload: error,
})

export const setAttribute = (type, attributes) => ({
type: SET_ATTRIBUTES,
payload: { type, attributes },
})
Loading