Commit 992699ae authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

Merge branch 'kimpen'

parents 1abc13d9 ced462de
import axios from "axios";
import { baseUrl } from "../utils/baseUrl.js";
const submit = async (sendData) => {
const { data } = await axios.post(`${baseUrl}/api/timetable`, sendData)
return data
}
const timetableApi = {
submit
}
export default timetableApi
\ No newline at end of file
...@@ -48,6 +48,7 @@ const TheaterEditForm = ({ edit, formRef }) => { ...@@ -48,6 +48,7 @@ const TheaterEditForm = ({ edit, formRef }) => {
window.location.reload() window.location.reload()
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
setTheater({ ...theater, ...INIT_THEATER })
} }
} }
......
const TimeTable = () => { const TimeTable = () => {
return ( return (
<> <div className="col-6">
</> </div>
) )
} }
......
...@@ -4,11 +4,11 @@ import TimeTable from "./TimeTable"; ...@@ -4,11 +4,11 @@ import TimeTable from "./TimeTable";
const TimeTableEdit = () => { const TimeTableEdit = () => {
return ( return (
<> <>
<h2 className="border-bottom border-2 text-center pb-2 me-2">현재 상영시간표 정보</h2> <h2 className="border-bottom border-2 text-center pb-2 me-2">현재 상영시간표 정보</h2>
<div> <div className="d-flex">
<TimeTableEditForm /> <TimeTableEditForm />
<TimeTable /> <TimeTable />
</div> </div>
</> </>
) )
} }
......
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import movieApi from "../../apis/movie.api.js"; import movieApi from "../../apis/movie.api.js";
import theaterApi from "../../apis/theater.api.js"; import theaterApi from "../../apis/theater.api.js";
import timetableApi from "../../apis/timetable.api.js";
import catchErrors from "../../utils/catchErrors.js"; import catchErrors from "../../utils/catchErrors.js";
import styles from "./admin.module.scss"; import styles from "./admin.module.scss";
const INIT_MOVIE = { const INIT_INFO = {
movieId: 0, theater: 0,
title: "", start: "",
release_date: "", end: ""
end_date: "",
theater: [],
times: []
} }
const TimeTableEditForm = () => { const TimeTableEditForm = () => {
...@@ -18,9 +16,9 @@ const TimeTableEditForm = () => { ...@@ -18,9 +16,9 @@ const TimeTableEditForm = () => {
const [theaterList, setTheaterList] = useState([]) const [theaterList, setTheaterList] = useState([])
const [selectId, setSelectId] = useState(0) const [selectId, setSelectId] = useState(0)
const [selectMovie, setSelectMovie] = useState({}) const [selectMovie, setSelectMovie] = useState({})
const [selectInfo, setSelectInfo] = useState({ theater: 0, start: "", end: "" }) const [info, setInfo] = useState({ end_date: "" })
const [selectInfo, setSelectInfo] = useState(INIT_INFO)
const [showTimes, setShowTimes] = useState({ list: [] }) const [showTimes, setShowTimes] = useState({ list: [] })
const [sendInfo, setSendInfo] = useState(INIT_MOVIE)
const [error, setError] = useState("") const [error, setError] = useState("")
useEffect(() => { useEffect(() => {
...@@ -28,6 +26,11 @@ const TimeTableEditForm = () => { ...@@ -28,6 +26,11 @@ const TimeTableEditForm = () => {
getTheater() getTheater()
}, []) }, [])
useEffect(() => {
setSelectInfo({ ...selectInfo, ...INIT_INFO })
setShowTimes({ list: [] })
}, [selectId])
async function getMoviesfromDB() { async function getMoviesfromDB() {
try { try {
setError("") setError("")
...@@ -48,17 +51,23 @@ const TimeTableEditForm = () => { ...@@ -48,17 +51,23 @@ const TimeTableEditForm = () => {
} }
} }
function getDate(string) {
const arr = string.split(':')
const date = new Date(0, 0, 0, Number(arr[0]), Number(arr[1]))
return date
}
function addRunTime(start, runTime) { function addRunTime(start, runTime) {
const startArr = start.split(':') const startArr = start.split(':')
const add = Number(startArr[1]) + runTime const add = Number(startArr[1]) + runTime
let hours = Number(startArr[0]) + Math.floor(add / 60) let hours = Number(startArr[0]) + Math.floor(add / 60)
if (hours <= 9) hours = '0' + hours if (Math.floor(hours / 24) > 0) hours = '0' + hours % 24
if (hours / 24 > 0) hours = '0' + hours % 24
else if (hours <= 9) hours = '0' + hours else if (hours <= 9) hours = '0' + hours
let mins = add % 60 let mins = add % 60
if (mins <= 9) mins = '0' + mins if (mins <= 9) mins = '0' + mins
setSelectInfo({ ...selectInfo, "start": start, "end": hours + ':' + mins }) setSelectInfo({ ...selectInfo, "start": start, "end": hours + ':' + mins })
} }
...@@ -66,23 +75,27 @@ const TimeTableEditForm = () => { ...@@ -66,23 +75,27 @@ const TimeTableEditForm = () => {
const { list } = showTimes const { list } = showTimes
const isSelect = Object.values(selectInfo).every((el) => Boolean(el)) const isSelect = Object.values(selectInfo).every((el) => Boolean(el))
if (isSelect) { if (isSelect) {
const theater = theaterList.find(theater => theater.theatertypeId === selectInfo.theater) const isTime = list.find(el => el.theaterTypeId === selectInfo.theater && (getDate(el.start) <= getDate(selectInfo.end) && getDate(el.end) >= getDate(selectInfo.start)))
if (theater) { if (isTime) alert('이미 추가한 상영시간대입니다. 다른 시간대를 골라주시기 바랍니다.')
const myTime = { else {
theaterTypeId: selectInfo.theater, const theater = theaterList.find(theater => theater.theatertypeId === selectInfo.theater)
theaterName: theater.theaterName + '관 / ' + theater.theatertype.theaterTypeName, if (theater) {
start: selectInfo.start, const myTime = {
end: selectInfo.end theaterTypeId: selectInfo.theater,
} theaterName: theater.theaterName + '관 / ' + theater.theatertype.theaterTypeName,
setShowTimes({ list: list.concat(myTime) }) start: selectInfo.start,
} else alert('선택한 상영관을 찾지 못했습니다. 다시 시도하길 바랍니다.') end: selectInfo.end
}
setShowTimes({ list: list.concat(myTime) })
} else alert('선택한 상영관을 찾지 못했습니다. 다시 시도하길 바랍니다.')
}
} else alert('추가할 데이터의 갯수가 부족합니다. 모든 항목을 입력해주시길 바랍니다.') } else alert('추가할 데이터의 갯수가 부족합니다. 모든 항목을 입력해주시길 바랍니다.')
setSelectInfo({ ...selectInfo, theater: 0, start: "", end: "" }) setSelectInfo({ ...selectInfo, ...INIT_INFO })
} }
function delData(index) { function delData(index) {
let { list } = showTimes let { list } = showTimes
list = list.splice(index, 1) list.splice(index, 1)
setShowTimes({ list: list }) setShowTimes({ list: list })
} }
...@@ -94,9 +107,9 @@ const TimeTableEditForm = () => { ...@@ -94,9 +107,9 @@ const TimeTableEditForm = () => {
setSelectId(value) setSelectId(value)
const res = await movieApi.getMovieInfofromTM(value) const res = await movieApi.getMovieInfofromTM(value)
setSelectMovie({ ...res }) setSelectMovie({ ...res })
setSendInfo({ ...sendInfo, movieId: value, title: res.title, release_date: res.release_date, end_date: "" }) setInfo({ ...info, end_date: "" })
} else if (name === "end_date") { } else if (name === "end_date") {
setSendInfo({ ...sendInfo, [name]: value }) setInfo({ ...info, [name]: value })
} else if (name === "theater") { } else if (name === "theater") {
setSelectInfo({ ...selectInfo, [name]: Number(value) }) setSelectInfo({ ...selectInfo, [name]: Number(value) })
} else if (name === "start") { } else if (name === "start") {
...@@ -105,13 +118,25 @@ const TimeTableEditForm = () => { ...@@ -105,13 +118,25 @@ const TimeTableEditForm = () => {
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
} }
async function handleSubmit(e) { async function handleSubmit(e) {
e.preventDefault() e.preventDefault()
const timeArr = []
try { try {
setError("") setError("")
showTimes.list.map(time => {
timeArr.push({ theater: time.theaterTypeId, start: time.start, end: time.end })
})
const sendData = {
movieId: selectMovie.id,
title: selectMovie.title,
release_date: selectMovie.release_date,
runtime: selectMovie.runtime,
theater: timeArr,
date: info.end_date
}
await timetableApi.submit(sendData)
alert("해당 상영시간표 정보 등록이 성공적으로 완료되었습니다.") alert("해당 상영시간표 정보 등록이 성공적으로 완료되었습니다.")
window.location.reload() window.location.reload()
} catch (error) { } catch (error) {
...@@ -120,8 +145,7 @@ const TimeTableEditForm = () => { ...@@ -120,8 +145,7 @@ const TimeTableEditForm = () => {
} }
return ( return (
<form onSubmit={handleSubmit}> <form className="col-6" onSubmit={handleSubmit}>
{console.log("select==", showTimes)}
<select className={`form-select mb-3 ${styles.shadowNone} ${styles.selectInput}`} id="movieId" name="movieId" value={selectId} onChange={handleChange} aria-label="select movie" defaultValue="0"> <select className={`form-select mb-3 ${styles.shadowNone} ${styles.selectInput}`} id="movieId" name="movieId" value={selectId} onChange={handleChange} aria-label="select movie" defaultValue="0">
{movieList.length !== 0 ? {movieList.length !== 0 ?
movieList.map((movie, index) => { movieList.map((movie, index) => {
...@@ -139,7 +163,7 @@ const TimeTableEditForm = () => { ...@@ -139,7 +163,7 @@ const TimeTableEditForm = () => {
</div> </div>
<div className="col-md-6 mb-3"> <div className="col-md-6 mb-3">
<label htmlFor="end_date" className="form-label">상영종료일</label> <label htmlFor="end_date" className="form-label">상영종료일</label>
<input type="date" className={`form-control ${styles.shadowNone}`} id="end_date" name="end_date" value={sendInfo.end_date} min={sendInfo.release_date} onChange={handleChange} /> <input type="date" className={`form-control ${styles.shadowNone}`} id="end_date" name="end_date" value={info.end_date} min={selectMovie.release_date} onChange={handleChange} />
</div> </div>
<p>시간대 설정</p> <p>시간대 설정</p>
<ul className="list-group list-group-flush"> <ul className="list-group list-group-flush">
......
...@@ -15,7 +15,7 @@ const getTheaterInfo = async (req, res) => { ...@@ -15,7 +15,7 @@ const getTheaterInfo = async (req, res) => {
} }
const getAll = async (req, res) => { const getAll = async (req, res) => {
try { try {
const findList = await Theater.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [ TheaterType ], order: [['theaterName']] }) const findList = await Theater.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [TheaterType], order: [['theaterName']] })
return res.json(findList) return res.json(findList)
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "상영관 정보 가져오는 중 에러 발생") return res.status(500).send(error.message || "상영관 정보 가져오는 중 에러 발생")
...@@ -25,7 +25,7 @@ const getAll = async (req, res) => { ...@@ -25,7 +25,7 @@ const getAll = async (req, res) => {
const getOne = async (req, res) => { const getOne = async (req, res) => {
try { try {
const { theaterId } = req.params const { theaterId } = req.params
const find = await Theater.findOne({ where: { id: theaterId } , attributes: { exclude: ['createdAt', 'updatedAt'] } }) const find = await Theater.findOne({ where: { id: theaterId }, attributes: { exclude: ['createdAt', 'updatedAt'] } })
if (!find) throw new Error("해당 정보를 찾지 못했습니다."); if (!find) throw new Error("해당 정보를 찾지 못했습니다.");
return res.json(find) return res.json(find)
} catch (error) { } catch (error) {
...@@ -47,7 +47,14 @@ const submit = async (req, res) => { ...@@ -47,7 +47,14 @@ const submit = async (req, res) => {
const { id, theatertypeId, theaterName, rows, columns } = req.body const { id, theatertypeId, theaterName, rows, columns } = req.body
let response = null let response = null
if (id) response = await Theater.update({ theatertypeId, theaterName, rows, columns }, { where: { id: id } }) if (id) response = await Theater.update({ theatertypeId, theaterName, rows, columns }, { where: { id: id } })
else response = await Theater.create({ theatertypeId, theaterName, rows, columns }) else {
const result = await Theater.findOrCreate({
where: { theaterName: theaterName },
defaults: { theatertypeId, theaterName, rows, columns }
})
if (!result[1]) throw new Error("이미 존재하는 이름의 상영관입니다. 다시 등록해주세요.");
else response = result[0]
}
return res.json(response) return res.json(response)
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "상영관 정보 저장 중 에러 발생") return res.status(500).send(error.message || "상영관 정보 저장 중 에러 발생")
......
import { TimeTable } from "../db/index.js";
import sequelize from 'sequelize'
const { Op } = sequelize
const submit = async (req, res) => {
try {
console.log("req.body==", req.body)
const { theater, runtime } = req.body
const result = theater.filter(async (theater) => {
const startDate = getDate(theater.start)
const endDate = getDate(theater.start, runtime)
// const isTimeTable = await TimeTable.findAll({
// where: {
// [Op.and]: [
// { theater: theater.theater },
// {
// [Op.and]: [
// { start_date: { [Op.lte]: endDate } },
// { end_date: { [Op.gte]: startDate } }
// ]
// }
// ]
// }
// })
// [Op.or]: [{ [Op.and]: [{ start_date: { [Op.gt]: startDate } }, { start_date: { [Op.gt]: endDate } }] },
// { [Op.and]: [{ end_date: { [Op.lt]: startDate } }, { end_date: { [Op.lt]: endDate } }] }]
console.log("isTimeTable==", isTimeTable)
return isTimeTable
})
console.log("result==", result)
} catch (error) {
return res.status(500).send(error.message || "상영시간표 저장 중 에러 발생")
}
}
const getDate = (string, runtime = 0) => {
const arr = string.split(':')
const date = new Date(0, 0, 0, Number(arr[0]), Number(arr[1]) + runtime)
// console.log("custom==", date.toString())
return date
}
export default {
submit
}
\ No newline at end of file
...@@ -41,7 +41,7 @@ const Guest = GuestModel(sequelize) ...@@ -41,7 +41,7 @@ const Guest = GuestModel(sequelize)
User.belongsTo(Role); User.belongsTo(Role);
Role.hasOne(User); Role.hasOne(User);
Theater.belongsTo(TheaterType); Theater.belongsTo(TheaterType, { onDelete: 'CASCADE' });
TicketFee.belongsTo(TheaterType, { onDelete: 'CASCADE' }); TicketFee.belongsTo(TheaterType, { onDelete: 'CASCADE' });
......
...@@ -20,11 +20,19 @@ const TimeTableModel = (sequelize) => { ...@@ -20,11 +20,19 @@ const TimeTableModel = (sequelize) => {
title: { title: {
type: DataTypes.STRING, type: DataTypes.STRING,
}, },
runtime: {
type: DataTypes.INTEGER,
},
release_date: { release_date: {
type: DataTypes.STRING type: DataTypes.STRING
}, },
date: { start_date: {
type: DataTypes.STRING, type: DataTypes.DATE,
defaultValue: new Date(0)
},
end_date: {
type: DataTypes.DATE,
defaultValue: new Date(0)
}, },
time: { time: {
type: DataTypes.TIME, type: DataTypes.TIME,
......
import express from "express"; import express from "express";
import userRouter from './user.route.js' import userRouter from './user.route.js'
import movieRouter from './movie.route.js' import movieRouter from './movie.route.js'
import theaterRouter from "./theater.route.js";
import timetableRouter from "./timetable.route.js";
import cinemaRouter from "./cinema.route.js"; import cinemaRouter from "./cinema.route.js";
import kakaopayRouter from "./kakaopay.route.js"; import kakaopayRouter from "./kakaopay.route.js";
import emailRouter from './email.route.js' import emailRouter from './email.route.js'
...@@ -16,5 +18,6 @@ router.use('/email',emailRouter) ...@@ -16,5 +18,6 @@ router.use('/email',emailRouter)
router.use('/info', cinemaRouter) router.use('/info', cinemaRouter)
router.use('/theater', theaterRouter) router.use('/theater', theaterRouter)
router.use('/reservation', reservationRouter) router.use('/reservation', reservationRouter)
router.use('/timetable', timetableRouter)
export default router; export default router;
\ No newline at end of file
import express from "express";
import timetableCtrl from "../controllers/timetable.controller.js";
const router = express.Router();
router
.route("/")
.post(timetableCtrl.submit)
export default router;
\ No newline at end of file
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