mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 14:37:13 +01:00
84 lines
1.8 KiB
TypeScript
84 lines
1.8 KiB
TypeScript
import * as mongoose from 'mongoose'
|
|
|
|
import Booker from './booker'
|
|
import Booking from './booking'
|
|
import { BOOKING_STATUS } from './bookingStatus'
|
|
|
|
let connectedPromise
|
|
|
|
function connect() {
|
|
if (connectedPromise) {
|
|
return
|
|
}
|
|
|
|
connectedPromise = mongoose.connect(process.env.MONGO_URI, {
|
|
useNewUrlParser: true,
|
|
useUnifiedTopology: true,
|
|
})
|
|
|
|
return connectedPromise
|
|
}
|
|
|
|
export async function getBookedDays() {
|
|
await connect()
|
|
|
|
const bookings = await Booking.find(
|
|
{
|
|
status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] },
|
|
$or: [
|
|
{ endDate: { $gt: new Date() } },
|
|
{ startDate: { $gt: new Date() } },
|
|
],
|
|
},
|
|
'startDate endDate'
|
|
).exec()
|
|
|
|
return bookings
|
|
.map((booking) => booking.days)
|
|
.flat()
|
|
.sort()
|
|
}
|
|
|
|
export async function getBookingByUUID(uuid) {
|
|
await connect()
|
|
const booking = await Booking.findOne({ uuid })
|
|
return booking.populate('booker').execPopulate()
|
|
}
|
|
|
|
export async function getBookingByUUIDAsJSON(uuid) {
|
|
const booking = await getBookingByUUID(uuid)
|
|
return booking.toJSON()
|
|
}
|
|
|
|
export async function createBooking({
|
|
startDate,
|
|
endDate,
|
|
purpose,
|
|
org,
|
|
destination,
|
|
name,
|
|
email,
|
|
street,
|
|
zip,
|
|
city,
|
|
}) {
|
|
await connect()
|
|
const booking = new Booking({ startDate, endDate, purpose, org, destination })
|
|
const bookedDays = await getBookedDays()
|
|
|
|
if (booking.days.some((day) => bookedDays.includes(day))) {
|
|
throw new mongoose.Error.ValidationError(booking)
|
|
}
|
|
|
|
let booker = await Booker.findOne({ email }).exec()
|
|
if (!booker) {
|
|
booker = new Booker({ name, email, street, zip, city })
|
|
await booker.save()
|
|
}
|
|
|
|
booking.booker = booker._id
|
|
await booking.save()
|
|
await booking.populate('booker').execPopulate()
|
|
return booking.toJSON()
|
|
}
|