Commit 7e4f390c authored by 한규민's avatar 한규민
Browse files

Merge branch 'master' into gyumin

parents 6d08d71f 73dd813f
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
"express": "^4.17.1", "express": "^4.17.1",
"fs": "0.0.1-security", "fs": "0.0.1-security",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"moment": "^2.29.1",
"multer": "^1.4.2", "multer": "^1.4.2",
"nodemailer": "^6.6.3", "nodemailer": "^6.6.3",
"pg": "^8.6.0", "pg": "^8.6.0",
......
...@@ -6,7 +6,7 @@ const getAll = async (req, res) => { ...@@ -6,7 +6,7 @@ const getAll = async (req, res) => {
where: { id: 1 }, where: { id: 1 },
attributes: ['cinemaName', 'transportation', 'parking', 'address', 'moreFeeInfo'] attributes: ['cinemaName', 'transportation', 'parking', 'address', 'moreFeeInfo']
}) })
console.log("INfo====",info) // console.log("INfo====",info)
return res.json(info) return res.json(info)
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "영화관 정보 가져오는 중 에러 발생") return res.status(500).send(error.message || "영화관 정보 가져오는 중 에러 발생")
......
...@@ -4,7 +4,7 @@ const SendMail = async (req, res) => { ...@@ -4,7 +4,7 @@ const SendMail = async (req, res) => {
// const { email, title, cinema, theater, time, name, nickname } = req.body.userData // const { email, title, cinema, theater, time, name, nickname } = req.body.userData
const { email, name, nickname } = req.body.userData const { email, name, nickname } = req.body.userData
const {title, cinema, time, theater} = req.body const {title, cinema, time, theater} = req.body
const selectedSeats = req.body.reservationData.map(el => String.fromCharCode(el.row + 65) + el.col) const selectedSeats = req.body.reservationData.map(el => String.fromCharCode(el.row + 64) + el.col)
const sendMail = async (email, title, cinema, theater, time, name, selectedSeats, nickname) => { const sendMail = async (email, title, cinema, theater, time, name, selectedSeats, nickname) => {
// 메일을 전달해줄 객체 // 메일을 전달해줄 객체
const transporter = nodemailer.createTransport({ const transporter = nodemailer.createTransport({
......
...@@ -36,7 +36,7 @@ const singleTest = async (req, res) => { ...@@ -36,7 +36,7 @@ const singleTest = async (req, res) => {
}, },
}) })
const resp = response.data const resp = response.data
console.log('resp', resp) // console.log('resp', resp)
res.json({ redirect_url: resp.next_redirect_pc_url }) res.json({ redirect_url: resp.next_redirect_pc_url })
} catch (error) { } catch (error) {
console.log(error) console.log(error)
......
...@@ -110,9 +110,10 @@ const getMovieList = async (req, res) => { ...@@ -110,9 +110,10 @@ const getMovieList = async (req, res) => {
where: { "movieId": movieId }, where: { "movieId": movieId },
attributes: ["ticket_sales", "vote_average"] attributes: ["ticket_sales", "vote_average"]
}) })
const totalReservationRate = Movie.sum('ticket_sales') const totalReservationRate = await Movie.findAll({
const rate = await Promise.all(cols.ticket_sales / totalReservationRate * 100) attributes: [[sequelize.fn('SUM', sequelize.col('ticket_sales')), 'totalReservationRate']]
return { ...movie.data, ticket_sales: rate, vote_average: cols.vote_average } });
return { ...movie.data, ticket_sales: cols.ticket_sales, vote_average: cols.vote_average, totalReservationRate: totalReservationRate[0]}
}) })
) )
...@@ -186,7 +187,14 @@ const findonlyTitle = async (req, res) => { ...@@ -186,7 +187,14 @@ const findonlyTitle = async (req, res) => {
const elements = await Promise.all( const elements = await Promise.all(
movieIds.map(async (movieId) => { movieIds.map(async (movieId) => {
const movie = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`) const movie = await axios.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR`)
return movie.data const cols = await Movie.findOne({
where: { "movieId": movieId },
attributes: ["ticket_sales", "vote_average"]
})
const totalReservationRate = await Movie.findAll({
attributes: [[sequelize.fn('SUM', sequelize.col('ticket_sales')), 'totalReservationRate']]
});
return { ...movie.data, ticket_sales: cols.ticket_sales, vote_average: cols.vote_average, totalReservationRate: totalReservationRate[0]}
}) })
) )
return res.json({ count: movieIds.length, results: elements }) return res.json({ count: movieIds.length, results: elements })
......
...@@ -49,7 +49,7 @@ const findOneReservation = async (req, res, next) => { ...@@ -49,7 +49,7 @@ const findOneReservation = async (req, res, next) => {
} }
} }
const saveReservation = async (req, res) => { const saveReservation = async (req, res) => {
const { movieId, selectedTheater, timetable, payment, user, userType } = req.body const { movieId, selectedTheater, timetable, payment, user, userType, totalFee } = req.body
const rows = req.body.selectedSeats.map(el => el.split('-')[0]) const rows = req.body.selectedSeats.map(el => el.split('-')[0])
const cols = req.body.selectedSeats.map(el => el.split('-')[1]) const cols = req.body.selectedSeats.map(el => el.split('-')[1])
try { try {
...@@ -62,7 +62,8 @@ const saveReservation = async (req, res) => { ...@@ -62,7 +62,8 @@ const saveReservation = async (req, res) => {
row: rows[index], row: rows[index],
col: cols[index], col: cols[index],
timetableId: timetable, timetableId: timetable,
payment: payment payment: payment,
totalFee: totalFee
}) })
} }
const movie = await Movie.findOne({ const movie = await Movie.findOne({
......
import { TimeTable } from "../db/index.js"; import { TimeTable, Theater, TheaterType } from "../db/index.js";
import moment from 'moment';
import sequelize from 'sequelize' import sequelize from 'sequelize'
const { Op } = sequelize const { Op } = sequelize
const getAll = async (req, res) => {
try {
const { when } = req.query
const selectDate = new Date(when)
const theaterArr = []
const findAll = await TimeTable.findAll({ where: { date: selectDate }, attributes: { exclude: ['createdAt', 'updatedAt'] }, order: [["theater", "ASC"], ["start_time", "ASC"]] })
findAll.forEach(element => {
if (!theaterArr.includes(element.theater)) theaterArr.push(element.theater)
})
const findTheater = await Theater.findAll({ where: { id: theaterArr }, attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [TheaterType], order: [['theaterName']] })
findTheater.forEach(el => {
const arr = findAll.filter(timetable => {
if (el.id === timetable.theater) return timetable.dataValues
})
el.dataValues.timetable = arr
})
return res.json(findTheater)
} catch (error) {
return res.status(500).send(error.message || "상영시간표 정보 가져오는 중 에러 발생")
}
}
const submit = async (req, res) => { const submit = async (req, res) => {
try { try {
console.log("req.body==", req.body) const { movieId, title, theater, runtime, release_date, date } = req.body
const { theater, runtime } = req.body const result = await Promise.all(
const result = theater.filter(async (theater) => { theater.map(async (theater) => {
const startDate = getDate(theater.start) const startTime = getTime(theater.start)
const endDate = getDate(theater.start, runtime) const endTime = getTime(theater.start, runtime)
// const isTimeTable = await TimeTable.findAll({ const isTimeTable = await TimeTable.findAll({
// where: { where: {
// [Op.and]: [ [Op.and]: [
// { theater: theater.theater }, { theater: theater.theater },
// { {
// [Op.and]: [ [Op.or]: [
// { start_date: { [Op.lte]: endDate } }, { [Op.and]: [{ start_time: { [Op.gt]: startTime } }, { end_time: { [Op.lte]: endTime } }] },
// { end_date: { [Op.gte]: startDate } } { start_time: { [Op.between]: [startTime, endTime] } }
// ] ]
// } }
// ] ]
// } }
// }) })
// [Op.or]: [{ [Op.and]: [{ start_date: { [Op.gt]: startDate } }, { start_date: { [Op.gt]: endDate } }] }, if (isTimeTable.length !== 0) return "unvalid"
// { [Op.and]: [{ end_date: { [Op.lt]: startDate } }, { end_date: { [Op.lt]: endDate } }] }] else return "valid"
console.log("isTimeTable==", isTimeTable) })
return isTimeTable )
result.map(el => {
if (el !== "valid") throw new Error("유효하지 않은 데이터입니다. 다시 등록해주시길 바랍니다.")
}) })
console.log("result==", result) let curDate = new Date(release_date)
const endDate = new Date(date)
do {
let day = curDate.getDay()
await Promise.all(
theater.map(async (theater) => {
let partTime = ""
if ('06:00' <= theater.start && theater.start < '10:00') partTime = "morning"
else if ('00:00' <= theater.start < '06:00') partTime = "night"
else partTime = "day"
await TimeTable.create({ theater: theater.theater, movieId, title, release_date, date: curDate, start_time: getTime(theater.start), end_time: getTime(theater.start, runtime), partTime: partTime, week: (day === 0 || day === 6) ? "weekend" : "weekdays" })
})
)
curDate.setDate(curDate.getDate() + 1)
} while (curDate <= endDate)
res.send("success!")
} catch (error) { } catch (error) {
return res.status(500).send(error.message || "상영시간표 저장 중 에러 발생") return res.status(500).send(error.message || "상영시간표 저장 중 에러 발생")
} }
} }
const getDate = (string, runtime = 0) => { const getTime = (string, runtime = 0) => {
const arr = string.split(':') const arr = string.split(':')
const date = new Date(0, 0, 0, Number(arr[0]), Number(arr[1]) + runtime) const date = new Date(0, 0, 0, Number(arr[0]), Number(arr[1]) + runtime)
// console.log("custom==", date.toString())
return date return date
} }
const remove = async (req, res) => {
try {
const { timeId } = req.params
const delNum = await TimeTable.destroy({ where: { id: timeId } })
if (delNum) res.json(delNum)
else throw new Error("해당 정보를 서버에서 삭제하는데 실패했습니다.")
} catch (error) {
return res.status(500).send(error.message || "상영시간표 삭제 중 에러 발생")
}
}
export default { export default {
submit getAll,
submit,
remove
} }
\ No newline at end of file
...@@ -447,13 +447,13 @@ const modifyUser = async (req, res) => { ...@@ -447,13 +447,13 @@ const modifyUser = async (req, res) => {
const getUserInfo = async (req, res) => { const getUserInfo = async (req, res) => {
const { id } = req.body const { id } = req.body
console.log(id) // console.log(id)
try { try {
const userInfo = await User.findOne({ const userInfo = await User.findOne({
where: { id: id }, where: { id: id },
attributes: ["id", "userId", "email", "nickname", "birth", "phoneNumber"] attributes: ["id", "userId", "email", "nickname", "birth", "phoneNumber"]
}) })
console.log(userInfo) // console.log(userInfo)
res.json(userInfo) res.json(userInfo)
} catch (error) { } catch (error) {
res.status(500).send("회원정보 불러오기 실패"); res.status(500).send("회원정보 불러오기 실패");
......
...@@ -10,7 +10,7 @@ dotenv.config({ ...@@ -10,7 +10,7 @@ dotenv.config({
}); });
sequelize sequelize
.sync({ force: false }) .sync({ force: false})
.then(async () => { .then(async () => {
await Promise.all( await Promise.all(
Object.keys(ROLE_NAME).map((name) => { Object.keys(ROLE_NAME).map((name) => {
......
...@@ -34,6 +34,9 @@ const ReservationModel = (sequelize) => { ...@@ -34,6 +34,9 @@ const ReservationModel = (sequelize) => {
}, },
payment:{ payment:{
type: DataTypes.STRING, type: DataTypes.STRING,
},
totalFee:{
type: DataTypes.INTEGER,
} }
}, },
{ {
......
...@@ -20,23 +20,26 @@ const TimeTableModel = (sequelize) => { ...@@ -20,23 +20,26 @@ 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
}, },
start_date: { date: {
type: DataTypes.DATE,
},
start_time: {
type: DataTypes.DATE, type: DataTypes.DATE,
defaultValue: new Date(0) defaultValue: new Date(0)
}, },
end_date: { end_time: {
type: DataTypes.DATE, type: DataTypes.DATE,
defaultValue: new Date(0) defaultValue: new Date(0)
}, },
time: { partTime: {
type: DataTypes.TIME, type: DataTypes.STRING,
}, },
week: {
type: DataTypes.STRING
}
}, },
{ {
// timestamps: true, // timestamps: true,
......
...@@ -5,6 +5,11 @@ const router = express.Router(); ...@@ -5,6 +5,11 @@ const router = express.Router();
router router
.route("/") .route("/")
.get(timetableCtrl.getAll)
.post(timetableCtrl.submit) .post(timetableCtrl.submit)
router
.route("/:timeId")
.delete(timetableCtrl.remove)
export default router; 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