All files / contexts CoursesProvider.tsx

27.27% Statements 39/143
0% Branches 0/50
11.9% Functions 5/42
29.69% Lines 38/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310              5x                                                                 5x           5x 20x 20x     20x 20x 20x 20x 20x 20x 20x   20x           20x   20x 4x 4x           20x 2x                       20x                           20x                 20x   20x   20x                   20x   20x               20x                                                             20x                       20x                           20x                       20x                         20x                     20x                       20x                                                       20x 10x 10x             20x                                                                
import React, { useState, createContext, useEffect, ReactNode } from 'react';
import { Course, Group, Basket, GroupType, SchedulerEvent, TimetableHistory } from '../types';
import { useSnackbar } from 'notistack';
import { axiosInstance } from '../utils/axiosInstance';
import CloseIcon from '@material-ui/icons/Close';
import styled from 'styled-components';
 
const StyledCloseIcon = styled(CloseIcon)`
  color: #000000;
  &:hover {
    color: white;
    cursor: pointer;
  }
`;
 
interface CourseContext {
  courses: Array<Course>;
  basket: Array<Basket>;
  timetableHistory: Array<TimetableHistory>;
  hoveredGroup: Group | undefined | null;
  userID: string;
  isDataLoading: boolean;
  historyBasket: Array<Basket>;
  addCourseToBasket: (courses: Course) => void;
  changeHoveredGroup: (group: Group | null) => void;
  changeGroupInBasket: (group: any, courseId: number) => void;
  restoreGroupInBasket: (restoreGroup: Group, courseId: number) => void;
  deleteFromBasket: (id: number) => void;
  saveBasket: (userID: string) => Promise<void>;
  changeStudent: (studentId: string) => void;
  selectSchedulerEvents: () => Array<SchedulerEvent>;
  selectHistorySchedulerEvents: () => Array<SchedulerEvent>;
  selectBasketNames: () => Array<string>;
  selectBasketCourses: () => Array<Course>;
  selectBasketCourseGroups: (courseId: number) => { lecture: Group | undefined; classes: Group | undefined };
  getNewestStudentTimetable: (studentId: string) => void;
  getStudentTimetablesHistory: (studentId: string) => void;
  changeDataLoading: (isLoading: boolean) => void;
  setHistoryBasketFromHistoryGroups: (groupsIds: Array<number>) => void;
}
export const coursesContext = createContext<CourseContext | undefined>(undefined);
 
interface CoursesProviderProps {
  children: ReactNode;
}
 
export const CoursesProvider = ({ children }: CoursesProviderProps) => {
  const { enqueueSnackbar } = useSnackbar();
  const { closeSnackbar } = useSnackbar();
 
  //fetch courses with groups
  const [courses, setCourses] = useState<Array<Course>>([]);
  const [basket, setBasket] = useState<Array<Basket>>([]);
  const [historyBasket, setHistoryBasket] = useState<Array<Basket>>([]);
  const [timetableHistory, setTimetableHistory] = useState<Array<TimetableHistory>>([]);
  const [userID, setUserID] = useState('');
  const [hoveredGroup, setHoveredGroup] = useState<Group | undefined | null>(null);
  const [isDataLoading, setIsDataLoading] = useState(false);
 
  const selectBasketIds = () => {
    const classesIds = basket.map((course) => course?.classes?.id).filter((course) => course !== undefined);
    const lecturesIds = basket.map((course) => course?.lecture?.id).filter((course) => course !== undefined);
    return [...classesIds, ...lecturesIds];
  };
 
  const selectBasketNames = () => basket.map(({ name }) => name);
 
  const selectBasketCourses = () => {
    const basketNames = selectBasketNames();
    return basketNames.reduce((sum, basketName) => {
      const course = courses.find(({ name }) => basketName === name);
      return course === undefined ? sum : [...sum, course];
    }, [] as Array<Course>);
  };
 
  const selectSchedulerEvents = () => {
    return basket.reduce((res, el) => {
      const { name } = el;
      if (el.classes) {
        res.push({ ...el.classes, name });
      }
      if (el.lecture) {
        res.push({ ...el.lecture, name });
      }
      return res;
    }, [] as Array<SchedulerEvent>);
  };
 
  const selectHistorySchedulerEvents = () => {
    return historyBasket.reduce((res, el) => {
      const { name } = el;
      if (el.classes) {
        res.push({ ...el.classes, name });
      }
      if (el.lecture) {
        res.push({ ...el.lecture, name });
      }
      return res;
    }, [] as Array<SchedulerEvent>);
  };
 
 
  const selectBasketCourseGroups = (courseId: number) => {
    const course = basket.find(({ id }) => id === courseId);
    if (course !== undefined) {
      return { lecture: course.lecture, classes: course.classes };
    } else {
      return { lecture: undefined, classes: undefined };
    }
  };
 
  const changeHoveredGroup = (group: Group | null) => setHoveredGroup(group);
 
  const changeDataLoading = (isLoading: boolean) => setIsDataLoading(isLoading);
 
  const addCourseToBasket = (course: Course) => {
    const courseToBasket: Basket = {
      name: course.name,
      id: course.id,
      classes: course.classes !== undefined ? course.classes[0] : undefined,
      lecture: course.lectures !== undefined ? course.lectures[0] : undefined,
    };
    setBasket([...basket, courseToBasket]);
  };
 
  const deleteFromBasket = (id: number) => setBasket(basket.filter((course) => course.id !== id));
 
  const changeStudent = async (studentId: string) => {
    setUserID(studentId);
    setTimeout(() => {
      getNewestStudentTimetable(studentId);
      getStudentTimetablesHistory(studentId);
    }, 100);
  };
 
  const saveBasket = async (userID: string) => {
    const basketIds = selectBasketIds();
    const action = (key: any) => (
      <>
        <StyledCloseIcon
          onClick={() => {
            closeSnackbar(key);
          }}
        ></StyledCloseIcon>
      </>
    );
 
    try {
      await axiosInstance.post(
        `${process.env.REACT_APP_API_URL}/api/v1/commisions/user/${userID}`,
        JSON.stringify(basketIds),
      );
      enqueueSnackbar('Plan został zapisany', {
        variant: 'success',
        action,
      });
    } catch (e) {
      console.log('error: ', e);
      enqueueSnackbar('Zapisywanie planu nie powiodło się', {
        variant: 'error',
        action,
      });
    }
    getStudentTimetablesHistory(userID);
  };
 
  const changeGroupInBasket = (choosenGroup: any, courseId: number) => {
    const basketCourse = basket.filter((course) => course.id === courseId)[0];
    if (choosenGroup.lecture && choosenGroup.classes)
    {
      const prev = choosenGroup.prev==="lecture"?choosenGroup.lecture : choosenGroup.classes
      setBasket(
        basket.map((basket) => (basket.id === basketCourse.id ? { ...basket, lecture: choosenGroup.lecture, classes:choosenGroup.classes } : basket)),
      );
      changeHoveredGroup(prev);
    }    
  };
 
  const restoreGroupInBasket = (restoreGroup: Group, courseId: number) => {
    const basketCourse = basket.filter((course) => course.id === courseId)[0];
    const { type } = restoreGroup;
    if (type === GroupType.CLASS) {
      setBasket(
        basket.map((basket) => (basket.id === basketCourse.id ? { ...basket, classes: restoreGroup } : basket)),
      );
    } else if (type === GroupType.LECTURE) {
      setBasket(
        basket.map((basket) => (basket.id === basketCourse.id ? { ...basket, lecture: restoreGroup } : basket)),
      );
    }
  };
 
  const getNewestTimetable = async () => {
    try {
      const { data } = await axiosInstance.get<Array<Basket> | ''>(
        `${process.env.REACT_APP_API_URL}/api/v1/commisions/user/schedule`,
      );
      const basket = data === '' ? [] : data;
      setBasket(basket);
    } catch (e) {
      console.log(e);
    }
  };
 
  const getNewestStudentTimetable = async (studentId: string) => {
    try {
      const { data } = await axiosInstance.get(
        `${process.env.REACT_APP_API_URL}/api/v1/commisions/user/${studentId}/schedule`,
      );
      const basket = data === '' ? [] : data;
 
      setBasket(basket);
    } catch (e) {
      console.log(e);
    }
  };
 
  const getStudentTimetablesHistory = async (studentId: string) => {
    try {
      const { data } = await axiosInstance.get<Array<TimetableHistory> | []>(
        `${process.env.REACT_APP_API_URL}/api/v1/commisions/user/${studentId}?groups=true`,
      );
      setTimetableHistory(data);
    } catch (e) {
      console.log(e);
    }
  };
 
  const fetchCourses = async () => {
    try {
      const { data: courses } = await axiosInstance.get<Array<Course>>(
        `${process.env.REACT_APP_API_URL}/api/v1/courses/all?groups=true&takenPlaces=true`,
      );
      const sortedCourses = courses.sort((a, b) => (a.name > b.name ? 1 : -1));
      setCourses(sortedCourses);
    } catch (e) {
      console.log(e);
    }
  };
 
  const setHistoryBasketFromHistoryGroups = (groupsIds: Array<number>) => {
    const basket: Array<Basket> = [];
    for (const groupId of groupsIds) {
      for (const course of courses) {
        const { lectures, classes, name, id } = course;
        let basketElement: Basket = { name: name, id: id };
        if (lectures) {
          for (const lecture of lectures) {
            if (groupId === lecture.id) {
              basketElement = { ...basketElement, lecture: lecture };
            }
          }
        }
        if (classes) {
          for (const singleClass of classes) {
            if (groupId === singleClass.id) {
              basketElement = { ...basketElement, classes: singleClass };
            }
          }
        }
        if (basketElement.classes !== undefined || basketElement.lecture !== undefined) {
          basket.push(basketElement);
        }
      }
    }
    setHistoryBasket(basket);
  };
 
  useEffect(() => {
    setIsDataLoading(true);
    setTimeout(() => {
      fetchCourses();
      getNewestTimetable();
      setIsDataLoading(false);
    }, 600);
  }, []);
 
  return (
    <coursesContext.Provider
      value={{
        userID,
        courses,
        basket,
        hoveredGroup,
        timetableHistory,
        isDataLoading,
        historyBasket,
        addCourseToBasket,
        changeHoveredGroup,
        changeGroupInBasket,
        deleteFromBasket,
        restoreGroupInBasket,
        saveBasket,
        selectSchedulerEvents,
        selectHistorySchedulerEvents,
        selectBasketNames,
        selectBasketCourses,
        selectBasketCourseGroups,
        getNewestStudentTimetable,
        changeStudent,
        getStudentTimetablesHistory,
        setHistoryBasketFromHistoryGroups,
        changeDataLoading,
      }}
    >
      {children}
    </coursesContext.Provider>
  );
};