mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 06:27:11 +01:00
populate days on save
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import * as mongoose from 'mongoose'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { startOfDay } from 'date-fns'
|
||||
import { dateFormatBackend, getDays } from '../helpers/date'
|
||||
import { BillDocument } from './bill'
|
||||
import { BookerDocument } from './booker'
|
||||
@@ -54,6 +55,10 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
|
||||
get: dateFormatBackend,
|
||||
min: new Date(),
|
||||
},
|
||||
days: {
|
||||
type: [String],
|
||||
required: true,
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: Object.values(BOOKING_STATUS),
|
||||
@@ -71,27 +76,29 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
|
||||
}
|
||||
)
|
||||
|
||||
BookingSchema.virtual('days').get(function () {
|
||||
return getDays({
|
||||
startDate: new Date(this.startDate),
|
||||
endDate: new Date(this.endDate),
|
||||
BookingSchema.pre('save', function (next) {
|
||||
const booking = this as BookingDocument
|
||||
booking.days = getDays({
|
||||
startDate: new Date(booking.startDate),
|
||||
endDate: new Date(booking.endDate),
|
||||
})
|
||||
next()
|
||||
})
|
||||
|
||||
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()
|
||||
const model = this as BookingModel
|
||||
const bookedDays = await model
|
||||
.find(
|
||||
{
|
||||
status: { $in: [BOOKING_STATUS.REQUESTED, BOOKING_STATUS.CONFIRMED] },
|
||||
endDate: { $gt: startOfDay(new Date()) },
|
||||
},
|
||||
'days'
|
||||
)
|
||||
.exec()
|
||||
|
||||
return bookings
|
||||
.map((booking: BookingDocument) => booking.days)
|
||||
return bookedDays
|
||||
.map((b) => b.days)
|
||||
.flat()
|
||||
.sort()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user