2021-11-27 13:11:09 +01:00
|
|
|
import { Dayjs } from 'dayjs'
|
2021-11-24 15:38:58 +01:00
|
|
|
|
2022-11-30 11:56:39 +01:00
|
|
|
import { asyncLocalStorage } from './logger'
|
2022-11-21 19:07:43 +01:00
|
|
|
import { Reservation } from './reservation'
|
|
|
|
|
import { validateJSONRequest } from './request'
|
2022-11-29 22:51:28 +01:00
|
|
|
import { reserve } from './reserver'
|
2021-11-27 13:11:09 +01:00
|
|
|
|
2022-10-23 11:55:47 +02:00
|
|
|
export interface ScheduledReservation {
|
|
|
|
|
reservation: Reservation
|
2021-11-28 13:06:52 +01:00
|
|
|
scheduledFor?: Dayjs
|
2021-11-27 13:11:09 +01:00
|
|
|
}
|
2021-11-24 15:38:58 +01:00
|
|
|
|
2022-03-29 22:41:44 +02:00
|
|
|
export interface SchedulerResult {
|
2022-10-23 11:55:47 +02:00
|
|
|
scheduledReservation?: ScheduledReservation
|
2021-11-28 13:06:52 +01:00
|
|
|
}
|
|
|
|
|
|
2022-10-23 11:55:47 +02:00
|
|
|
export type SchedulerInput = Record<string, unknown>
|
2021-11-28 19:40:16 +01:00
|
|
|
|
2022-11-29 22:51:28 +01:00
|
|
|
export const schedule = async (
|
2022-03-29 22:41:44 +02:00
|
|
|
payload: SchedulerInput
|
|
|
|
|
): Promise<SchedulerResult> => {
|
2022-11-30 11:56:39 +01:00
|
|
|
const logger = asyncLocalStorage.getStore()
|
2022-10-23 11:55:47 +02:00
|
|
|
|
2022-11-30 11:56:39 +01:00
|
|
|
logger?.debug('Handling reservation', { payload })
|
2022-10-23 11:55:47 +02:00
|
|
|
let reservation: Reservation
|
2021-11-28 13:06:52 +01:00
|
|
|
try {
|
2022-10-23 11:55:47 +02:00
|
|
|
reservation = await validateJSONRequest(payload)
|
2021-11-28 13:06:52 +01:00
|
|
|
} catch (err) {
|
2022-11-30 11:56:39 +01:00
|
|
|
logger?.error('Failed to validate request', { err })
|
2021-11-28 13:06:52 +01:00
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-30 11:56:39 +01:00
|
|
|
logger?.debug('Successfully validated request', {
|
2023-01-30 12:38:42 +01:00
|
|
|
reservation: reservation.toString(true),
|
2022-10-23 11:55:47 +02:00
|
|
|
})
|
2021-11-28 13:06:52 +01:00
|
|
|
|
2022-10-23 11:55:47 +02:00
|
|
|
if (!reservation.isAvailableForReservation()) {
|
2022-11-30 11:56:39 +01:00
|
|
|
logger?.debug(
|
2022-10-23 11:55:47 +02:00
|
|
|
'Reservation date is more than 7 days away; saving for later reservation'
|
2021-11-28 13:06:52 +01:00
|
|
|
)
|
2022-11-29 22:51:28 +01:00
|
|
|
|
2023-01-30 12:38:42 +01:00
|
|
|
await reservation.save()
|
2022-11-29 22:51:28 +01:00
|
|
|
|
2021-11-28 13:06:52 +01:00
|
|
|
return {
|
2022-10-23 11:55:47 +02:00
|
|
|
scheduledReservation: {
|
|
|
|
|
reservation,
|
|
|
|
|
scheduledFor: reservation.getAllowedReservationDate(),
|
2021-11-28 13:06:52 +01:00
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-30 11:56:39 +01:00
|
|
|
logger?.info('Reservation request can be performed now')
|
2022-11-29 22:51:28 +01:00
|
|
|
await reserve(reservation)
|
2021-11-28 13:06:52 +01:00
|
|
|
return {
|
2022-10-23 11:55:47 +02:00
|
|
|
scheduledReservation: { reservation },
|
2021-11-27 13:11:09 +01:00
|
|
|
}
|
2021-11-24 15:38:58 +01:00
|
|
|
}
|