Merge branch 'task-110-enhance/CRUD_author_tasks' into 'development'

Task 110 enhance/crud author tasks

See merge request !93
parents f766ad1f 913aff40
......@@ -176,7 +176,7 @@ export const taskFinderByDateTimeTaskId = async (dateTimeTaskId:string):Promise<
/**member finder by userId and projectId, return one task */
export const memberFinderById = async (userId:string, projectId:string)=>{
export const memberFinderById = async (userId:string, projectId:string):Promise<Member|null>=>{
const member = await dataSource
.getRepository(Member)
.findOne({
......@@ -210,6 +210,13 @@ export let transporter = nodemailer.createTransport({
})
export const subtractHours= (date:Date, hours:number)=> {
const dateCopy = new Date(date);
dateCopy.setHours(dateCopy.getHours() - hours);
return dateCopy;
}
export const FRONTEND_URL = 'localhost:3000';
......@@ -83,6 +83,8 @@ export class User extends BaseEntity implements IUser {
@OneToMany(() => Member, (member: { user: User }) => member.user, {onDelete: 'CASCADE'})
members!: Member[];
// @OneToOne(()=>PasswordRecovery,)
@BeforeInsert()
......
......@@ -6,7 +6,7 @@ import { auth, authAdminProject } from '../helpers';
const router:Router = express.Router();
const dataSource = myDataSource;
router.get('/',async (req:Request, res:Response): Promise<Response>=> {
const projects:Project[] = await dataSource.manager.find(Project)
......@@ -121,7 +121,6 @@ router.get('/user/:userId', async (req : Request, res : Response): Promise<Respo
router.post('/add-user/', authAdminProject, async (req: Request, res: Response):Promise<Response>=>{
const {userId, projectId, roleProject} = req.body;
console.log("req body" + req.body)
const newMember:Member = new Member();
try{
newMember.user= userId;
......@@ -139,10 +138,8 @@ router.post('/add-user/', authAdminProject, async (req: Request, res: Response):
/** Remove user from specific project by userId */
router.delete('/remove-user/:userId', authAdminProject,async (req: Request, res: Response):Promise<Response>=> {
console.log('req.body ', req.body)
const {projectId} = req.body;
const {userId }=req.params;
console.log('projectId ', projectId, 'userId ',userId )
try{
const projectMember = await dataSource
......@@ -161,10 +158,8 @@ router.delete('/remove-user/:userId', authAdminProject,async (req: Request, res:
}
}
})
console.log('projectMember ', projectMember)
if(!projectMember) return res.status(404).send({message:"this member is not present"})
await Member.delete({id:projectMember.id})
console.log('projectMember deleted successfully')
return res.send({message:"User removed from project successfully" })
} catch(e){
return res.send({message:'Failed to remove user from project'})
......
......@@ -3,9 +3,9 @@ import {Task} from '../models/Task';
import {myDataSource} from '../app-data-source';
import { User } from '../models/User';
import { Member, MemberRole } from '../models/Member';
import { In } from 'typeorm';
import { Equal, In, Not } from 'typeorm';
import { DateTimeTask } from '../models/DateTimeTask';
import { auth, authAuthorOrExecutorOfTask, taskFinderById } from '../helpers';
import { auth, authAuthorOrExecutorOfTask, subtractHours, taskFinderById } from '../helpers';
import { Project } from '../models/Project';
const router:Router = express.Router();
const dataSource = myDataSource;
......@@ -27,6 +27,15 @@ router.get('/', async(req:Request, res:Response):Promise<Response> => {
/**create new task for table MyTask*/
router.post('/', auth, async(req:Request, res:Response):Promise<Response>=>{
const {user,title,description,project,executor,dateTimeStart,dateTimeDue, dateTimeDeadLine,priority} = req.body;
//** if dateTimeDue is null , then dateTimeDeadLine copied to dateTimeDue and dateTimeStart = dateTimeDue - 1 hour*/
let dateTimeDueFinal = dateTimeDue
let dateTimeStartFinal = dateTimeStart
let dateTimeDeadlineFinal= dateTimeDeadLine
if (!dateTimeDue && dateTimeDeadLine) {
dateTimeDueFinal = dateTimeDeadLine
dateTimeStartFinal = subtractHours(dateTimeDueFinal, 1)
}
const newTask = new Task();
newTask.title = title;
newTask.description = description;
......@@ -75,20 +84,24 @@ router.post('/', auth, async(req:Request, res:Response):Promise<Response>=>{
newMember.project=newPersonalProject;
newMember.roleProject = MemberRole.ADMIN;
await newMember.save();
console.log ('newPersonalProject ', newPersonalProject)
}
}
newTask.dateTimeDeadLine=dateTimeDeadLine;
newTask.dateTimeDeadLine= dateTimeDeadlineFinal;
newTask.author= user;
newTask.executor= executor;
if(newTask.project.title==="Личные дела"){
newTask.executor=user;
} else {
newTask.executor= executor;
}
newTask.priority = priority;
await newTask.save();
if (dateTimeDeadlineFinal) {
const newDateTimeTask = new DateTimeTask();
newDateTimeTask.dateTimeStart = dateTimeStart
newDateTimeTask.dateTimeDue = dateTimeDue
newDateTimeTask.dateTimeStart = dateTimeStartFinal
newDateTimeTask.dateTimeDue = dateTimeDueFinal
newDateTimeTask.task = newTask
await newDateTimeTask.save()
}
return res.send({newTask});
})
......@@ -142,7 +155,6 @@ router.post('/users', auth, async(req:Request, res:Response):Promise<Response>=>
newMember.project=newPersonalProject;
newMember.roleProject = MemberRole.ADMIN;
await newMember.save();
console.log ('newPersonalProject ', newPersonalProject)
}
}
......@@ -151,11 +163,13 @@ router.post('/users', auth, async(req:Request, res:Response):Promise<Response>=>
newTask.executor= executor;
newTask.priority = priority;
await newTask.save();
const newDateTimeTask = new DateTimeTask();
if(dateTimeDue && dateTimeStart){
const newDateTimeTask = new DateTimeTask();
newDateTimeTask.dateTimeStart = dateTimeStart
newDateTimeTask.dateTimeDue = dateTimeDue
newDateTimeTask.task = newTask
await newDateTimeTask.save()
}
return res.send({newTask});
})
......@@ -169,48 +183,72 @@ router.get('/user/:userId', async (req: Request, res: Response):Promise<Response
relations:{
executor:true,
},
where:[
where:
{
executor:{
id:userId
}
},
]
})
return res.send({tasks})
})
/**check tasks of current user where he is author or executor, search by id*/
/**check tasks of current user where he is executor(works for tbl MyTasks), search by id*/
router.get('/my',auth, async (req: Request, res: Response):Promise<Response>=>{
const user = req.body.user
const projectsRawId = await dataSource
.getRepository(Project)
.find({
select:{
id:true
},
where:{
title:Not(Equal("Не определено")),
members:{
user:{
id: user.id
},
roleProject:Not(MemberRole.WATCHER)
}
}
}
)
const projectsList= projectsRawId.map(project=> {return project.id})
const tasks = await dataSource
.getRepository(Task)
.find({
relations:{
.find(
{relations:{
author:true,
executor:true,
author:true,
project:true
},
where:[
{
executor:{
id:user.id
where:{
executor:{
id:user.id
},
}
},
{
author:{
id:user.id
}
)
const projects = await dataSource
.getRepository(Project)
.find({
relations:{
members:true
},
where:{
id:In(projectsList)
}
},
]
})
return res.send({tasks})
})
})
return res.send({tasks, projects})
})
/**return tasks & users of projects in which current user is involved, search by token*/
router.get('/related', auth,async (req: Request, res: Response):Promise<Response>=>{
console.log('related')
const user = req.body.user
const tasks = await dataSource
.createQueryBuilder()
......@@ -269,7 +307,8 @@ router.delete('/:taskId',async (req: Request, res: Response):Promise<Response>=>
/**change of task by task id */
router.put('/:taskId',authAuthorOrExecutorOfTask,async(req:Request, res:Response)=> {
const {taskId} = req.params
const {authorStatus,executorStatus,title,description,note, archive,project,dateTimeTaskId,dateTimeStart,dateTimeDue,executor,accomplish,dateTimeDeadLine, dateTimeFactDeadLine,priority} = req.body;
const {authorStatus,executorStatus,title,description,note, archive,project,dateTimeTaskId,dateTimeStart,
dateTimeDue,executor,accomplish,dateTimeDeadLine, dateTimeFactDeadLine,priority} = req.body;
const task = await taskFinderById(taskId)
if (!task) return res.status(404).send({Message:'task not found'})
let dateTimeTask = null;
......@@ -341,7 +380,7 @@ router.post('/project',async (req: Request, res: Response):Promise<Response>=>{
/**check other users tasks that are related to the user through common projects, by user token*/
router.get('/users-tasks', auth,async (req: Request, res: Response):Promise<Response>=>{
const {user} = req.body
const projects = await dataSource
const projectsWithTasks = await dataSource
.getRepository(Project)
.find(
{ relations:{
......@@ -355,21 +394,38 @@ router.get('/users-tasks', auth,async (req: Request, res: Response):Promise<Resp
members:{
user:{
id:user.id
},
project:{
title:Not(Equal("Личные дела"))
}
}
}})
if (!projects) return res.status(404).send({Message:'projects not found'})
if (!projectsWithTasks) return res.status(404).send({Message:'projects not found'})
let tasks:Task[] = []
if (projects.length>0) {
for (let project of projects){
if (projectsWithTasks.length>0) {
for (let project of projectsWithTasks){
if (project?.tasks) {
tasks=tasks.concat(project.tasks)
}
}
}
const projectIds= projectsWithTasks.map(project=> {return project.id})
const projects = await dataSource
.getRepository(Project)
.find({
relations:{
members:{
user:true
}},
where:{
id:In(projectIds),
members:{
roleProject: Not(MemberRole.WATCHER)
}
},
})
return res.send({projects, tasks})
})
......
......@@ -62,7 +62,6 @@ router.get('/all-fields/', async (req : Request, res : Response):Promise<object>
},
}
})
console.log('all fields users ', users)
return res.send({users})
})
......
......@@ -8,18 +8,18 @@ import MultipleSelect from '../../components/UI/MultipleSelect/MultipleSelect';
import Add from "@mui/icons-material/Add";
import Close from "@mui/icons-material/Close";
export default function MyTaskToolBar({projects,onClose,projectName,setProjectName,formStatus,onClick}) {
export default function MyTaskToolBar({projects,onClose,projectIdListForTaskSelect,setProjectIdListForTaskSelect,formStatus,onClick}) {
let projectsFilter =
<></>
if (projects) {
if (Array.isArray(projects)) {
projectsFilter=
<MultipleSelect
projects={projects}
onClose={onClose}
projectName={projectName}
setProjectName={setProjectName}
projectName={projectIdListForTaskSelect}
setProjectName={setProjectIdListForTaskSelect}
/>
}
......
......@@ -35,7 +35,7 @@ export default function NewTaskForm({ projects, setAddTaskForm }) {
dateTimeDeadLine: null,
dateTimeTasks: [],
dateTimeDue: null,
project: projects[0],
project: null,
accomplish: "opened",
priority: "B",
author: { id: user.id },
......@@ -127,14 +127,7 @@ export default function NewTaskForm({ projects, setAddTaskForm }) {
/>
</TableCell>
<CustomTableCell
{...{
task,
name: "createdAt",
value: moment(task.createdAt).format("DD-MM-YYYY hh:mm A"),
width: "15%",
}}
/>
<CustomTableCell
{...{
......@@ -161,14 +154,6 @@ export default function NewTaskForm({ projects, setAddTaskForm }) {
/>
</TableCell>
{/* <TableCell>
<MaterialUIPickers
task={task}
name="dateTimeStart"
onChange={onDateChange}
/>
</TableCell> */}
<TableCell style={{ width: "20%", paddingLeft: "0" }}>
<MaterialUIPickers
task={task}
......@@ -213,12 +198,6 @@ export const header = [
disablePadding: true,
label: "Приоритет",
},
{
id: "createdAt",
numeric: true,
disablePadding: false,
label: "Дата создания",
},
{
id: "title",
numeric: false,
......
......@@ -45,7 +45,10 @@ export default function MultipleSelect({projects,projectName,onClose,setProjectN
return (
<div>
<FormControl sx={{ m: 1, width: 250,borderColor:'white' }}>
<InputLabel placeholder='Choose Project' label='I am a really really long green TextField label' id="demo-multiple-name-label" sx={{color:'white', padding:'1' }}>Project</InputLabel>
<InputLabel placeholder='Choose Project'
label='I am a really really long green TextField label'
id="demo-multiple-name-label" sx={{color:'white', padding:'1' }}
>Project</InputLabel>
<Select
labelId="demo-multiple-name-label"
label='Choose Project'
......@@ -59,13 +62,13 @@ export default function MultipleSelect({projects,projectName,onClose,setProjectN
sx={{color:'white' }}
onClose={(e)=>{onClose(projectName)}}
>
{projects?.map((project) => (
{projects?.map((project,index) => (
<MenuItem
key={project}
value={project}
style={getStyles(project, projectName, theme)}
key={index}
value={project.id}
style={getStyles(project.title, projectName, theme)}
>
{project}
{project.title}
</MenuItem>
))}
</Select>
......
......@@ -6,7 +6,11 @@ import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
export default function BasicSelect({value,label,name,onChange,task,items}) {
console.log('select value ', value)
console.log('select label ', label)
console.log('select name ', name)
console.log('select task ', task)
console.log('select items ', items)
return (
<Box sx={{ minWidth: 60, m: 0}}>
<FormControl fullWidth>
......@@ -19,11 +23,11 @@ export default function BasicSelect({value,label,name,onChange,task,items}) {
name={name}
onChange={(e) => onChange(e, task)}
>
{items.map((item) => (
<MenuItem key={item.value} value={item.value}>
{items ?items.map((item,index) => (
<MenuItem key={index} value={item.value}>
{item.title}
</MenuItem>
))}
)):null}
</Select>
</FormControl>
</Box>
......
......@@ -12,6 +12,7 @@ const CustomTableCell = ({
onModalOpen,
placeholder,
user,
colSpan
}) => {
const styles = placeholder ? { width: "100%" } : { width: "auto" };
const divStyle = {
......@@ -32,6 +33,7 @@ const CustomTableCell = ({
return (
<>
<TableCell
colSpan={colSpan}
onClick={(e) => (onModalOpen ? onModalOpen(e, task) : null)}
align="left"
// style={styles}
......
......@@ -18,13 +18,13 @@ import moment from "moment";
import CustomTableCell from "./CustomTableCell";
import MaterialUIPickers from "./DateTimePicker/DateTimePicker";
import BasicSelect from "../UI/Select/Select";
import { addTask } from "../../store/actions/tasksActions";
import { addTaskToUserTasksTable } from "../../store/actions/tasksActions";
import TaskModal from "./TaskModal/TaskModal";
export default function NewTaskForm({
projects,
currentProject,
setCurrentProject,
setAddTaskForm,
}) {
const dispatch = useDispatch();
......@@ -40,7 +40,7 @@ export default function NewTaskForm({
dateTimeDeadLine: null,
dateTimeTasks: [],
dateTimeDue: null,
project: projects[0],
project: null,
accomplish: "opened",
priority: "B",
author: { id: user.id },
......@@ -48,8 +48,8 @@ export default function NewTaskForm({
executor:null,
isEditMode: true,
});
const [modal, setModal] = useState(false);
console.log('NewTaskForm currentProject ', currentProject )
const onModalOpen = (event, task) => {
event.stopPropagation();
......@@ -69,17 +69,21 @@ export default function NewTaskForm({
const onProjectChange = (e, task) => {
const value = e.target.value;
const project = projects.find((e) => e.id === value);
const project = projects.find((project) => project.id === value);
setCurrentProject(project)
const newTask = { ...task };
newTask.project = project;
setTask(newTask);
};
const onExecutorChange = (e, task) => {
const value = e.target.value;
const executor = projects.find((e) => e.id === value);
const {value, name} = e.target.value;
let executorMember = null
const newTask = { ...task };
newTask.executor = executor;
if( name==='executor' && value!==null) {
executorMember = currentProject.find((member) => member.user.id === value);
newTask.executor = executorMember?.user;
}
setTask(newTask);
};
......@@ -92,7 +96,7 @@ export default function NewTaskForm({
};
const handleAddTask = () => {
dispatch(addTask(task));
dispatch(addTaskToUserTasksTable(task));
setAddTaskForm();
};
......@@ -115,6 +119,7 @@ export default function NewTaskForm({
key={headCell.id}
align="center"
padding={headCell.disablePadding ? "none" : "normal"}
colSpan={headCell.colSpan}
>
{headCell.label}
</TableCell>
......@@ -139,14 +144,9 @@ export default function NewTaskForm({
/>
</TableCell>
<CustomTableCell
{...{
task,
name: "createdAt",
value: moment(task.createdAt).format("DD-MM-YYYY hh:mm A"),
}}
/>
<CustomTableCell
colSpan={3}
{...{
task,
name: "title",
......@@ -159,9 +159,9 @@ export default function NewTaskForm({
<TableCell>
<BasicSelect
items={projects.map((e) => ({
value: e?.id,
title: e?.title,
items={projects?.map((project) => ({
value: project?.id,
title: project?.title,
}))}
task={task}
onChange={onProjectChange}
......@@ -171,24 +171,19 @@ export default function NewTaskForm({
</TableCell>
<TableCell>
<BasicSelect
items={currentProject.members.map((member) => ({
value: member?.id,
title: member?.displayName,
}))}
items={currentProject?currentProject?.members.map((member) => ({
value: member?.user?.id,
title: member?.user?.displayName,
})):null}
task={task}
onChange={onExecutorChange}
name="executor"
value={task.executor?.id}
defaultValue={user.id}
/>
</TableCell>
{/* <TableCell>
<MaterialUIPickers
task={task}
name="dateTimeStart"
onChange={onDateChange}
/>
</TableCell> */}
<TableCell>
<MaterialUIPickers
......@@ -235,17 +230,12 @@ export const header = [
disablePadding: true,
label: "Приоритет",
},
{
id: "createdAt",
numeric: true,
disablePadding: false,
label: "Дата создания",
},
{
{
id: "title",
numeric: false,
disablePadding: false,
label: "Заголовок",
colSpan:3
},
{
id: "projectName",
......@@ -260,7 +250,7 @@ export const header = [
label: "Исполнитель",
},
{
id: "dateTimeDue",
id: "dateTimeDeadLine",
numeric: true,
disablePadding: false,
label: "Дедлайн",
......
......@@ -8,18 +8,18 @@ import MultipleSelect from '../UI/MultipleSelect/MultipleSelect';
import Add from "@mui/icons-material/Add";
import Close from "@mui/icons-material/Close";
export default function MyTaskToolBar({projects,onClose,projectName,setProjectName,formStatus,onClick}) {
export default function UsersTaskToolBar({projects,onClose,projectIdListForTaskSelect,setProjectIdListForTaskSelect,formStatus,onClick}) {
let projectsFilter =
<></>
if (projects) {
if (Array.isArray(projects)) {
projectsFilter=
<MultipleSelect
projects={projects}
onClose={onClose}
projectName={projectName}
setProjectName={setProjectName}
projectName={projectIdListForTaskSelect}
setProjectName={setProjectIdListForTaskSelect}
/>
}
......@@ -27,7 +27,8 @@ export default function MyTaskToolBar({projects,onClose,projectName,setProjectNa
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<Toolbar
>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
Задачи сотрудников
</Typography>
......
......@@ -7,6 +7,7 @@ import PersonIcon from '@mui/icons-material/Person';
import styled from "@emotion/styled";
import { Alert, Avatar, Container, Typography } from "@mui/material";
import ResetPasswordForm from "../../components/UserForm/ResetPasswordForm";
import axios from "axios";
const StyledContainer = styled(Container)`
padding-top: 30px;
......
......@@ -22,6 +22,7 @@ export default function EnhancedTable() {
const dispatch = useDispatch();
const tasks = useSelector((state) => state.tasks.tasks);
const projects = useSelector((state) => state.tasks.projects);
const user = useSelector((state) => state.users.user);
const [recievedTasks, setRecievedTasks] = useState([]);
const [addTaskForm, setAddTaskForm] = useState(false);
......@@ -33,22 +34,15 @@ export default function EnhancedTable() {
open: false,
task: null,
});
const [projects, setProjects] = useState(["1", "2"]);
useEffect(() => {
dispatch(fetchAllTasks());
filterProjectsNamesFromTasks();
}, [dispatch]);
useEffect(() => {
dispatch(fetchAllTasks());
if (tasks && tasks?.length > 0) {
setRecievedTasks(tasks);
}
}, [dispatch, tasks]);
useEffect(() => {
dispatch(fetchAllTasks());
}, [addTaskForm, setAddTaskForm]);
}, [ tasks?.length,addTaskForm, setAddTaskForm, dispatch]);
console.log('tasks ', tasks, 'projects ', projects)
......@@ -111,7 +105,7 @@ export default function EnhancedTable() {
const onProjectChange = (e, task) => {
const value = e.target.value;
const project = uniqueProjects.find((e) => e.id === value);
const project = projects.find((e) => e.id === value);
const { id } = task;
const newTasks = recievedTasks.map((task) => {
if (task.id === id) {
......@@ -162,16 +156,9 @@ export default function EnhancedTable() {
};
const deleteDateTimeTaskHandle=(dateTimeTaskId)=>{
console.log('delete by dateTimeTaskId ', dateTimeTaskId)
dispatch(deleteDateTimeTask(dateTimeTaskId))
}
const handleEditDateTimeTask=(dateTimeTask)=>{
console.log('edit by dateTImeTask')
// dispatch(handleEditDateTimeTask(dateTimeTask))
}
const onModalOpen = (event, task) => {
event.stopPropagation();
setModal({ ...modal, open: true, id: task.id });
......@@ -182,48 +169,19 @@ export default function EnhancedTable() {
};
// ++++++++фильтрация по проектам+++++++++++++++
const [projectName, setProjectName] = React.useState([]);
const [filterProjectTumbler, setFilterProjectTumbler] = React.useState(false);
const onClose = (projectName) => {
let tasksFilteredByProject = tasks;
if (projectName.length > 0) {
tasksFilteredByProject = tasks.filter((task) =>
projectName.includes(task.project?.title)
);
}
setRecievedTasks(tasksFilteredByProject);
setFilterProjectTumbler(true);
};
const rawProjects = tasks?.map((task) => task.project);
const filterProjectsNamesFromTasks = () => {
if (tasks && tasks?.length > 0) {
let rawSetProjectNames = [];
for (let project of rawProjects) {
if (project === null) {
} else {
rawSetProjectNames.push(project.title);
}
}
let uniqueTitlesProjects = [...new Set(rawSetProjectNames)];
setProjects(uniqueTitlesProjects);
}
};
const uniqueProjects = rawProjects?.reduce((results, value, index) => {
const exist = results.find((v) => {
return v !== null && v.id === value?.id;
});
if (!exist && value !== null) {
results.push(value);
}
return results;
}, []);
const [projectIdListForTaskSelect, setProjectIdListForTaskSelect] = React.useState([]);
const [filterProjectTumbler, setFilterProjectTumbler] = React.useState(false);
console.log('tasks', tasks)
const onClose=(projectIdListForTaskSelect)=>{
let tasksFilteredByProject = tasks
if (projectIdListForTaskSelect.length>0) {
tasksFilteredByProject = tasks.filter(task=>projectIdListForTaskSelect.includes(task.project?.id))
}
setRecievedTasks(tasksFilteredByProject)
setFilterProjectTumbler(true)
}
if (
if (
tasks &&
tasks?.length > 0 &&
recievedTasks &&
......@@ -237,13 +195,13 @@ console.log('tasks', tasks)
formStatus={addTaskForm}
projects={projects}
onClose={onClose}
projectName={projectName}
setProjectName={setProjectName}
projectIdListForTaskSelect={projectIdListForTaskSelect}
setProjectIdListForTaskSelect={setProjectIdListForTaskSelect}
/>
{addTaskForm ? (
<NewTaskForm
projects={uniqueProjects}
projects={projects}
setAddTaskForm={() => setAddTaskForm(false)}
/>
) : null}
......@@ -267,13 +225,11 @@ console.log('tasks', tasks)
task={task}
deleteHandle={deleteHandle}
handleEditTask ={handleEditTask}
handleEditDateTimeTask={handleEditDateTimeTask}
deleteDateTimeTask={deleteDateTimeTaskHandle}
onChange={onChange}
onModalOpen={onModalOpen}
onProjectChange={onProjectChange}
uniqueProjects={uniqueProjects}
onAuthorChange={onAuthorChange}
uniqueProjects={projects}
onDateChange={onDateChange}
onToggleEditMode={onToggleEditMode}
onToggleEditModeDone={onToggleEditModeDone}
......
......@@ -11,8 +11,8 @@ import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import TaskModal from "../../components/UsersTasksCompoments/TaskModal/TaskModal";
import moment from "moment";
import MyTaskToolBar from "../../components/UsersTasksCompoments/UsersTaskToolBar";
import { fetchAllTasks, deleteTask,editTask, deleteDateTimeTask} from "../../store/actions/tasksActions";
import UsersTaskToolBar from "../../components/UsersTasksCompoments/UsersTaskToolBar";
import { deleteTask, editTask, deleteDateTimeTask , fetchAllTasksByMembership} from "../../store/actions/tasksActions";
import NewTaskForm from "../../components/UsersTasksCompoments/NewTaskForm";
import TableRowTask from "../../components/UsersTasksCompoments/TableRowTask/TableRowTask";
import UsersTasksHeader from "./UsersTasksHeader/UsersTasksHeader";
......@@ -23,35 +23,30 @@ export default function UsersTasks() {
const dispatch = useDispatch();
const tasks = useSelector((state) => state.tasks.tasks);
const projects = useSelector((state) => state.tasks.projects);
const user = useSelector((state) => state.users.user);
const [executors, setExecutors]=useState([])
const [projects,setProjects]=useState([])
const [currentProject, setCurrentProject] = useState(null);
const [recievedTasks, setRecievedTasks] = useState([]);
const [addTaskForm, setAddTaskForm] = useState(false);
const [order, setOrder] = useState("asc");
const [orderBy, setOrderBy] = useState("id");
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] =useState(5);
const [rowsPerPage, setRowsPerPage] =useState(25);
const [modal, setModal] = useState({
open: false,
task: null,
});
useEffect(() => {
dispatch(fetchAllTasks());
filterProjectsNamesFromTasks()
dispatch(fetchAllTasksByMembership());
if (tasks && tasks?.length > 0) {
setRecievedTasks(tasks);
}
}, [dispatch, tasks?.length]);
useEffect(() => {
dispatch(fetchAllTasks());
}, [addTaskForm, setAddTaskForm]);
}, [dispatch,
tasks?.length,
addTaskForm, setAddTaskForm]);
const handleRequestSort = ( property) => {
const isAsc = orderBy === property && order === "asc";
......@@ -73,7 +68,6 @@ useEffect(() => {
const name = e.target.name;
const { id } = task;
const newTasks = recievedTasks.map((task) => {
console.log('recievedTasks.map ',task)
if (task.id === id) {
return { ...task, [name]: value };
}
......@@ -82,20 +76,6 @@ useEffect(() => {
setRecievedTasks(newTasks);
};
const onAuthorChange = (e, task) => {
const value = e.target.value;
const { id } = task;
const newTasks = recievedTasks.map((task) => {
if (task.id === id) {
const updated = { ...task };
updated.author.displayName = value;
updated.authorDisplayName = value;
return updated;
}
return task;
});
setRecievedTasks(newTasks);
};
const onDateChange = (id, value, property) => {
const newTasks = recievedTasks.map((task) => {
......@@ -112,13 +92,22 @@ useEffect(() => {
const onProjectChange = (e, task) => {
const projectId = e.target.value;
const project = uniqueProjects.find((uniqueProject) => uniqueProject.id === projectId);
const project = projects.length>0 ?projects.find((uniqueProject) => uniqueProject.id === projectId):null;
setCurrentProject(project)
let executorList=[]
if(project?.members){
for (let member of project.members){
executorList.push(member.user)
}
}
setExecutors(executorList)
const { id } = task;
const newTasks = recievedTasks.map((task) => {
if (task.id === id) {
const updated = { ...task };
updated.project = project;
updated.projectName = project.title;
updated.projectName =project.title? project.title:null;
return updated;
}
return task;
......@@ -187,12 +176,6 @@ useEffect(() => {
dispatch(deleteDateTimeTask(dateTimeTaskId))
}
const handleEditDateTimeTask=(dateTimeTask)=>{
console.log('edit by dateTImeTask')
// dispatch(handleEditDateTimeTask(dateTimeTask))
}
const onModalOpen = (event, task) => {
event.stopPropagation();
setModal({ ...modal, open: true, id: task.id });
......@@ -203,48 +186,19 @@ useEffect(() => {
};
// ++++++++фильтрация по проектам+++++++++++++++
const [projectName, setProjectName] = React.useState([]);
const [projectIdListForTaskSelect, setProjectIdListForTaskSelect] = React.useState([]);
const [filterProjectTumbler, setFilterProjectTumbler] = React.useState(false);
const onClose=(projectName)=>{
const onClose=(projectIdListForTaskSelect)=>{
let tasksFilteredByProject = tasks
if (projectName.length>0) {
tasksFilteredByProject = tasks.filter(task=>projectName.includes(task.project?.title))
if (projectIdListForTaskSelect.length>0) {
tasksFilteredByProject = tasks.filter(task=>projectIdListForTaskSelect.includes(task.project?.id))
}
setRecievedTasks(tasksFilteredByProject)
setFilterProjectTumbler(true)
}
const rawProjects= tasks?.map(task=>task.project)
const filterProjectsNamesFromTasks = ()=>{
if (tasks && tasks?.length > 0) {
let rawSetProjectNames = []
for (let project of rawProjects){
if (project===null){
} else{
rawSetProjectNames.push(project.title)
}
}
let uniqueTitlesProjects = [...new Set(rawSetProjectNames)];
setProjects(uniqueTitlesProjects)
}
}
const uniqueProjects = rawProjects?.reduce((results, value, index) => {
const exist = results.find((v) => {
return v !== null && v.id === value?.id
});
if (!exist && value !== null) {
results.push(value);
}
return results;
}, []);
console.log('tasks', tasks)
if (
tasks &&
tasks?.length > 0 &&
......@@ -254,18 +208,19 @@ console.log('tasks', tasks)
return (
<Box sx={{ width: "fullwidth" }}>
<Paper sx={{ width: "100%", mb: 2 }}>
<MyTaskToolBar
<UsersTaskToolBar
onClick={() => setAddTaskForm(!addTaskForm)}
formStatus={addTaskForm}
projects={projects}
onClose={onClose}
projectName={projectName}
setProjectName={setProjectName}
projectIdListForTaskSelect={projectIdListForTaskSelect}
setProjectIdListForTaskSelect={setProjectIdListForTaskSelect}
/>
{addTaskForm ? (
<NewTaskForm
projects={uniqueProjects}
projects={projects}
setCurrentProject={setCurrentProject}
currentProject={currentProject}
setAddTaskForm={()=>setAddTaskForm(false)}
/>
......@@ -273,7 +228,7 @@ console.log('tasks', tasks)
<TableContainer>
<Table sx={{ minWidth: 600 }} aria-labelledby="tableTitle">
<Table sx={{ minWidth: 600 }} aria-labelledby="tableTitle" size='small'>
<UsersTasksHeader
order={order}
orderBy={orderBy}
......@@ -292,15 +247,13 @@ console.log('tasks', tasks)
task={task}
deleteHandle={deleteHandle}
handleEditTask ={handleEditTask}
handleEditDateTimeTask={handleEditDateTimeTask}
deleteDateTimeTask={deleteDateTimeTaskHandle}
onChange={onChange}
onModalOpen={onModalOpen}
onProjectChange={onProjectChange}
executors={executors}
onExecutorChange={onExecutorChange}
uniqueProjects={uniqueProjects}
// onAuthorChange={onAuthorChange}
uniqueProjects={projects}
onDateChange={onDateChange}
onToggleEditMode={onToggleEditMode}
onToggleEditModeDone={onToggleEditModeDone}
......
......@@ -24,4 +24,8 @@ export const EDIT_CALENDAR_TASK = "EDIT_CALENDAR_TASK";
export const DELETE_DATETIMETASK_REQUEST = "DELETE_TASK_REQUEST";
export const DELETE_DATETIMETASK_SUCCESS = "DELETE_TASK_SUCCESS";
export const DELETE_DATETIMETASK_FAILURE = "DELETE_TASK_FAILURE";
\ No newline at end of file
export const DELETE_DATETIMETASK_FAILURE = "DELETE_TASK_FAILURE";
export const FETCH_ALL_TASKS_BY_MEMBERSHIP_REQUEST = "FETCH_ALL_TASKS_BY_MEMBERSHIP_REQUEST";
export const FETCH_ALL_TASKS_BY_MEMBERSHIP_SUCCESS = "FETCH_ALL_TASKS_BY_MEMBERSHIP_SUCCESS";
export const FETCH_ALL_TASKS_BY_MEMBERSHIP_FAILURE = "FETCH_ALL_TASKS_BY_MEMBERSHIP_FAILURE";
\ No newline at end of file
......@@ -18,6 +18,7 @@ import {
DELETE_DATETIMETASK_FAILURE,
DELETE_DATETIMETASK_SUCCESS,
DELETE_DATETIMETASK_REQUEST,
FETCH_ALL_TASKS_BY_MEMBERSHIP_SUCCESS
} from "../actionTypes/tasksTypes";
import axios from '../../axiosPlanner'
......@@ -29,8 +30,8 @@ const fetchCalendarTasksSuccess = (tasks) => {
return {type: FETCH_CALENDAR_TASKS_SUCCESS, tasks}
};
const fetchAllTasksSuccess = (tasks) => {
return {type: FETCH_ALL_TASKS_SUCCESS, tasks}
const fetchAllTasksSuccess = (tasks,projects) => {
return {type: FETCH_ALL_TASKS_SUCCESS, tasks, projects}
};
......@@ -54,15 +55,38 @@ export const fetchAllTasks = () => {
return async (dispatch) => {
dispatch(fetchCalendarTasksRequest());
try {
const response = await axios.get("/tasks");
dispatch(fetchAllTasksSuccess(response.data.tasks))
const response = await axios.get("/tasks/my");
dispatch(fetchAllTasksSuccess(response.data.tasks,response.data.projects))
} catch (error) {
dispatch(fetchCalendarTasksFailure(error.response.data));
}
}
};
//**fetch tasks for table UsersTasks, start*/
const fetchAllTasksByMembershipSuccess = (tasks, projects) => {
return {type: FETCH_ALL_TASKS_BY_MEMBERSHIP_SUCCESS, tasks, projects}
};
export const fetchAllTasksByMembership = () => {
return async (dispatch) => {
dispatch(fetchCalendarTasksRequest());
try {
const response = await axios.get("/tasks/users-tasks");
dispatch(fetchAllTasksByMembershipSuccess(response.data.tasks, response.data.projects))
} catch (error) {
dispatch(fetchCalendarTasksFailure(error.response.data));
}
}
};
//**end*/
const addTaskRequest = () => {
return {type: ADD_NEW_TASK_REQUEST}
return {type: ADD_NEW_TASK_REQUEST}
};
const addTaskSuccess = () => {
......@@ -241,3 +265,33 @@ export const deleteDateTimeTask = (dateTimeTaskId) => {
}
}
}
/** add new task in UserTasks Table */
const addTaskToUserTasksTableRequest = () => {
return {type: ADD_NEW_TASK_REQUEST}
};
const addTaskToUserTasksTableSuccess = () => {
return {type: ADD_NEW_TASK_SUCCESS}
};
const addTaskToUserTasksTableFailure = (error) => {
return {type: ADD_NEW_TASK_FAILURE, error}
};
export const addTaskToUserTasksTable = (task) => {
return async (dispatch) => {
dispatch(addTaskToUserTasksTableRequest());
try {
await axios.post("/tasks/users", task);
dispatch(addTaskToUserTasksTableSuccess())
dispatch(fetchAllTasksByMembership())
} catch (error) {
dispatch(addTaskToUserTasksTableFailure(error.response.data));
}
}
}
/** end */
\ No newline at end of file
......@@ -17,7 +17,8 @@ import {
FETCH_TASKS_BY_PROJECT_FAILURE,
DELETE_DATETIMETASK_FAILURE,
DELETE_DATETIMETASK_SUCCESS,
DELETE_DATETIMETASK_REQUEST
DELETE_DATETIMETASK_REQUEST,
FETCH_ALL_TASKS_BY_MEMBERSHIP_SUCCESS
} from "../actionTypes/tasksTypes";
const initialState = {
......@@ -77,7 +78,9 @@ const tasksReduсer = (state = initialState, action) => {
})
return {...state, loading: false, calendarTasks: newTasksWithInfoForCell};
case FETCH_ALL_TASKS_SUCCESS:
return {...state, loading: false, tasks: action.tasks};
return {...state, loading: false, tasks: action.tasks, projects:action.projects};
case FETCH_ALL_TASKS_BY_MEMBERSHIP_SUCCESS:
return {...state, loading: false, tasks: action.tasks, projects:action.projects};
case FETCH_CALENDAR_TASKS_FAILURE:
return {...state, loading: false, error: action.error};
case ADD_NEW_TASK_SUCCESS:
......
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