Commit e07268be authored by Нелли Ибрагимова's avatar Нелли Ибрагимова

настроила функцию удаления задачи с сервера

parents 44c01629 ba39a466
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
dateTimeStart:Date| null; dateTimeStart:Date| null;
dateTimeDue:Date| null; dateTimeDue:Date| null;
accomplish: taskFinishType; accomplish: taskFinishType;
priority: priorityType; priority: priorityType | null;
author: User; author: User;
project:Project|null; project:Project|null;
executors:User[] executors:User[]
...@@ -54,9 +54,10 @@ import { ...@@ -54,9 +54,10 @@ import {
@Column({ @Column({
type: "enum", type: "enum",
enum: ["A", "B" , "C"], enum: ["A", "B" , "C"],
default: "C" default: "C",
nullable: true
}) })
priority!: priorityType priority!: priorityType | null;
......
...@@ -97,7 +97,7 @@ router.put('/',async(req:Request, res:Response)=> { ...@@ -97,7 +97,7 @@ router.put('/',async(req:Request, res:Response)=> {
.getOne() .getOne()
if (!user) return res.status(404).send({Message:'user not found'}) if (!user) return res.status(404).send({Message:'user not found'})
const {id,title,description,project,executors,dateTimeDue,dateTimeStart,accomplish,priority} = req.body; const {id,title,description,project,dateTimeDue,dateTimeStart,accomplish,priority} = req.body;
await dataSource await dataSource
.createQueryBuilder() .createQueryBuilder()
.update(Task) .update(Task)
...@@ -105,7 +105,6 @@ router.put('/',async(req:Request, res:Response)=> { ...@@ -105,7 +105,6 @@ router.put('/',async(req:Request, res:Response)=> {
title: title, title: title,
description: description, description: description,
project: project, project: project,
executors: executors,
dateTimeDue: dateTimeDue, dateTimeDue: dateTimeDue,
dateTimeStart: dateTimeStart, dateTimeStart: dateTimeStart,
author:user, author:user,
......
import { Grid } from "@mui/material"; import { Grid, TextField, Typography } from "@mui/material";
import { useEffect, useState } from "react";
const CalendarStandartCell = ({children, xs, onClick}) => { const CalendarStandartCell = ({children, xs, currentTask, hours, dayNumber, createTaskInCellHandler, handleOpen, modal}) => {
const [isThisCell, setIsThisCell] = useState(false)
useEffect(()=>{
if(!modal) {
setIsThisCell(false);
}
}, [modal])
return <> return <>
<Grid <Grid
item xs={xs} item xs={xs}
sx={{borderRight: '1px solid black'}} sx={{borderRight: '1px solid black'}}
onClick={onClick}> onClick={(e)=>{createTaskInCellHandler(dayNumber, hours); setIsThisCell(true); handleOpen(e)}}>
{children} {children}
{isThisCell ?
<Grid
sx={{backgroundColor: 'lightgreen', padding: '10px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}
>
<span>
{currentTask.title}
</span>
</Grid> : null}
</Grid> </Grid>
</> </>
}; };
......
import { Grid, TextField } from "@mui/material"; import { Grid, TextField, Typography } from "@mui/material";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
const CalendarTask = ({year, month, tasks, day, hours, setCurrentTask, onChange, hourFormat}) => { const CalendarTask = ({year, month, tasks, day, hours, setCurrentTask, hourFormat, handleOpen, currentTask}) => {
const [thisCellCurrentTask, setThisCellCurrentTask] = useState({})
const getTaskInDayCell = (tasks, day, hours) => { const getTaskInDayCell = (tasks, day, hours) => {
const hour = parseInt(hours.split(':')[0]) const hour = parseInt(hours.split(':')[0])
let hourDiffEnd let hourDiffEnd
let hourDiffStart
if (hourFormat) { if (hourFormat) {
hourDiffEnd = hour + 1 hourDiffEnd = hour + 1
} else { } else {
hourDiffEnd = hour + 2 hourDiffEnd = hour + 2
} }
if (hourFormat) {
hourDiffStart = hour - 1
} else {
hourDiffStart = hour - 2
}
const tasksCell = tasks.filter(task=> { const tasksCell = tasks.filter(task=> {
if (year === task.infoForCell.startYear) { if (year === task.infoForCell.startYear) {
if (month + 1 === task.infoForCell.startMonth) { if (month + 1 === task.infoForCell.startMonth) {
...@@ -32,24 +26,36 @@ const CalendarTask = ({year, month, tasks, day, hours, setCurrentTask, onChange, ...@@ -32,24 +26,36 @@ const CalendarTask = ({year, month, tasks, day, hours, setCurrentTask, onChange,
}) })
return tasksCell return tasksCell
} }
const tasksCell = getTaskInDayCell(tasks, day, hours) const tasksCell = getTaskInDayCell(tasks, day, hours)
useEffect(()=>{
if (!currentTask.title) {
setThisCellCurrentTask({})
}
}, [currentTask])
const renderText = (i, task) => {
if (thisCellCurrentTask && i === thisCellCurrentTask.i) {
return (<>{currentTask.title}</>)
} else {
return (<>{task.title}</>)
}
}
return (<> return (<>
{tasksCell.length ? tasksCell.map((task, i)=> {tasksCell.length ? tasksCell.map((task, i)=>
{ {
return ( return (
<Grid key={task.id} sx={{backgroundColor: 'lightgreen'}}> <Grid
<TextField key={task.id}
id={task.title} sx={{backgroundColor: 'lightgreen', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', padding: '10px', borderBottom: '1px solid rgb(29, 161, 51);;'}}
variant="standard" onClick={(e)=>{e.stopPropagation(); setCurrentTask(task); handleOpen(e); setThisCellCurrentTask({...task, i: i})}}
value={task.title} >
name='title' {renderText(i, task)}
onClick={(e)=>{e.stopPropagation(); setCurrentTask(task)}} </Grid>
onChange={onChange}> )}
</TextField> )
</Grid>)} : null}
) : null }
</>) </>)
}; };
......
import { FormControlLabel, Switch } from "@mui/material"; import { FormControlLabel, Switch} from "@mui/material";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import CalendarRow from "./CalendarRow/CalendarRow"; import CalendarRow from "./CalendarRow/CalendarRow";
import CalendarSmallCell from "./CalendarSmallCell/CalendarSmallCell"; import CalendarSmallCell from "./CalendarSmallCell/CalendarSmallCell";
import CalendarStandartCell from "./CalendarStandartCell.js/CalendarStandartCell"; import CalendarStandartCell from "./CalendarStandartCell.js/CalendarStandartCell";
import CalendarTask from "./CalendarTask/CalendarTask"; import CalendarTask from "./CalendarTask/CalendarTask";
import ModalTask from "../UI/ModalTask/ModalTask";
import MonthCalendarModalContent from "../MonthCalendarModalContent/MonthCalendarModalContent";
function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, onChangeCellTaskTitle, setCurrentTask, hourFormat, setHourFormat}) { function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, currentTask, setCurrentTask, hourFormat, setHourFormat, onChangeCurrentTaskHandler, sendNewTaskHandler, deleteTaskHandler}) {
const [hoursInDay, setHoursInDay] = useState(['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00']) const [hoursInDay, setHoursInDay] = useState(['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'])
const [daysInMonth, setDaysInMonth] = useState([]) const [daysInMonth, setDaysInMonth] = useState([])
const [cellSizes, setCellSizes] = useState({}) const [cellSizes, setCellSizes] = useState({})
const [modal, setModal] = useState({open:false, y: 0, x: 0,});
const handleOpen = (e) => {
setModal( {
open: true,
yPage: e.pageY,
xPage: e.pageX,
yDivClick: e.nativeEvent.offsetY,
xDivClick: e.nativeEvent.offsetX,
yDiv: e.target.offsetHeight,
xDiv: e.target.offsetWidth,
})
};
const handleClose = () => {
setModal({...modal, open: false})
setCurrentTask({})
};
useEffect(()=>{ useEffect(()=>{
const cells = hoursInDay.length const cells = hoursInDay.length
const xs = 10.8/cells const xs = 10.8/cells
...@@ -94,17 +114,23 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, onChang ...@@ -94,17 +114,23 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, onChang
<CalendarStandartCell <CalendarStandartCell
key={i} key={i}
item xs={cellSizes.standarCell} item xs={cellSizes.standarCell}
onClick={()=>{createTaskInCellHandler(day.dayNumber, hours)}} createTaskInCellHandler={createTaskInCellHandler}
hours={hours}
dayNumber={day.dayNumber}
currentTask={currentTask}
handleOpen={handleOpen}
modal={modal.open}
> >
<CalendarTask <CalendarTask
setCurrentTask={setCurrentTask} setCurrentTask={setCurrentTask}
onChange={(e)=>{onChangeCellTaskTitle(e)}}
year={year} year={year}
month={month} month={month}
tasks={tasks} tasks={tasks}
day={day} day={day}
hours={hours} hours={hours}
hourFormat={hourFormat} hourFormat={hourFormat}
handleOpen={handleOpen}
currentTask={currentTask}
/> />
</CalendarStandartCell> </CalendarStandartCell>
) )
...@@ -112,6 +138,19 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, onChang ...@@ -112,6 +138,19 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, onChang
</CalendarRow> </CalendarRow>
) )
})} })}
<ModalTask
modal={modal}
handleClose={()=>{handleClose()}}
>
<MonthCalendarModalContent
title={currentTask.title}
description={currentTask.description}
priority={currentTask.priority}
onChangeCurrentTaskHandler={(e)=>{ onChangeCurrentTaskHandler(e)}}
sendNewTaskHandler={()=>{sendNewTaskHandler(); handleClose()}}
deleteTaskHandler={()=>{deleteTaskHandler(currentTask.id); handleClose()}}
/>
</ModalTask>
</> </>
); );
} }
......
import { Button, FormControl, InputLabel, MenuItem, Select, TextField } from "@mui/material";
function MonthCalendarModalContent({title, onChangeCurrentTaskHandler, description, priority, sendNewTaskHandler, deleteTaskHandler}) {
return (<>
<TextField
id="task-description-title"
value={title}
label="Название"
variant="outlined"
sx={{marginBottom: '30px'}}
name='title'
onChange={(e)=>{onChangeCurrentTaskHandler(e)}}
/>
<TextField
id="task-description"
multiline
rows={4}
value={description}
label="Описание"
variant="outlined"
sx={{marginBottom: '30px'}}
name='description'
onChange={(e)=>{onChangeCurrentTaskHandler(e)}}
/>
<FormControl variant="outlined" sx={{width: '160px', marginBottom: '30px'}}>
<InputLabel id="priority-type-label">Приоритет</InputLabel>
<Select
labelId="priority-type-label"
id="priority-type"
label="Приоритет"
sx={{width: '160px'}}
value={priority}
name='priority'
onChange={onChangeCurrentTaskHandler}
>
<MenuItem value={null}>
<em>-- Выберите Приоритет --</em>
</MenuItem>
<MenuItem value={"A"}>A</MenuItem>
<MenuItem value={"B"}>B</MenuItem>
<MenuItem value={"C"}>C</MenuItem>
</Select>
</FormControl>
<Button sx={{marginRight: '40px'}} onClick={sendNewTaskHandler}>Сохранить</Button>
<Button onClick={deleteTaskHandler}>Удалить</Button>
</>);
}
export default MonthCalendarModalContent;
\ No newline at end of file
import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';
export default function ModalTask({modal, handleClose, children}) {
const style = {
position: 'absolute',
top: modal.yPage - modal.yDiv - modal.yDivClick,
left: modal.xPage + modal.xDiv - modal.xDivClick + 10,
width: 250,
height: 350,
bgcolor: 'background.paper',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
return (
<>
<Modal
open={modal.open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
BackdropProps={{ style: { backgroundColor: 'rgba(255,255,255, 0)' } }}
>
<Box sx={style}>
{children}
</Box>
</Modal>
</>
);
}
\ No newline at end of file
import { Container } from '@mui/material';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import MonthCalendarBody from '../../components/MonthCalendarBody/MonthCalendarBody'; import MonthCalendarBody from '../../components/MonthCalendarBody/MonthCalendarBody';
import MonthCalendarHeader from '../../components/MonthCalendarHeader/MonthCalendarHeader'; import MonthCalendarHeader from '../../components/MonthCalendarHeader/MonthCalendarHeader';
import { addTask, fetchTasks} from '../../store/actions/tasksActions'; import { addTask, deleteTask, editTask, fetchCalendarTasks} from '../../store/actions/tasksActions';
function MonthCalendar() { function MonthCalendar() {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { tasks } = useSelector(state => state.tasks); const { calendarTasks } = useSelector(state => state.tasks);
const [hourFormat, setHourFormat] = useState(false); const [hourFormat, setHourFormat] = useState(false);
const [month, setMonth] = useState('') const [month, setMonth] = useState('')
const [year, setYear] = useState('') const [year, setYear] = useState('')
const [worker, setWorker] = useState(''); const [worker, setWorker] = useState('');
const [calendarType, setCalendarType] = useState('Месяц'); const [calendarType, setCalendarType] = useState('Месяц');
const [currentTask, setCurrentTask] = useState({}) const [currentTask, setCurrentTask] = useState({title: '', description: '', priority: null, dateTimeStart: '', dateTimeDue:''})
useEffect(()=>{ useEffect(()=>{
setMonth(new Date().getMonth()) setMonth(new Date().getMonth())
setYear(new Date().getFullYear()) setYear(new Date().getFullYear())
dispatch(fetchTasks()) dispatch(fetchCalendarTasks())
}, [dispatch]) }, [dispatch])
const onChangeWorkerHandler = (event) => { const onChangeWorkerHandler = (event) => {
...@@ -62,6 +60,16 @@ function MonthCalendar() { ...@@ -62,6 +60,16 @@ function MonthCalendar() {
return iso; return iso;
} }
const onChangeCurrentTaskHandler = (e) => {
const {name, value} = e.target;
setCurrentTask((prevState) => {
return {
...prevState,
[name]: value
}
});
};
const createTaskInCellHandler = (dayNumber, dayHour) => { const createTaskInCellHandler = (dayNumber, dayHour) => {
const hour = parseInt(dayHour.split(':')[0]) const hour = parseInt(dayHour.split(':')[0])
let hourDue let hourDue
...@@ -73,24 +81,40 @@ function MonthCalendar() { ...@@ -73,24 +81,40 @@ function MonthCalendar() {
const newTask = { const newTask = {
title:"Задача", title:"Задача",
description:"описание", description:"описание",
priority: null,
dateTimeStart: dateToISOLikeButLocal(new Date(year, month, dayNumber, hour, 0)), dateTimeStart: dateToISOLikeButLocal(new Date(year, month, dayNumber, hour, 0)),
dateTimeDue: dateToISOLikeButLocal(new Date(year, month, dayNumber, hourDue, 59)), dateTimeDue: dateToISOLikeButLocal(new Date(year, month, dayNumber, hourDue, 59)),
} }
console.log(newTask)
dispatch(addTask(newTask))
setCurrentTask((newTask)) setCurrentTask((newTask))
} }
const onChangeCellTaskTitle = (e) => { const sendNewTaskHandler = async () => {
e.stopPropagation()
const value = e.target.value; if (currentTask.id) {
const name = e.target.name; setCurrentTask(() => {
setCurrentTask({ ...currentTask, [name]: value }) return{
...currentTask,
}}
)
delete currentTask.infoForCell
await dispatch(editTask(currentTask))
} else {
setCurrentTask(() => {
return{
...currentTask,
}}
)
delete currentTask.infoForCell
await dispatch(addTask(currentTask))
}
}
const deleteTaskHandler = async (taskId) => {
dispatch(deleteTask(taskId))
} }
return ( return (
<> <>
<Container>
<MonthCalendarHeader <MonthCalendarHeader
month={month} month={month}
year={year} year={year}
...@@ -105,14 +129,16 @@ function MonthCalendar() { ...@@ -105,14 +129,16 @@ function MonthCalendar() {
<MonthCalendarBody <MonthCalendarBody
month={month} month={month}
year={year} year={year}
tasks={tasks} tasks={calendarTasks}
createTaskInCellHandler={createTaskInCellHandler} createTaskInCellHandler={createTaskInCellHandler}
onChangeCellTaskTitle={onChangeCellTaskTitle}
setCurrentTask={setCurrentTask} setCurrentTask={setCurrentTask}
hourFormat={hourFormat} hourFormat={hourFormat}
setHourFormat={setHourFormat} setHourFormat={setHourFormat}
currentTask={currentTask}
onChangeCurrentTaskHandler={onChangeCurrentTaskHandler}
sendNewTaskHandler={sendNewTaskHandler}
deleteTaskHandler={deleteTaskHandler}
/> />
</Container>
</> </>
); );
} }
......
...@@ -10,8 +10,7 @@ import { ...@@ -10,8 +10,7 @@ import {
Paper, Paper,
IconButton, IconButton,
Tooltip, Tooltip,
} from "@mui/material";
} from "@mui/material";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import {useDispatch, useSelector} from "react-redux"; import {useDispatch, useSelector} from "react-redux";
import { Done, Edit } from "@mui/icons-material"; import { Done, Edit } from "@mui/icons-material";
...@@ -25,6 +24,7 @@ import MaterialUIPickers from "../../components/MyTasksCompoments/DateTimePicker ...@@ -25,6 +24,7 @@ import MaterialUIPickers from "../../components/MyTasksCompoments/DateTimePicker
import MaterialUIPickersDue from "../../components/MyTasksCompoments/DateTimePicker/DateTimePickerDue"; import MaterialUIPickersDue from "../../components/MyTasksCompoments/DateTimePicker/DateTimePickerDue";
import BasicSelect from "../../components/UI/Select/Select"; import BasicSelect from "../../components/UI/Select/Select";
import { fetchAllTasks} from "../../store/actions/tasksActions"; import { fetchAllTasks} from "../../store/actions/tasksActions";
import { deleteTask } from "../../store/actions/tasksActions";
function descendingComparator(a, b, orderBy) { function descendingComparator(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) { if (b[orderBy] < a[orderBy]) {
...@@ -77,6 +77,7 @@ export default function EnhancedTable() { ...@@ -77,6 +77,7 @@ export default function EnhancedTable() {
}, []); }, []);
const tasks = useSelector(state => state.tasks.tasks); const tasks = useSelector(state => state.tasks.tasks);
console.log(tasks) console.log(tasks)
// const [tasks,setTasks]=useState([ // const [tasks,setTasks]=useState([
// { // {
// user:"first", // user:"first",
...@@ -157,6 +158,7 @@ console.log(tasks) ...@@ -157,6 +158,7 @@ console.log(tasks)
if (task.id === id) { if (task.id === id) {
return { ...task, isEditMode: !task.isEditMode }; return { ...task, isEditMode: !task.isEditMode };
} }
return task; return task;
}); });
...@@ -195,11 +197,8 @@ console.log(tasks) ...@@ -195,11 +197,8 @@ console.log(tasks)
setOrderBy(property); setOrderBy(property);
}; };
const deleteTask=(id)=>{ const deleteHandle=(id)=>{
console.log(id) dispatch(deleteTask(id))
let newTasks=[...tasks]
newTasks.splice(tasks[id],1)
tasks=newTasks
}; };
const handleChangePage = (event, newPage) => { const handleChangePage = (event, newPage) => {
...@@ -242,7 +241,8 @@ console.log(tasks) ...@@ -242,7 +241,8 @@ console.log(tasks)
tasks=newTasks; tasks=newTasks;
}; };
return ( if (tasks)
{return (
<Box sx={{ width: 'fullwidth' }}> <Box sx={{ width: 'fullwidth' }}>
<Paper sx={{ width: '100%', mb: 2 }}> <Paper sx={{ width: '100%', mb: 2 }}>
...@@ -332,7 +332,7 @@ console.log(tasks) ...@@ -332,7 +332,7 @@ console.log(tasks)
</TableCell> </TableCell>
<TableCell> <TableCell>
<Tooltip title="Delete"> <Tooltip title="Delete">
<IconButton onClick={(id)=>{deleteTask(id)}}> <IconButton onClick={(id)=>{deleteHandle(task.id)}}>
<DeleteIcon /> <DeleteIcon />
</IconButton> </IconButton>
</Tooltip> </Tooltip>
...@@ -365,5 +365,5 @@ console.log(tasks) ...@@ -365,5 +365,5 @@ console.log(tasks)
// setTasks={setTasks} // setTasks={setTasks}
/> />
</Box> </Box>
); )};
} }
...@@ -56,7 +56,7 @@ const Register = () => { ...@@ -56,7 +56,7 @@ const Register = () => {
} }
}); });
}; };
console.log(state)
const submitHandler = async (e) => { const submitHandler = async (e) => {
e.preventDefault(); e.preventDefault();
const formData = new FormData(); const formData = new FormData();
......
export const FETCH_TASKS_REQUEST = "FETCH_TASKS_REQUEST"; export const FETCH_CALENDAR_TASKS_REQUEST = "FETCH_CALENDAR_TASKS_REQUEST";
export const FETCH_TASKS_SUCCESS = "FETCH_TASKS_SUCCESS"; export const FETCH_CALENDAR_TASKS_SUCCESS = "FETCH_CALENDAR_TASKS_SUCCESS";
export const FETCH_CALENDAR_TASKS_FAILURE = "FETCH_CALENDAR_TASKS_FAILURE";
export const FETCH_ALL_TASKS_SUCCESS = "FETCH_ALL_TASKS_SUCCESS"; export const FETCH_ALL_TASKS_SUCCESS = "FETCH_ALL_TASKS_SUCCESS";
export const FETCH_TASKS_FAILURE = "FETCH_TASKS_FAILURE";
export const ADD_NEW_TASK_REQUEST = "ADD_NEW_TASK_REQUEST"; export const ADD_NEW_TASK_REQUEST = "ADD_NEW_TASK_REQUEST";
export const ADD_NEW_TASK_SUCCESS = "ADD_NEW_TASK_SUCCESS"; export const ADD_NEW_TASK_SUCCESS = "ADD_NEW_TASK_SUCCESS";
export const ADD_NEW_TASK_FAILURE = "ADD_NEW_TASK_FAILURE"; export const ADD_NEW_TASK_FAILURE = "ADD_NEW_TASK_FAILURE";
export const EDIT_TASK_REQUEST = "EDIT_TASK_REQUEST";
export const EDIT_TASK_SUCCESS = "EDIT_TASK_SUCCESS";
export const EDIT_TASK_FAILURE = "EDIT_TASK_FAILURE";
export const DELETE_TASK_REQUEST = "DELETE_TASK_REQUEST";
export const DELETE_TASK_SUCCESS = "DELETE_TASK_SUCCESS";
export const DELETE_TASK_FAILURE = "DELETE_TASK_FAILURE";
\ No newline at end of file
import { ADD_NEW_TASK_FAILURE, ADD_NEW_TASK_REQUEST, ADD_NEW_TASK_SUCCESS, FETCH_TASKS_FAILURE, FETCH_TASKS_REQUEST, FETCH_TASKS_SUCCESS, FETCH_ALL_TASKS_SUCCESS} from "../actionTypes/tasksTypes"; import {
ADD_NEW_TASK_FAILURE,
ADD_NEW_TASK_REQUEST,
ADD_NEW_TASK_SUCCESS,
DELETE_TASK_FAILURE,
DELETE_TASK_REQUEST,
DELETE_TASK_SUCCESS,
EDIT_TASK_FAILURE,
EDIT_TASK_REQUEST,
EDIT_TASK_SUCCESS,
FETCH_CALENDAR_TASKS_FAILURE,
FETCH_CALENDAR_TASKS_REQUEST,
FETCH_CALENDAR_TASKS_SUCCESS,
FETCH_ALL_TASKS_SUCCESS} from "../actionTypes/tasksTypes";
import axios from '../../axiosPlanner' import axios from '../../axiosPlanner'
const fetchTasksRequest = () => { const fetchCalendarTasksRequest = () => {
return {type: FETCH_TASKS_REQUEST} return {type: FETCH_CALENDAR_TASKS_REQUEST}
}; };
const fetchTasksSuccess = (tasks) => { const fetchCalendarTasksSuccess = (tasks) => {
return {type: FETCH_TASKS_SUCCESS, tasks} return {type: FETCH_CALENDAR_TASKS_SUCCESS, tasks}
}; };
const fetchAllTasksSuccess = (tasks) => { const fetchAllTasksSuccess = (tasks) => {
return {type: FETCH_ALL_TASKS_SUCCESS, tasks} return {type: FETCH_ALL_TASKS_SUCCESS, tasks}
}; };
const fetchTasksFailure = (error) => {
return {type: FETCH_TASKS_FAILURE, error} const fetchCalendarTasksFailure = (error) => {
return {type: FETCH_CALENDAR_TASKS_FAILURE, error}
}; };
export const fetchTasks = () => { export const fetchCalendarTasks = () => {
return async (dispatch) => { return async (dispatch) => {
dispatch(fetchTasksRequest()); dispatch(fetchCalendarTasksRequest());
try { try {
const response = await axios.get("/tasks"); const response = await axios.get("/tasks");
dispatch(fetchCalendarTasksSuccess(response.data.tasks))
dispatch(fetchTasksSuccess(response.data.tasks))
} catch (error) { } catch (error) {
dispatch(fetchTasksFailure(error.response.data)); dispatch(fetchCalendarTasksFailure(error.response.data));
} }
} }
}; };
export const fetchAllTasks = () => { export const fetchAllTasks = () => {
return async (dispatch) => { return async (dispatch) => {
dispatch(fetchTasksRequest()); dispatch(fetchCalendarTasksRequest());
try { try {
const response = await axios.get("/tasks"); const response = await axios.get("/tasks");
console.log(response)
dispatch(fetchAllTasksSuccess(response.data.tasks)) dispatch(fetchAllTasksSuccess(response.data.tasks))
} catch (error) { } catch (error) {
dispatch(fetchTasksFailure(error.response.data)); dispatch(fetchCalendarTasksFailure(error.response.data));
} }
} }
}; };
...@@ -60,13 +73,74 @@ export const addTask = (task) => { ...@@ -60,13 +73,74 @@ export const addTask = (task) => {
try { try {
await axios.post("/tasks", task, { await axios.post("/tasks", task, {
headers: { headers: {
'Authorization': 'yjBjcPCQwytwrYo9rRuiK' 'Authorization': 'IwGVRaksGTWtnKlOZd7zJ'
} }
}); });
dispatch(addTaskSuccess()) dispatch(addTaskSuccess())
dispatch(fetchTasks()) dispatch(fetchCalendarTasks())
} catch (error) { } catch (error) {
dispatch(addTaskFailure(error.response.data)); dispatch(addTaskFailure(error.response.data));
} }
} }
} }
const editTaskRequest = () => {
return {type: EDIT_TASK_REQUEST}
};
const editTaskSuccess = () => {
return {type: EDIT_TASK_SUCCESS}
};
const editTaskFailure = (error) => {
return {type: EDIT_TASK_FAILURE, error}
};
export const editTask = (task) => {
return async (dispatch, getState) => {
dispatch(editTaskRequest());
const token = getState().users?.user?.token;
try {
await axios.put("/tasks", task, {
headers: {
'Authorization': 'IwGVRaksGTWtnKlOZd7zJ'
}
});
dispatch(editTaskSuccess())
dispatch(fetchCalendarTasks())
} catch (error) {
dispatch(editTaskFailure(error.response.data));
}
}
}
const deleteTaskRequest = () => {
return {type: DELETE_TASK_REQUEST}
};
const deleteTaskSuccess = () => {
return {type: DELETE_TASK_SUCCESS}
};
const deleteTaskFailure = (error) => {
return {type: DELETE_TASK_FAILURE, error}
};
export const deleteTask = (taskId) => {
return async (dispatch, getState) => {
dispatch(deleteTaskRequest());
const token = getState().users?.user?.token;
try {
await axios.delete(`/tasks/${taskId}`, {
headers: {
'Authorization': 'IwGVRaksGTWtnKlOZd7zJ'
}
});
dispatch(deleteTaskSuccess())
dispatch(fetchCalendarTasks())
dispatch(fetchAllTasks())
} catch (error) {
dispatch(deleteTaskFailure(error.response.data));
}
}
}
\ No newline at end of file
import { FETCH_TASKS_FAILURE, FETCH_TASKS_REQUEST, FETCH_TASKS_SUCCESS,FETCH_ALL_TASKS_SUCCESS} from "../actionTypes/tasksTypes"; import {
ADD_NEW_TASK_FAILURE,
ADD_NEW_TASK_REQUEST,
ADD_NEW_TASK_SUCCESS,
EDIT_TASK_FAILURE,
EDIT_TASK_REQUEST,
EDIT_TASK_SUCCESS,
FETCH_CALENDAR_TASKS_FAILURE,
FETCH_CALENDAR_TASKS_REQUEST,
FETCH_CALENDAR_TASKS_SUCCESS,
DELETE_TASK_SUCCESS,
DELETE_TASK_REQUEST,
DELETE_TASK_FAILURE,
FETCH_ALL_TASKS_SUCCESS} from "../actionTypes/tasksTypes";
const initialState = { const initialState = {
tasks: [], calendarTasks: [],
loading: false, loading: false,
error: null error: null,
}; };
const tasksReduсer = (state = initialState, action) => { const tasksReduсer = (state = initialState, action) => {
switch(action.type) { switch(action.type) {
case FETCH_TASKS_REQUEST: case FETCH_CALENDAR_TASKS_REQUEST:
return {...state, loading: true}; return {...state, loading: true};
case FETCH_TASKS_SUCCESS: case FETCH_CALENDAR_TASKS_SUCCESS:
const newArr = [] const newArr = []
action.tasks.forEach((task)=>{ action.tasks.forEach((task)=>{
if (task.dateTimeStart && task.dateTimeDue) { if (task.dateTimeStart && task.dateTimeDue) {
if (new Date(task.dateTimeDue).getTime() - new Date(task.dateTimeStart).getTime() < (4 * 3600000)) { if (new Date(task.dateTimeDue).getTime() - new Date(task.dateTimeStart).getTime() < (10 * 3600000)) {
const dateStart = task.dateTimeStart.split('T')[0] const dateStart = task.dateTimeStart.split('T')[0]
const timeStart = task.dateTimeStart.split('T')[1] const timeStart = task.dateTimeStart.split('T')[1]
const timeEnd = task.dateTimeDue.split('T')[1] const timeEnd = task.dateTimeDue.split('T')[1]
...@@ -38,11 +51,28 @@ const tasksReduсer = (state = initialState, action) => { ...@@ -38,11 +51,28 @@ const tasksReduсer = (state = initialState, action) => {
} }
} }
}) })
return {...state, loading: false, tasks: newArr}; return {...state, loading: false, calendarTasks: newArr};
case FETCH_ALL_TASKS_SUCCESS: case FETCH_ALL_TASKS_SUCCESS:
return {...state, loading: false, tasks: action.tasks}; return {...state, loading: false, tasks: action.tasks};
case FETCH_CALENDAR_TASKS_FAILURE:
case FETCH_TASKS_FAILURE: return {...state, loading: false, error: action.error};
case ADD_NEW_TASK_SUCCESS:
return {...state, loading: false};
case ADD_NEW_TASK_REQUEST:
return {...state, loading: true};
case ADD_NEW_TASK_FAILURE:
return {...state, loading: false, error: action.error};
case EDIT_TASK_SUCCESS:
return {...state, loading: false};
case EDIT_TASK_REQUEST:
return {...state, loading: true};
case EDIT_TASK_FAILURE:
return {...state, loading: false, error: action.error};
case DELETE_TASK_SUCCESS:
return {...state, loading: false};
case DELETE_TASK_REQUEST:
return {...state, loading: true};
case DELETE_TASK_FAILURE:
return {...state, loading: false, error: action.error}; return {...state, loading: false, error: action.error};
default: default:
return state; return state;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment