예제 #1
0
        public async Task <IActionResult> CreateUpdate(OfferCreateUpdateViewModel model)
        {
            try
            {
                if (!CurrentPolyclinic.ServiceSupplyIds.Contains(model.ServiceSupplyId))
                {
                    throw new AwroNoreException("You don not have permission to add offer to this doctor");
                }

                var startDateTime = DateTime.Parse($"{model.Date} {model.StartTime}");

                var endDateTime = DateTime.Parse($"{model.Date} {model.Endtime}");

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

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

                _scheduleManager.EnsureHasSchedule(serviceSupply, model.ShiftCenterServiceId ?? 0, startDateTime, endDateTime);

                var success = false;
                var message = Global.Err_ErrorOccured;

                var strategy = _dbContext.Database.CreateExecutionStrategy();
                await strategy.ExecuteAsync(async() =>
                {
                    using (var transaction = _dbContext.Database.BeginTransaction())
                    {
                        if (model.Id != null)
                        {
                            var offer = await _offerRepository.GetByIdAsync(model.Id.Value);

                            if (offer == null)
                            {
                                throw new Exception("Patient Not Found");
                            }

                            offer.StartDateTime        = startDateTime;
                            offer.EndDateTime          = endDateTime;
                            offer.MaxCount             = model.MaxCount;
                            offer.Description          = model.Description;
                            offer.UpdatedAt            = DateTime.Now;
                            offer.ServiceSupplyId      = model.ServiceSupplyId;
                            offer.ShiftCenterServiceId = model.ShiftCenterServiceId;
                            offer.Type = model.Type;

                            _offerRepository.UpdateOffer(offer);

                            if (model.ImageUpload != null)
                            {
                                var(newName, thumbName, dirPath, baseUrl) = _uploadService.GenerateOfferPhotoName(offer.Id, Lang.EN.ToString(), model.ImageUpload);

                                offer.Photo = $"{baseUrl}/{newName}";

                                _dbContext.Offers.Attach(offer);

                                _dbContext.Entry(offer).State = EntityState.Modified;

                                await _dbContext.SaveChangesAsync();

                                await _uploadService.UploadOfferPhotoAsync(model.ImageUpload, dirPath, newName, thumbName);
                            }

                            message = Core.Resources.EntitiesResources.Messages.ItemUpdatedSuccessFully;
                        }
                        else
                        {
                            var uniqueCode = await _offerRepository.GenerateUniqueCodeAsync();

                            var offer = new Offer
                            {
                                StartDateTime        = startDateTime,
                                EndDateTime          = endDateTime,
                                MaxCount             = model.MaxCount,
                                RemainedCount        = model.MaxCount,
                                CreatedAt            = DateTime.Now,
                                Description          = model.Description,
                                ServiceSupplyId      = model.ServiceSupplyId,
                                ShiftCenterServiceId = model.ShiftCenterServiceId,
                                Status               = OfferStatus.PENDING,
                                Code                 = uniqueCode,
                                Type                 = model.Type,
                                Photo                = "",
                                SendNotification     = model.SendNotification,
                                NotificationTitle    = model.NotificationTitle,
                                NotificationTitle_Ku = model.NotificationTitle_Ku,
                                NotificationTitle_Ar = model.NotificationTitle_Ar,
                                NotificationBody     = model.NotificationBody,
                                NotificationBody_Ku  = model.NotificationBody_Ku,
                                NotificationBody_Ar  = model.NotificationBody_Ar
                            };

                            await _offerRepository.InsertOfferAsync(offer);

                            if (model.ImageUpload != null)
                            {
                                var(newName, thumbName, dirPath, baseUrl) = _uploadService.GenerateOfferPhotoName(offer.Id, Lang.EN.ToString(), model.ImageUpload);

                                offer.Photo = $"{baseUrl}/{newName}";

                                _dbContext.Offers.Attach(offer);

                                _dbContext.Entry(offer).State = EntityState.Modified;

                                await _dbContext.SaveChangesAsync();

                                await _uploadService.UploadOfferPhotoAsync(model.ImageUpload, dirPath, newName, thumbName);
                            }

                            message = Core.Resources.EntitiesResources.Messages.ItemAddedSuccessFully;
                        }

                        transaction.Commit();

                        success = true;
                    }
                });

                return(Json(new { success, message }));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        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);
        }