import { startOfHour , isBefore , getHours } from 'date-fns' ; import { injectable , inject } from 'tsyringe' ; import AppError from '@shared/errors/AppError' ; import Appointment from '../infra/typeorm/entities/Appointment' ; import IAppointmentsRepository from '../repositories/IAppointmentsRepository' ; interface IRequestDTO { provider_id : string ; user_id : string ; date : Date ; } @ injectable ( ) class CreateAppointmentService { constructor ( @ inject ( 'AppointmentsRepository' ) private appointmentsRepository ) { } public async execute ( { date , user_id , provider_id , } ) { const appointmentDate = startOfHour ( date ) ; if ( isBefore ( appointmentDate , Date . now ( ) ) ) { throw new AppError ( "You can't create an appointment on a past date." ) ; } if ( user_id === provider_id ) { throw new AppError ( "You can't create an appointment with the same user and provider." ) ; } if ( getHours ( appointmentDate ) < 8 || getHours ( appointmentDate ) > 17 ) { throw new AppError ( "You can't create an appointment out of working hours." ) ; } const findAppointmentInSameDate = await this . appointmentsRepository . findByDate ( appointmentDate ) ; if ( findAppointmentInSameDate ) { throw new AppError ( 'This time is already booked.' ) ; } const appointment = await this . appointmentsRepository . create ( { provider_id , user_id , date : appointmentDate , } ) ; return appointment ; } } export default CreateAppointmentService ;