Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/Together42/frontend into…
Browse files Browse the repository at this point in the history
… 141-TokenStorage_refactor
  • Loading branch information
Jiwon-Woo committed Dec 20, 2023
2 parents 8fe342c + c285538 commit e67bdbe
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 96 deletions.
1 change: 0 additions & 1 deletion src/components/Auth/AuthSignUp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ const AuthSignUp = () => {
imageUrl: profileImage,
})
.then((res) => {
console.log('success', res.data);
saveToken(res.data.access_token);
setLoginState(() => {
return {
Expand Down
90 changes: 36 additions & 54 deletions src/components/Rotation/Calendar.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import React from 'react';
import { formatDate } from '@fullcalendar/core';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import { createEventId, getRotationArr } from './event_utils';
import axios from 'axios';
import getAddress from '@globalObj/function/getAddress';
import { getToken } from '@cert/TokenStorage';
import errorAlert from '@globalObj/function/errorAlert';
import '@css/Rotation/Calendar.scss';
import { getDecodedToken } from '@cert/TokenStorage';
import { DAY_OF_SUNDAY } from './rotation_utils';
Expand Down Expand Up @@ -96,7 +91,6 @@ export default class Calendar extends React.Component {
if (isSunday) {
return;
}

const { currentEvents, auth } = this.state;
const title = auth?.id;

Expand Down Expand Up @@ -171,40 +165,25 @@ export default class Calendar extends React.Component {
}
};

/*
todo
1. use apiClient
2. 인자를 들어오는 데이터들을 간소화
*/
requestRotationUpdate = async (info, config, successMsg, errorMsg) => {
try {
const res = await axios(config);
window.alert(successMsg);
} catch (err) {
window.alert(errorMsg);
info.revert();
console.error(err);
}
};

requestAdd = async (info) => {
const dateString: string = info.event.startStr;
const dateParts: string[] = dateString.split('-');
const year: number = parseInt(dateParts[0]);
const month: number = parseInt(dateParts[1]);
const day: number = parseInt(dateParts[2]);

await this.requestRotationUpdate(
info,
{
method: 'post',
url: `${getAddress()}/rotations/`,
data: { attendDate: [day], year: year, month: month },
headers: { Authorization: `Bearer ${getToken()}` },
},
`사서 로테이션 일정<${info.event.startStr}>이 성공적으로 추가되었습니다.`,
`사서 로테이션 일정<${info.event.startStr}>추가에 실패했습니다.`,
);
apiClient
.post(`/rotations/`, {
attendDate: [day],
year: year,
month: month,
})
.then((res) => {
window.alert(`사서 로테이션 일정<${info.event.startStr}>이 성공적으로 추가되었습니다.`);
})
.catch(() => {
window.alert(`사서 로테이션 일정<${info.event.startStr}>추가에 실패했습니다.`);
});
};

requestRemove = async (info) => {
Expand All @@ -214,17 +193,16 @@ export default class Calendar extends React.Component {
const month: number = parseInt(dateParts[1]);
const day: number = parseInt(dateParts[2]);

await this.requestRotationUpdate(
info,
{
method: 'delete',
url: `${getAddress()}/rotations/`,
apiClient
.delete(`/rotations/`, {
data: { day: day, year: year, month: month },
headers: { Authorization: `Bearer ${getToken()}` },
},
`사서 로테이션 일정<${info.event.startStr}>이 성공적으로 제거되었습니다.`,
`사서 로테이션 일정<${info.event.startStr}>제거에 실패했습니다.`,
);
})
.then(() => {
window.alert(`사서 로테이션 일정<${info.event.startStr}>이 성공적으로 제거되었습니다.`);
})
.catch(() => {
window.alert(`사서 로테이션 일정<${info.event.startStr}>제거에 실패했습니다.`);
});
};

requestChange = async (info) => {
Expand All @@ -240,17 +218,21 @@ export default class Calendar extends React.Component {
const newMonth: number = parseInt(newDateParts[1]);
const newDay: number = parseInt(newDateParts[2]);

await this.requestRotationUpdate(
info,
{
method: 'patch',
url: `${getAddress()}/rotations/${info.event.title}`,
data: { attendDate: [oldDay], updateDate: newDay, year: newYear, month: newMonth },
headers: { Authorization: `Bearer ${getToken()}` },
},
`${info.oldEvent.title}의 사서 로테이션 일정<${info.oldEvent.startStr}>이 <${info.event.startStr}>으로 성공적으로 변경되었습니다.`,
`${info.oldEvent.title}의 사서 로테이션 일정<${info.oldEvent.startStr}>을 <${info.event.startStr}>로 변경에 실패했습니다.`,
);
apiClient
.patch(`/rotations/${info.event.title}`, {
attendDate: [oldDay],
updateDate: newDay,
year: newYear,
month: newMonth,
})
.then(() => {
window.alert(
`사서 로테이션 일정<${info.oldEvent.title}>이 <${info.event.startStr}>으로 성공적으로 변경되었습니다.`
);
})
.catch(() => {
window.alert(`사서 로테이션 일정<${info.oldEvent.title}>을 <${info.event.startStr}>로 변경에 실패했습니다.`);
});
};
}

Expand Down
51 changes: 26 additions & 25 deletions src/components/Rotation/Rotation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useNavigate } from 'react-router-dom';
import { getDecodedToken } from '@cert/TokenStorage';
import Calendar, { CalendarTileProperties } from 'react-calendar';
import getAddress from '@globalObj/function/getAddress';
import axios from 'axios';
import { getToken } from '@cert/TokenStorage';
import errorAlert from '@globalObj/function/errorAlert';
import { useSWRConfig } from 'swr';
Expand Down Expand Up @@ -151,16 +150,21 @@ const periodToString = getNextAttendPeriodStrFunction(getRotationApplicationPeri
/**
* Axios 요청
*/
const getAttendLimit = async (intraId: string, currDate: Date) => {
const url = `${getAddress()}/rotations/attendance`;
const headers = { Authorization: 'Bearer ' + getToken() };
const { data } = await axios.get<BackendAttendLimitData>(url, { headers });
const getAttendLimit = async () => {
const data: BackendAttendLimitData = await apiClient
.get(`/rotations/attendance`)
.then((res) => {
return res.data;
})
.catch((err) => {
throw err;
});

const year = data.year;
const month = data.month;
const attendDate = JSON.stringify(
data.attendLimit
.map((day) => `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`)
?.map((day) => `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`)
.join(','),
);

Expand Down Expand Up @@ -263,24 +267,25 @@ const SelectDateBox = ({
*/
const setTileClassName = ({ activeStartDate, date, view }: CalendarTileProperties) => {
const classNames: string[] = [];
const nextMonth = currentDate.getMonth() + 1;
const dDate = date.getDate();
const dMonth = date.getMonth();
if (nextMonth !== dMonth || !(dDate in record)) {
const nextMonth = currentDate.getMonth() + 2 > 12 ? 1 : currentDate.getMonth() + 2;
const _currentDate = date.getDate();
const _currentMonth = date.getMonth() + 1;
if (nextMonth !== _currentMonth) {
classNames.push('disabled');
return classNames;
}
if (!isSubmit) {
classNames.push('selectable');
}
if (isSubmit && record[dDate]) {
if (isSubmit && record[_currentDate]) {
classNames.push('attendLimited');
}
if (!isSubmit && record[dDate]) {
if (!isSubmit && record[_currentDate]) {
classNames.push('selected');
}
return classNames;
};

return (
<div className="rotation--selectDates">
<SelectDateNoticeBox isSubmit={isSubmit} />
Expand Down Expand Up @@ -328,7 +333,7 @@ export const Rotate = () => {
const intraId = getDecodedToken()?.id ?? null;
const isRotationApplicationPeriod = calculateIsRotationApplicationPeriod(currentDate);
const [record, setRecord] = useState(() => ({ ...initialRecord }));
const [isSubmit, setIsSumbit] = useState(false);
const [isSubmit, setIsSubmit] = useState(false);
const [isLoading, setIsLoading] = useState(true); // pageReload 관련하여 추가, 아지 관련 기능 완전 업데이트 X
const { mutate } = useSWRConfig();

Expand Down Expand Up @@ -392,10 +397,10 @@ export const Rotate = () => {
return;
}
if (window.confirm('사서 로테이션 참석 신청하시겠습니까?')) {
await apiClient
.post(`/rotations/`, {
intraId: intraId,
attendDate: createUnavailableDates(record),
const attendDate = createUnavailableDates(record);
apiClient
.post('/rotations/attendance', {
attendLimit: attendDate,
})
.then(() => {
alert('성공적으로 신청되었습니다');
Expand All @@ -421,11 +426,7 @@ export const Rotate = () => {
}
if (window.confirm('사서 로테이션 참석을 취소하시겠습니까?')) {
await apiClient
.delete(`/rotations/`, {
data: {
intraId: intraId,
},
})
.delete(`/rotations/attendance`)
.then(() => {
alert('성공적으로 신청 취소되었습니다');
mutate(`${getAddress()}/rotations/attendance`);
Expand Down Expand Up @@ -463,12 +464,12 @@ export const Rotate = () => {
// }
if (checkTokenAndRedirect(null) && intraId) {
try {
const attendLimitData = await getAttendLimit(intraId, currDate);
const attendLimitData = await getAttendLimit();
const attendLimit = attendLimitData.attendLimit;
setIsSumbit(true);
setIsSubmit(true);
setRecord(updateRecord(initialRecord, attendLimit));
} catch (error) {
errorAlert(error);
setIsSubmit(false);
}
}
setIsLoading(false);
Expand Down
22 changes: 7 additions & 15 deletions src/components/Rotation/event_utils.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import getAddress from '@globalObj/function/getAddress';
import { getDecodedToken } from '@cert/TokenStorage';
import apiClient from '@service/apiClient';
import errorAlert from '@globalObj/function/errorAlert';

let eventGuid = 0;
let todayStr = new Date().toISOString().replace(/T.*$/, ''); // YYYY-MM-DD of today

export function createEventId() {
return String(eventGuid++);
Expand All @@ -21,40 +19,34 @@ function rotatedArrAllInfo(data) {
}));
}

function rotatedArr(data) {
return data.map((el) => ({
title: el.intraId,
start: `${el.year}-${el.month}-${el.day}`,
}));
}

// 일단 다음 달 로테이션만 반환
// DB 내 전체 로테이션 반환
export async function getRotationArr() {
let rotationArr = [];
apiClient
await apiClient
.get(`/rotations/`)
.then((res) => {
const data = res.data;
rotationArr = rotatedArr(data);
rotationArr = rotatedArrAllInfo(data);
})
.catch((err) => {
errorAlert(err);
});
return rotationArr;
}

// month와 year에 해당하는 로테이션 반환
export async function getRotationMonthArr(month, year) {
let rotationArr = [];
apiClient
await apiClient
.get(`/rotations/`, {
params: { month: month, year: year },
})
.then((res) => {
const data = res.data;
rotationArr = rotatedArr(data);
rotationArr = rotatedArrAllInfo(data);
})
.catch((err) => {
errorAlert(err);
});
return rotatedArr;
return rotationArr;
}
1 change: 0 additions & 1 deletion src/service/apiClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ apiClient.interceptors.request.use(
return config;
},
(error: Error) => {
console.log('error : ', error);
Promise.reject(error);
},
);
Expand Down

0 comments on commit e67bdbe

Please sign in to comment.