Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
12 kB
4
Indexable
Never
#task manager
import React, { useEffect, useState, useContext } from 'react';
import { Box, Button, IconButton } from '@mui/material';
import { DataGrid, GridToolbar } from '@mui/x-data-grid';
import EditIcon from '@mui/icons-material/Edit';
import { Context } from '../context/ContextProvider';
import { getData, postData } from '../actions/CrudService';
import { CustomPageHeader } from '../components/MUICustomComponents';
import useIncrementVisitCount from '../actions/useIncrementVisitCount';
import GridCellExpand from '../components/GridCellExpand';
import '../styles/datagrid.css';
import TaskDetails from './TaskDetails';
import NewFormComponent from '../components/NewFormComponent';
import { constants } from '../constants';
import MarkAsInactiveButton from '../components/MarkAsInactiveButton';
import {useNavigate, } from 'react-router-dom';
import MoreHorizIcon from '@mui/icons-material/MoreHoriz';

function renderCellExpand(params) {
    const today = new Date();
    const twoDaysFromNow = new Date(today.getTime() + 2 * 24 * 60 * 60 * 1000);
    const date = new Date(params.value);
    const dateString = date.toLocaleDateString();
  if(!Number.isInteger(params.value) ){
        if (date < today) {
        return <GridCellExpand value={dateString} width={params.colDef.computedWidth} style={{ color: 'red', fontWeight: 'bold' }} />;
        } else if (date < twoDaysFromNow && date >= today) {
        return <GridCellExpand value={dateString} width={params.colDef.computedWidth} style={{ color: 'blue', fontWeight: 'bold' }} />;
        } else if (date >= twoDaysFromNow) {
        return <GridCellExpand value={dateString} width={params.colDef.computedWidth} style={{ color: 'green', fontWeight: 'bold' }} />;
        } 
    } 
        return <GridCellExpand value={params.value || ''} width={params.colDef.computedWidth} />;
    
};

const TaskManager = () => {

    const navigate = useNavigate();
    const { dispatch } = useContext(Context);
    const [services, setServices] = useState([]);
    const [rowId, setRowId] = useState(null);
    const [open, setOpen] = useState(false); //yeni kayıt ekleme formunun açılıp-kapanmasıın yöneten state.
    const [currentRow, setcurrentRow] = useState({});
    const [pageSize, setPageSize] = useState(10);
    const url = constants.rootApiUrl + "/parameterizedquery";
    useIncrementVisitCount();
    const crudParams = {
        "tns": "reportdbtns",
        "path": 'Pages/TaskManagement/TaskManagementQuery',
        "tableName": 'INNOVAZONE.temp_task_management'
    };
    const HandleDetailsClick = (taskId) => {
        navigate(`/task-details/${taskId}`);
    };
    const fetchTaskData = ()  => {
        getData({ params: crudParams, dispatch, data: services, setData: setServices })
            .then((data) => {
                
                const dataArray = Array.isArray(data) ? data : [data];
                // Function to generate a unique ID
                const selectId = (row) => {
                    if (row.TASK_ID) {
                      return {
                        ...row,
                        id: row.TASK_ID,
                      };
                    } else {
                      return row;
                    }
                  };
                // Add a unique 'id' property to each row
                const servicesWithIds = dataArray.map(selectId);
                setServices(servicesWithIds);
            })
            .catch(function (error) {
                if (error && error.response && error.response.data) {
                    console.log(error.response.data);
                } else {
                    console.log("An unexpected error occurred:", error);
                }
            });
    };
    const handleDeleteRow = (taskId) => {
        // Update the IS_ACTIVE column for the specified task ID to 0
        const updatedServices = services.map((row) => {
        if (row.TASK_ID === taskId) {
        return {
                ...row,
                IS_ACTIVE: 0,
            };
        }
            return row;
        });
        // Update the state with the modified data
        setServices(updatedServices);
        // Perform the API request to update the database
        const crudParamsUpdate = {
            "tns": "reportdbtns",
            "path": 'Pages/TaskManagement/TaskManagementUpdate',
            "tableName": 'INNOVAZONE.temp_task_management',
            "searchParams": {
                "@TASK_ID": taskId,
                "@IS_ACTIVE": 0, // Update IS_ACTIVE to 0
            },
        };
        postData(crudParamsUpdate, dispatch, url)
            .then((response) => {
            //console.log('API Response:', response);
            })
            .catch((error) => {
            console.error('API Error:', error);
            });
        };

    useEffect(() => {
        fetchTaskData();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
   
    const columns = [
        {
            field: 'TASK_ID',
            headerName: 'Task Id',
            width: '70',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'TYPE',
            headerName: 'Kategori',
            width: '80',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'SUBJECT',
            headerName: 'Konu Başlığı',
            width: '250',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'PRIORITY',
            headerName: 'Öncelik',
            width: '80',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'ASSIGNEE',
            headerName: 'Sorumlu',
            width: '150',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'ASSIGNED_BY',
            headerName: 'Talep Sahibi',
            width: '120',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'DEADLINE',
            headerName: 'Teslim Tarihi',
            width: '100',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'STATUS',
            headerName: 'Durum',
            width: '100',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'CREATED_AT',
            headerName: 'Oluşturulma Zamanı',
            width: '140',
            renderCell: renderCellExpand,
            
        },
        {
            field: 'actions',
            headerName: 'İşlemler',
            type: 'actions',
            renderCell: (params) => (
                <MarkAsInactiveButton taskId={params.row.TASK_ID} onClick={handleDeleteRow}></MarkAsInactiveButton>
            ),
        },
        {
            field: 'DETAILS',
            headerName: 'Detaylar',
            type: 'actions',
            renderCell: (params) => (
                <IconButton aria-label="Details" onClick={() => HandleDetailsClick(params.row.TASK_ID)}>
                    <MoreHorizIcon></MoreHorizIcon>
                </IconButton>
            ),
        },
    ];

    const closeForm = () => {
        setOpen(false);
    };
    function formatDateToSql(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed
        const day = String(date.getDate()).padStart(2, '0');
      
        return `${year}-${month}-${day}`;
      }
    const addNewRow = (data) => {
         // Parse the string date into a Date object
        const deadlineDate = new Date(data.DEADLINE);
        const maxTaskId = services.reduce((max, row) => (row.TASK_ID > max ? row.TASK_ID : max), 0);
        const newTaskId = maxTaskId + 1;
        // Check if the parsed date is a valid Date object
        if (isNaN(deadlineDate.getTime())) {
            console.error('Invalid deadline date:', data.DEADLINE);
            return;
        }
        
        // Format the date
        const formattedDate = formatDateToSql(deadlineDate);
        //console.log('Formatted date:', formattedDate);
        //console.log('Formatted id:', newTaskId);
        //console.log(data);
        const crudParamsWrite = {
            "tns": "reportdbtns",
            "path": 'Pages/TaskManagement/TaskManagementInsert',
            "tableName": 'INNOVAZONE.temp_task_management',
            "searchParams": {
                "@TASK_ID": newTaskId,
                "@TYPE": data.TYPE,
                "@SUBJECT": data.SUBJECT,
                "@PRIORITY": data.PRIORITY,
                "@ASSIGNEE": data.ASSIGNEE,
                "@ASSIGNED_BY": data.ASSIGNED_BY,
                "@DEADLINE": formattedDate,
                "@STATUS": data.STATUS,
                "@TEAM": "CNO"
              }
        };
        console.log(crudParamsWrite);
        postData(crudParamsWrite, dispatch, url)
        .then((response) => {
          //console.log('API Response:', response);
          
          ;
        })
        .catch((error) => {
          console.error('API Error:', error);
          
        });
        
        setOpen(false);
        setcurrentRow({});
    };

   
    
      
      

    return (
        <Box sx={{
            flexDirection: 'column',
            alignItems: 'center',
            display: 'flex',
            justifyContent: 'center'
        }}>
            <Box
                sx={{
                    height: 600,
                    width: '100%',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                }}
            >
                <CustomPageHeader pageName='Görev Takip Ekranı' />
                <Button style={{ marginTop: 10, marginBottom: 10 }} variant="contained" onClick={() => setOpen(true)}> Yeni Görev oluştur </Button >
                <DataGrid
                    columns={columns}
                    renderCellExpand={renderCellExpand}
                    //renderCellExpandDate={renderCellExpandDate}
                    components={{
                        Toolbar: GridToolbar,

                    }}
                    rows={services}
                    getRowId={(row) => row.TASK_ID}
                    rowsPerPageOptions={[10, 20, 50, 100]}
                    pageSize={pageSize}
                    onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
                    disableDensitySelector
                    disableSelectionOnClick
                    hideFooterSelectedRowCount
                    getRowClassName={(params) =>
                        (params.indexRelativeToCurrentPage % 2 === 0 ? 'stripe-even' : 'stripe-odd')
                    }
                    componentsProps={{
                        toolbar: {
                            showQuickFilter: true,
                            quickFilterProps: { debounceMs: 100 },
                            csvOptions: { disableToolbarButton: true },
                            printOptions: { disableToolbarButton: true },
                        },
                    }}
                    sx={{
                        ".MuiTablePagination-displayedRows, .MuiTablePagination-selectLabel": {
                            "marginTop": "1em",
                            "marginBottom": "1em"
                        } //options elementlerini dikeyde hizala,
                    }}
                    onCellEditCommit={(params) => setRowId(params.id)}

                />
                <NewFormComponent open={open} onClose={closeForm} addNewRow={addNewRow} theadData={columns} currentRow={currentRow} setcurrentRow={setcurrentRow} />
            </Box>
            <Box
                sx={{
                    height: 600,
                    width: '50%',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginTop: 20
                }}
            >   
            </Box>
        </Box>
    );
};

export default TaskManager;
Leave a Comment