コード例 #1
0
 public IActionResult CreateAppointment(Appointment appointment)
 {
     if (ModelState.IsValid)
     {
         try
         {
             appointmentRepository.Add(appointment);
             ViewBag.CustList    = getCustomersList(null);
             ViewBag.CLeanList   = getCleanersList(null);
             ViewBag.ServiceList = getServiceList(null);
             ViewBag.finDate     = DateTime.Now.ToString("yyyy-MM-dd");
             return(View("../Home/Index"));
         }
         catch (Exception)
         {
             ViewBag.CustList    = getCustomersList(null);
             ViewBag.CLeanList   = getCleanersList(null);
             ViewBag.ServiceList = getServiceList(null);
             ViewBag.finDate     = DateTime.Now.ToString("yyyy-MM-dd");
             TempData["message"] = "Date of Service and Start Time must be greater than today's datetime !";
             return(View("CreateAppointment"));
         }
     }
     else
     {
         ViewBag.CustList    = getCustomersList(null);
         ViewBag.CLeanList   = getCleanersList(null);
         ViewBag.ServiceList = getServiceList(null);
         ViewBag.finDate     = DateTime.Now.ToString("yyyy-MM-dd");
         TempData["message"] = "Appointment was not created! Please fill all the information required!";
         return(View("CreateAppointment"));
     }
 }
コード例 #2
0
        public async Task <Response> Handle(AddAppointmentRequest request, CancellationToken cancellationToken)
        {
            //Verifica se a requisição é nula
            if (request == null)
            {
                AddNotification("Request", "A requisição não pode ser nula!");
                return(new Response(this));
            }

            //Instancia uma nova consulta e valida os dados inseridos
            Entities.Appointment appointment = new(request.Schedule, request.PatientId,
                                                   request.AppointmentType);
            AddNotifications(appointment);

            if (IsInvalid())
            {
                return(new Response(this));
            }

            //Insere os dados no banco
            _appointmentRepository.Add(appointment);

            //Cria o objeto da resposta
            var response = new Response(this, appointment);

            //Retorna o resultado
            return(await Task.FromResult(response));
        }
コード例 #3
0
        public ContractResponse <AppointmentGetResponse> Add(ContractRequest <AddUpdateAppointmentRequest> request)
        {
            try
            {
                var model = request.Data.Appointment.ToAppointment();
                model.AppointmentInSameDate(_appointmentRepository.IsAppointmentInSameDay(model));

                var brokenRules = model.GetBrokenRules().ToList();
                if (!brokenRules.Any())
                {
                    _appointmentRepository.Add(model);
                    _uow.Commit();


                    var responseModel = new AppointmentGetResponse {
                        Id = model.Id
                    };
                    return(ContractUtil.CreateResponse(request, responseModel));
                }

                return(ContractUtil.CreateInvalidResponse <AppointmentGetResponse>(brokenRules));
            }
            catch (Exception ex)
            {
                _logger.LogError(20, ex, ex.Message);
                return(ContractUtil.CreateInvalidResponse <AppointmentGetResponse>(ex));
            }
        }
コード例 #4
0
 public ActionResult Create(Appointment appointment)
 {
     if (_repo.isAppointmentAvailable(appointment))
     {
         if (_custRepo.ThisCustomerExists(appointment.CustomerId))
         {
             if (_servRepo.ThisProviderExists(appointment.ProviderId))
             {
                 _repo.Add(appointment);
                 return(RedirectToAction(nameof(Index)));
             }
             else
             {
                 ModelState.AddModelError("",
                                          "There is no Service ProProviderIdvider that exists with the selected ID..." +
                                          "I'm begging you, think very carefully and give this just one more shot, Big Guy");
                 return(View());
             }
         }
         else
         {
             ModelState.AddModelError("CustomerId",
                                      "There is no customer that exists with that ID... Please try.. maybe... one more time?");
             return(View());
         }
     }
     else
     {
         ModelState.AddModelError("AppTime",
                                  "The selected Service Provider is not available for an appointment at this time. Please try again.");
         return(View());
     }
 }
コード例 #5
0
        public async Task <Appointment> Add(Appointment entity)
        {
            // we will check that there is no any appointment for the same day for this patient
            var appointmentsInTheSameDay = _AppointmentRepository.GetAll().FirstOrDefault(q => q.patientId == entity.patientId && q.appointmentDate.Date == entity.appointmentDate.Date);

            try
            {
                if (appointmentsInTheSameDay != null)
                {
                    throw new ValidationException("There is already an appointment for this patient this day");
                }

                if (entity.appointmentDate <= DateTime.Now)
                {
                    throw new ValidationException("The date of the appointment is before current date");
                }
                var bOpDoneSuccessfully = await _AppointmentRepository.Add(entity);

                return(bOpDoneSuccessfully);
            }
            catch (Exception ex) when(ex.GetType().ToString() != "System.ComponentModel.DataAnnotations.ValidationException")
            {
                throw new Exception("BusinessLogic:AppointmentBusiness::InsertAppointment::Error occured.", ex);
            }
        }
コード例 #6
0
 public JsonResult GetAppointment(AppointmentP obj)
 {
     try
     {
         string result = string.Empty;
         obj.PatientID = Convert.ToInt64(Session["UserID"]);
         var myUser = _Repository.GetAppointment()
                      .FirstOrDefault(u => u.Date == obj.Date && u.DoctorID == obj.DoctorID);
         if (myUser == null)    //User was found
         {
             _Repository.Add(obj);
             _Repository.Save();
             result = "You got a appointment Successfully";
         }
         else    //User was not found
         {
             result = "Doctor has appointment on this time.";
         }
         return(Json(result, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         //return View("Error", new HandleErrorInfo(ex, "EmployeeInfo", "Create"));
         return(Json(ex.ToString(), JsonRequestBehavior.AllowGet));
     }
 }
コード例 #7
0
        public void AddAppointment(Guid medicId, int duration, DateTime date, string adminId)
        {
            Guid adminIdGuid = Guid.Empty;

            if (!Guid.TryParse(adminId, out adminIdGuid))
            {
                throw new Exception("Invalid Guid Format");
            }
            var admin = adminRepository.GetAdminByUserId(adminIdGuid);

            if (admin == null)
            {
                throw new EntityNotFoundException(adminIdGuid);
            }

            var medic = medicRepository.GetMedicByID(medicId);

            var appointment = appointmentRepository.Add(new Appointment()
            {
                Id       = Guid.NewGuid(),
                Duration = duration,
                Date     = date,
                Admin    = admin,
                Medic    = medic
            });
        }
コード例 #8
0
        public async Task <ActionResult <AppointmentDTO> > PostAppointment(AppointmentDTO appointmentDTO)
        {
            var doctor = _appointmentRepository.Add(appointmentDTO);

            if (doctor == null)
            {
                return(BadRequest());
            }
            return(CreatedAtAction(nameof(GetAppointment), new { id = doctor.ID }, doctor));
        }
コード例 #9
0
        public async Task <IActionResult> Create([Bind("Id,StartDate,EndDate,Summary,Location,Color,Driver,Vehicle")] Appointment appointment)
        {
            if (ModelState.IsValid)
            {
                _appointmentRepository.Add(appointment);
                await _appointmentRepository.SaveChanges();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(appointment));
        }
コード例 #10
0
        public int Add(appointment appointment)
        {
            ValidateAppointment(appointment);
            appointment.createdBy    = _authRepository.Username;
            appointment.lastUpdateBy = _authRepository.Username;
            var now = CommonMethods.ConvertToUtc(DateTime.Now);

            appointment.createDate = now;
            appointment.lastUpdate = now;
            appointment.start      = CommonMethods.ConvertToUtc(appointment.start);
            appointment.end        = CommonMethods.ConvertToUtc(appointment.end);
            return(_repository.Add(appointment));
        }
コード例 #11
0
        public async Task <IActionResult> CreateAppointment([FromBody] AppointmentCreateDto apptDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var appointment = mapper.Map <AppointmentCreateDto, Appointment>(apptDto);

            repository.Add(appointment);
            await unitOfWork.CompleteAsync();

            return(Ok(mapper.Map <AppointmentCreateDto>(appointment)));
        }
        public async Task <IActionResult> AddAvailableAppointments(AppointViewModel appointViewModel)
        {
            var counselorEmail = User.Identity.Name;
            var user           = await userManager.FindByEmailAsync(counselorEmail);

            var appointment = new Appointment()
            {
                CounselorId   = user.Id,
                Accepted      = true,
                Appointed     = false,
                Date          = appointViewModel.Date,
                CounselorName = user.FirstName + " " + user.LastName
            };

            appointmentRepository.Add(appointment);
            return(RedirectToAction("Index"));
        }
コード例 #13
0
        public bool MakeAppointment(int patientId, int doctorId, int departmentId, string date)
        {
            Appointment appointment = new Appointment();

            appointment.Doctor     = doctorRepo.FindById(doctorId);
            appointment.Patient    = patientRepo.FindById(patientId);
            appointment.Department = departmentRepo.FindById(departmentId);
            appointment.Timestamp  = Convert.ToDateTime(date);

            try
            {
                appointmentRepo.Add(appointment);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #14
0
        public async Task <IActionResult> CreateAppointment(int userId, [FromBody] AppointmentToCreateDto appointmentToCreateDto)
        {
            var client = await _userRepo.GetUser(userId);

            if (client.Id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            appointmentToCreateDto.ClientId = client.Id;

            var carer = await _userRepo.GetCarer(appointmentToCreateDto.CarerId);

            if (carer == null)
            {
                return(BadRequest("No se puedo encontrar al usuario"));
            }

            //diferencia de las fechas para asignar el cost
            TimeSpan difference = appointmentToCreateDto.End - appointmentToCreateDto.Start;

            if (difference.Hours <= 0)
            {
                return(BadRequest("El intervalo de fechas es incorrecto"));
            }

            //seleccionar el costo
            appointmentToCreateDto.Cost = carer.FareForHour * difference.Hours;

            //mapear appoinment
            var appointment = _mapper.Map <Appointment>(appointmentToCreateDto);

            _appointmentRepo.Add(appointment);

            if (await _appointmentRepo.SaveAll())
            {
                var appointmentToReturn = _mapper.Map <AppointmentToReturnDto>(appointment);
                return(CreatedAtRoute("GetAppointment", new { userId, id = appointment.Id }, appointmentToReturn));
            }

            throw new Exception("No se pudo crear el mensaje al guardar");
        }
コード例 #15
0
        public async Task <IActionResult> CreateAppointment([FromBody] SaveAppointmentResource appointmentResource)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var specialists = await repository.GetListOfSpecialistsIds();

            var customers = await repository.GetListOfCustomersIds();

            var companies = await repository.GetListOfCompaniesIds();

            var dates = await repository.GetListOfAppointmentDates();

            if (!specialists.Contains(appointmentResource.SpecialistId) ||
                !customers.Contains(appointmentResource.CustomerId) ||
                !companies.Contains(appointmentResource.CompanyId) ||
                dates.Contains(appointmentResource.AppointmentDate))
            {
                return(BadRequest("Wrong type of data provided"));
            }

            var specialistsInCompany = await repository.GetListOfSpecialistsIds(appointmentResource.CompanyId);

            if (!specialistsInCompany.Contains(appointmentResource.SpecialistId))
            {
                return(BadRequest("Provided specialist doesn't belong to this company"));
            }

            var appointment = mapper.Map <SaveAppointmentResource, Appointment>(appointmentResource);

            repository.Add(appointment);
            await unitOfWork.CompleteAsync();

            appointment = await repository.GetAppointment(appointment.Id);

            var result = mapper.Map <Appointment, AppointmentResource>(appointment);

            return(Ok(result));
        }
コード例 #16
0
        public async Task <AppointmentDTO> Add(AppointmentDTO appointmentDTO)
        {
            try
            {
                var existAppointment = _appoinmentRepository.HasAppointment(appointmentDTO.PatientId, appointmentDTO.Date);
                if (existAppointment)
                {
                    throw new Exception("This patient has already an appointment for this date");
                }
                var appointment = _mapper.Map <AppointmentDTO, Appointment>(appointmentDTO);
                _appoinmentRepository.Add(appointment);

                await _appoinmentRepository.SaveAsync();

                return(_mapper.Map <Appointment, AppointmentDTO>(appointment));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #17
0
        public ActionResult <AppointmentItemDto> CreateAppointment([FromBody] AppointmentCreateDto appointmentCreateDto)
        {
            if (appointmentCreateDto == null)
            {
                return(BadRequest());
            }

            var appointmentItem = _mapper.Map <AppointmentItem>(appointmentCreateDto);

            _appointmentRepository.Add(appointmentItem);

            if (!_appointmentRepository.Save())
            {
                throw new Exception("Creating an appointment failed on save!");
            }

            AppointmentItem newAppointmentItem = _appointmentRepository.GetSingle(appointmentItem.Id);

            return(CreatedAtRoute(nameof(GetSingleAppointment), new { id = newAppointmentItem.Id },
                                  _mapper.Map <AppointmentItemDto>(newAppointmentItem)));
        }
コード例 #18
0
        public async Task <IActionResult> Post([FromBody] Appointment model)
        {
            try
            {
                _repository.Add(model);

                if (await _repository.SaveAllAsync())
                {
                    var newUri = Url.Link("AppointmentGet", new { id = model.Id });
                    return(Created(newUri, model));
                }
                else
                {
                    _logger.LogWarning("Could not save appointment to the database");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Critical error when saving new appointment, Ex: {ex}");
            }

            return(BadRequest());
        }
コード例 #19
0
        public async Task <Result> Handle(MakeAppointmentCommand request, CancellationToken cancellationToken)
        {
            var dbCandidate = await _candidateRepository.Get(request.CandidateId);

            if (dbCandidate == null)
            {
                return(Result.Failure("Candidate not found!"));
            }

            var dbVacancy = await _clientRepository.GetVacancy(request.VacancyId);

            if (dbVacancy == null)
            {
                return(Result.Failure("Vacancy not found!"));
            }


            var appointment = new Appointment(request.AppointmentType, request.StartsAt, dbCandidate, dbVacancy);

            _appointmentRepository.Add(appointment);
            await _appointmentRepository.UnitOfWork.SaveEntitiesAsync();

            return(Result.Ok());
        }
コード例 #20
0
        public async Task Execute(Appointment appointment)
        {
            if (appointment.HourPrice <= 0)
            {
                throw new ValuesInvalidException("Valor de hora por locação invalido. Verifique!");
            }
            if (appointment.HourLocation <= 0)
            {
                throw new ValuesInvalidException("Quantidade de horas locadas invalido. Verifique!");
            }
            if (appointment.Subtotal <= 0)
            {
                throw new ValuesInvalidException("SubTotal Inválido. Verifique!");
            }
            if (appointment.Amount <= 0)
            {
                throw new ValuesInvalidException("Total invalido.Verifique!");
            }

            var car = await _repositoryCar.FindById(appointment.IdCar);

            if (car == null)
            {
                throw new NotFoundRegisterException("Carro não encontrado, verifique informações.");
            }

            var client = await _repositoryClient.FindById(appointment.IdClient);

            if (client == null)
            {
                throw new NotFoundRegisterException("Cliente não encontrado, verifique informações.");
            }

            var op = await _repositoryOperator.FindById(appointment.IdOperator);

            if (op == null)
            {
                throw new NotFoundRegisterException("Operador não encontrado, verifique informações.");
            }


            if (appointment.Id == 0)
            {
                if (appointment.DateTimeExpectedCollected > appointment.DateTimeCollected)
                {
                    throw new DateTimeColectedInvalidException("Data da coleta maior que a data esperada para coleta verifique.");
                }

                if (appointment.DateTimeExpectedCollected > appointment.DateTimeExpectedDelivery)
                {
                    throw new DateTimeColectedInvalidException("Data esperada da coleta maior que a data esperada para entrega. Verifique.");
                }

                if (appointment.DateTimeExpectedCollected < DateTime.Now)
                {
                    throw new DateTimeColectedInvalidException("Data esperada da coleta menor que data atual. Verifique!");
                }

                var avalabilityCar = await _repository.CheckAvailabilityCar(appointment.IdCar, appointment.DateTimeExpectedCollected);

                if (!avalabilityCar)
                {
                    throw new CarNotAvalabityException("Carro já está alocado.");
                }

                var avalabilityClient = await _repository.CheckAvailabilityCar(appointment.IdCar, appointment.DateTimeExpectedCollected);

                if (!avalabilityClient)
                {
                    throw new ClientNotAvalabityException("Cliente já possui um agendamento para está data.");
                }


                appointment.IdCheckList       = null;
                appointment.DateTimeCollected = null;
                appointment.DateTimeDelivery  = null;
                appointment.Schedule          = DateTime.Now;

                await _repository.Add(appointment);

                return;
            }

            await _repository.Update(appointment);
        }
コード例 #21
0
 public IActionResult AddAppointment([FromBody] Appointment model)
 {
     model.AppointmentDay = model.TentativeTime.Value.DayOfWeek.ToString();
     _repo.Add(model);
     return(new OkObjectResult(new { AppointmentID = model.AppointmentId }));
 }
コード例 #22
0
 public void Post([FromBody] Appointment appointment)
 {
     _appointmentRepository.Add(appointment);
 }
コード例 #23
0
 public void Add(Appointment appointment)
 {
     _appointmentFileRepository.Add(appointment);
 }
コード例 #24
0
 public StatusDto AddAppointment(Appointment model)
 {
     return(_appointmentRepository.Add(model));
 }
コード例 #25
0
 public int Add(AppointmentTable entity)
 {
     return(_repo.Add(entity));
 }
コード例 #26
0
        public async Task <string> Post([FromBody] Appointment appointment)
        {
            await _appointmentRepository.Add(appointment);

            return("");
        }
コード例 #27
0
        public async Task <ActionResult <Attendee> > Post(Attendee attendee)
        {
            await _appointmentRepository.Add(attendee);

            return(CreatedAtAction("Get", new { id = attendee.AttendeeId }, attendee));
        }