Skip to content

Commit

Permalink
Feat: Add Snackbar Errors in transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
heronlancellot committed Oct 13, 2023
1 parent 914265c commit f7a2afa
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 95 deletions.
22 changes: 12 additions & 10 deletions src/components/Task/CardMultiTasks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,6 @@ import { styled } from '@mui/material/styles';
import SuspenseLoader from 'src/components/SuspenseLoader'
import { TaskFront } from 'src/models/task';

/**
* CardMultiTasks Component
*
* A component that displays a grid of multiple cards for NFTs representing tasks.
*
* @component
* @param multiTasksData - An array of TaskFront objects representing task data for multiple cards obtained from the Solidity contract function getTask() + Multicall.
* @param loading - A boolean indicating whether the data is still loading.
* @returns Multiple Card NFTs Grid to display
*/

const CardAddAction = styled(Card)(
({ theme }) => `
Expand All @@ -39,6 +29,18 @@ const CardAddAction = styled(Card)(
`
);

/**
* CardMultiTasks Component
*
* A component that displays a grid of multiple cards for NFTs representing tasks.
*
* @component
* @param multiTasksData - An array of TaskFront objects representing task data for multiple cards obtained from the Solidity contract function getTask() + Multicall.
* @param loading - A boolean indicating whether the data is still loading.
* @param page - The current page number.
* @returns Multiple Card NFTs Grid to display
*/

export const CardMultiTasks = ({ multiTasksData, loading, page }) => {

const handleCardSelect = (taskId) => {
Expand Down
54 changes: 16 additions & 38 deletions src/components/Task/CardTask.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
import { useState, forwardRef, useEffect } from 'react';
import { useState, useEffect } from 'react';
import { Box, Button, Grid, CardMedia, CardContent, Typography, Card, useMediaQuery } from '@mui/material'
import SuspenseLoader from 'src/components/SuspenseLoader'
import AccessTime from '@mui/icons-material/AccessTime';
import Snackbar from '@mui/material/Snackbar';
import MuiAlert, { AlertProps } from '@mui/material/Alert';
import { AlertColor } from '@mui/material/Alert';
import { useTaskService } from "src/services/tasks-service";
import { useWeb3Utils } from 'src/hooks/Web3UtilsHook';
import { useTheme } from '@mui/system';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import { useSnackBar } from 'src/contexts/SnackBarContext';

/**
* CardTasks Component
*
* A component that displays a card for an NFT representing a task.
*
* @component
* @param taskId - ID of the Task
* @param taskData - An array of TaskFront objects representing task data obtained from the Solidity contract function getTask().
* @param loading - A boolean indicating whether the data is still loading.
* @returns Card NFT to display
*/

const Alert = forwardRef<HTMLDivElement, AlertProps>(function Alert(
props,
ref,
) {
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

export const CardTask = ({ taskId, taskData, loading }: any) => {
const { startTask, reviewTask, completeTask, cancelTask, hasMemberRole, hasLeaderRole } = useTaskService();
const [openInformartion, setOpenInformartion] = useState(false);
const [openError, setOpenError] = useState(false);
const [error, setError] = useState<string>();
const [action, setAction] = useState<string>();
Expand All @@ -39,6 +33,12 @@ export const CardTask = ({ taskId, taskData, loading }: any) => {
const theme = useTheme();
const isSmallScreen = useMediaQuery(theme.breakpoints.down('sm'));

const { showSnackBar } = useSnackBar();

const handleSnackbar = (message: string, color: AlertColor) => {
showSnackBar(message, color)
};

const getAction = (status: string) => {
switch (status) {
case "Created":
Expand All @@ -60,18 +60,20 @@ export const CardTask = ({ taskId, taskData, loading }: any) => {
switch (taskData.status) {
case "Created":
await startTask(BigInt(taskId));
handleSnackbar('Task Start process initiated with success!', 'info')
break;
case "In Progress":
await reviewTask(BigInt(taskId));
handleSnackbar('Review Task process initiated with success!', 'info')
break;
case "In Review":
await completeTask(BigInt(taskId));
handleSnackbar('Complete Task process initiated with success!', 'info')
break;
default:
break;
}

setOpenInformartion(true);
} catch (error) {
setError(error.message)
setOpenError(true);
Expand All @@ -81,28 +83,13 @@ export const CardTask = ({ taskId, taskData, loading }: any) => {
const handleCancel = async () => {
try {
await cancelTask(BigInt(taskId));
handleSnackbar('Cancel Task process initiated with success!', 'warning')
} catch (error) {
setError(error.message)
setOpenError(true);
}
}

const handleCloseSnackInformation = (event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === 'clickaway') {
return;
}

setOpenInformartion(false);
};

const handleCloseSnackError = (event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === 'clickaway') {
return;
}

setOpenError(false);
};

useEffect(() => {
console.log("taskData", taskData)
if (taskData != null) {
Expand All @@ -118,18 +105,8 @@ export const CardTask = ({ taskId, taskData, loading }: any) => {

return (


<Grid item xs={'auto'} sm={'auto'} md={'auto'} lg={'auto'}>
<Snackbar open={openInformartion} autoHideDuration={6000} onClose={handleCloseSnackInformation}>
<Alert onClose={handleCloseSnackInformation} severity="info" sx={{ width: '100%' }}>
Task Start process initiated with sucess!
</Alert>
</Snackbar>
<Snackbar open={openError} autoHideDuration={6000} onClose={handleCloseSnackError}>
<Alert onClose={handleCloseSnackError} severity="error" sx={{ width: '100%' }}>
{error && error + " "} Try again!
</Alert>
</Snackbar>

{loading ? (
<SuspenseLoader />
) : (
Expand Down Expand Up @@ -250,6 +227,7 @@ export const CardTask = ({ taskId, taskData, loading }: any) => {
</>
)
}

</Grid >

)
Expand Down
42 changes: 32 additions & 10 deletions src/hooks/TaskServiceHook.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useState } from 'react';
import { Task, TaskStatus, TaskFront } from 'src/models/task';
import { useWeb3Utils } from 'src/hooks/Web3UtilsHook';
import { useSnackBar } from 'src/contexts/SnackBarContext';
import { AlertColor } from '@mui/material/Alert';

/**
* Interface for the Task Service, defining methods to interact with tasks.
Expand All @@ -24,6 +26,12 @@ export const useTaskServiceHook = (task: TaskService) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const { shortenAddressFromAddress } = useWeb3Utils();
const { showSnackBar } = useSnackBar();

const handleSnackbar = (message: string, color: AlertColor) => {
showSnackBar(message, color)
};


/**
* getStatus
Expand All @@ -35,7 +43,7 @@ export const useTaskServiceHook = (task: TaskService) => {
* @param taskId - The ID of the task to fetch.
* @returns - A promise that resolves when data is fetched.
*/
function getStatus(status: TaskStatus) : string {
function getStatus(status: TaskStatus): string {
switch (status) {
case TaskStatus.Created:
return "Created"
Expand Down Expand Up @@ -69,13 +77,13 @@ export const useTaskServiceHook = (task: TaskService) => {
* @returns - A promise that resolves when data is fetched.
*/
const handleTask = async (taskId: number) => {

try {
setLoading(true);
setError(null);

const result: any = await task.getTask(taskId);

let nft: TaskFront = {
taskId: taskId,
status: getStatus(result.status),
Expand All @@ -88,20 +96,21 @@ export const useTaskServiceHook = (task: TaskService) => {
assignee: result.assignee,
metadata: result.metadata
}

const shortenedAddressOrName = shortenAddressFromAddress(nft.assignee);
nft.assignee = shortenedAddressOrName;
//const d = new Date(Number(nft.endDate));
//nft.endDate = d.toDateString();
const timeInSeconds = Math.floor(Number(nft.endDate)*1000);


const timeInSeconds = Math.floor(Number(nft.endDate) * 1000);
const date = new Date(timeInSeconds);
const dateFormatted = `${date.getDate().toString().padStart(2, '0')}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getFullYear()}`;
nft.endDate = dateFormatted;
setTaskData(nft);
} catch (error) {
setError('Erro ao buscar tarefa');
handleSnackbar('Error Searching Task', 'error')
} finally {
setLoading(false);
}
Expand Down Expand Up @@ -150,6 +159,7 @@ export const useTaskServiceHook = (task: TaskService) => {
}
} catch (error) {
setError('Erro ao buscar tarefas múltiplas' + error);
handleSnackbar('Error Searching Tasks', 'error')
} finally {
setLoading(false);
}
Expand All @@ -160,15 +170,27 @@ export const useTaskServiceHook = (task: TaskService) => {
console.log('authorizedAddress ', authorizedAddress)
console.log('isAuthorized ', isAuthorized)

return await task.setRole(roleId, authorizedAddress, isAuthorized);
try {
handleSnackbar('Set Role process initiated with success!', 'info')
return await task.setRole(roleId, authorizedAddress, isAuthorized);
} catch (error) {
handleSnackbar('Error Set Role!', 'error')
}

};

const handleOperator = async (interfaceId: any, roleId: any, isAuthorized: boolean) => {
console.log('interfaceId ', interfaceId)
console.log('roleId ', roleId)
console.log('isAuthorized ', isAuthorized)

return await task.setOperator(interfaceId, roleId, isAuthorized);
try {
handleSnackbar('Set Operator process initiated with success!', 'info')
return await task.setOperator(interfaceId, roleId, isAuthorized);
} catch (error) {
handleSnackbar('Error Set Operator!', 'error')
}

};

return {
Expand Down
Loading

0 comments on commit f7a2afa

Please sign in to comment.