Skip to content

Commit

Permalink
OM-347: adjust public page, add toasts to worker page
Browse files Browse the repository at this point in the history
  • Loading branch information
olewandowski1 committed Oct 24, 2024
1 parent b987c7f commit 8e5beec
Show file tree
Hide file tree
Showing 9 changed files with 101 additions and 57 deletions.
13 changes: 10 additions & 3 deletions src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,14 @@ export function deleteGroup(economicUnit, groupsToDelete, clientMutationLabel) {
}

export function fetchPublicVoucherDetails(voucherUuid) {
const queryParams = [`code: "${voucherUuid}"`];
const payload = formatPageQueryWithCount('voucherCheck', queryParams, WORKER_VOUCHER_CHECK_PROJECTION);
return graphql(payload, ACTION_TYPE.REQUEST);
return graphqlWithVariables(
`
query checkVoucherValidity($voucherUuid: String!) {
voucherCheck(code: $voucherUuid) {
${WORKER_VOUCHER_CHECK_PROJECTION.join('\n')}
}
}
`,
{ voucherUuid },
);
}
3 changes: 2 additions & 1 deletion src/components/VoucherQRCode.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ const useStyles = makeStyles(() => ({
}));

export default function VoucherQRCode({ voucher, bgColor = '#e4f2ff' }) {
const classes = useStyles();

if (!voucher) {
return null;
}

const classes = useStyles();
const voucherUrl = new URL(`${window.location.origin}${process.env.PUBLIC_URL}/voucher/check/${voucher.code}`);

return (
Expand Down
5 changes: 3 additions & 2 deletions src/components/VoucherSearcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
VOUCHER_RIGHT_SEARCH,
} from '../constants';
import VoucherFilter from './VoucherFilter';
import { trimDate } from '../utils/utils';

function VoucherSearcher({ downloadWorkerVoucher, fetchWorkerVouchers, clearWorkerVoucherExport }) {
const history = useHistory();
Expand Down Expand Up @@ -116,8 +117,8 @@ function VoucherSearcher({ downloadWorkerVoucher, fetchWorkerVouchers, clearWork
? `${workerVoucher.insuree?.chfId} ${workerVoucher.insuree?.lastName}`
: formatMessage('workerVoucher.unassigned')),
(workerVoucher) => formatMessage(`workerVoucher.status.${workerVoucher.status}`),
(workerVoucher) => workerVoucher.assignedDate,
(workerVoucher) => workerVoucher.expiryDate,
(workerVoucher) => trimDate(workerVoucher.assignedDate),
(workerVoucher) => trimDate(workerVoucher.expiryDate),
(workerVoucher) => (
<div style={{ textAlign: 'right' }}>
<Tooltip title={formatMessage('workerVoucher.tooltip.details')}>
Expand Down
24 changes: 20 additions & 4 deletions src/components/WorkerSearcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import {
useTranslations,
downloadExport,
SelectDialog,
journalize,
EXPORT_FILE_FORMATS,
useToast,
} from '@openimis/fe-core';
import {
fetchWorkers, downloadWorkers, clearWorkersExport, deleteWorkerFromEconomicUnit,
Expand All @@ -37,6 +37,7 @@ import {
import WorkerFilter from './WorkerFilter';
import { ACTION_TYPE } from '../reducer';
import { useUploadWorkerContext } from '../context/UploadWorkerContext';
import { getLastMutationLog } from '../utils/utils';

const WORKER_SEARCHER_ACTION_CONTRIBUTION_KEY = 'workerVoucher.WorkerSearcherAction.select';

Expand Down Expand Up @@ -68,6 +69,7 @@ function WorkerSearcher({
|| !rights.includes(INSPECTOR_RIGHT));

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

const [failedExport, setFailedExport] = useState(false);
const [queryParams, setQueryParams] = useState([]);
Expand Down Expand Up @@ -241,11 +243,25 @@ function WorkerSearcher({
}
}, [validationSuccess, validationWarning]);

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

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

showError(
formatMessageWithValues('deleteWorker.error', {
detail: parsedMutationError[0]?.detail || EMPTY_STRING,
}),
);
return;
}

showSuccess(formatMessage('deleteWorker.success'));
fetchWorkers(queryParams);
}
}, [submittingMutation]);
}, [submittingMutation, mutation]);

useEffect(() => {
prevSubmittingMutationRef.current = submittingMutation;
Expand Down
14 changes: 1 addition & 13 deletions src/components/WorkerSearcherSelectActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import { makeStyles } from '@material-ui/styles';
import DeleteIcon from '@material-ui/icons/Delete';

import { SelectDialog, journalize, useTranslations } from '@openimis/fe-core';
import { SelectDialog, useTranslations } from '@openimis/fe-core';
import { deleteWorkersFromEconomicUnit } from '../actions';
import { MODULE_NAME } from '../constants';

Expand All @@ -27,11 +27,9 @@ function WorkerSearcherSelectActions({
withSelection,
downloadWithIconButton = false,
}) {
const prevSubmittingMutationRef = useRef();
const prevEconomicUnitRef = useRef();
const [isBulkDeleteDialogOpen, setIsBulkDeleteDialogOpen] = useState(false);
const { economicUnit } = useSelector((state) => state.policyHolder);
const { mutation, submittingMutation } = useSelector((state) => state.workerVoucher);
const dispatch = useDispatch();
const classes = useStyles();
const { formatMessage } = useTranslations(MODULE_NAME);
Expand Down Expand Up @@ -61,16 +59,6 @@ function WorkerSearcherSelectActions({
prevEconomicUnitRef.current = economicUnit;
}, [economicUnit, selectedWorkers, clearSelected]);

useEffect(() => {
if (prevSubmittingMutationRef.current && !submittingMutation) {
dispatch(journalize(mutation));
}
}, [submittingMutation]);

useEffect(() => {
prevSubmittingMutationRef.current = submittingMutation;
});

if (!withSelection) {
return null;
}
Expand Down
70 changes: 43 additions & 27 deletions src/pages/PublicVoucherDetailsPage.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import { useDispatch } from 'react-redux';

import {
Box, Button, Divider, Grid, Paper, Typography,
Box, Button, Divider, Grid, Paper, Typography, CircularProgress,
} from '@material-ui/core';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import CheckIcon from '@material-ui/icons/Check';
import ErrorIcon from '@material-ui/icons/Error';
import WarningIcon from '@material-ui/icons/Warning';
import { makeStyles } from '@material-ui/styles';

import {
decodeId, parseData, useHistory, useModulesManager, useTranslations,
useToast, useHistory, useModulesManager, useTranslations,
} from '@openimis/fe-core';
import { fetchPublicVoucherDetails } from '../actions';
import { EMPTY_STRING, MODULE_NAME } from '../constants';
import { trimDate } from '../utils/utils';

const useStyles = makeStyles((theme) => ({
root: {
Expand Down Expand Up @@ -93,13 +92,20 @@ const useStyles = makeStyles((theme) => ({
color: '#00796b',
},
button: theme.dialog.primaryButton,
spinnerContainer: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
},
}));

export default function PublicVoucherDetailsPage({ match, logo }) {
const modulesManager = useModulesManager();
const dispatch = useDispatch();
const classes = useStyles();
const { formatMessage, formatMessageWithValues } = useTranslations(MODULE_NAME);
const { showError } = useToast();
const voucherUuid = match.params.voucher_uuid;
const [voucherSearcher, setVoucherSearcher] = useState({
isExisted: false,
Expand All @@ -108,32 +114,43 @@ export default function PublicVoucherDetailsPage({ match, logo }) {
employerCode: EMPTY_STRING,
employerName: EMPTY_STRING,
});
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
useEffect(async () => {
const fetchVoucher = async () => {
if (voucherUuid) {
try {
const response = await dispatch(fetchPublicVoucherDetails(voucherUuid));
const vouchers = parseData(response.payload.data.workerVoucher);
const voucherData = vouchers?.map((voucher) => ({
...voucher,
uuid: decodeId(voucher.id),
}))?.[0];

setVoucherSearcher({
isFound: Boolean(voucherData),
voucherDetails: voucherData || {},
});
} catch (error) {
// eslint-disable-next-line no-console
console.error(`[PUBLIC_VOUCHER_DETAILS_PAGE]: Fetching voucher details failed. ${error}`);
}
}
const response = await dispatch(fetchPublicVoucherDetails(voucherUuid || EMPTY_STRING));

const {
assignedDate, employerCode, employerName, isExisted, isValid,
} = response.payload.data.voucherCheck;

setVoucherSearcher({
assignedDate,
employerCode,
employerName,
isExisted,
isValid,
});
};

fetchVoucher();
try {
setIsLoading(true);
await fetchVoucher();
} catch {
showError('[PUBLIC_VOUCHER_DETAILS_PAGE]: Fetching voucher details failed.');
} finally {
setIsLoading(false);
}
}, [voucherUuid, dispatch, modulesManager]);

if (isLoading) {
return (
<div className={classes.spinnerContainer}>
<CircularProgress />
</div>
);
}

if (!voucherUuid) {
return (
<RootLayout logo={logo}>
Expand All @@ -158,9 +175,8 @@ export default function PublicVoucherDetailsPage({ match, logo }) {
return formatMessageWithValues(
isValid ? 'PublicVoucherDetailsPage.voucherFound' : 'PublicVoucherDetailsPage.invalidVoucherFound',
{
assignedDate,
employerCode,
employerName,
assignedDate: <strong>{trimDate(assignedDate)}</strong>,
employer: <strong>{`${employerCode} - ${employerName}`}</strong>,
},
);
};
Expand Down
23 changes: 16 additions & 7 deletions src/pages/WorkerDetailsPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useDispatch, useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/styles';

import {
Form, Helmet, useHistory, useModulesManager, useTranslations, parseData, journalize,
Form, Helmet, useHistory, useModulesManager, useTranslations, parseData, useToast,
} from '@openimis/fe-core';
import {
appendWorkerToEconomicUnit, clearWorker, fetchWorker, fetchWorkerVoucherCount,
Expand All @@ -14,6 +14,7 @@ import {
} from '../constants';
import WorkerMasterPanel from '../components/WorkerMasterPanel';
import WorkerMConnectMasterPanel from '../components/WorkerMConnectMasterPanel';
import { getLastMutationLog } from '../utils/utils';

const useStyles = makeStyles((theme) => ({
page: theme.page,
Expand All @@ -35,6 +36,7 @@ function WorkerDetailsPage({ match }) {
const [reset, setReset] = useState(0);
const [workerVoucherCount, setWorkerVoucherCount] = useState(0);
const { mutation, submittingMutation } = useSelector((state) => state.workerVoucher);
const { showSuccess, showError } = useToast();

const titleParams = (worker) => ({
chfId: worker?.chfId ?? EMPTY_STRING,
Expand Down Expand Up @@ -79,20 +81,27 @@ function WorkerDetailsPage({ match }) {
code: 'M',
};

dispatch(appendWorkerToEconomicUnit(economicUnit.code, data, 'Append Worker to Economic Unit')).then(
() => history.goBack(),
);
dispatch(appendWorkerToEconomicUnit(economicUnit.code, data, 'Append Worker to Economic Unit'))
.then(() => history.goBack());
} catch (error) {
setReset((prevReset) => prevReset + 1);
throw new Error(`[WORKER_DETAILS_PAGE]: Saving worker failed. ${error}`);
}
};

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

if (mutationLog?.error) {
showError(formatMessageWithValues('saveWorker.error'));
setReset((prevReset) => prevReset + 1);
return;
}

showSuccess(formatMessage('saveWorker.success'));
}
}, [submittingMutation]);
}, [submittingMutation, mutation]);

useEffect(() => {
prevSubmittingMutationRef.current = submittingMutation;
Expand Down
4 changes: 4 additions & 0 deletions src/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@
"workerVoucher.WorkerSearcher.dialog.message": "You are about to delete the worker. This action cannot be undone. Please confirm if you wish to proceed with this action.",
"workerVoucher.WorkerSearcher.dialog.confirm": "Delete",
"workerVoucher.WorkerSearcher.dialog.abandon": "Cancel",
"workerVoucher.deleteWorker.success": "The worker(s) has been deleted successfully.",
"workerVoucher.deleteWorker.error": "Something went wrong while deleting the worker(s). {detail}",
"workerVoucher.saveWorker.success": "The worker has been saved successfully.",
"workerVoucher.saveWorker.error": "Something went wrong while saving the worker.",
"workerVoucher.priceManagement": "Confirm Voucher Price",
"workerVoucher.mobileAppPassword": "Submit Change",
"workerVoucher.password.mustMatch": "The new password and confirmation password must match",
Expand Down
2 changes: 2 additions & 0 deletions src/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,5 @@ export const getLastMutationLog = async (dispatch, mutationId) => {

export const isTheVoucherExpired = (voucher) => voucher.status === WORKER_VOUCHER_STATUS.EXPIRED
|| new Date(voucher.expiryDate) < new Date();

export const trimDate = (date) => date.split('T')[0];

0 comments on commit 8e5beec

Please sign in to comment.