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

OM-342: update all mutation, adjust group view #76

Merged
merged 2 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
103 changes: 89 additions & 14 deletions src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import {
graphqlWithVariables,
formatGQLString,
parseData,
decodeId,
} from '@openimis/fe-core';
import { ACTION_TYPE } from './reducer';
import {
CLEAR, ERROR, REQUEST, SUCCESS,
} from './utils/action-type';
import { EMPTY_STRING } from './constants';

const WORKER_VOUCHER_PROJECTION = (modulesManager) => [
'id',
Expand Down Expand Up @@ -44,14 +46,21 @@ const WORKER_PROJECTION = (modulesManager) => [
'photo { photo }',
];

// TODO: Adjust the group projection after BE changes
// eslint-disable-next-line no-unused-vars
export const GROUP_PROJECTION = (modulesManager) => [
'id',
'uuid',
'otherNames',
'lastName',
// `workers {${WORKER_PROJECTION(modulesManager)}}`,
'name',
'isDeleted',
'dateCreated',
`policyholder ${modulesManager.getProjection('policyHolder.PolicyHolderPicker.projection')}`,
`groupWorkers {
edges {
node {
isDeleted,
insuree ${modulesManager.getProjection('insuree.InsureePicker.projection')},
}
}
totalCount
}`,
];

function formatGraphQLDateRanges(dateRanges) {
Expand Down Expand Up @@ -546,15 +555,13 @@ export function validateMConnectWorker(nationalId, economicUnitCode) {

export function fetchGroupsAction(modulesManager, params) {
const queryParams = [...params];
// TODO: Change to `group` after BE changes
const payload = formatPageQueryWithCount('worker', queryParams, GROUP_PROJECTION(modulesManager));
const payload = formatPageQueryWithCount('groupOfWorker', queryParams, GROUP_PROJECTION(modulesManager));
return graphql(payload, ACTION_TYPE.GET_GROUPS);
}

export function fetchGroup(modulesManager, params) {
const queryParams = [...params];
// TODO: Change to `group` after BE changes
const payload = formatPageQueryWithCount('worker', queryParams, GROUP_PROJECTION(modulesManager));
const payload = formatPageQueryWithCount('groupOfWorker', queryParams, GROUP_PROJECTION(modulesManager));
return graphql(payload, ACTION_TYPE.GET_GROUP);
}

Expand All @@ -564,9 +571,77 @@ export const clearGroup = () => (dispatch) => {
});
};

// TODO: Adjust the group mutation after BE changes
export function createGroup() {}
export function createGroup(economicUnit, groupToCreate, clientMutationLabel) {
const workersChfIds = groupToCreate?.workers?.map((worker) => worker.chfId) ?? [];
const workerChfIdsString = workersChfIds.map((chfId) => `"${chfId}"`).join(', ');

export function updateGroup() {}
const mutationInput = `
${economicUnit.code ? `economicUnitCode: "${economicUnit.code}"` : EMPTY_STRING}
${groupToCreate.name ? `name: "${formatGQLString(groupToCreate.name)}"` : EMPTY_STRING}
${workerChfIdsString.length ? `insureesChfId: [${workerChfIdsString}]` : EMPTY_STRING}
`;

export function deleteGroup() {}
const mutation = formatMutation('createOrUpdateGroupOfWorkers', mutationInput, clientMutationLabel);
const requestedDateTime = new Date();

return graphql(
mutation.payload,
[REQUEST(ACTION_TYPE.MUTATION), SUCCESS(ACTION_TYPE.CREATE_GROUP), ERROR(ACTION_TYPE.MUTATION)],
{
actionType: ACTION_TYPE.CREATE_GROUP,
clientMutationId: mutation.clientMutationId,
clientMutationLabel,
requestedDateTime,
},
);
}

export function updateGroup(economicUnit, groupToUpdate, clientMutationLabel) {
const workersChfIds = groupToUpdate?.workers?.map((worker) => worker.chfId) ?? [];
const workerChfIdsString = workersChfIds.map((chfId) => `"${chfId}"`).join(', ');

const mutationInput = `
${groupToUpdate.id ? `id: "${decodeId(groupToUpdate.id)}"` : EMPTY_STRING}
${economicUnit.code ? `economicUnitCode: "${economicUnit.code}"` : EMPTY_STRING}
${groupToUpdate.name ? `name: "${formatGQLString(groupToUpdate.name)}"` : EMPTY_STRING}
${workerChfIdsString.length ? `insureesChfId: [${workerChfIdsString}]` : EMPTY_STRING}
`;

const mutation = formatMutation('createOrUpdateGroupOfWorkers', mutationInput, clientMutationLabel);
const requestedDateTime = new Date();

return graphql(
mutation.payload,
[REQUEST(ACTION_TYPE.MUTATION), SUCCESS(ACTION_TYPE.UPDATE_GROUP), ERROR(ACTION_TYPE.MUTATION)],
{
actionType: ACTION_TYPE.UPDATE_GROUP,
clientMutationId: mutation.clientMutationId,
clientMutationLabel,
requestedDateTime,
},
);
}

export function deleteGroup(economicUnit, groupsToDelete, clientMutationLabel) {
const groupsUuids = groupsToDelete.map((group) => decodeId(group.id));
const groupUuidsString = groupsUuids.map((uuid) => `"${uuid}"`).join(', ');

const mutationInput = `
${economicUnit.code ? `economicUnitCode: "${economicUnit.code}"` : EMPTY_STRING}
${groupsToDelete.length ? `uuids: [${groupUuidsString}]` : EMPTY_STRING}
`;

const mutation = formatMutation('deleteGroupOfWorkers', mutationInput, clientMutationLabel);
const requestedDateTime = new Date();

return graphql(
mutation.payload,
[REQUEST(ACTION_TYPE.MUTATION), SUCCESS(ACTION_TYPE.DELETE_GROUP), ERROR(ACTION_TYPE.MUTATION)],
{
actionType: ACTION_TYPE.DELETE_GROUP,
clientMutationId: mutation.clientMutationId,
clientMutationLabel,
requestedDateTime,
},
);
}
4 changes: 2 additions & 2 deletions src/components/groups/GroupFilter.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ function GroupFilter({ filters, onChangeFilters }) {
<TextInput
module="workerVoucher"
label="workerVoucher.group.name"
value={filterTextFieldValue('groupName')}
onChange={onChangeStringFilter('groupName', CONTAINS_LOOKUP)}
value={filterTextFieldValue('name')}
onChange={onChangeStringFilter('name', CONTAINS_LOOKUP)}
/>
</Grid>
</Grid>
Expand Down
77 changes: 49 additions & 28 deletions src/components/groups/GroupSearcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,32 @@ import { useDispatch, useSelector } from 'react-redux';

import { IconButton, Tooltip } from '@material-ui/core';
import DeleteIcon from '@material-ui/icons/Delete';
import EditIcon from '@material-ui/icons/Edit';
import VisibilityIcon from '@material-ui/icons/Visibility';

import {
Searcher, SelectDialog, journalize, useHistory, useModulesManager, useTranslations,
Searcher,
SelectDialog,
useToast,
useHistory,
useModulesManager,
useTranslations,
decodeId,
} from '@openimis/fe-core';
import { deleteGroup, fetchGroupsAction } from '../../actions';
import {
ADMIN_RIGHT,
DEFAULT_PAGE_SIZE,
EMPTY_STRING,
MODULE_NAME,
RIGHT_GROUP_DELETE,
RIGHT_GROUP_EDIT,
RIGHT_GROUP_SEARCH,
ROWS_PER_PAGE_OPTIONS,
} from '../../constants';
import GroupFilter from './GroupFilter';
import { getLastMutationLog } from '../../utils/utils';

function GroupSearcher() {
function GroupSearcher({ searcherActions, enableActionButtons }) {
const history = useHistory();
const dispatch = useDispatch();
const modulesManager = useModulesManager();
Expand All @@ -33,32 +42,35 @@ function GroupSearcher() {
fetchedGroups,
errorGroups,
groups,
// TODO: Uncomment when BE is ready
// groupsPageInfo,
// groupsTotalCount,
groupsPageInfo,
groupsTotalCount,
mutation,
submittingMutation,
} = useSelector((state) => state.workerVoucher);
const { economicUnit } = useSelector((state) => state.policyHolder);

const { formatMessage, formatMessageWithValues } = useTranslations(MODULE_NAME, modulesManager);
const { showSuccess, showError } = useToast();

const [queryParams, setQueryParams] = useState([]);
const [deleteGroupDialogOpen, setDeleteGroupDialogOpen] = useState(false);
const [groupToDelete, setGroupToDelete] = useState(null);
const isAdmin = rights.includes(ADMIN_RIGHT);

const fetchGroups = useCallback(
(params) => {
try {
const actionParams = [...params];

if (economicUnit?.code) {
if (!isAdmin && economicUnit?.code) {
actionParams.push(`economicUnitCode:"${economicUnit.code}"`);
}

actionParams.push('isDeleted: false');

dispatch(fetchGroupsAction(modulesManager, actionParams));
} catch (error) {
throw new Error(`[GROUP_SEARCHER]: Fetching groups failed. ${error}`);
throw new Error(`[GROUP_SEARCHER]: Fetching groups failed.. ${error}`);
}
},
[economicUnit],
Expand All @@ -67,18 +79,16 @@ function GroupSearcher() {
const headers = () => [
'workerVoucher.GroupSearcher.groupName',
'workerVoucher.GroupSearcher.dateCreated',
'workerVoucher.GroupSearcher.workersCount',
'emptyLabel',
];

const sorts = () => [
['groupName', true],
['dateCreated', true],
];
const sorts = () => [['name', true], ['dateCreated', true], null];

const rowIdentifier = (group) => group.uuid;

const openGroup = (group) => rights.includes(RIGHT_GROUP_SEARCH)
&& history.push(`/${modulesManager.getRef('workerVoucher.route.group')}/${group?.uuid}`);
&& history.push(`/${modulesManager.getRef('workerVoucher.route.group')}/${decodeId(group.id)}`);

const onDoubleClick = (group) => openGroup(group);

Expand All @@ -94,8 +104,7 @@ function GroupSearcher() {

const onDeleteGroupConfirm = () => {
try {
dispatch(deleteGroup(economicUnit, groupToDelete, 'Delete Group'));
fetchGroups(queryParams);
dispatch(deleteGroup(economicUnit, [groupToDelete], 'Delete Group'));
} catch (error) {
throw new Error(`[GROUP_SEARCHER]: Deletion failed. ${error}`);
} finally {
Expand All @@ -104,15 +113,15 @@ function GroupSearcher() {
};

const itemFormatters = () => [
(group) => group.chfId,
(group) => group.lastName,
(group) => group.otherNames,
(group) => group.name,
(group) => group.dateCreated.split('T')[0],
(group) => group.groupWorkers.totalCount,
(group) => (
<div style={{ textAlign: 'right' }}>
{rights.includes(RIGHT_GROUP_EDIT) && (
<Tooltip title={formatMessage('workerVoucher.tooltip.edit')}>
<IconButton onClick={() => openGroup(group)}>
<EditIcon />
<VisibilityIcon />
</IconButton>
</Tooltip>
)}
Expand Down Expand Up @@ -161,11 +170,25 @@ function GroupSearcher() {
}
}, [economicUnit, queryParams]);

useEffect(() => {
useEffect(async () => {
if (prevSubmittingMutationRef.current && !submittingMutation) {
dispatch(journalize(mutation));
const mutationLog = await getLastMutationLog(dispatch, mutation?.clientMutationId || EMPTY_STRING);

if (mutationLog?.error) {
const { detail } = JSON.parse(mutationLog.error);

showError(
formatMessageWithValues('GroupDetailsPage.delete.error', {
detail,
}),
);
return;
}

showSuccess(formatMessage('GroupDetailsPage.delete.success'));
fetchGroups(queryParams);
}
}, [submittingMutation]);
}, [submittingMutation, mutation]);

useEffect(() => {
prevSubmittingMutationRef.current = submittingMutation;
Expand All @@ -178,23 +201,21 @@ function GroupSearcher() {
FilterPane={groupFilters}
fetch={fetchGroups}
items={groups}
// TODO: Uncomment when BE is ready
// itemsPageInfo={groupsPageInfo}
itemsPageInfo={{ totalCount: 0 }}
itemsPageInfo={groupsPageInfo}
fetchedItems={fetchedGroups}
fetchingItems={fetchingGroups}
errorItems={errorGroups}
filtersToQueryParams={filtersToQueryParams}
// TODO: Uncomment when BE is ready
// tableTitle={formatMessageWithValues('workerVoucher.GroupSearcher.resultsTitle', { groupsTotalCount })}
tableTitle={formatMessageWithValues('workerVoucher.GroupSearcher.resultsTitle', { groupsTotalCount: 0 })}
tableTitle={formatMessageWithValues('workerVoucher.GroupSearcher.resultsTitle', { groupsTotalCount })}
headers={headers}
itemFormatters={itemFormatters}
sorts={sorts}
rowsPerPageOptions={ROWS_PER_PAGE_OPTIONS}
defaultPageSize={DEFAULT_PAGE_SIZE}
rowIdentifier={rowIdentifier}
onDoubleClick={onDoubleClick}
enableActionButtons={enableActionButtons}
searcherActions={searcherActions}
/>
<SelectDialog
confirmState={deleteGroupDialogOpen}
Expand Down
Loading
Loading