Commit dd1c9aee authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

Merge branch 'kimpen'

parents 44b5a715 2135143b
......@@ -16,8 +16,8 @@ const getTicketFee = async () => {
return data
}
const getTicketFeeOne = async (theaterType) => {
const { data } = await axios.get(`${baseUrl}/api/info/ticketfee/${theaterType}`)
const getTicketFeeOne = async (theatertypeId) => {
const { data } = await axios.get(`${baseUrl}/api/info/ticketfee/${theatertypeId}`)
return data
}
......@@ -26,8 +26,8 @@ const editTicketFee = async (ticketFeeInfo) => {
return data
}
const removeTicketFee = async (theaterType) => {
const { data } = await axios.delete(`${baseUrl}/api/info/ticketfee?theaterType=${theaterType}`)
const removeTicketFee = async (theatertypeId) => {
const { data } = await axios.delete(`${baseUrl}/api/info/ticketfee?theaterTypeId=${theatertypeId}`)
return data
}
......
......@@ -10,23 +10,24 @@ const getAllfromTM = async () => {
const { data } = await axios.get(`${baseUrl}/api/movie/all`, payload)
return data
}
const getMoviesfromTM = async (category) => {
console.log(category)
const response = await axios.get(`${baseUrl}/api/movie/showmovies/${category}`)
console.log(response.data)
return response.data
}
const getMovieInfofromTM = async (id) => {
const movieId = id
const response = await axios.get(`${TMDBUrl}/${movieId}?api_key=${process.env.REACT_APP_TMDB_API_KEY}&language=ko-KR`)
console.log(response.data)
return response.data
}
const getImagesfromTM = async (id) => {
const movieId = id
const response = await axios.get(`${TMDBUrl}/${movieId}/images?api_key=${process.env.REACT_APP_TMDB_API_KEY}`)
return response.data
}
const getCreditsfromTM = async (id) =>{
const movieId = id
const response = await axios.get(`${TMDBUrl}/${movieId}/credits?api_key=${process.env.REACT_APP_TMDB_API_KEY}`)
......@@ -39,9 +40,14 @@ const getVideosfromTM = async (id) =>{
return response.data.results
}
const getListfromDB = async () => {
const { data } = await axios.get(`${baseUrl}/api/movie`)
return data
}
const submit = async (movieId) => {
const { data } = await axios.post(`${baseUrl}/api/movie/${movieId}`)
console.log("data==", data)
return data
}
const remove = async (movieId) => {
......@@ -66,6 +72,7 @@ const movieApi = {
getImagesfromTM,
getCreditsfromTM,
getVideosfromTM,
getListfromDB,
submit,
remove,
search,
......
......@@ -6,8 +6,8 @@ const getAll = async () => {
return data
}
const getOne = async () => {
const { data } = await axios.get(`${baseUrl}/api/theater`)
const getOne = async (theaterId) => {
const { data } = await axios.get(`${baseUrl}/api/theater/${theaterId}`)
return data
}
......@@ -17,12 +17,12 @@ const getTheaterType = async () => {
}
const sendData = async (theater) => {
const { data } = await axios.put(`${baseUrl}/api/theater/type`, theater)
const { data } = await axios.put(`${baseUrl}/api/theater`, theater)
return data
}
const remove = async () => {
const { data } = await axios.delete(`${baseUrl}/api/theater`)
const remove = async (theaterId) => {
const { data } = await axios.delete(`${baseUrl}/api/theater/${theaterId}`)
return data
}
......
......@@ -4,8 +4,9 @@ import catchErrors from "../../utils/catchErrors.js";
import styles from "./admin.module.scss";
const INIT_THEATER = {
id: 0,
theaterName: "",
theaterType: 0,
theatertypeId: 0,
rows: 1,
columns: 1
}
......@@ -51,22 +52,23 @@ const TheaterEditForm = ({ edit, formRef }) => {
}
return (
<form ref={formRef} onSubmit={handleSubmit}>
<div className="d-flex justify-content-lg-between row row-cols-2 row-cols-lg-4 gx-0 gy-2 gy-lg-0 mb-2 mb-lg-3">
<form ref={formRef} className="mb-5" onSubmit={handleSubmit}>
<div className="d-flex justify-content-lg-between row row-cols-2 row-cols-lg-5 gx-0 gy-2 gy-lg-0 mb-2 mb-lg-3">
<label htmlfor="theaterName" className="col-3 col-lg-auto col-form-label">상영관 이름</label>
<div className="col-9 col-lg-4">
<div className="col-8 col-lg-4">
<input className={`form-control ${styles.shadowNone}`} id="theaterName" name="theaterName" type="text" value={theater.theaterName} onChange={handleChange} />
</div>
<label htmlfor="theaterName" className="col-auto col-form-label mx-2 mx-lg-0"></label>
<label htmlfor="theaterType" className="col-3 col-lg-auto col-form-label text-lg-center">상영관 종류</label>
<div className="col-9 col-lg-5">
<select className={`form-select ${styles.shadowNone} ${styles.selectInput}`} id="theaterType" name="theaterType" onChange={handleChange} aria-label="select theaterType" defaultValue={theater.theaterType}>
<select className={`form-select ${styles.shadowNone} ${styles.selectInput}`} id="theatertypeId" name="theatertypeId" value={theater.theatertypeId} onChange={handleChange} aria-label="select theaterType" defaultValue="0">
{types.length !== 0 ?
types.map((type, index) => {
if (index === 0) return <>
<option value="0" disabled>상영관 종류를 선택해주십시오.</option>
<option value={type.id}>{type.theaterType}</option>
<option value={type.id}>{type.theaterTypeName}</option>
</>
else return <option value={type.id}>{type.theaterType}</option>
else return <option value={type.id}>{type.theaterTypeName}</option>
})
: <option value="0" disabled>서버에 등록된 상영관 종류가 없습니다.</option>}
</select>
......
......@@ -21,10 +21,10 @@ const TheaterTable = ({ setEdit, formRef }) => {
}
}
async function editTheater() {
async function editTheater(theaterId) {
try {
setError("")
const res = await theaterApi.getOne()
const res = await theaterApi.getOne(theaterId)
setEdit({ ...res })
formRef?.current.scrollIntoView({ behavior: "smooth", block: "center" })
} catch (error) {
......@@ -32,10 +32,10 @@ const TheaterTable = ({ setEdit, formRef }) => {
}
}
async function deleteTheater() {
async function deleteTheater(theaterId) {
try {
setError("")
await theaterApi.remove()
await theaterApi.remove(theaterId)
alert("해당 상영관 정보를 성공적으로 삭제했습니다.")
getTheaterList()
} catch (error) {
......@@ -56,13 +56,13 @@ const TheaterTable = ({ setEdit, formRef }) => {
<tbody>
{theaterList.length !== 0 ? theaterList.map(info =>
<tr>
<td>ads</td>
<td>ads</td>
<td>ads</td>
<td>{info.theaterName}</td>
<td>{info.theatertype.theaterTypeName}</td>
<td>{info.rows} {info.columns}<br /> {info.rows*info.columns}</td>
<td>
<div className="d-flex flex-column">
<button type="button" className="btn btn-primary my-1" onClick={() => editTheater()}>수정</button>
<button type="button" className="btn btn-danger my-1" onClick={() => deleteTheater()}>삭제</button>
<button type="button" className="btn btn-primary my-1" onClick={() => editTheater(info.id)}>수정</button>
<button type="button" className="btn btn-danger my-1" onClick={() => deleteTheater(info.id)}>삭제</button>
</div>
</td>
</tr>)
......
......@@ -4,7 +4,8 @@ import catchErrors from "../../utils/catchErrors.js";
import styles from "./admin.module.scss";
const INIT_TICKETFEE = {
theaterType: "",
theatertypeId: 0,
theaterTypeName: "",
weekdays: "",
weekend: "",
morning: "",
......@@ -46,7 +47,7 @@ const TicketEditForm = ({ editFee, formRef }) => {
<div className="d-flex row row-cols-2 mb-2 mb-md-3 gx-0 gy-2 gy-md-0">
<label htmlfor="theaterType" className="col-md-auto col-form-label text-center text-md-start">상영관 종류</label>
<div className="col-md-4 col-lg-3 mx-md-2">
<input className={`form-control ${styles.shadowNone}`} type="text" id="theaterType" name="theaterType" value={ticketFee.theaterType} onChange={handleChange} />
<input className={`form-control ${styles.shadowNone}`} type="text" id="theaterTypeName" name="theaterTypeName" value={ticketFee.theaterTypeName} onChange={handleChange} />
</div>
<label htmlfor="defaultPrice" className="col-md-auto col-form-label text-center text-md-start">기본 가격</label>
<div className="col-md-3 col-lg-2 mx-md-2">
......
......@@ -20,10 +20,10 @@ const TicketFeeTable = ({ setEditFee, formRef }) => {
}
}
async function editRow(theaterType) {
async function editRow(theatertypeId) {
try {
setError("")
const res = await cinemaApi.getTicketFeeOne(theaterType)
const res = await cinemaApi.getTicketFeeOne(theatertypeId)
setEditFee({ ...res })
formRef?.current.scrollIntoView({ behavior: "smooth", block: "center" })
} catch (error) {
......@@ -31,10 +31,10 @@ const TicketFeeTable = ({ setEditFee, formRef }) => {
}
}
async function deleteData(theaterType) {
async function deleteData(theatertypeId) {
try {
setError("")
await cinemaApi.removeTicketFee(theaterType)
await cinemaApi.removeTicketFee(theatertypeId)
alert("해당 관람료 정보를 성공적으로 삭제했습니다.")
getInfo()
} catch (error) {
......@@ -64,7 +64,7 @@ const TicketFeeTable = ({ setEditFee, formRef }) => {
{ticketFee.length !== 0 ? ticketFee.map(info =>
<>
<tr>
<td rowSpan="6" className={`d-block d-md-table-cell ${styles.Row} ${styles.type}`}>{info.theaterType}</td>
<td rowSpan="6" className={`d-block d-md-table-cell ${styles.Row} ${styles.type}`}>{info.theatertype.theaterTypeName}</td>
<td rowSpan="3" className={`d-block d-md-table-cell ${styles.Row} ${styles.moreData}`} data-label="- 청소년 / 성인 / 경로">주중(~)</td>
<td className="d-inline-block d-md-table-cell">조조 (06:00 ~ )</td>
<td className="d-inline-block d-md-table-cell">{priceToString(info.weekdays + info.morning + info.youth + info.defaultPrice)}</td>
......@@ -72,8 +72,8 @@ const TicketFeeTable = ({ setEditFee, formRef }) => {
<td className="d-inline-block d-md-table-cell">{priceToString(info.weekdays + info.morning + info.senior + info.defaultPrice)}</td>
<td rowSpan="6" className="d-none d-md-table-cell">
<div className="d-flex flex-column">
<button type="button" className="btn btn-primary my-1" onClick={() => editRow(info.theaterType)}>수정</button>
<button type="button" className="btn btn-danger my-1" onClick={() => deleteData(info.theaterType)}>삭제</button>
<button type="button" className="btn btn-primary my-1" onClick={() => editRow(info.theatertypeId)}>수정</button>
<button type="button" className="btn btn-danger my-1" onClick={() => deleteData(info.theatertypeId)}>삭제</button>
</div>
</td>
</tr>
......@@ -109,8 +109,8 @@ const TicketFeeTable = ({ setEditFee, formRef }) => {
<td className="d-inline-block d-md-table-cell">{priceToString(info.weekend + info.night + info.senior + info.defaultPrice)}</td>
<td className={`d-block d-md-none ${styles.borderTop}`}>
<div className="d-flex justify-content-end">
<button type="button" className="btn btn-primary" onClick={() => editRow(info.theaterType)}>수정</button>
<button type="button" className="btn btn-danger ms-2" onClick={() => deleteData(info.theaterType)}>삭제</button>
<button type="button" className="btn btn-primary" onClick={() => editRow(info.theatertypeId)}>수정</button>
<button type="button" className="btn btn-danger ms-2" onClick={() => deleteData(info.theatertypeId)}>삭제</button>
</div>
</td>
</tr>
......
const TimeTable = () => {
return (
<>
</>
)
}
export default TimeTable
\ No newline at end of file
import TimeTableEditForm from "./TimeTableEditForm";
import TimeTable from "./TimeTable";
const TimeTableEdit = () => {
return (
<>
<h2 className="border-bottom border-2 text-center pb-2 me-2">현재 상영시간표 정보</h2>
<div>
<TimeTableEditForm />
<TimeTable />
</div>
</>
)
}
......
import { useState, useEffect } from "react";
import movieApi from "../../apis/movie.api.js";
import theaterApi from "../../apis/theater.api.js";
import catchErrors from "../../utils/catchErrors.js";
import styles from "./admin.module.scss";
const INIT_MOVIE = {
movieId: 0,
title: "",
release_date: "",
end_date: "",
theater: [],
times: []
}
const TimeTableEditForm = () => {
const [movieList, setMovieList] = useState([])
const [theaterList, setTheaterList] = useState([])
const [selectId, setSelectId] = useState(0)
const [selectMovie, setSelectMovie] = useState({})
const [selectInfo, setSelectInfo] = useState({ theater: 0, start: "", end: "" })
const [showTimes, setShowTimes] = useState({ list: [] })
const [sendInfo, setSendInfo] = useState(INIT_MOVIE)
const [error, setError] = useState("")
useEffect(() => {
getMoviesfromDB()
getTheater()
}, [])
async function getMoviesfromDB() {
try {
setError("")
const res = await movieApi.getListfromDB()
setMovieList(res)
} catch (error) {
catchErrors(error, setError)
}
}
async function getTheater() {
try {
setError("")
const res = await theaterApi.getAll()
setTheaterList(res)
} catch (error) {
catchErrors(error, setError)
}
}
function addRunTime(start, runTime) {
const startArr = start.split(':')
const add = Number(startArr[1]) + runTime
let hours = Number(startArr[0]) + Math.floor(add / 60)
if (hours <= 9) hours = '0' + hours
if (hours / 24 > 0) hours = '0' + hours % 24
else if (hours <= 9) hours = '0' + hours
let mins = add % 60
if (mins <= 9) mins = '0' + mins
setSelectInfo({ ...selectInfo, "start": start, "end": hours + ':' + mins })
}
function addData() {
const { list } = showTimes
const isSelect = Object.values(selectInfo).every((el) => Boolean(el))
if (isSelect) {
const theater = theaterList.find(theater => theater.theatertypeId === selectInfo.theater)
if (theater) {
const myTime = {
theaterTypeId: selectInfo.theater,
theaterName: theater.theaterName + '관 / ' + theater.theatertype.theaterTypeName,
start: selectInfo.start,
end: selectInfo.end
}
setShowTimes({ list: list.concat(myTime) })
} else alert('선택한 상영관을 찾지 못했습니다. 다시 시도하길 바랍니다.')
} else alert('추가할 데이터의 갯수가 부족합니다. 모든 항목을 입력해주시길 바랍니다.')
setSelectInfo({ ...selectInfo, theater: 0, start: "", end: "" })
}
function delData(index) {
let { list } = showTimes
list = list.splice(index, 1)
setShowTimes({ list: list })
}
async function handleChange(e) {
try {
setError("")
const { name, value } = e.target
if (name === "movieId") {
setSelectId(value)
const res = await movieApi.getMovieInfofromTM(value)
setSelectMovie({ ...res })
setSendInfo({ ...sendInfo, movieId: value, title: res.title, release_date: res.release_date, end_date: "" })
} else if (name === "end_date") {
setSendInfo({ ...sendInfo, [name]: value })
} else if (name === "theater") {
setSelectInfo({ ...selectInfo, [name]: Number(value) })
} else if (name === "start") {
addRunTime(value, selectMovie.runtime)
} else setSelectInfo({ ...selectInfo, [name]: value })
} catch (error) {
catchErrors(error, setError)
}
}
async function handleSubmit(e) {
e.preventDefault()
try {
setError("")
alert("해당 상영시간표 정보 등록이 성공적으로 완료되었습니다.")
window.location.reload()
} catch (error) {
catchErrors(error, setError)
}
}
return (
<form 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">
{movieList.length !== 0 ?
movieList.map((movie, index) => {
if (index === 0) return <>
<option value="0" disabled>영화를 선택해주십시오.</option>
<option value={movie.movieId}>{movie.title}</option>
</>
else return <option value={movie.movieId}>{movie.title}</option>
})
: <option value="0" disabled>서버에 등록된 영화가 없습니다.</option>}
</select>
<div className="col-md-6 mb-3">
<label htmlFor="release_date" className="form-label">상영시작일</label>
<input type="text" className={`form-control ${styles.shadowNone}`} id="release_date" name="release_date" value={selectMovie?.release_date || ''} disabled />
</div>
<div className="col-md-6 mb-3">
<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} />
</div>
<p>시간대 설정</p>
<ul className="list-group list-group-flush">
{showTimes.list.length !== 0 ?
showTimes.list.map((timeInfo, index) => <li className="list-group-item d-flex justify-content-between align-items-center">
{timeInfo.theaterName}&nbsp;&nbsp;&nbsp;{timeInfo.start} ~ {timeInfo.end}
<button type="button" className="btn btn-danger" onClick={() => delData(index)}>삭제</button>
</li>) : <li className="list-group-item text-center">추가된 시간대가 없습니다. 폼을 작성해 시간대를 추가해 주세요.</li>}
</ul>
<div>
<div>
<select className={`form-select mb-3 ${styles.shadowNone} ${styles.selectInput}`} id="theater" name="theater" value={selectInfo.theater} onChange={handleChange} aria-label="select theater" defaultValue="0">
{theaterList.length !== 0 ?
theaterList.map((theater, index) => {
if (index === 0) return <>
<option value="0" disabled>상영관을 선택해주십시오.</option>
<option value={theater.theatertypeId}>{theater.theaterName} / {theater.theatertype.theaterTypeName}</option>
</>
else return <option value={theater.theatertypeId}>{theater.theaterName} / {theater.theatertype.theaterTypeName}</option>
})
: <option value="0" disabled>서버에 등록된 상영관이 없습니다.</option>}
</select>
</div>
<div>
<input type="time" id="start" name="start" value={selectInfo.start} onChange={handleChange} disabled={!selectId || !selectInfo.theater} />
<p>{(selectId && selectInfo.start !== "") ? "~ " + selectInfo.end : ""}</p>
</div>
<div>
<button type="button" className={`btn btn-dark ${styles.customBtn}`} onClick={addData}>추가</button>
</div>
</div>
<div>
<button type="submit" className={`btn btn-dark ${styles.customBtn}`}>등록</button>
</div>
</form>
)
}
export default TimeTableEditForm
\ No newline at end of file
......@@ -3,20 +3,25 @@ import { Movie } from '../db/index.js'
import sequelize from 'sequelize'
const { Op } = sequelize
const getListfromDB = async (req, res) => {
try {
const findAll = await Movie.findAll({ attributes: [ 'movieId', 'title', 'release_date' ] })
res.json(findAll)
} catch (error) {
return res.status(500).send(error.message || "영화 목록 가져오기 중 에러 발생");
}
}
const getMovieByCategory = async (req, res, next, category) => {
try {
console.log(category)
const TMDBmovieIds = []
const movieIds = []
console.log(process.env.TMDB_APP_KEY)
const response = await axios.get(`https://api.themoviedb.org/3/movie/${category}?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR&page=1`)
console.log(response.data)
const TMDBmovies = response.data.results
TMDBmovies.forEach(element => {
TMDBmovieIds.push(element.id)
})
console.log(TMDBmovies)
const responseAfterCompare = await Movie.findAll({
where: {
movieId: {
......@@ -27,7 +32,6 @@ const getMovieByCategory = async (req, res, next, category) => {
responseAfterCompare.forEach(el => {
movieIds.push(el.movieId)
})
console.log('movieIds=', movieIds)
req.movieIds = movieIds
next()
} catch (error) {
......@@ -38,14 +42,12 @@ const getMovieByCategory = async (req, res, next, category) => {
const getMovieById = async (req, res) => {
try {
const movieIds = req.movieIds
console.log(movieIds)
const elements = await Promise.all(
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`)
return movie.data
})
)
console.log(elements)
res.json(elements)
} catch (error) {
return res.status(500).send(error.message || "영화 가져오기 중 에러 발생");
......@@ -107,7 +109,6 @@ const getAllMovie = async (req, res, next) => {
const getMovieList = async(req,res)=>{
try {
const movieList = await Movie.findAll()
// console.log(movieList)
const movieIds=[]
movieList.forEach(el => {
movieIds.push(el.movieId)
......@@ -118,7 +119,6 @@ const getMovieList = async(req,res)=>{
return movie.data
})
)
console.log(elements)
res.json(elements)
} catch (error) {
console.log(error)
......@@ -184,6 +184,7 @@ const findaboutAll = async (req, res, next) => {
}
export default {
getListfromDB,
getMovieByCategory,
getMovieById,
getAllMovie,
......
import { Theater, TicketFee } from "../db/index.js";
import { Theater, TheaterType } from "../db/index.js";
const getTheaterInfo = async (req, res) => {
const { theaterNum } = req.body
......@@ -15,17 +15,27 @@ const getTheaterInfo = async (req, res) => {
}
const getAll = async (req, res) => {
try {
const findList = await Theater.findAll({ include: [{ model: TicketFee, attributes: ["theaterType"] }] })
console.log("Ads==", findList)
const findList = await Theater.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [ TheaterType ], order: [['theaterName']] })
return res.json(findList)
} catch (error) {
return res.status(500).send(error.message || "상영관 정보 가져오는 중 에러 발생")
}
}
const getOne = async (req, res) => {
try {
const { theaterId } = req.params
const find = await Theater.findOne({ where: { id: theaterId } , attributes: { exclude: ['createdAt', 'updatedAt'] } })
if (!find) throw new Error("해당 정보를 찾지 못했습니다.");
return res.json(find)
} catch (error) {
return res.status(500).send(error.message || "상영관 정보 가져오는 중 에러 발생")
}
}
const getTypes = async (req, res) => {
try {
const findTypes = await TicketFee.findAll({ attributes: ['id', 'theaterType'] })
const findTypes = await TheaterType.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] } })
return res.json(findTypes)
} catch (error) {
return res.status(500).send(error.message || "상영관 정보 가져오는 중 에러 발생")
......@@ -34,10 +44,10 @@ const getTypes = async (req, res) => {
const submit = async (req, res) => {
try {
const { id } = req.body
const { id, theatertypeId, theaterName, rows, columns } = req.body
let response = null
if (id) response = await Theater.update({ ...req.body }, { where: { id: id } })
else response = await Theater.create({ ...req.body })
if (id) response = await Theater.update({ theatertypeId, theaterName, rows, columns }, { where: { id: id } })
else response = await Theater.create({ theatertypeId, theaterName, rows, columns })
return res.json(response)
} catch (error) {
return res.status(500).send(error.message || "상영관 정보 저장 중 에러 발생")
......@@ -46,7 +56,10 @@ const submit = async (req, res) => {
const remove = async (req, res) => {
try {
const { theaterId } = req.params
const delNum = await Theater.destroy({ where: { id: theaterId } })
if (delNum) res.json(delNum)
else throw new Error("해당 정보를 서버에서 삭제하는데 실패했습니다.");
} catch (error) {
return res.status(500).send(error.message || "상영관 정보 삭제 중 에러 발생")
}
......@@ -54,6 +67,7 @@ const remove = async (req, res) => {
export default {
getAll,
getOne,
getTypes,
submit,
remove,
......
import { TicketFee } from "../db/index.js";
import { TheaterType, TicketFee } from "../db/index.js";
const getAll = async (req, res) => {
try {
const findAll = await TicketFee.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] } })
const findAll = await TicketFee.findAll({ attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [ TheaterType ] })
return res.json(findAll)
} catch (error) {
return res.status(500).send(error.message || "관람료 정보 가져오는 중 에러 발생")
......@@ -11,8 +11,9 @@ const getAll = async (req, res) => {
const getOne = async (req, res) => {
try {
const { theaterType } = req.params
const find = await TicketFee.findOne({ where: { theaterType: theaterType }, attributes: { exclude: ['createdAt', 'updatedAt'] } })
const { theaterTypeId } = req.params
const find = await TicketFee.findOne({ where: { theatertypeId: theaterTypeId }, attributes: { exclude: ['createdAt', 'updatedAt'] }, include: [ TheaterType ] })
find.dataValues.theaterTypeName = find.dataValues.theatertype.dataValues.theaterTypeName
if (!find) throw new Error("해당 정보를 찾지 못했습니다.");
return res.json(find)
} catch (error) {
......@@ -22,26 +23,29 @@ const getOne = async (req, res) => {
const edit = async (req, res) => {
try {
const { theaterType } = req.body
const { theatertypeId, theaterTypeName, defaultPrice, weekdays, weekend, morning, day, night, youth, adult, senior } = req.body
let response = null
const result = await TicketFee.findOrCreate({
where: { theaterType: theaterType },
defaults: { ...req.body }
const result = await TheaterType.findOrCreate({
where: { id: theatertypeId },
defaults: { theaterTypeName: theaterTypeName }
})
if (!result[1]) {
const updateData = await TicketFee.update({ ...req.body }, { where: { theaterType: theaterType } })
response = updateData
} else response = result[0]
if (result[1]) {
response = await TicketFee.create({ theatertypeId: result[0].id, defaultPrice, weekdays, weekend, morning, day, night, youth, adult, senior })
} else {
await TheaterType.update({ theaterTypeName: theaterTypeName }, { where: { id: theatertypeId } })
response = await TicketFee.update({ defaultPrice, weekdays, weekend, morning, day, night, youth, adult, senior }, { where: { theatertypeId: result[0].id } })
}
return res.json(response)
} catch (error) {
return res.status(500).send(error.message || "관람료 정보 수정 중 에러 발생")
return res.status(500).send(error.message || "관람료 정보 추가 및 수정 중 에러 발생")
}
}
const remove = async (req, res) => {
try {
const { theaterType } = req.query
const delNum = await TicketFee.destroy({ where: { theaterType: theaterType } })
const { theaterTypeId } = req.query
const delNum = await TicketFee.destroy({ where: { theatertypeId: theaterTypeId } })
await TheaterType.destroy({ where: { id: theaterTypeId } })
if (delNum) res.json(delNum)
else throw new Error("해당 정보를 서버에서 삭제하는데 실패했습니다.");
} catch (error) {
......
......@@ -10,7 +10,7 @@ router
.put(cinemaCtrl.edit)
router
.route("/ticketfee/:theaterType")
.route("/ticketfee/:theaterTypeId")
.get(ticketfeeCtrl.getOne)
router
......
......@@ -5,12 +5,14 @@ const router = express.Router();
router
.route("/")
// .post(movieCtrl.comparePopularMovie)
.get(movieCtrl.getListfromDB)
router.route('/showmovies/:category')
router
.route('/showmovies/:category')
.get(movieCtrl.getMovieById)
router.route('/movielist')
router
.route('/movielist')
.get(movieCtrl.getMovieList)
router
......
......@@ -10,10 +10,14 @@ router
.route("/")
.get(theaterCtrl.getAll)
.put(theaterCtrl.submit)
.delete(theaterCtrl.remove)
router
.route("/type")
.get(theaterCtrl.getTypes)
router
.route("/:theaterId")
.get(theaterCtrl.getOne)
.delete(theaterCtrl.remove)
export default router;
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