Skip to content

Commit 6d569c2

Browse files
committed
Feature: 날짜 선택기능 구현
- reservation.js를 reservation/index.js로 옮김 - 기능 및 URL은 동일
1 parent 87820af commit 6d569c2

File tree

2 files changed

+142
-52
lines changed

2 files changed

+142
-52
lines changed

src/pages/reservation.js

Lines changed: 0 additions & 52 deletions
This file was deleted.

src/pages/reservation/index.js

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import React, { useEffect, useState } from "react"
2+
import { DayPicker } from "react-day-picker"
3+
import Header from "../../components/header"
4+
import Layout from "../../components/layout"
5+
import NavBar from "../../components/navbar"
6+
7+
import "react-day-picker/style.css";
8+
import * as styles from "../../styles/elements.module.css"
9+
import { navigate } from "gatsby"
10+
import { getUserInfo } from "../../scripts/libraryRequest"
11+
import { useCookies } from "react-cookie"
12+
13+
// 날짜를 YYYYMMDD로 변환
14+
function toYYYYMMDD(date) {
15+
return `${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2,'0')}`
16+
}
17+
18+
export default function Reservation() {
19+
const [selectedDate, setSelectedDate] = useState(new Date())
20+
const [userData, setUserData] = useState({})
21+
22+
function nextMonth(date) {
23+
date.setMonth(date.getMonth() + 1)
24+
return date
25+
}
26+
27+
// 마운트 될때 한 번만 실행
28+
const [cookies, setCookie, removeCookie] = useCookies(['userId'])
29+
useEffect(() => {
30+
console.log('[useEffect]')
31+
if(!cookies.userId) {
32+
navigate('../')
33+
return
34+
}
35+
let userId = cookies['userId']
36+
37+
// 사용가능한 방들의 데이터, 휴관일 데이터, 사용자 정보를 가져옴.
38+
// 이번달과 다음달의 infocount를 요청하기 위해서 Promise.all 사용
39+
const today = new Date()
40+
const nextMonthDate = (() => {
41+
let a = new Date()
42+
a.setMonth(a.getMonth() + 1)
43+
return a
44+
}) ()
45+
Promise.all([getUserInfo(userId, toYYYYMMDD(today)), getUserInfo(userId, toYYYYMMDD(nextMonthDate))]).then(([res1, res2]) => {
46+
if(res1.status === 200 && res1.data.info[0].USER_ID === userId.toString() && res2.status === 200 && res2.data.info[0].USER_ID === userId.toString()) {
47+
let dataTmp = {...res1.data}
48+
dataTmp.infoCount = [dataTmp.infoCount]
49+
dataTmp.infoCount.push(res2.data.infoCount)
50+
console.log('[dataTmp]' + JSON.stringify(dataTmp))
51+
setUserData(dataTmp)
52+
} else {
53+
throw Error('Failed: Cannot update userData')
54+
}
55+
}).catch(() => removeCookie('userId')) // 오류라면 쿠키를 삭제하여 로그인 페이지로 넘김
56+
}, [cookies, removeCookie])
57+
58+
59+
// 선택할 수 없는 날짜 정하는 함수
60+
// date를 받아서 이 날짜가 선택할 수 없으면 true
61+
// date는 한국 시간으로 00시임.
62+
function disabledDateMatcher(date) {
63+
function isSameDate(a, b) {
64+
if(a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getb() === b.getDate()) {
65+
return true
66+
}
67+
else {
68+
return false
69+
}
70+
}
71+
let today = new Date()
72+
today.setHours(0,0,0,0) // 대한민국 시간 기준 자정(GMT+9)
73+
let endDate = new Date(today)
74+
endDate.setMonth(endDate.getMonth() + 1)
75+
76+
// 날짜가 앞으로 한달 이내에 없으면 false return
77+
if(date < today || endDate <= date) {
78+
return true
79+
}
80+
81+
// 날짜가 휴관일이면 true 리턴
82+
if(userData.notAvailableRoomDays) {
83+
for(const data of userData.notAvailableRoomDays) {
84+
// data 예시 테스트 안해봄
85+
// {
86+
// "OFF_DT": 1726498800000,
87+
// "REMARK": "대출휴관일데이터",
88+
// "CREATE_ID": "lib13",
89+
// "CREATE_DT": 1556515709530
90+
// }
91+
if(isSameDate(date, new Date(data.OFF_DT))) {
92+
return true
93+
}
94+
}
95+
}
96+
return false
97+
}
98+
function goNext(e) {
99+
// 날짜를 받아서 다음 페이지로 넘어가기
100+
// 유효성 검사 필요
101+
const infoCountIndex = selectedDate.getMonth() - new Date().getMonth()
102+
console.log(userData)
103+
104+
// 예약 할 수 있는 시간이 얼마나 남았는지 체크
105+
// 여기서 넘겨도 나중에 다시 체크해야함
106+
const remainCount = userData.info[0].FAC_DUR5 - userData.infoCount[infoCountIndex]
107+
if(remainCount<= 0) {
108+
alert('해당 달에는 더이상 예약할 수 없습니다.')
109+
return
110+
}
111+
console.log('[Remain Reserve Count] ' + remainCount)
112+
console.log("Selected Date: " + selectedDate)
113+
navigate('/reservation/select', {state: {selectedDate: selectedDate}})
114+
115+
}
116+
117+
return <>
118+
<Layout>
119+
<Header>
120+
<Header.Title><strong>예약 날짜</strong><br/> 선택해주세요.</Header.Title>
121+
</Header>
122+
<DayPicker
123+
mode="single"
124+
selected={selectedDate}
125+
onSelect={setSelectedDate}
126+
startMonth={new Date()}
127+
endMonth={nextMonth(new Date())}
128+
required
129+
disabled={disabledDateMatcher}
130+
// TODO: 테마에 맞게 스타일 수정 필요
131+
132+
style={{marginTop: "3rem"}}
133+
/>
134+
<div className={styles.buttonContainer}>
135+
<button type="button" onClick={goNext}>
136+
다음
137+
</button>
138+
</div>
139+
</Layout>
140+
<NavBar />
141+
</>
142+
}

0 commit comments

Comments
 (0)