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

Cu 86bz9q0gr save unique to golden record fields to local storage #265

Merged
Show file tree
Hide file tree
Changes from 14 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
22 changes: 7 additions & 15 deletions JeMPI_Apps/JeMPI_UI/src/hooks/useUIConfiguration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,36 +14,28 @@ export interface UIConfigurationProviderProps {
children: React.ReactNode
}

export const ConfigurationContext = createContext<
ConfigurationContextType | undefined
>(undefined)
export const ConfigurationContext = createContext<ConfigurationContextType | undefined>(undefined)

export const useConfiguration = () => {
const context = useContext(ConfigurationContext)
if (!context) {
throw new Error(
'useConfiguration must be used within a ConfigurationProvider'
)
throw new Error('useConfiguration must be used within a ConfigurationProvider')
}
return context
}

export const ConfigurationProvider = ({
children
}: UIConfigurationProviderProps) => {
export const ConfigurationProvider = ({ children }: UIConfigurationProviderProps) => {
const { apiClient } = useConfig()
const { data, error, isLoading, isError } = useQuery<Configuration>({
queryKey: ['configuration'],
queryFn: () => apiClient.fetchConfiguration(),
refetchOnWindowFocus: false
})

const [configuration, setConfiguration] = useState<Configuration | null>(
() => {
const savedConfig = localStorage.getItem('configuration')
return savedConfig ? JSON.parse(savedConfig) : null
}
)
const [configuration, setConfiguration] = useState<Configuration | null>(() => {
const savedConfig = localStorage.getItem('configuration')
return savedConfig ? JSON.parse(savedConfig) : null
})

useEffect(() => {
if (data && !configuration) {
Expand Down
2 changes: 1 addition & 1 deletion JeMPI_Apps/JeMPI_UI/src/pages/settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ const Settings = () => {
<Typography variant="h5" sx={{ py: 3 }}>
Setup properties for Golden record lists
</Typography>
<GoldenRecordLists goldenRecordList={[]}/>
<GoldenRecordLists/>
</CustomTabPanel>
<CustomTabPanel value={value} index={4}>
<Deterministic
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useState} from 'react';
import Box from '@mui/material/Box';
import {
DataGrid,
Expand All @@ -8,116 +9,134 @@ import {
GridRowModel,
GridRowModes,
GridRowModesModel,
GridActionsCellItem
GridActionsCellItem,
} from '@mui/x-data-grid';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import { useEffect, useState } from 'react';
import { EditToolbar } from 'components/shared/EditToolBar';
import { formatNodeName, toSnakeCase, toUpperCase } from 'utils/helpers';
import { Configuration } from 'types/Configuration';
import { Configuration, CustomNode } from 'types/Configuration';
import { useConfiguration } from 'hooks/useUIConfiguration';

interface RowData {
id: string;
nodeName: string;
fieldName: string;
fieldType: string;
csvCol: number;
nodeIndex: number;
fieldIndex: number;
}

const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
const [rows, setRows] = useState<any>([]);

const GoldenRecordLists = () => {
const [rows, setRows] = useState<RowData[]>([]);
const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});
const [configuration, setConfiguration] = useState<Configuration>();
const { configuration, setConfiguration } = useConfiguration();

useEffect(() => {
if (goldenRecordList) {
const rowsWithIds = goldenRecordList.flatMap(
(node: { fields: any[]; nodeName: string }, nodeIndex: number) => {
return node.fields
? node.fields.map((field, fieldIndex) => ({
id: `${node.nodeName}_${nodeIndex}_${fieldIndex}`,
nodeName: node.nodeName,
fieldName: field.fieldName,
fieldType: field.fieldType,
csvCol: field.csvCol,
nodeIndex,
fieldIndex
}))
: [];
}
);

if (configuration && configuration.additionalNodes) {
MatthewErispe marked this conversation as resolved.
Show resolved Hide resolved
const rowsWithIds = configuration.additionalNodes.flatMap((node: CustomNode, nodeIndex: number) => {
return node.fields.map((field, fieldIndex) => ({
id: `${node.nodeName}_${nodeIndex}_${fieldIndex}`,
nodeName: node.nodeName,
fieldName: field.fieldName,
fieldType: field.fieldType,
csvCol: field.source?.csvCol ?? 0,
nodeIndex,
fieldIndex,
}));
});
setRows(rowsWithIds);
}
MatthewErispe marked this conversation as resolved.
Show resolved Hide resolved
}, [goldenRecordList]);
}, [configuration]);

const handleEditClick = (id: GridRowId) => () => {
setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.Edit } });
setRowModesModel((prevModel) => ({ ...prevModel, [id]: { mode: GridRowModes.Edit } }));
};

const handleSaveClick = (id: GridRowId) => () => {
const updatedRow = rows.find((row: { id: GridRowId; }) => row.id === id);

const updatedRow = rows.find((row) => row.id === id);
if (updatedRow) {
setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
handleUpdateConfiguration(updatedRow, updatedRow.fieldIndex);
setRowModesModel((prevModel) => ({ ...prevModel, [id]: { mode: GridRowModes.View } }));
}
};

const handleUpdateConfiguration = (updatedRow: any, rowIndex: number) => {

setConfiguration(previousConfiguration => {
if (!previousConfiguration) return previousConfiguration;
const updatedConfiguration = getUpdatedConfiguration(updatedRow, rowIndex, previousConfiguration);
localStorage.setItem('configuration', JSON.stringify(updatedConfiguration));
return updatedConfiguration;
});
};

const getUpdatedConfiguration = (
updatedRow: any,
rowIndex: number,
currentConfiguration: Configuration
): Configuration => {

const handleUpdateConfiguration = (updatedRow: RowData, rowIndex: number) => {
const storedConfiguration = localStorage.getItem('configuration');
const currentConfiguration = storedConfiguration ? JSON.parse(storedConfiguration) : {};
const updatedConfiguration = getUpdatedConfiguration(updatedRow, rowIndex, currentConfiguration);
localStorage.setItem('configuration', JSON.stringify(updatedConfiguration));
setConfiguration(updatedConfiguration);
};

const getUpdatedConfiguration = (updatedRow: RowData, fieldIndex: number, currentConfig: Configuration): Configuration => {
const nodeIndex = updatedRow.nodeIndex;
const fieldName = toSnakeCase(updatedRow.fieldName);
const fieldToUpdate = { ...currentConfiguration.additionalNodes[rowIndex], fieldName };
const updatedAdditionalNodes = [...currentConfiguration.additionalNodes];
updatedAdditionalNodes[rowIndex] = fieldToUpdate;
const csvCol = updatedRow.csvCol !== undefined ? updatedRow.csvCol : null;
const nodeName = updatedRow.nodeName !== undefined ? updatedRow.nodeName : null;

const updatedNode = { ...currentConfig.additionalNodes[nodeIndex] };
if (nodeName !== null) {
updatedNode.nodeName = nodeName;
}

updatedNode.fields = updatedNode.fields.map((field, index) => {
if (index === fieldIndex) {
const updatedField = { ...field, fieldName };
if (csvCol !== null) {
updatedField.source = { ...field.source, csvCol };
}
return updatedField;
}
return field;
});

const updatedAdditionalNodes = [...currentConfig.additionalNodes];
updatedAdditionalNodes[nodeIndex] = updatedNode;

return {
...currentConfiguration,
additionalNodes: updatedAdditionalNodes
...currentConfig,
additionalNodes: updatedAdditionalNodes,
};
};

const handleCancelClick = (id: GridRowId) => () => {
setRowModesModel({
...rowModesModel,
[id]: { mode: GridRowModes.View, ignoreModifications: true }
setRowModesModel((prevModel) => {
const newModel = { ...prevModel };
delete newModel[id];
return newModel;
});
};

const processRowUpdate = (newRow: GridRowModel) => {
const { id, ...updatedRow } = newRow;
const updatedRows = rows.map((row: { id: any; }) => (row.id === id ? { ...updatedRow, id } as RowData : row));
const updatedRows = rows.map((row) => (row.id === id ? ({ ...updatedRow, id } as RowData) : row));
setRows(updatedRows);
console.log('Row updated:', updatedRow);
handleUpdateConfiguration(updatedRow as RowData, updatedRow.fieldIndex);

return { ...updatedRow, id } as RowData;
};


const handleRowModesModelChange = (newRowModesModel: GridRowModesModel) => {
setRowModesModel(newRowModesModel);
};
setRowModesModel(newRowModesModel)
}

const handleRowEditStop: GridEventListener<'rowEditStop'> = (params, event) => {
if (params.reason === GridRowEditStopReasons.rowFocusOut) {
event.defaultMuiPrevented = true;
event.defaultMuiPrevented = true;
MatthewErispe marked this conversation as resolved.
Show resolved Hide resolved
}
};

const handleProcessRowUpdateError = (error: any) => {
console.error('Error during row update:', error);
};

const columns: GridColDef[] = [
{
field: 'Name',
Expand All @@ -126,10 +145,7 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
editable: true,
align: 'left',
headerAlign: 'left',
valueGetter: (params) => {
if (params.row.fieldName === 'patient') return '';
else return formatNodeName(params.row.nodeName);
}
valueGetter: (params) => (params.row.fieldName === 'patient' ? '' : formatNodeName(params.row.nodeName)),
},
{
field: 'fieldName',
Expand All @@ -139,7 +155,7 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
align: 'center',
headerAlign: 'center',
editable: true,
valueGetter: (params) => toUpperCase(params.row.fieldName)
valueGetter: (params) => toUpperCase(params.row.fieldName),
},
{
field: 'fieldType',
Expand All @@ -149,7 +165,7 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
align: 'center',
headerAlign: 'center',
editable: false,
valueGetter: (params) => params.row.fieldType
valueGetter: (params) => params.row.fieldType,
},
{
field: 'csvCol',
Expand All @@ -159,7 +175,7 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
align: 'center',
headerAlign: 'center',
editable: true,
valueGetter: (params) => params.row.csvCol
valueGetter: (params) => params.row.csvCol,
},
{
field: 'actions',
Expand All @@ -175,34 +191,37 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
return [
<GridActionsCellItem
icon={<SaveIcon />}
key="save"
id="save-button"
label="Save"
sx={{ color: 'white' }}
onClick={handleSaveClick(id)}
/>,
<GridActionsCellItem
icon={<CancelIcon />}
key="cancel"
id="cancel-button"
label="Cancel"
className="textPrimary"
onClick={handleCancelClick(id)}
color="inherit"
/>
/>,
];
}

return [
<GridActionsCellItem
icon={<EditIcon />}
key="edit"
id="edit-button"
label="Edit"
className="textPrimary"
onClick={handleEditClick(id)}
color="inherit"
/>
/>,
];
}
}
},
},
];

return (
Expand All @@ -211,14 +230,14 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
height: 500,
width: '100%',
'& .actions': {
color: '#fff'
color: '#fff',
},
'& .textPrimary': {
color: '#fff'
}
color: '#fff',
},
}}
>
{goldenRecordList && (
{configuration && (
<DataGrid
rows={rows}
columns={columns}
Expand All @@ -227,12 +246,13 @@ const GoldenRecordLists = ({ goldenRecordList }: { goldenRecordList: any }) => {
onRowModesModelChange={handleRowModesModelChange}
onRowEditStop={handleRowEditStop}
processRowUpdate={processRowUpdate}
onProcessRowUpdateError={handleProcessRowUpdateError}
getRowId={(row) => row.id}
slots={{
toolbar: EditToolbar
toolbar: EditToolbar,
}}
slotProps={{
toolbar: { setRows, setRowModesModel }
toolbar: { setRows, setRowModesModel },
}}
/>
)}
Expand Down
20 changes: 14 additions & 6 deletions JeMPI_Apps/JeMPI_UI/src/test/settings/GoldenRecordLists.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,27 @@ import userEvent from '@testing-library/user-event';
import mockData from 'services/mockData';
import '@testing-library/jest-dom';
import GoldenRecordLists from 'pages/settings/goldenRecordLists/GoldenRecordLists';
import { useConfiguration } from 'hooks/useUIConfiguration';

jest.mock('hooks/useUIConfiguration', () => ({
useConfiguration: jest.fn(),
}));

describe('GoldenRecordLists', () => {
const goldenRecordListsWithIds = mockData.configuration.auxGoldenRecordFields.map((row, index) => ({
...row,
id: `row_${index}`,
}));
const mockConfiguration = mockData.configuration.additionalNodes;

beforeEach(() => {
(useConfiguration as jest.Mock).mockReturnValue({
configuration: mockConfiguration,
setConfiguration: jest.fn(),
});
});
it('renders without crashing', () => {
render(<GoldenRecordLists goldenRecordList={goldenRecordListsWithIds} />);
render(<GoldenRecordLists />);
});

it('handles edit mode', async () => {
render(<GoldenRecordLists goldenRecordList={goldenRecordListsWithIds} />);
render(<GoldenRecordLists />);

const editIcon = await waitFor(() => document.getElementById('edit-button'));
const saveButton = await waitFor(() => document.getElementById('save-button'));
Expand Down
Loading