Files
pfadi-bussle/db/booking.ts
2020-10-07 22:46:13 +02:00

101 lines
2.4 KiB
TypeScript

import * as mongoose from 'mongoose'
import { v4 as uuidv4 } from 'uuid'
import { dateFormatBackend, getDays } from '../helpers/date'
import { BillDocument } from './bill'
import { BookerDocument } from './booker'
import { BOOKING_STATUS } from './enums'
export interface BookingDocument
extends mongoose.Document,
mongoose.SchemaTimestampsConfig {
uuid: string
booker: BookerDocument
bill: BillDocument
startDate: Date
endDate: Date
status: BOOKING_STATUS
purpose?: string
org?: string
destination?: string
days?: string[]
}
export interface BookingModel extends mongoose.Model<BookingDocument> {
findBookedDays(): Promise<string[]>
}
const BookingSchema = new mongoose.Schema<BookingDocument>(
{
// need a seperate uuid to be able to target a booking anonimously
uuid: {
type: String,
default: uuidv4,
index: true,
},
booker: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Booker',
required: true,
},
bill: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Bill',
required: false,
},
startDate: {
type: Date,
required: true,
get: dateFormatBackend,
min: new Date(),
},
endDate: {
type: Date,
required: false,
get: dateFormatBackend,
min: new Date(),
},
status: {
type: String,
enum: Object.values(BOOKING_STATUS),
required: true,
default: 'requested',
},
purpose: { type: String, required: false },
org: { type: String, required: false },
destination: { type: String, required: false },
},
{
timestamps: true,
toJSON: { virtuals: true, getters: true },
toObject: { virtuals: true, getters: true },
}
)
BookingSchema.virtual('days').get(function () {
return getDays({
startDate: new Date(this.startDate),
endDate: new Date(this.endDate),
})
})
BookingSchema.static('findBookedDays', async function (): Promise<string[]> {
const bookings = await this.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: BookingDocument) => booking.days)
.flat()
.sort()
})
export default <BookingModel>mongoose.models.Booking ||
mongoose.model<BookingDocument, BookingModel>('Booking', BookingSchema)