Skip to content

Commit

Permalink
Merge: merge with main
Browse files Browse the repository at this point in the history
  • Loading branch information
ohinhyuk committed Nov 1, 2023
2 parents feaa448 + f5dff0c commit 429f120
Show file tree
Hide file tree
Showing 8 changed files with 306 additions and 9 deletions.
37 changes: 31 additions & 6 deletions src/auth/jwtCookie.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { accessToken } from 'mapbox-gl';
import axiosInstance from 'src/utils/axios';

export function setCookie(name, value, days) {
Expand All @@ -10,17 +11,41 @@ export function setCookie(name, value, days) {
document.cookie = `${name}=${value || ''}${expires}; path=/`;
}

export function getCookie(name) {
const value = document.cookie.match(`(^|;) ?${name}=([^;]*)(;|$)`);
return value ? value[2] : null;
}

export function setServerSideCookie(context) {
let { cookie } = context.req.headers;

cookie = cookie ? cookie.split('=')[1] : '';
cookie = getKeyFromPairString(cookie, 'accessToken');

if (cookie !== '') {
axiosInstance.defaults.headers.common.Authorization = `Bearer ${cookie}`;
}
}

export function getKeyFromPairString(pairString, key) {
const pairArr = pairString ? pairString?.split(';').map((pair) => pair.trim()) : [];

// eslint-disable-next-line no-restricted-syntax
for (const pair of pairArr) {
const [pairKey, pairValue] = pair.split('=').map((c) => c.trim());

if (pairKey === key) {
return pairValue;
}
}

return '';
}

export function getCookie(key) {
const cookies = document.cookie.split(';').map((cookie) => cookie.trim());
console.log(cookies);
// eslint-disable-next-line no-restricted-syntax
for (const cookie of cookies) {
const [cookieKey, cookieValue] = cookie.split('=').map((c) => c.trim());
if (cookieKey === key) {
console.log(cookieValue);
return cookieValue;
}
}
return null;
}
3 changes: 3 additions & 0 deletions src/components/common/Drawer/Drawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,11 @@ export default function MiniDrawer() {
return '/manage/student';
case 7:
return '/manage/user';

case 9:
return '/mileage/result';
case 10:
return '/manage/setting';
case 11:
return '/report';
default:
Expand Down
200 changes: 200 additions & 0 deletions src/components/common/Table/SemesterTable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import * as React from 'react';
import { useState } from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import { Box, Button, TextField } from '@mui/material';
import axiosInstance from 'src/utils/axios';
import {
// formatDateToISOString,
// formatDateToISOStringExceptT,
getCurrentKST,
} from 'src/utils/formatTime';
import { rowSelectionStateInitializer } from '@mui/x-data-grid/internals';

const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: 'darkGray',
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
// hide last border
'&:last-child td, &:last-child th': {
border: 0,
},
}));

interface IGetAllSemesterWithStatus {
count: number;
list: ISemesterWithStatus[];
}

interface IISemesterWithStatus {
id: number;
name: string;
status: string;
applyStart: string;
applyEnd: string;
}

const FlexBox = styled(Box)({
display: 'flex',
gap: '10px',
alignItems: 'center',
});

const headRow = ['번호', '학기 이름', '시작일', '마감일', '신청 상태', '설정'];

export default function SemesterTable({ data }: IGetAllSemesterWithStatus) {
const [isModifying, setIsModifying] = React.useState<boolean[]>(
new Array(data.list.length).fill(false)
);
const [startDate, setStartDate] = React.useState();
const [endDate, setEndDate] = React.useState();

const handleModify = (semesterId: number, rowIdx: number) => {
if (isModifying[rowIdx]) {
modifyApply(semesterId);
}

setStartDate(data.list[rowIdx].applyStart);
setEndDate(data.list[rowIdx].applyEnd);

let newIsModifying = new Array(data.list.length).fill(false);
newIsModifying[rowIdx] = true;

setIsModifying(newIsModifying);
};

const handleCancel = (rowIdx: number) => {
console.log(data.list.length);
setIsModifying(new Array(data.list.length).fill(false));
};

const modifyApply = async (semesterId: number) => {
const modifyData = {
semesterId: semesterId,
applyStart: startDate,
applyEnd: endDate,
};
if (window.confirm('정말 수정하시겠습니까??')) {
axiosInstance.patch('/api/mileage/semesters/period', modifyData).then((res) => {
setIsModifying(new Array(data.list.length).fill(false));

window.location.reload();
});
}
};

const handleEnd = (row) => {
// console.log(formatDateToISOStringExceptT(getCurrentKST()));

if (window.confirm('정말 마감하시겠습니까??')) {
const endData = {
semesterId: row.id,
applyStart: row.applyStart,
applyEnd: getCurrentKST(),
};
console.log(endData);

axiosInstance.patch('/api/mileage/semesters/period', endData).then((res) => {
window.location.reload();
});
}
};
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<StyledTableRow>
{headRow.map((elem, index) => (
<StyledTableCell key={index} align="left">
{elem}
</StyledTableCell>
))}
</StyledTableRow>
</TableHead>
<TableBody>
{data.list.map((row, idx) => (
<StyledTableRow key={row.id}>
<StyledTableCell component="th" scope="row" align="left">
{idx + 1}
</StyledTableCell>
<StyledTableCell align="left">{row.name}</StyledTableCell>
{isModifying[idx] ? (
<StyledTableCell align="left">
<TextField
type="datetime-local"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
</StyledTableCell>
) : (
<StyledTableCell align="left">{row?.applyStart}</StyledTableCell>
)}
{isModifying[idx] ? (
<StyledTableCell align="left">
<TextField
type="datetime-local"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</StyledTableCell>
) : (
<StyledTableCell align="left">{row?.applyEnd}</StyledTableCell>
)}

<StyledTableCell align="left">{row.status}</StyledTableCell>
<StyledTableCell align="left">
{isModifying[idx] ? (
<FlexBox>
<Button type="button" onClick={() => handleCancel(idx)} variant="contained">
취소
</Button>
<Button
type="button"
onClick={() => handleModify(row.id, idx)}
variant="outlined"
>
확인
</Button>
</FlexBox>
) : (
<FlexBox>
{row.status !== '선정 완료' && (
<Button
type="button"
onClick={() => handleModify(row.id, idx)}
variant="contained"
>
수정
</Button>
)}
{row.status === '신청 가능' && (
<Button type="button" onClick={() => handleEnd(row)} variant="outlined">
마감
</Button>
)}
</FlexBox>
)}
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
1 change: 0 additions & 1 deletion src/components/modalForm/CategoryForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ export default function CategoryForm({ handleClose }) {
[DESCRIPTION1]: values[DESCRIPTION1],
[DESCRIPTION2]: values[DESCRIPTION2],
};

switch (modalType) {
case ADDCATEGORY:
axiosInstance
Expand Down
39 changes: 39 additions & 0 deletions src/pages/manage/setting/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import axios from 'axios';
import { setServerSideCookie } from 'src/auth/jwtCookie';
import SemesterTable from 'src/components/common/Table/semesterTable';
import axiosInstance from 'src/utils/axios';

interface IGetAllSemesterWithStatus {
count: number;
list: ISemesterWithStatus[];
}

interface IISemesterWithStatus {
id: number;
name: string;
status: string;
}

export const getServerSideProps: GetServerSideProps<{
fetchData: IGetAllSemesterWithStatus;
}> = async (context) => {
await setServerSideCookie(context);

const res = await axiosInstance.get(`/api/mileage/semesters/admin/status`);
console.log();
// const res = await axios.get('http://localhost:8080/api/mileage/semesters/admin/status');
const fetchData = res.data;
console.log(fetchData);

return { props: { fetchData } };
};

export default function SettingPage({
fetchData,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<>
<SemesterTable data={fetchData} />
</>
);
}
2 changes: 1 addition & 1 deletion src/pages/mileage/view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import axiosInstance from 'src/utils/axios';
import { useEffect } from 'react';
import axios from 'axios';
import { setCookie } from 'src/auth/jwtCookie';
import { getCookie, setCookie } from 'src/auth/jwtCookie';

/**
* @component [마일리지 조회] 게시판
Expand Down
2 changes: 1 addition & 1 deletion src/utils/axios.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import { HOST_API_KEY } from '../config-global';
import { getCookie } from 'src/pages/mileage/view';
import { getCookie } from 'src/auth/jwtCookie';

const axiosInstance = axios.create({ baseURL: HOST_API_KEY });

Expand Down
31 changes: 31 additions & 0 deletions src/utils/formatTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,34 @@ export function fToNow(date) {
})
: '';
}

// export function formatDateToISOString(date) {
// const now = new Date(date).toISOString();
// return now.slice(0, 19);
// }

// export function formatDateToISOStringExceptT(date) {
// const now = new Date(date).toISOString();
// return now.slice(0, 16); // 초를 제거하고 T를 포함한 형식으로 반환
// }

export function getCurrentKST() {
const now = new Date();
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: 'Asia/Seoul',
};

const parts = new Intl.DateTimeFormat('en-US', options).formatToParts(now);
const { year, month, day, hour, minute, second } = Object.fromEntries(
parts.map(({ type, value }) => [type, value])
);

return `${year}-${month}-${day}T${hour}:${minute}:${second}`;
}

0 comments on commit 429f120

Please sign in to comment.