Commit fb898090 authored by Ermolaev Timur's avatar Ermolaev Timur

Merge branch 'task-61-enhance/refactoring_code' into 'development'

Task 61 enhance/refactoring code

See merge request !43
parents 61f20b6e ef008f9f
......@@ -10,6 +10,7 @@ function randomIntFromInterval(min:number, max:number) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
const loadFixtures = async () => {
myDataSource
.initialize()
......
......@@ -3,6 +3,7 @@ import { memo, useEffect, useMemo, useState } from "react";
import CalendarStandartCell from "../CalendarStandartCell.js/CalendarStandartCell";
import CalendarTask from "../CalendarTask/CalendarTask";
import EmptyBox from "./EmptyBox/EmptyBox";
import { getAvailableTasks, getBoxesInLine, getLinesInDay, getSortedTasks } from "./Helpers";
const CalendarRowDay = ({xs, hoursInDay, createTaskInCellHandler, currentTask, handleOpen, modal, setCurrentTask, year, month, tasks, day, hourFormat, setCurrentLine, currentLine, dragTaskHandler, increaseTaskHandler, reduceTaskHandler, createCopyTask, setCopyTask, copyTask}) => {
......@@ -11,124 +12,16 @@ const CalendarRowDay = ({xs, hoursInDay, createTaskInCellHandler, currentTask, h
[hoursInDay])
const availableTasks = useMemo(() => {
const tasksInDay = tasks.filter((task)=> {
if (year === task.infoForCell.startYear) {
if (month + 1 === task.infoForCell.startMonth) {
if (day.dayNumber === task.infoForCell.startDay) {
return task
} else {return false}
} else {return false}
} else {return false}
})
return tasksInDay
return getAvailableTasks(tasks, year, month, day.dayNumber)
}, [tasks, month, year, day.dayNumber])
const sortedTasks = useMemo(() => {
if (availableTasks.length) {
const newSortedArr = [...availableTasks].sort(function(a,b){
const durattionFirstDate = a.infoForCell.endHour - a.infoForCell.startHour
const durattionSecondDate = b.infoForCell.endHour - b.infoForCell.startHour
return durattionSecondDate - durattionFirstDate;
})
return newSortedArr
}
return getSortedTasks(availableTasks)
}, [availableTasks])
const linesInDay = useMemo(() => {
let hourDiff
let hourDiffEnd
const lines = []
if (hourFormat) {
hourDiff = 1
hourDiffEnd = 0
} else {
hourDiff = 2
hourDiffEnd = 1
}
if (availableTasks.length) {
lines.push(hoursInDay.map((hour)=>parseInt(hour.split(':')[0])))
for (let k = 0; k < sortedTasks.length; k++) {
let skipLine = false
for (let j = 0; j < lines.length; j++) {
const line = lines[j]
const task = sortedTasks[k]
if (skipLine) {
skipLine = false
break;
}
for (let i = 0; i < line.length; i++) {
const hour = hours[i]
let havePlace = true
if (((task.infoForCell.endHour <= hour || task.infoForCell.startHour <= hour) && (task.infoForCell.endHour > hour))
|| (!hourFormat && task.infoForCell.startHour >= hour && task.infoForCell.endHour < hour + hourDiff)
|| (!hourFormat && task.infoForCell.startHour === hour + hourDiffEnd && task.infoForCell.endHour > hour)
|| (task.infoForCell.endMinute <= 59 && task.infoForCell.endHour === hour)) {
if (!isNaN(line[i])) {
for (let a = 0; a < hours.length; a++) {
const hour = hours[a]
if ((task.infoForCell.endMinute === 59 && task.infoForCell.endHour === hour + hourDiffEnd) || (!hourFormat && task.infoForCell.endMinute === 59 && task.infoForCell.endHour === hour)) {
if (isNaN(line[a])) {
havePlace = false
break;
}
}
}
if (!havePlace) {
if (j + 1 === lines.length) {
lines.push(hoursInDay.map((hour)=>parseInt(hour.split(':')[0])))
}
havePlace = true
break;
}
line[i] += `-${k}`
if ((task.infoForCell.endMinute === 59 && task.infoForCell.endHour === hour + hourDiffEnd)
|| (!hourFormat && task.infoForCell.endMinute === 59 && task.infoForCell.endHour === hour)) {
skipLine = true
break;
}
} else {
if (j + 1 === lines.length) {
lines.push(hoursInDay.map((hour)=>parseInt(hour.split(':')[0])))
}
break;
}
}
}
}
}
}
return lines
}, [availableTasks.length, hourFormat, hours, hoursInDay, sortedTasks])
const getBoxesInLine = (line) => {
if (line) {
let xs = 12/hoursInDay.length
const boxes = []
for (let i = 0; i < line.length; i++) {
if (!isNaN(line[i])) {
// if (boxes[boxes.length -1]?.task === null) {
// boxes[boxes.length -1].xs += xs
// } else {
boxes.push({xs: xs, task: null, hour: line[i]})
// }
} else {
const task = sortedTasks[line[i].split('-')[1]]
const taskIsThere = boxes.find((taskFind)=>{
if (taskFind?.task?.id === task.id) return taskFind
})
if (taskIsThere) {
taskIsThere.xs +=xs
} else {
boxes.push({
xs: xs,
task: sortedTasks[line[i].split('-')[1]]})
}
}
}
return boxes
}
}
return getLinesInDay(availableTasks, sortedTasks, hoursInDay, hours, hourFormat)
}, [availableTasks, hourFormat, hours, hoursInDay, sortedTasks])
return <>
<Grid
......@@ -136,9 +29,28 @@ const CalendarRowDay = ({xs, hoursInDay, createTaskInCellHandler, currentTask, h
item
xs={10.8}
align='center'
sx={{position: 'relative'}}
>
{hoursInDay.map((hour, i)=>{
return (
<CalendarStandartCell
linesInDay={linesInDay}
key={i}
item xs={xs}
createTaskInCellHandler={createTaskInCellHandler}
hours={hour}
dragTaskHandler={dragTaskHandler}
dayNumber={day.dayNumber}
currentTask={currentTask}
handleOpen={handleOpen}
modal={modal}
>
</CalendarStandartCell>
)
})}
<Grid sx={{position: 'absolute', top: '0'}} container item xs={12}>
{linesInDay?.map((line, i)=>{
const boxes = getBoxesInLine(line)
const boxes = getBoxesInLine(line, hoursInDay, sortedTasks)
return(
<Grid key={i} container sx={{height: '35px', backgroundColor: 'rgb(0,0,0,0)', marginBottom: '5px'}}>
{boxes.map((box, index)=>{
......@@ -182,8 +94,9 @@ const CalendarRowDay = ({xs, hoursInDay, createTaskInCellHandler, currentTask, h
})}
</Grid>)
})}
</Grid>
<Grid container sx={{height: '35px', backgroundColor: 'rgb(0,0,0,0)', marginBottom: '5px'}}>
<Grid container sx={{height: '35px', backgroundColor: 'rgb(0,0,0,0)', marginBottom: '5px', position: 'absolute', bottom: '0'}}>
{hoursInDay.map((hour, i)=>{
const hourNumber = parseInt(hour)
return(<EmptyBox
......@@ -205,5 +118,8 @@ const CalendarRowDay = ({xs, hoursInDay, createTaskInCellHandler, currentTask, h
</>
};
export default memo(CalendarRowDay);
export default memo(CalendarRowDay, (prevProps, nextProps)=>{
if(!prevProps.modal) return false
if(nextProps.modal) return true
});
......@@ -34,7 +34,11 @@ const EmptyBox = ({hourNumber, handleOpen, dayNumber, xs, dragTaskHandler, modal
onDragOver={(e)=>{dragOverHandler(e)}}
onDrop={(e)=>{dropHandler(e)}}
onClick={(e)=>{onClickHandler(e, dayNumber, hourNumber)}}
item xs={xs} sx={{height: '35px', backgroundColor: 'rgb(0,0,0,0)'}}>
item xs={xs} sx={{
height: '35px',
backgroundColor: 'rgb(0,0,0,0)',
zIndex: '6',
}}>
{isThisCell ?
<DefaultTask/> : null}
</Grid>)
......
const taskIsAvailableInCell = (task, hour, hourDiffEnd, hourDiff, hourFormat) => {
if (((task.infoForCell.endHour <= hour || task.infoForCell.startHour <= hour) && (task.infoForCell.endHour > hour))
|| (!hourFormat && task.infoForCell.startHour >= hour && task.infoForCell.endHour < hour + hourDiff)
|| (!hourFormat && task.infoForCell.startHour === hour + hourDiffEnd && task.infoForCell.endHour > hour)
|| (task.infoForCell.endMinute <= 59 && task.infoForCell.endHour === hour)) {
return true
} else {
return false
}
}
const lastPlaceInLineForTask = (task, hour, hourDiffEnd, hourFormat) => {
if ((task.infoForCell.endMinute === 59 && task.infoForCell.endHour === hour + hourDiffEnd) || (!hourFormat && task.infoForCell.endMinute === 59 && task.infoForCell.endHour === hour)) {
return true
} else {
return false
}
}
export const getLinesInDay = (availableTasks, sortedTasks, hoursInDay, hours, hourFormat) => {
let hourDiff
let hourDiffEnd
const lines = []
if (hourFormat) {
hourDiff = 1
hourDiffEnd = 0
} else {
hourDiff = 2
hourDiffEnd = 1
}
if (availableTasks.length) {
lines.push(hoursInDay.map((hour)=>parseInt(hour.split(':')[0])))
for (let k = 0; k < sortedTasks.length; k++) {
let skipLine = false
for (let j = 0; j < lines.length; j++) {
const line = lines[j]
const task = sortedTasks[k]
if (skipLine) {
skipLine = false
break;
}
for (let i = 0; i < line.length; i++) {
const hour = hours[i]
let havePlace = true
if (taskIsAvailableInCell(task, hour, hourDiffEnd, hourDiff, hourFormat)) {
if (!isNaN(line[i])) {
for (let a = 0; a < hours.length; a++) {
const hour = hours[a]
if (lastPlaceInLineForTask(task, hour, hourDiffEnd, hourFormat)) {
if (isNaN(line[a])) {
havePlace = false
break;
}
}
}
if (!havePlace) {
if (j + 1 === lines.length) {
lines.push(hoursInDay.map((hour)=>parseInt(hour.split(':')[0])))
}
havePlace = true
break;
}
line[i] += `-${k}`
if (lastPlaceInLineForTask(task, hour, hourDiffEnd, hourFormat)) {
skipLine = true
break;
}
} else {
if (j + 1 === lines.length) {
lines.push(hoursInDay.map((hour)=>parseInt(hour.split(':')[0])))
}
break;
}
}
}
}
}
}
return lines
}
export const getSortedTasks = (availableTasks) => {
if (availableTasks.length) {
const newSortedArr = [...availableTasks].sort(function(a,b){
const durattionFirstDate = a.infoForCell.endHour - a.infoForCell.startHour
const durattionSecondDate = b.infoForCell.endHour - b.infoForCell.startHour
return durattionSecondDate - durattionFirstDate;
})
return newSortedArr
}
}
export const getAvailableTasks = (tasks, year, month, dayNumber) => {
const tasksInDay = tasks.filter((task)=> {
if (year === task.infoForCell.startYear) {
if (month + 1 === task.infoForCell.startMonth) {
if (dayNumber === task.infoForCell.startDay) {
return task
} else {return false}
} else {return false}
} else {return false}
})
return tasksInDay
}
export const getBoxesInLine = (line, hoursInDay, sortedTasks) => {
if (line) {
let xs = 12/hoursInDay.length
const boxes = []
for (let i = 0; i < line.length; i++) {
if (!isNaN(line[i])) {
// if (boxes[boxes.length -1]?.task === null) {
// boxes[boxes.length -1].xs += xs
// } else {
boxes.push({xs: xs, task: null, hour: line[i]})
// }
} else {
const task = sortedTasks[line[i].split('-')[1]]
const taskIsThere = boxes.find((taskFind)=>{
if (taskFind?.task?.id === task.id) return taskFind
return false
})
if (taskIsThere) {
taskIsThere.xs +=xs
} else {
boxes.push({
xs: xs,
task: sortedTasks[line[i].split('-')[1]]})
}
}
}
return boxes
}
}
\ No newline at end of file
......@@ -3,15 +3,14 @@ import { memo, useEffect, useState } from "react";
import DefaultTask from "../DefaultTask/DefaultTask";
const CalendarStandartCell = ({children, xs, hours, dayNumber, createTaskInCellHandler, handleOpen, modal, dragTaskHandler, linesInDay}) => {
const [isThisCell, setIsThisCell] = useState(false)
const cellClass = {
transition: '0.3s',
position: 'relative',
height: '35px',
height: linesInDay?.length ? `${40*linesInDay.length+35}px` : `${35+35}px`,
borderRight: '1px solid black',
}
const CalendarStandartCell = ({children, xs, hours, dayNumber, createTaskInCellHandler, handleOpen, modal, divRef, dragTaskHandler, linesInDay}) => {
const [isThisCell, setIsThisCell] = useState(false)
useEffect(()=>{
if(!modal) {
setIsThisCell(false);
......@@ -27,21 +26,26 @@ const CalendarStandartCell = ({children, xs, hours, dayNumber, createTaskInCell
e.preventDefault();
dragTaskHandler(dayNumber, parseInt(hours.split(':')[0]))
}
const onClickHandler = (e) => {
if (!linesInDay?.length) {
createTaskInCellHandler(dayNumber, hours);
setIsThisCell(true);
handleOpen(e)
}
}
return <>
<Grid
item xs={xs}
sx={cellClass}
onClick={(e)=>{createTaskInCellHandler(dayNumber, hours); setIsThisCell(true); handleOpen(e)}}
onClick={(e)=>{onClickHandler(e)}}
onDragOver={(e)=>{dragOverHandler(e)}}
onDrop={(e)=>{dropHandler(e)}}
>
{children}
{isThisCell ?
<DefaultTask/> : null}
<div style={{position: 'absolute', height: children ? divRef : 0, width: '1px', backgroundColor: 'black', right: '0', top: '0', zIndex: '3'}}>
</div>
</Grid>
</>
};
......
.resizeable {
border: 2px solid #533535;
border-radius: 3px;
display: flex;
justify-content: center;
align-items: center;
min-width: 15px;
min-height: 15px;
}
.resizer {
position: absolute;
background: black;
}
.resizer-r {
cursor: col-resize;
height: 100%;
right: 0;
top: 0;
width: 5px;
}
.resizer-l {
cursor: col-resize;
height: 100%;
left: 0;
top: 0;
width: 5px;
}
\ No newline at end of file
import { Box } from "@mui/material";
import { memo } from "react";
const DefaultTask = ({}) => {
const DefaultTaskStyles = {
position: 'relative',
height: '30px',
backgroundColor: 'lightgreen',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
borderRadius: '10px',
margin: '5px 10px',
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
paddingLeft: '5px',
zIndex: '5'
}
const DefaultTask = ({}) => {
return (<>
<Box
sx={{ position: 'relative', height: '30px', backgroundColor: 'lightgreen', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', borderRadius: '10px', margin: '5px 10px', display: 'flex', justifyContent: 'flex-start', alignItems: 'center', paddingLeft: '5px', zIndex: '5'}}
sx={DefaultTaskStyles}
>
<span>
Задача
......
import { FormControlLabel, Switch} from "@mui/material";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Box, FormControlLabel, Switch} from "@mui/material";
import { useState } from "react";
import CalendarRow from "./CalendarRow/CalendarRow";
import CalendarSmallCell from "./CalendarSmallCell/CalendarSmallCell";
import CalendarStandartCell from "./CalendarStandartCell.js/CalendarStandartCell";
......@@ -29,20 +29,8 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, current
setCurrentTask({})
};
const divRef = useRef(null)
const [divHeight, setDivHeight] = useState('')
useEffect(() => {
if (divRef) {
setDivHeight(()=>{
return divRef.current?.offsetHeight
})
}
}, [divRef.current?.offsetHeight, hourFormat, month, tasks]);
return (
<div ref={divRef} style={{marginBottom: '30px'}}>
<Box style={{marginBottom: '30px'}}>
<CalendarRow
>
<CalendarSmallCell xs={1.2}>
......@@ -54,7 +42,7 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, current
</CalendarSmallCell>
{hoursInDay?.map((hours, i)=>{
return (
<CalendarStandartCell key={i} xs={cellSizes.standarCell} divRef={divHeight}>
<CalendarStandartCell key={i} xs={cellSizes.standarCell}>
{hours}
</CalendarStandartCell>
)
......@@ -106,7 +94,7 @@ function MonthCalendarBody({month, year, tasks, createTaskInCellHandler, current
deleteTaskHandler={()=>{deleteTaskHandler(currentTask.id); handleClose()}}
/>
</ModalTask>
</div>
</Box>
);
}
......
......@@ -3,7 +3,7 @@ import { Box, Typography } from '@mui/material';
import { memo } from 'react';
import MonthDecrementButton from './MonthDecrementButton/MonthDecrementButton';
import MonthIncrementButton from './MonthIncrementButton/MonthIncrementButton';
function MonthAndYearInfo({getCurrentMonthString, year, incrementMonth, decrementMonth}) {
function MonthAndYearInfo({currentMonthString, year, incrementMonth, decrementMonth}) {
return (
<>
......@@ -26,7 +26,7 @@ function MonthAndYearInfo({getCurrentMonthString, year, incrementMonth, decremen
justifyContent: 'center',
}}
>
{getCurrentMonthString}
{currentMonthString}
</Typography>
<Typography align='center'>{year}</Typography>
</Box>
......
......@@ -3,10 +3,10 @@ import { Box } from '@mui/system';
import MonthAndYearInfo from './MonthAndYearInfo/MonthAndYearInfo';
import СustomSelect from '../UI/СustomSelect/СustomSelect'
const workers = [{value: '', text: '--выберите сотрудника'}, {value: 'Василий', text: 'Василий'}, {value: 'Никита', text: 'Никита'}]
const workers = [{value: '', text: '--выберите сотрудника--'}, {value: 'Василий', text: 'Василий'}, {value: 'Никита', text: 'Никита'}]
const types = [{value: 'Месяц', text: 'Месяц'}, {value: 'Неделя', text: 'Неделя'}]
function MonthCalendarHeader({ getCurrentMonthString, decrementMonth, incrementMonth, calendarType, onChangeWorkerHandler, onChangeCalendarTypeHandler, worker, year}) {
function MonthCalendarHeader({ currentMonthString, decrementMonth, incrementMonth, calendarType, onChangeWorkerHandler, onChangeCalendarTypeHandler, worker, year}) {
return (
<>
......@@ -15,7 +15,7 @@ function MonthCalendarHeader({ getCurrentMonthString, decrementMonth, incrementM
<Toolbar>
<MonthAndYearInfo
getCurrentMonthString={getCurrentMonthString}
currentMonthString={currentMonthString}
decrementMonth={decrementMonth}
incrementMonth={incrementMonth}
year={year}
......
import { Button, FormControl, InputLabel, MenuItem, Select, TextField } from "@mui/material";
import { memo } from "react";
import CustomSelect from '../UI/СustomSelect/СustomSelect'
const priorities = [{value: '', text: '--Приоритет--'}, {value: 'A', text: 'A'}, {value: 'B', text: 'B'}, {value: 'C', text: 'C'}]
function MonthCalendarModalContent({title, onChangeCurrentTaskHandler, description, priority, sendNewTaskHandler, deleteTaskHandler}) {
return (<>
......@@ -22,28 +27,20 @@ function MonthCalendarModalContent({title, onChangeCurrentTaskHandler, descripti
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'}}
<CustomSelect
defaultValue={''}
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>
name={'priority'}
variant={'outlined'}
onChange={(e)=>{onChangeCurrentTaskHandler(e)}}
label={'Приоритет'}
id={'priority-type'}
items={priorities}
/>
<Button sx={{marginRight: '40px'}} onClick={sendNewTaskHandler}>Сохранить</Button>
<Button onClick={deleteTaskHandler}>Удалить</Button>
</>);
}
export default MonthCalendarModalContent;
\ No newline at end of file
export default memo(MonthCalendarModalContent);
\ No newline at end of file
import { FormControl, InputLabel, MenuItem, Select} from '@mui/material';
import { memo } from 'react';
function СustomSelect({value, onChange, label, variant='standard', items, id}) {
function СustomSelect({value, onChange, label, variant='standard', items, id, defaultValue, name}) {
return (
<>
......@@ -13,6 +13,8 @@ function СustomSelect({value, onChange, label, variant='standard', items, id})
value={value}
onChange={onChange}
label={label}
name={name}
defaultValue={defaultValue}
>
{items.map((item, i)=>{
return (
......
......@@ -2,7 +2,8 @@ import { useEffect, useCallback, useState, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import MonthCalendarBody from '../../components/MonthCalendarBody/MonthCalendarBody';
import MonthCalendarHeader from '../../components/MonthCalendarHeader/MonthCalendarHeader';
import { addTask, deleteTask, editTask, fetchCalendarTasks} from '../../store/actions/tasksActions';
import { dateToISOLikeButLocal, getCurrentMonthString, getDaysInMonth } from '../../helpers/CalendarHelpers';
import { addCalendarTask, deleteCalendarTask, editCalendarTask, fetchCalendarTasks} from '../../store/actions/tasksActions';
function MonthCalendar() {
const dispatch = useDispatch();
......@@ -26,35 +27,27 @@ function MonthCalendar() {
const hoursInDay = useMemo(()=>{
let arr
if (hourFormat) {
const arr = ['8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00','21:00','22:00']
const cells = arr.length
const xs = 10.8/cells
setCellSizes(()=>{
return {smallCell: 0.6, standarCell: xs, dayCell: 12/cells}
})
return arr
arr = ['8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00','21:00','22:00']
} else {
const arr = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00']
arr = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00']
}
const cells = arr.length
const xs = 10.8/cells
setCellSizes(()=>{
return {smallCell: 0.6, standarCell: xs, dayCell: 12/cells}
})
return arr
}
}, [hourFormat])
const daysInMonth = useMemo(() => {
const newDaysInMonth = []
const daysInMonthNumber = new Date(dateNow.year, dateNow.month + 1, 0).getDate()
for (let i = 1; i <= daysInMonthNumber; i++) {
const dayOfWeekNumber = new Date(dateNow.year, dateNow.month, i).getDay()
const getDayOfWeekString = ["ВС","ПН","ВТ","СР","ЧТ","ПТ","СБ"][dayOfWeekNumber]
newDaysInMonth.push({dayNumber: i, dayOfWeek: getDayOfWeekString})
}
return newDaysInMonth
}, [dateNow.month, dateNow.year])
return getDaysInMonth(dateNow)
}, [dateNow])
const currentMonthString = useMemo(() => {
return getCurrentMonthString(dateNow)
}, [dateNow])
const onChangeWorkerHandler = useCallback((event) => {
setWorker(event.target.value);
......@@ -64,10 +57,6 @@ function MonthCalendar() {
setCalendarType(event.target.value);
}, []);
const getCurrentMonthString = useMemo(() => {
return ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь", "Декабрь"][dateNow.month];
}, [dateNow.month])
const incrementMonth = useCallback(() => {
setDateNow((prevState)=>{
if (prevState.month + 1 === 12 ) {
......@@ -95,13 +84,6 @@ function MonthCalendar() {
}
});
}, []);
function dateToISOLikeButLocal(date) {
const offsetMs = date.getTimezoneOffset() * 60 * 1000;
const msLocal = date.getTime() - offsetMs;
const dateLocal = new Date(msLocal);
const iso = dateLocal.toISOString();
return iso;
}
const createTaskInCellHandler = (dayNumber, dayHour) => {
let hour
......@@ -128,7 +110,13 @@ function MonthCalendar() {
const dragTaskHandler = async (dayNumber, hour) => {
const hourDiff = currentTask.infoForCell.endHour - currentTask.infoForCell.startHour
const due = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour + hourDiff, 59))
const lastHour = hoursInDay[hoursInDay.length - 1].split(':')[0]
let due
if (hour + hourDiff >= lastHour) {
due = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, lastHour, 59))
} else {
due = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour + hourDiff, 59))
}
const start = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour, 0))
const newObj = {
...currentTask,
......@@ -136,15 +124,13 @@ function MonthCalendar() {
dateTimeDue: due
}
delete newObj.infoForCell
await dispatch(editTask(newObj))
await dispatch(editCalendarTask(newObj))
setCurrentTask({})
}
const increaseTaskHandler = async (dayNumber, task, isStartTask) => {
const timeEnd = task.dateTimeDue.split('T')[1]
const timeEndHour = parseInt(timeEnd.split(':')[0])
const timeStart = task.dateTimeStart.split('T')[1]
const timeStartHour = parseInt(timeStart.split(':')[0])
const timeEndHour = task.infoForCell.endHour
const timeStartHour = task.infoForCell.startHour
let hourDiff
if (hourFormat) {
hourDiff = 1
......@@ -166,16 +152,14 @@ function MonthCalendar() {
dateTimeDue: due
}
delete newObj.infoForCell
await dispatch(editTask(newObj))
await dispatch(editCalendarTask(newObj))
setCurrentTask({})
}
const reduceTaskHandler = async (dayNumber, task, isStartTask) => {
const timeEnd = task.dateTimeDue.split('T')[1]
const timeEndHour = parseInt(timeEnd.split(':')[0])
const timeStart = task.dateTimeStart.split('T')[1]
const timeStartHour = parseInt(timeStart.split(':')[0])
const timeEndHour = task.infoForCell.endHour
const timeStartHour = task.infoForCell.startHour
let hourDiff
let hourDiffCheck
if (hourFormat) {
......@@ -201,7 +185,7 @@ function MonthCalendar() {
dateTimeDue: due
}
delete newObj.infoForCell
await dispatch(editTask(newObj))
await dispatch(editCalendarTask(newObj))
setCurrentTask({})
}
}
......@@ -214,7 +198,7 @@ function MonthCalendar() {
...currentTask,
}}
)
await dispatch(editTask(currentTask))
await dispatch(editCalendarTask(currentTask))
} else {
setCurrentTask(() => {
return{
......@@ -222,32 +206,40 @@ function MonthCalendar() {
}}
)
delete currentTask.infoForCell
await dispatch(addTask(currentTask))
await dispatch(addCalendarTask(currentTask))
}
}
const createCopyTask = async (dayNumber, hour) => {
const hourDiff = copyTask.infoForCell.endHour - copyTask.infoForCell.startHour
const lastHour = hoursInDay[hoursInDay.length - 1].split(':')[0]
let due
if (hour + hourDiff >= lastHour) {
due = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, lastHour, 59))
} else {
due = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour + hourDiff, 59))
}
const start = dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour, 0))
const newTask = {
...copyTask,
dateTimeStart: dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour, 0)),
dateTimeDue: dateToISOLikeButLocal(new Date(dateNow.year, dateNow.month, dayNumber, hour + hourDiff, 59)),
dateTimeStart: start,
dateTimeDue: due,
}
delete newTask.infoForCell
delete newTask.id
await dispatch(addTask(newTask))
await dispatch(addCalendarTask(newTask))
setCopyTask(null)
}
const deleteTaskHandler = async (taskId) => {
dispatch(deleteTask(taskId))
dispatch(deleteCalendarTask(taskId))
}
return (
<>
<MonthCalendarHeader
year={dateNow.year}
getCurrentMonthString={getCurrentMonthString}
currentMonthString={currentMonthString}
decrementMonth={decrementMonth}
incrementMonth={incrementMonth}
onChangeCalendarTypeHandler={onChangeCalendarTypeHandler}
......
export const getDaysInMonth = (dateNow) => {
const newDaysInMonth = []
const daysInMonthNumber = new Date(dateNow.year, dateNow.month + 1, 0).getDate()
for (let i = 1; i <= daysInMonthNumber; i++) {
const dayOfWeekNumber = new Date(dateNow.year, dateNow.month, i).getDay()
const getDayOfWeekString = ["ВС","ПН","ВТ","СР","ЧТ","ПТ","СБ"][dayOfWeekNumber]
newDaysInMonth.push({dayNumber: i, dayOfWeek: getDayOfWeekString})
}
return newDaysInMonth
}
export const getCurrentMonthString = (dateNow) => {
return ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь", "Декабрь"][dateNow.month];
}
export const dateToISOLikeButLocal = (date) => {
const offsetMs = date.getTimezoneOffset() * 60 * 1000;
const msLocal = date.getTime() - offsetMs;
const dateLocal = new Date(msLocal);
const iso = dateLocal.toISOString();
return iso;
}
\ No newline at end of file
......@@ -46,6 +46,7 @@ export const fetchCalendarTasks = () => {
}
}
};
export const fetchAllTasks = () => {
return async (dispatch) => {
dispatch(fetchCalendarTasksRequest());
......@@ -69,34 +70,26 @@ const addTaskFailure = (error) => {
return {type: ADD_NEW_TASK_FAILURE, error}
};
// export const addTask = (task) => {
// return async (dispatch, getState) => {
// dispatch(addTaskRequest());
// const token = getState().users?.user?.token;
// try {
// await axios.post("/tasks", task, {
// headers: {
// Authorization: token,
// },
// });
// dispatch(addTaskSuccess());
// dispatch(fetchCalendarTasks());
// } catch (error) {
// dispatch(addTaskFailure(error.response.data));
// }
// };
// };
export const addCalendarTask = (task) => {
return async (dispatch, getState) => {
dispatch(addTaskRequest());
try {
await axios.post("/tasks", task);
dispatch(addTaskSuccess())
dispatch(fetchCalendarTasks())
} catch (error) {
dispatch(addTaskFailure(error.response.data));
}
}
}
export const addTask = (task) => {
return async (dispatch, getState) => {
dispatch(addTaskRequest());
// const token = getState().users?.user?.token;
try {
await axios.post("/tasks", task);
dispatch(addTaskSuccess())
dispatch(fetchAllTasks())
dispatch(fetchCalendarTasks())
} catch (error) {
dispatch(addTaskFailure(error.response.data));
}
......@@ -122,6 +115,18 @@ export const editTask = (task) => {
await axios.put("/tasks", task);
dispatch(editTaskSuccess())
dispatch(fetchAllTasks())
} catch (error) {
dispatch(editTaskFailure(error.response.data));
}
}
}
export const editCalendarTask = (task) => {
return async (dispatch, getState) => {
dispatch(editTaskRequest());
try {
await axios.put("/tasks", task);
dispatch(editTaskSuccess())
dispatch(fetchCalendarTasks())
} catch (error) {
dispatch(editTaskFailure(error.response.data));
......@@ -144,11 +149,9 @@ const deleteTaskFailure = (error) => {
export const deleteTask = (taskId) => {
return async (dispatch, getState) => {
dispatch(deleteTaskRequest());
// const token = getState().users?.user?.token;
try {
await axios.delete(`/tasks/${taskId}`);
dispatch(deleteTaskSuccess())
dispatch(fetchCalendarTasks())
dispatch(fetchAllTasks())
} catch (error) {
dispatch(deleteTaskFailure(error.response.data));
......@@ -156,6 +159,20 @@ export const deleteTask = (taskId) => {
}
}
export const deleteCalendarTask = (taskId) => {
return async (dispatch, getState) => {
dispatch(deleteTaskRequest());
try {
await axios.delete(`/tasks/${taskId}`);
dispatch(deleteTaskSuccess())
dispatch(fetchCalendarTasks())
} catch (error) {
dispatch(deleteTaskFailure(error.response.data));
}
}
}
const fetchTasksByProjectRequest = () => {
return {type: FETCH_TASKS_BY_PROJECT_REQUEST}
......
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