public async Task <(string trackingCode, int appointmentId)> CreateRequestedAppointmentAsync(string userMobile, FinalBookTurnDTO model, Lang requestLang)
        {
            var person = await _dbContext.Persons.FirstOrDefaultAsync(x => x.Mobile == userMobile);

            if (person == null)
            {
                throw new AwroNoreException("Person not found");
            }

            var turnDate          = DateTime.Parse(model.Date);
            var turnStartDateTime = DateTime.Parse($"{model.Date} {model.StartTime}");
            var turnEndDateTime   = DateTime.Parse($"{model.Date} {model.EndTime}");

            var serviceSupply = await _dbContext.ServiceSupplies.FindAsync(model.ServiceSupplyId);

            if (serviceSupply == null)
            {
                throw new AwroNoreException(Global.Err_DoctorNotFound);
            }

            var centerService = await _dbContext.CenterServices.FindAsync(model.CenterServiceId);

            if (centerService == null)
            {
                throw new AwroNoreException(NewResource.NotAnyServiceDefinedForThisCenter);
            }

            _scheduleManager.EnsureHasSchedule(serviceSupply, model.CenterServiceId, turnStartDateTime, turnEndDateTime, passIfNoSchedules: true);

            // Ensure that user don't have another appointment with same time
            await EnsureNotHaveSameTimeAppointmentAsync(turnStartDateTime, userMobile);

            var trackingCode = await _appointmentService.GenerateUniqueTrackingNumberAsync();

            var appointment = new Appointment
            {
                UniqueTrackingCode   = trackingCode,
                Book_DateTime        = DateTime.Now,
                Start_DateTime       = turnStartDateTime,
                End_DateTime         = turnEndDateTime,
                Description          = "#Requested",
                Status               = AppointmentStatus.Unknown,
                ServiceSupplyId      = serviceSupply.Id,
                PersonId             = person.Id,
                PatientInsuranceId   = null,
                IsAnnounced          = false,
                Paymentstatus        = PaymentStatus.Free,
                IsDeleted            = false,
                ShiftCenterServiceId = centerService.Id,
                ReservationChannel   = ReservationChannel.MobileApplication,
                CreatedAt            = DateTime.Now,
                OfferId              = null,
                RequestLang          = requestLang
            };

            _dbContext.Appointments.Add(appointment);

            // Send notification for agents here
            var agents = _settings?.Value?.AwroNoreSettings?.RequestAppointmentAgents;

            if (agents != null && agents.Any())
            {
                foreach (var agent in agents)
                {
                    var agentPerson = await _dbContext.Persons.FirstOrDefaultAsync(x => x.Mobile == agent);

                    if (agentPerson != null)
                    {
                        var title   = "Appointment Request";
                        var message = "New Appointment Request Created";
                        foreach (var item in agentPerson.FcmInstanceIds)
                        {
                            await _notificationService.SendFcmToSingleDeviceAsync(item.InstanceId, title, message);
                        }
                    }
                }
            }

            // Send SMS For Doctor
            try
            {
                var posetMessage = $"نۆرەیەک داواکراوە لە ڕێگای ئەوڕۆنۆرە{Environment.NewLine}" +
                                   $"ژمارە: {person.Mobile}{Environment.NewLine}" +
                                   $"ناو: {person.FullName}";

                if (serviceSupply.ServiceSupplyInfo != null && !string.IsNullOrEmpty(serviceSupply.ServiceSupplyInfo.Phone))
                {
                    var mobile = serviceSupply.ServiceSupplyInfo.Phone;

                    var isNumeric = double.TryParse(mobile, out _);

                    if (isNumeric)
                    {
                        if (mobile.Length > 10)
                        {
                            mobile = mobile.Substring(mobile.Length - 10);
                        }

                        if (mobile.StartsWith("7"))
                        {
                            var receipinet = $"964{mobile}";

                            await _smsService.SendSmsAsync(receipinet, posetMessage);
                        }
                    }
                }
            }
            catch
            {
                // IGNORED
            }

            await _dbContext.SaveChangesAsync();

            return(trackingCode, appointment.Id);
        }
Exemple #2
0
        public async Task <IActionResult> FinalBookTurn([FromBody] FinalBookTurnDTO model)
        {
            if (string.IsNullOrEmpty(CurrentUserName))
            {
                return(Unauthorized());
            }

            var mobile = CurrentUserName;

            // Check if this patient has reserved appointment today or not?
            if (_appointmentsManager.HaveAppointmentForDate(model.Date, mobile, model.ServiceSupplyId, model.CenterServiceId))
            {
                throw new AwroNoreException(Global.Err_UserHaveTurnForDate);
            }

            // Save Requested Turn
            if (model.IsRequested)
            {
                var(trackingCode, appointmentId) = await _appointmentsManager.CreateRequestedAppointmentAsync(mobile, model, requestLang : RequestLang);

                var result = new FinalBookTurnResultDTO
                {
                    IsSucceeded  = true,
                    IsRequested  = true,
                    Message      = "داواکاری نۆرەکەتان بە سەرکەوتوویی تۆمار کرا",
                    Description  = "This is just request",
                    TurnId       = appointmentId,
                    TrackingCode = trackingCode
                };

                return(Ok(result));
            }
            else
            {
                var offerCode = string.Empty;

                var turnDate          = DateTime.Parse(model.Date);
                var turnStartDateTime = DateTime.Parse($"{model.Date} {model.StartTime}");
                var turnEndDateTime   = DateTime.Parse($"{model.Date} {model.EndTime}");

                var serviceSupply = await _serviceSupplyService.GetServiceSupplyByIdAsync(model.ServiceSupplyId);

                if (serviceSupply == null)
                {
                    throw new AwroNoreException(Global.Err_DoctorNotFound);
                }

                var centerService = _servicesService.GetShiftCenterServiceById(model.CenterServiceId);

                if (centerService == null)
                {
                    throw new AwroNoreException(NewResource.NotAnyServiceDefinedForThisCenter);
                }

                if (!serviceSupply.IsAvailable)
                {
                    throw new AwroNoreException(serviceSupply.ShiftCenter.Type == ShiftCenterType.BeautyCenter ? Global.BeautyCenterNotActive : Global.DoctorNotActive);
                }

                if (_blockedMobileService.IsMobileBlocked(serviceSupply.ShiftCenterId, mobile))
                {
                    throw new AwroNoreException(Global.Err_MobileBlocked);
                }

                try
                {
                    // Ensure that user don't have another appointment with same time
                    await _appointmentsManager.EnsureNotHaveSameTimeAppointmentAsync(turnStartDateTime, mobile);

                    // Reserve Turn In In-Progress Appointments

                    var emptyPeriods = _doctorServiceManager.Calculate_Available_Empty_TimePeriods_By_Percent(serviceSupply, turnDate, centerService);
                    if (emptyPeriods == null || !emptyPeriods.Any())
                    {
                        throw new AwroNoreException(NewResource.TurnReservedBeforeByAnotherPerson);
                    }
                    var emptyTurn = emptyPeriods.FirstOrDefault(x => x.StartDateTime == turnStartDateTime && x.EndDateTime == turnEndDateTime);
                    if (emptyTurn == null)
                    {
                        throw new AwroNoreException(NewResource.TurnReservedBeforeByAnotherPerson);
                    }
                    var ipa = new IPAModel
                    {
                        AddedAt                 = DateTime.Now,
                        ServiceSupplyId         = model.ServiceSupplyId,
                        StartDateTime           = emptyTurn.StartDateTime,
                        EndDateTime             = emptyTurn.EndDateTime,
                        UserHostAgent           = "Stand-WPF",
                        IsForSelectedDoctor     = false,
                        PolyclinicHealthService = centerService,
                        OfferId                 = model.OfferId
                    };
                    if (_doctorServiceManager.IsAvailableEmptyTimePeriod(ipa.ServiceSupplyId, ipa.StartDateTime, ipa.EndDateTime, ipa.PolyclinicHealthService))
                    {
                        if (model.OfferId != null)
                        {
                            var offer = await _offerRepository.GetByIdAsync(model.OfferId.Value);

                            if (offer == null)
                            {
                                throw new AwroNoreException("Offer Not Found");
                            }

                            offerCode = offer.Code;

                            var offerAllTimePeriods = _doctorServiceManager.CalculateAllTimePeriodsForOffer(offer);

                            if (offerAllTimePeriods == null)
                            {
                                throw new AwroNoreException("Empty Turns Not Found");
                            }

                            var isEmptyOffer = offerAllTimePeriods.Any(x => x.Type == TimePeriodType.EmptyOffer && x.StartDateTime == turnStartDateTime && x.EndDateTime == turnEndDateTime);

                            if (!isEmptyOffer)
                            {
                                throw new AwroNoreException("All Offer Appointments Are Reserved");
                            }
                        }

                        _iPAsManager.Insert(ipa);
                    }
                    else
                    {
                        throw new Exception(Global.Err_ValidTimePeriodNotFound);
                    }


                    var currentUser = await _userService.GetPersonByMobileAsync(mobile);

                    var patientModel = new PatientModel
                    {
                        Mobile = mobile,
                    };

                    string message     = string.Empty;
                    var    queueNumber = -1;
                    var    bookAppoint = await _appointmentsManager.BookAppointmentAsync(serviceSupply, patientModel, model.Date, model.StartTime, model.EndTime, true, PaymentStatus.Free, centerService, ReservationChannel.MobileApplication, requestLang : RequestLang, offerId : model.OfferId);

                    if (bookAppoint.Status == BookingAppointmentStatus.Success)
                    {
                        try
                        {
                            var appointment = _appointmentService.GetAppointmentById((int)bookAppoint.AppointmentId);
                            try
                            {
                                logger.Info("Begin try to send notification...");

                                var polyclinic  = serviceSupply.ShiftCenter;
                                var instanceIds = new List <string>();
                                if (polyclinic.FcmInstanceIds != null && polyclinic.FcmInstanceIds.Count() > 0)
                                {
                                    instanceIds = polyclinic.FcmInstanceIds.Where(x => x.IsOn).Select(x => x.FcmId).ToList();
                                }
                                if (instanceIds.Count > 0)
                                {
                                    var patientName = appointment.Person.FullName;
                                    var date        = appointment.Start_DateTime.ToShortDateString();
                                    var title       = "New Turn!";
                                    var text        = patientName + " reserved turn for " + date;

                                    foreach (var item in instanceIds)
                                    {
                                        await _notificationService.SendFcmToSingleDeviceAsync(item, title, text);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                logger.Error("Error sending notification...");
                                logger.Error(e.Message);
                                logger.Error(e.InnerException);
                            }
                            queueNumber = _appointmentService.GetQueueNumberForAppointment(serviceSupply.Id, appointment.Id, centerService.Id, appointment.Start_DateTime);

                            if (serviceSupply.ShiftCenter.IsIndependent)
                            {
                                if (serviceSupply.ShiftCenter.FinalBookMessage_Ku != null)
                                {
                                    message = serviceSupply.ShiftCenter.FinalBookMessage_Ku;
                                }
                            }
                            else if (serviceSupply.ShiftCenter.Clinic.IsIndependent)
                            {
                                if (serviceSupply.ShiftCenter.Clinic.FinalBookMessage_Ku != null)
                                {
                                    message = serviceSupply.ShiftCenter.Clinic.FinalBookMessage_Ku;
                                }
                            }
                            else if (serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookMessage_Ku != null)
                            {
                                message = serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookMessage_Ku;
                            }
                        }
                        catch { }
                    }
                    var result = new FinalBookTurnResultDTO
                    {
                        IsSucceeded  = bookAppoint.Status == BookingAppointmentStatus.Success,
                        Message      = bookAppoint.Message,
                        TurnId       = (int)bookAppoint.AppointmentId,
                        QueueNumber  = queueNumber,
                        TrackingCode = bookAppoint.TrackingCode,
                        OfferCode    = offerCode
                    };
                    return(Ok(result));
                }
                catch (Exception e)
                {
                    try
                    {
                        _iPAsManager.Delete(model.ServiceSupplyId, turnStartDateTime);
                    }
                    catch
                    {
                        // IGNORED
                    }

                    if (e is AwroNoreException)
                    {
                        return(Ok(new FinalBookTurnResultDTO
                        {
                            IsSucceeded = false,
                            Message = e.Message
                        }));
                    }
                    throw e;
                }
            }
        }