2021-11-27 13:11:09 +01:00
|
|
|
import { Dayjs } from 'dayjs'
|
2022-02-10 17:27:35 +01:00
|
|
|
import { v4 } from 'uuid'
|
2021-11-24 15:38:58 +01:00
|
|
|
|
2022-11-21 19:07:43 +01:00
|
|
|
import { Logger, LogLevel } from './logger'
|
|
|
|
|
import { Reservation } from './reservation'
|
|
|
|
|
import { validateJSONRequest } from './request'
|
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-21 19:07:43 +01:00
|
|
|
export const work = async (
|
2022-03-29 22:41:44 +02:00
|
|
|
payload: SchedulerInput
|
|
|
|
|
): Promise<SchedulerResult> => {
|
2022-10-23 11:55:47 +02:00
|
|
|
Logger.instantiate('scheduler', v4(), LogLevel.DEBUG)
|
|
|
|
|
|
2022-02-11 13:20:15 +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) {
|
2021-11-28 19:40:16 +01:00
|
|
|
Logger.error('Failed to validate request', { err })
|
2021-11-28 13:06:52 +01:00
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-23 11:55:47 +02:00
|
|
|
Logger.debug('Successfully validated request', {
|
|
|
|
|
reservation: reservation.format(),
|
|
|
|
|
})
|
2021-11-28 13:06:52 +01:00
|
|
|
|
2022-10-23 11:55:47 +02:00
|
|
|
if (!reservation.isAvailableForReservation()) {
|
|
|
|
|
Logger.debug(
|
|
|
|
|
'Reservation date is more than 7 days away; saving for later reservation'
|
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
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-28 19:40:16 +01:00
|
|
|
Logger.info('Reservation request can be performed now')
|
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
|
|
|
}
|