fix double booked day validation

This commit is contained in:
Thomas Ruoff
2020-12-23 23:38:53 +01:00
parent b723fc5660
commit 2a5c9b8638
4 changed files with 37 additions and 21 deletions

View File

@@ -4,7 +4,8 @@ import { dateFormatBackend, getDays, nowInTz } from '../helpers/date'
import { Bill } from './bill'
import { Booker } from './booker'
import { BOOKING_STATUS } from './enums'
import { BOOKING_STATUS, VALIDATION_ERRORS } from './enums'
import { getBookedDays } from './index'
export interface Booking {
uuid: string
@@ -71,6 +72,19 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
days: {
type: [String],
required: true,
validate: {
validator: async function (days: string[]) {
const bookedDays = await getBookedDays()
const doubleBookedDays = days.filter((day: string) =>
bookedDays.includes(day)
)
return doubleBookedDays.length === 0
},
message: (props: { value: string[] }) =>
`At least one day is of ${props.value.join(',')} is already booked`,
type: VALIDATION_ERRORS.AT_LEAST_ONE_DAY_BOOKED,
},
},
status: {
type: String,
@@ -89,7 +103,7 @@ const BookingSchema = new mongoose.Schema<BookingDocument>(
}
)
BookingSchema.pre('save', function (next) {
BookingSchema.pre('validate', function (next: () => void) {
const booking = this as BookingDocument
booking.days = getDays({
startDate: new Date(booking.startDate),