timetable.controller.js 5.96 KB
Newer Older
Kim, Subin's avatar
Kim, Subin committed
1
import { TimeTable, Theater, TheaterType, Reservation } from "../db/index.js";
2
3
4
import sequelize from 'sequelize'
const { Op } = sequelize

5
6
const getAll = async (req, res) => {
    try {
Kim, Subin's avatar
Kim, Subin committed
7
        const { when, movieId } = req.query
8
        const selectDate = new Date(when)
Kim, Subin's avatar
Kim, Subin committed
9
        let findAll = null
10
        const theaterArr = []
11
        findAll = movieId !== "0" ? await TimeTable.findAll({ where: { date: selectDate, movieId: movieId }, attributes: { exclude: ['createdAt', 'updatedAt'] }, order: [["theaterId", "ASC"], ["start_time", "ASC"]], include: [Theater] })
Kim, Subin's avatar
Kim, Subin committed
12
13
14
15
16
17
18
            : await TimeTable.findAll({ where: { date: selectDate }, attributes: { exclude: ['createdAt', 'updatedAt'] }, order: [["theaterId", "ASC"], ["start_time", "ASC"]], include: [Theater] })
        findAll.forEach(async (element) => {
            if (!theaterArr.includes(element.theaterId)) theaterArr.push(element.theaterId)
            if (movieId) {
                const { count } = await Reservation.findAndCountAll({ where: { movieId: movieId, timetableId: element.id } })
                element.dataValues.reservations = count
            }
19
        })
Kim, Subin's avatar
Kim, Subin committed
20
        const findTheater = await Theater.findAll({ where: { id: theaterArr }, attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [TheaterType], order: [['theaterName']] })
21
        findTheater.forEach(el => {
Kim, Subin's avatar
Kim, Subin committed
22
            el.dataValues.theaterTypeName = el.dataValues.theatertype.dataValues.theaterTypeName
23
            const arr = findAll.filter(timetable => {
Kim, Subin's avatar
Kim, Subin committed
24
                if (el.id === timetable.theaterId) return timetable.dataValues
25
26
27
28
29
30
31
32
            })
            el.dataValues.timetable = arr
        })
        return res.json(findTheater)
    } catch (error) {
        return res.status(500).send(error.message || "상영시간표 정보 가져오는 중 에러 발생")
    }
}
한규민's avatar
한규민 committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const getTimeTable = async (req, res, next) => {
    try {
        const reservation = req.reservation;
        const timetableId = reservation.map(movie => movie.timetableId);
        const elements = await Promise.all(
            timetableId.map(async (timetableId) => {
                const time = await TimeTable.findOne({ where: { id: timetableId } })
                const movieData = {
                    timetableId: time.id,
                    date: time.date,
                    start_time: time.start_time,
                    end_time: time.end_time,
                }
                return movieData
            })
        );
        reservation.map(reservation => {
            const timetableId = elements.find(el => reservation.timetableId === el.timetableId);
            reservation.dataValues = {
                ...reservation.dataValues,
                date: timetableId.date,
                start_time: timetableId.start_time,
                end_time: timetableId.end_time,
            }
        });
        req.reservation = reservation;
        next();
    } catch (error) {
        return res.status(500).send(error.message || "상영 시간표 불러오기 실패")
    }
}
64

65
66
const submit = async (req, res) => {
    try {
Kim, Subin's avatar
Kim, Subin committed
67
68
69
70
71
72
73
74
        const { movieId, title, theater, runtime, release_date, date } = req.body
        const result = await Promise.all(
            theater.map(async (theater) => {
                const startTime = getTime(theater.start)
                const endTime = getTime(theater.start, runtime)
                const isTimeTable = await TimeTable.findAll({
                    where: {
                        [Op.and]: [
Kim, Subin's avatar
Kim, Subin committed
75
                            { theaterId: theater.theater },
Kim, Subin's avatar
Kim, Subin committed
76
77
78
79
80
81
82
83
84
85
86
87
88
                            {
                                [Op.or]: [
                                    { [Op.and]: [{ start_time: { [Op.gt]: startTime } }, { end_time: { [Op.lte]: endTime } }] },
                                    { start_time: { [Op.between]: [startTime, endTime] } }
                                ]
                            }
                        ]
                    }
                })
                if (isTimeTable.length !== 0) return "unvalid"
                else return "valid"
            })
        )
89
        result.map(el => {
Kim, Subin's avatar
Kim, Subin committed
90
            if (el !== "valid") throw new Error("유효하지 않은 데이터입니다. 다시 등록해주시길 바랍니다.")
91
        })
Kim, Subin's avatar
Kim, Subin committed
92
93
94
95
96
97
98
        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 = ""
99
100
101
102
103
104
105
                    if ('06:00' <= theater.start && theater.start < '10:00') {
                        partTime = "morning"
                    } else if ('00:00' <= theater.start && theater.start < '06:00') {
                        partTime = "night"
                    } else {
                        partTime = "day"
                    }
Kim, Subin's avatar
Kim, Subin committed
106
                    await TimeTable.create({ theaterId: 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" })
Kim, Subin's avatar
Kim, Subin committed
107
108
                })
            )
109
110
            curDate.setDate(curDate.getDate() + 1)
        } while (curDate <= endDate)
Kim, Subin's avatar
Kim, Subin committed
111
        res.send("success!")
112
113
114
115
116
    } catch (error) {
        return res.status(500).send(error.message || "상영시간표 저장 중 에러 발생")
    }
}

Kim, Subin's avatar
Kim, Subin committed
117
const getTime = (string, runtime = 0) => {
118
119
120
121
122
    const arr = string.split(':')
    const date = new Date(0, 0, 0, Number(arr[0]), Number(arr[1]) + runtime)
    return date
}

123
124
125
const remove = async (req, res) => {
    try {
        const { timeId } = req.params
Kim, Subin's avatar
Kim, Subin committed
126
        const delNum = await TimeTable.destroy({ where: { id: timeId } })
127
128
129
130
131
132
133
        if (delNum) res.json(delNum)
        else throw new Error("해당 정보를 서버에서 삭제하는데 실패했습니다.")
    } catch (error) {
        return res.status(500).send(error.message || "상영시간표 삭제 중 에러 발생")
    }
}

134
export default {
135
    getAll,
한규민's avatar
한규민 committed
136
    getTimeTable,
137
138
    submit,
    remove
139
}