React Basic
React Basic
React Basic
const {
isCodeEditable,
hasUserMadeChanges,
isEditButtonDisabled,
saveClicked,
isSaveButtonDisplayed,
isSaveButtonDisabled,
isRowEditDisabled,
isConditonalAddDisabled,
validateRecordOnSave
} = state;
/**
* API call to get the reference table data
* Returns the response body which is used to populate the reference table data
* @async
* @param {boolean} isSortOrderAsc - The sorting order.
* @returns {*} response body
*/
const getTableData = async (isSortOrderAsc) => {
await getReferenceTableData(
tableName,
refDataApiUrl,
tenantId,
locale,
getEllucianInternalJwt,
setTableData,
setResults,
setLoader,
isSortOrderAsc
);
};
/**
* Event Handler to add the editable rows in the table when clicked on Add button
*/
const onClickAdd = () => {
handleAdd(dispatch, results, defaultResults, setResults, setTableData);
};
/**
* calling api with field values when table does not have any validation errors
* Returns the response body which is used to display the corresponding alert
message
* @param {*} api - api
*/
const updateReferenceDataValuesResponse = async (api) => {
const validation = results?.every((item) => {
return (
item?.description?.trim() &&
item.properties?.startDate &&
item.properties?.endDate &&
new Date(item.properties?.startDate) < new Date(item.properties?.endDate)
);
});
if (validation) {
if (updatedItemArray.length > 0) {
dispatch({ type: 'save' });
const putApiResponse = await putReferenceDataApi(
api,
refDataApiUrl,
tenantId,
updatedItemArray,
tableName,
locale,
getEllucianInternalJwt,
setAlert,
dispatch,
setLoader,
setUpdatedItemArray,
setCheckValueChange,
setButtonLoader,
intl
);
if (putApiResponse === apiStatus.success) {
getTableData(false);
}
} else {
setAlert({
alertType: 'info',
text: intl.formatMessage({ id: 'No-Changes-Error' }),
autoHideDuration: null,
open: true
});
results.forEach((res) => {
if (!res.isEdit) {
res.isEdit = true;
}
});
dispatch({ type: 'successResponse' });
}
} else {
dispatch({ type: 'helperText' });
}
};
/**
* calling api with field values when table does not have any validation errors
* Returns the response body which is used to display the corresponding alert
message
* @param {*} api - api
*/
const createReferenceDataValuesResponse = async (api) => {
const newRecords = [];
const validation = results.reduce((reducer, item) => {
// reducer - The reducer method is called on the results array with an
initial value of true
const {
isAdd,
code,
description,
properties,
properties: { startDate, endDate }
} = item;
if (isAdd) {
// push the newly added object and its attributes
newRecords.push({ code, description, properties });
// when isAdd is false we will just return the current reducer value
return reducer;
}, true);
/**
* Event handler to save the updated data
*
*/
const handleSave = () => {
if (hasUserMadeChanges) {
// edit record
if (!isCodeEditable) {
updateReferenceDataValuesResponse(referenceDataApiService.updateReferenceDataValues
);
}
// add record
else {
createReferenceDataValuesResponse(referenceDataApiService.createReferenceDataValues
);
}
}
};
/**
* Updates the state of textfield values on change event
*
* @param {*} index - index of the object
*/
/**
* Event handler to display the dialog with Yes or No options, when updates are
made and not saved
*
*/
const onClickCancel = () => {
handleCancel(hasUserMadeChanges, saveClicked, setOpenConfirmationDialog,
history, checkValueChange);
};
const styleError = (spanStyle, saveButtonValidator, index) => {
const errRecords = results.filter((item) => {
const {
code,
description,
properties: { startDate, endDate },
styleErrMsg
} = item;
if (
code &&
!findDuplicateByIndex(results, 'code', index).length &&
description?.trim() &&
startDate &&
new Date(startDate) < new Date(endDate)
) {
item.styleErrMsg = null;
} else if (saveButtonValidator) {
item.styleErrMsg = <span className={spanStyle}></span>;
}
return styleErrMsg;
});
return saveButtonValidator && errRecords.length ? <span
className={spanStyle}></span> : null;
};
/**
* function is executed on click of cancel in ConfirmationDialogBox Box
*
* setLoader - state is used to display loader
* getTableData - function is used to get the table values
* dispatch - used to set the table values
* setCheckValueChange - state is used to check if there is any unsaved Changes
* setOpenConfirmationDialog - state used to close/open ConfirmationDialogBox Box
*/
const handleClose = () => {
setOpenConfirmationDialog(false);
setCheckValueChange(false);
setLoader(true);
getTableData(false);
dispatch({ type: 'successResponse' });
};
const onClickDelete = (index) => {
handleRowDelete(index, results, setResults, dispatch, setCheckValueChange);
};
/**
* Function to merge the AidYear columns with Generic columns
* Adding style object to each header
* set the state, so that the mergedAidYearColmnObj value is updated when
component is rendered asynchronously on UseEffect
*/
const applyAidYearHeaderStyleObj = () => {
const mergedResults = genericReferenceDataValueColumns.concat(aidYearColumns);
mergedResults.forEach((data) => {
data.styleObject = headerWidth;
});
setMergedAidYearColmnObj(mergedResults);
};
useEffect(() => {
setLoader(true);
getTableData(false);
applyAidYearHeaderStyleObj();
}, []);
useEffect(() => {
reduxDispatch(setRefAidYearList(results));
}, [results]);
useEffect(() => {
setExitPrompt(checkValueChange);
}, [checkValueChange]);
return (
<React.Fragment>
<AlertMessage
alertType={alert.alertType}
id={`${customId}_Alert`}
open={alert.open}
autoHideDuration={alert.autoHideDuration}
text={alert.text}
userInfo={userInfo}
setAlert={setAlert}
/>
<Typography variant="h2" id={`${customId}_Title`} className={refHeading}>
{title}
</Typography>
{!loader && (
<Grid container spacing={20}>
<Grid item xs={6} sm={6}>
<SearchData
id={`${customId}_searchBox`}
tableData={tableData}
searchResults={results}
setSearchResults={setResults}
placeholder={intl.formatMessage({ id: 'Search-Label' })}
searchKey="code"
disabled={hasUserMadeChanges}
/>
</Grid>
<ActionButton
intl={intl}
customId={customId}
isSaveButtonDisplayed={isSaveButtonDisplayed}
handleCancel={onClickCancel}
canModifyRecord={canModifyRecord}
isSaveButtonDisabled={isSaveButtonDisabled}
canCreateRecord={canCreateRecord}
handleSave={handleSave}
handleAllEdit={onClickEditAll}
results={results}
isEditButtonDisabled={isEditButtonDisabled}
isAddButtonDisabled={isConditonalAddDisabled}
handleAdd={onClickAdd}
addText="Create-Aid-Year"
buttonLoader={buttonLoader}
/>
</Grid>
)}
{!loader ? (
<Card className={card}>
<Table stickyHeader id={`${customId}_Table`} className={table}>
<TableHead>
<TableRow>
<ReferenceDataTableHeader customId={customId} intl={intl}
tableHeadersObject={mergedAidYearColmnObj} />
<TableCell></TableCell>
</TableRow>
</TableHead>
{results?.length ? (
<TableBody>
{results?.map((refDataValue, index) => {
const {
code,
isAdd,
isEdit,
codeEdit,
description,
properties,
properties: { startDate, endDate }
} = refDataValue;
return (
<TableRow key={`${customId}_Key_${index}`}>
<GenericReferenceDataColumns
customId={customId}
refDataValue={refDataValue}
state={state}
intl={intl}
results={results}
handleChange={handleChange}
index={index}
styleError={styleError}
codeFieldType="number"
/>
<AidYearColumns
customId={customId}
results={results}
setResults={setResults}
userInfo={locale}
handleChange={handleChange}
setTableData={setTableData}
updatedRefDataValues={{ code, isEdit, codeEdit,
description, properties }}
state={state}
index={index}
intl={intl}
styleError={styleError}
/>
AidYearPage.propTypes = {
intl: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired,
userInfo: PropTypes.object.isRequired,
extensionInfo: PropTypes.object.isRequired,
data: PropTypes.object.isRequired,
pageControl: PropTypes.object.isRequired
};