public async Task <string> UpdateProfileAvatarAsync(string mobile, IFormFile photo) { var person = await _dbContext.Persons.FirstOrDefaultAsync(x => x.Mobile == mobile); if (person == null) { throw new AwroNoreException(NewResource.UserNotFound); } var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { var(newName, thumbName, dirPath, baseUrl) = _uploadService.GeneratePersonAvatarName(person.Id, photo); person.Avatar = $"{baseUrl}/{thumbName}"; _dbContext.Persons.Attach(person); _dbContext.Entry(person).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); await _uploadService.UploadPersonAvatarAsync(photo, dirPath, newName, thumbName); transaction.Commit(); } }); return(person.RealAvatar); }
public async Task <IActionResult> CreateUpdateCategory(CmsCategoryCreateUpdateViewModel model) { if (model.Id != null) { var category = await _dbContext.ContentCategories.FindAsync(model.Id); if (category == null) { throw new AwroNoreException("Category not found"); } category.Title = model.Title; category.Title_Ar = model.Title_Ar; category.Title_Ku = model.Title_Ku; category.LayoutStyle = model.LayoutStyle; category.UpdatedAt = DateTime.Now; _dbContext.Entry(category).State = EntityState.Modified; } else { var category = _mapper.Map <ContentCategory>(model); await _dbContext.ContentCategories.AddAsync(category); } await _dbContext.SaveChangesAsync(); return(Json(new { success = true, message = Messages.ActionDoneSuccesfully })); }
public async Task <string> UploadShiftCenterLogoAsync(int shiftCenterId, IFormFile photo) { var shiftCenter = await _dbContext.ShiftCenters.FindAsync(shiftCenterId); if (shiftCenter == null) { throw new AwroNoreException("Shift Center Not Found"); } string logoUrl = string.Empty; var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { var originFileName = photo.FileName; var ext = Path.GetExtension(originFileName); var time = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss-fffff"); var newFileName = $"logo_{time}{ext}"; var physicalDirPath = $"uploaded\\logos\\shiftcenters\\{shiftCenterId}"; var baseUrl = $"/{physicalDirPath.Replace("\\", "/")}"; logoUrl = $"{baseUrl}/{newFileName}"; shiftCenter.Logo = logoUrl; _dbContext.ShiftCenters.Attach(shiftCenter); _dbContext.Entry(shiftCenter).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); var fullDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", physicalDirPath); if (!Directory.Exists(fullDirectoryPath)) { Directory.CreateDirectory(fullDirectoryPath); } var path = Path.Combine(fullDirectoryPath, newFileName); using (var stream = new FileStream(path, FileMode.Create)) { await photo.CopyToAsync(stream); } transaction.Commit(); } }); return(logoUrl); }
public IActionResult EditVocationDay(VocationDayViewModel model) { try { if (ModelState.IsValid) { var vocationDay = _dbContext.VocationDays.SingleOrDefault(x => x.Id == model.Id); _dbContext.Entry(vocationDay).State = Microsoft.EntityFrameworkCore.EntityState.Modified; vocationDay.Date = DateTime.Parse(model.Date); vocationDay.Description = model.Description; vocationDay.UpdatedAt = DateTime.Now; _dbContext.SaveChanges(); TempData.Put("message", new MVCResultModel { status = MVCResultStatus.success, message = Messages.ItemUpdatedSuccessFully }); return(RedirectToAction("VocationDays", "Schedule", new { area = "Admin" })); } } catch (FormatException) { TempData.Put("message", new MVCResultModel { status = MVCResultStatus.danger, message = Messages.PleaseEnterValidDate }); } catch (Exception) { TempData.Put("message", new MVCResultModel { status = MVCResultStatus.danger, message = Messages.AnErrorOccuredWhileUpdateItem }); } return(View(model)); }
public async Task Execute(IJobExecutionContext context) { try { var pendingPastAppoints = await _dbContext.Appointments.Where(x => x.Status == AppointmentStatus.Pending && x.End_DateTime < DateTime.Now).ToListAsync(); if (pendingPastAppoints.Count >= 1) { foreach (var item in pendingPastAppoints) { _dbContext.Entry(item).State = Microsoft.EntityFrameworkCore.EntityState.Modified; item.Status = AppointmentStatus.Done; } _dbContext.SaveChanges(); } } catch (Exception ex) { //ReFire job if it is stopped var jee = new JobExecutionException(ex) { RefireImmediately = true }; throw jee; } }
public async Task UpdateAsync(InsuranceService insuranceService) { _dbContext.InsuranceServices.Attach(insuranceService); _dbContext.Entry(insuranceService).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); }
public async Task <IActionResult> CreateUpdate(NotificationCreateUpdateViewModel model) { var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { var notification = _mapper.Map <Notification>(model); await _dbContext.Notifications.AddAsync(notification); await _dbContext.SaveChangesAsync(); var(newName, thumbName, dirPath, baseUrl) = _uploadService.GenerateNotificationImageName(notification.Id, model.Image); notification.Image = $"{baseUrl}/{newName}"; _dbContext.Notifications.Attach(notification); _dbContext.Entry(notification).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); await _uploadService.UploadNotificationImageAsync(model.Image, dirPath, newName, thumbName); var notificationDTO = new NotificationListItemDTO { Id = notification.Id, Text = notification.Text ?? notification.Text_Ku ?? notification.Text_Ar, TextKu = notification.Text_Ku ?? notification.Text ?? notification.Text_Ar, TextAr = notification.Text_Ar ?? notification.Text_Ku ?? notification.Text, Title = notification.Title ?? notification.Title_Ku ?? notification.Title_Ar, TitleKu = notification.Title_Ku ?? notification.Title ?? notification.Title_Ar, TitleAr = notification.Title_Ar ?? notification.Title_Ku ?? notification.Title, CreatedAt = notification.CreatedAt, Description = notification.Description ?? notification.Description_Ku ?? notification.Description_Ar, DescriptionKu = notification.Description_Ku ?? notification.Description ?? notification.Description_Ar, DescriptionAr = notification.Description_Ar ?? notification.Description_Ku ?? notification.Description, PayloadJson = notification.PayloadJson, Image = notification.Image, IsExpired = DateTime.Now > notification.ValidUntil }; await _notificationService.SendInboxNotificationAsync(new BaseNotificationPayload { Title = notificationDTO.Title, TitleKu = notificationDTO.TitleKu, TitleAr = notificationDTO.TitleAr, Body = notificationDTO.Text?.TruncateLongString(50), BodyKu = notificationDTO.TextKu?.TruncateLongString(50), BodyAr = notificationDTO.TextAr?.TruncateLongString(50) }, notificationDTO); transaction.Commit(); } }); return(Json(new { success = true, message = Messages.ItemAddedSuccessFully })); }
public async Task ApproveRegistrationRequestAsync(int id) { var center = await _dbContext.ShiftCenters.FirstOrDefaultAsync(x => x.Id == id && !x.IsApproved); if (center == null) { throw new AwroNoreException("Shift center not found"); } center.IsApproved = true; _dbContext.Entry(center).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); }
public async Task <IActionResult> GetZipFile([FromBody] RegisterDownloadAppModel inputModel) { HttpContext.Response.ContentType = ContentType; byte[] resultFileBytes = null; // Center & Person Data #region Validations if (string.IsNullOrEmpty(inputModel.Mobile)) { throw new Exception("Mobile is not valid"); } if (inputModel.Mobile.Length > 10) { inputModel.Mobile = inputModel.Mobile.Substring(inputModel.Mobile.Length - 10); } else if (inputModel.Mobile.Length < 10) { inputModel.Mobile = inputModel.Mobile.PadLeft(10, '0'); } var isMobileValid = long.TryParse(inputModel.Mobile, out long mobileNumber); if (!isMobileValid) { throw new AwroNoreException("Mobile is not valid"); } var existPerson = await _dbContext.Persons.FirstOrDefaultAsync(x => x.Mobile == inputModel.Mobile); var existCenter = await _dbContext.ShiftCenters.FirstOrDefaultAsync(x => x.Type == inputModel.CenterType && x.Name == inputModel.PoliClinicName && x.Name_Ku == inputModel.PoliClinicName && x.Name_Ar == inputModel.PoliClinicName && x.CityId == inputModel.CityId); var phones = new List <ShiftCenterPhoneModel> { new ShiftCenterPhoneModel { PhoneNumber = inputModel.Mobile } }; #endregion var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { // DB operations // TODO: Add db operations here (Create person & Center) #region ShiftCenter var center = existCenter; if (center == null) { center = new ShiftCenter { Type = inputModel.CenterType, Name = inputModel.PoliClinicName, Name_Ku = inputModel.PoliClinicName, Name_Ar = inputModel.PoliClinicName, Description = inputModel.Description, Description_Ku = inputModel.Description, Description_Ar = inputModel.Description, CityId = inputModel.CityId, Address = inputModel.PoliClinicAddress, Address_Ku = inputModel.PoliClinicAddress, Address_Ar = inputModel.PoliClinicAddress, IsIndependent = true, ClinicId = null, BookingRestrictionHours = 0, CreatedAt = DateTime.Now, PhoneNumbers = phones, IsApproved = false, IsDeleted = false, ActiveDaysAhead = 30, AutomaticScheduleEnabled = false, FinalBookMessage = "", FinalBookMessage_Ar = "", FinalBookMessage_Ku = "", FinalBookSMSMessage = "", FinalBookSMSMessage_Ar = "", FinalBookSMSMessage_Ku = "", Notification = "Offline", Notification_Ar = "", Notification_Ku = "", PrescriptionPath = "", Location = new NetTopologySuite.Geometries.Point(0.0, 0.0) { SRID = 4326 // Set the SRID (spatial reference system id) to 4326, which is the spatial reference system used by Google maps (WGS84) }, }; await _dbContext.ShiftCenters.AddAsync(center); await _dbContext.SaveChangesAsync(); } var person = existPerson; if (person == null) { person = new Person { Mobile = inputModel.Mobile, MobileConfirmed = false, FirstName = inputModel.FirstName, FirstName_Ku = inputModel.FirstName, FirstName_Ar = inputModel.FirstName, SecondName = inputModel.SecondName, SecondName_Ku = inputModel.SecondName, SecondName_Ar = inputModel.SecondName, ThirdName = inputModel.ThirdName, ThirdName_Ku = inputModel.ThirdName, ThirdName_Ar = inputModel.ThirdName, UniqueId = await _personService.GenerateUniqueIdAsync(), Avatar = null, Age = 0, Gender = inputModel.Gender, BloodType = Core.Enums.BloodType.Unknown, IsApproved = true, IsEmployee = true, IsDeleted = false, Birthdate = DateTime.Now, Address = "", CreatedAt = DateTime.Now, CreationPlaceId = null, CreatorRole = Shared.Enums.LoginAs.UNKNOWN, Email = inputModel.Email, Description = "", Weight = 0, Height = 0, ZipCode = "", IdNumber = "", Language = null, MarriageStatus = null }; await _dbContext.Persons.AddAsync(person); await _dbContext.SaveChangesAsync(); } #endregion #region ShiftCenter Person var centerPerson = await _dbContext.ShiftCenterPersons.FirstOrDefaultAsync(x => x.PersonId == person.Id && x.ShiftCenterId == center.Id); if (centerPerson == null) { centerPerson = new ShiftCenterPersons { IsManager = true, PersonId = person.Id, ShiftCenterId = center.Id, CreatedAt = DateTime.Now }; await _dbContext.ShiftCenterPersons.AddAsync(centerPerson); await _dbContext.SaveChangesAsync(); } #endregion #region Service Supply var serviceSupply = await _dbContext.ServiceSupplies.FirstOrDefaultAsync(x => x.PersonId == person.Id && x.ShiftCenterId == center.Id); if (serviceSupply == null) { serviceSupply = new ServiceSupply { Duration = 5, ShiftCenterId = center.Id, ReservationType = ReservationType.Selective, PersonId = person.Id, OnlineReservationPercent = 100, IsAvailable = false, StartReservationDate = DateTime.Now, VisitPrice = 0, PrePaymentPercent = 0, PaymentType = PaymentType.Free, ReservationRangeStartPoint = 0, ReservationRangeEndPointPosition = Position.AFTER, ReservationRangeEndPointDiffMinutes = 30, RankScore = 0, CreatedAt = DateTime.Now, Notification = "", Notification_Ar = "", Notification_Ku = "", PrescriptionPath = "" }; _dbContext.ServiceSupplies.Add(serviceSupply); await _dbContext.SaveChangesAsync(); await _dbContext.ServiceSupplyInfo.AddAsync(new ServiceSupplyInfo { ServiceSupplyId = serviceSupply.Id, MedicalCouncilNumber = "", AcceptionDate = DateTime.Now, Bio = "", Bio_Ar = "", Bio_Ku = "", Website = "", Description = "#Requested", Description_Ar = "#Requested", Description_Ku = "#Requested", Picture = "", IsDeleted = false, WorkExperience = 0, CreatedAt = DateTime.Now }); await _dbContext.SaveChangesAsync(); } #endregion #region Prescription File var destinationDirPath = $"wwwroot\\uploaded\\prescriptions\\shiftcenters\\{center.Id}\\{serviceSupply.Id}"; var fullDestinationDirPath = Path.Combine(_hostingEnvironment.ContentRootPath, destinationDirPath); if (!Directory.Exists(fullDestinationDirPath)) { Directory.CreateDirectory(fullDestinationDirPath); } _dbContext.Entry(serviceSupply).State = EntityState.Modified; serviceSupply.PrescriptionPath = Path.Combine(destinationDirPath, $"prescript_{serviceSupply.Id}.mrt"); await _dbContext.SaveChangesAsync(); var destinationPrescriptPath = Path.Combine(_hostingEnvironment.ContentRootPath, serviceSupply.PrescriptionPath); if (!System.IO.File.Exists(destinationPrescriptPath)) { // Remove all existing files try { DirectoryInfo di = new DirectoryInfo("fullDestinationDirPath"); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } } catch { // Ignored } try { System.IO.File.Copy(BasePrescriptFullPath, destinationPrescriptPath, true); } catch { throw new AwroNoreException("Can not copy prescription file. please try again"); } } #endregion // HTTP operations #region Identity User var userDTO = new UserDTO { UserName = inputModel.Username, Email = inputModel.Email, IsSystemUser = false, Mobile = inputModel.Mobile, Password = inputModel.Password, TwoFactorEnabled = false, UserProfile = new UserProfileDTO { CenterId = center.Id, PersonId = person.Id, ServiceSupplyIds = new List <int> { serviceSupply.Id }, LoginAs = SystemRoles.GetLoginAs(Role) }, Roles = new List <string> { Role } }; var(_, isSucceeded, message, _, _) = await _identityService.PostCreateAsync("user", userDTO); // if (!isSucceeded) throw new AwroNoreException(message); #endregion // IO operations #region Zip Archive Operations using (FileStream zipToOpen = new FileStream(ZipFilePath, FileMode.Open)) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { // Delete old readme file var item = archive.Entries.FirstOrDefault(x => x.FullName == ReadmeFileName); if (item != null) { item.Delete(); } // Create new readme file var readmeEntry = archive.CreateEntry(ReadmeFileName); // Read new file and write data using (Stream writer = readmeEntry.Open()) { var xmlSerializer = new XmlSerializer(typeof(RegisterOfflineResult)); var resultModel = new RegisterOfflineResult { Doctor = _mapper.Map <RegisterOfflineData>(inputModel) }; xmlSerializer.Serialize(writer, resultModel); } } } resultFileBytes = await System.IO.File.ReadAllBytesAsync(ZipFilePath); #endregion transaction.Commit(); } }); // Create result file var result = new FileContentResult(resultFileBytes, ContentType) { FileDownloadName = $"{Path.GetFileName(ZipFilePath)}" }; return(result); }
public async Task <DoctorDetailsDTO> GetDoctorDetailsAsync(int serviceSupplyId, Lang lang, int?centerServiceId = null, int?offerId = null) { var serviceSupply = await _serviceSupplyService.GetServiceSupplyByIdAsync(serviceSupplyId); if (serviceSupply == null) { throw new AwroNoreException(Global.Err_DoctorNotFound); } var Lng = lang; // Get all places that doctor work var suppliedSerivices = _serviceSupplyService.Table.Where(x => x.PersonId == serviceSupply.PersonId && x.IsAvailable).ToList(); var healthCentersWorkingHours = new List <DoctorCenterModel>(); foreach (var item in suppliedSerivices) { var centerName = ""; var centertype = HealthCenterType.Polyclinic; var centerAddress = ""; if (item.ShiftCenter.IsIndependent) { centerName = Lng == Lang.AR ? item.ShiftCenter.Name_Ar : Lng == Lang.KU ? item.ShiftCenter.Name_Ku : item.ShiftCenter.Name; centertype = HealthCenterType.Polyclinic; centerAddress = Lng == Lang.AR ? $"{item.ShiftCenter.City.Name_Ar}: {item.ShiftCenter.Address_Ar}" : lang == Lang.KU ? $"{item.ShiftCenter.City.Name_Ku}: {item.ShiftCenter.Address_Ku}" : $"{item.ShiftCenter.City.Name}: {item.ShiftCenter.Address}"; } else if (!item.ShiftCenter.IsIndependent && item.ShiftCenter.Clinic.IsIndependent) { centerName = Lng == Lang.AR ? item.ShiftCenter.Clinic.Name_Ar : Lng == Lang.KU ? item.ShiftCenter.Clinic.Name_Ku : item.ShiftCenter.Clinic.Name; centertype = HealthCenterType.Clinic; centerAddress = Lng == Lang.AR ? item.ShiftCenter.Clinic.City.Name_Ar : Lng == Lang.KU ? item.ShiftCenter.Clinic.City.Name_Ku + ": " + item.ShiftCenter.Clinic.Address_Ku : item.ShiftCenter.Clinic.City.Name + ": " + item.ShiftCenter.Clinic.Address; } else { centerName = Lng == Lang.AR ? item.ShiftCenter.Clinic.Hospital.Name_Ar : Lng == Lang.KU ? item.ShiftCenter.Clinic.Hospital.Name_Ku : item.ShiftCenter.Clinic.Hospital.Name; centertype = HealthCenterType.Hospital; centerAddress = Lng == Lang.AR ? $"{item.ShiftCenter.Clinic.Hospital.City.Name_Ar}: {item.ShiftCenter.Clinic.Hospital.Address_Ar}" : Lng == Lang.KU ? $"{item.ShiftCenter.Clinic.Hospital.City.Name_Ku}: {item.ShiftCenter.Clinic.Hospital.Address_Ku}" : $"{item.ShiftCenter.Clinic.Hospital.City.Name}: {item.ShiftCenter.Clinic.Hospital.Address}"; } var WorkingHours = new List <WorkingHourModel>(); var plans = item.UsualSchedulePlans.Where(x => x.ServiceSupplyId == serviceSupplyId).OrderBy(x => x.DayOfWeek).ToList(); foreach (var schedule in plans) { WorkingHours.Add(new WorkingHourModel { DayOfWeek = Utils.ConvertDayOfWeek(schedule.DayOfWeek.ToString()), Shift = schedule.Shift == ScheduleShift.Morning ? Global.Morning : Global.Evening, FromTime = schedule.StartTime, ToTime = schedule.EndTime, Service = Lng == Lang.AR ? schedule.ShiftCenterService?.Service.Name_Ar : Lng == Lang.KU ? schedule.ShiftCenterService?.Service.Name_Ku : schedule.ShiftCenterService?.Service.Name, MaxCount = schedule.MaxCount }); } healthCentersWorkingHours.Add(new DoctorCenterModel { CenterName = centerName, CenterType = centertype, CenterAddress = centerAddress, WorkingHoures = WorkingHours }); } TurnModel firstTurn = null; if (centerServiceId != null) { firstTurn = await GetNextFirstAvailableTurnAsync(serviceSupplyId, centerServiceId.Value, lang); } var firstExpertise = serviceSupply.DoctorExpertises.FirstOrDefault(); var result = new DoctorDetailsDTO { Id = serviceSupply.Id, FullName = lang == Lang.KU ? serviceSupply.Person.FullName_Ku : lang == Lang.AR ? serviceSupply.Person.FullName_Ar : serviceSupply.Person.FullName, Avatar = serviceSupply.Person.RealAvatar, ExpertiseCategory = firstExpertise != null ? lang == Lang.AR ? firstExpertise.Expertise.ExpertiseCategory.Name_Ar : lang == Lang.KU ? firstExpertise.Expertise.ExpertiseCategory.Name_Ku : firstExpertise.Expertise.ExpertiseCategory.Name : "", Address = lang == Lang.KU ? serviceSupply.ShiftCenter.Address_Ku : lang == Lang.AR ? serviceSupply.ShiftCenter.Address_Ar : serviceSupply.ShiftCenter.Address, HasEmptyTurn = firstTurn != null, Province = serviceSupply.ShiftCenter.IsIndependent ? (Lng == Lang.AR ? serviceSupply.ShiftCenter.City.Province.Name_Ar : Lng == Lang.KU ? serviceSupply.ShiftCenter.City.Province.Name_Ku : serviceSupply.ShiftCenter.City.Province.Name) : (Lng == Lang.AR ? serviceSupply.ShiftCenter.Clinic.City.Province.Name_Ar : Lng == Lang.KU ? serviceSupply.ShiftCenter.Clinic.City.Province.Name_Ku : serviceSupply.ShiftCenter.Clinic.City.Province.Name), MedicalCouncilNumber = serviceSupply.ServiceSupplyInfo?.MedicalCouncilNumber, FirstAvailableTurn = firstTurn, Latitude = serviceSupply.ShiftCenter.Location?.Y.ToString(), Longitude = serviceSupply.ShiftCenter.Location?.X.ToString(), Schedules = await GetSchedulesAsync(serviceSupply.Id, lang) }; if (serviceSupply.ShiftCenter.PhoneNumbers != null) { result.Phones = serviceSupply.ShiftCenter.PhoneNumbers.Where(p => p.IsForReserve).Select(x => new ShiftCenterPhoneModel { PhoneNumber = x.PhoneNumber, IsForReserve = x.IsForReserve }).ToList(); } result.Expertises = serviceSupply.DoctorExpertises.Select(x => Lng == Lang.AR ? x.Expertise.Name_Ar : Lng == Lang.KU ? x.Expertise.Name_Ku : x.Expertise.Name).ToList(); result.Description = Lng == Lang.AR ? serviceSupply.ShiftCenter.Description_Ar : Lng == Lang.KU ? serviceSupply.ShiftCenter.Description_Ku : serviceSupply.ShiftCenter.Description; result.Notification = Lng == Lang.AR ? serviceSupply.ShiftCenter.Notification_Ar : Lng == Lang.KU ? serviceSupply.ShiftCenter.Notification_Ku : serviceSupply.ShiftCenter.Notification; result.WorkingCenters = healthCentersWorkingHours; var photosQuery = _dbContext.Attachments.Where(x => x.Owner == FileOwner.SHIFT_CENTER && x.OwnerTableId == serviceSupply.ShiftCenterId && x.FileType == FileType.Image); result.Photos = await photosQuery.Select(x => x.Url).ToListAsync(); result.PhotosThumbs = await photosQuery.Select(x => x.ThumbnailUrl).ToListAsync(); result.Grades = serviceSupply.ServiceSupplyInfo?.DoctorScientificCategories.Select(x => Lng == Lang.AR ? x.ScientificCategory.Name_Ar : Lng == Lang.KU ? x.ScientificCategory.Name_Ku : x.ScientificCategory.Name).ToList(); result.Bio = Lng == Lang.EN ? serviceSupply.ServiceSupplyInfo?.Bio : Lng == Lang.AR ? serviceSupply.ServiceSupplyInfo?.Bio_Ar : serviceSupply.ServiceSupplyInfo?.Bio_Ku; if (offerId != null) { var offer = await _dbContext.Offers.FindAsync(offerId); if (offer != null) { offer.VisitsCount += 1; _dbContext.Attach(offer); _dbContext.Entry(offer).State = EntityState.Modified; _dbContext.Offers.Update(offer); await _dbContext.SaveChangesAsync(); } } return(result); }
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 <IActionResult> CreateUpdate(PersonCreateUpdateViewModel model) { if (string.IsNullOrEmpty(model.Mobile) || model.Mobile.Length < 10) { throw new Exception("Mobile is not valid"); } var isNumeric = double.TryParse(model.Mobile, out _); if (!isNumeric) { throw new Exception("Mobile Number Is Not Valid"); } if (model.Mobile.Length > 10) { model.Mobile = model.Mobile.Substring(model.Mobile.Length - 10); } var duplicateMobile = await _dbContext.Persons.AnyAsync(x => x.Id != model.Id && x.Mobile == model.Mobile); if (duplicateMobile) { throw new AwroNoreException(Core.Resources.EntitiesResources.Messages.PersonMobileDuplicate); } var success = false; var message = Core.Resources.Global.Global.Err_ErrorOccured; var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { if (model.Id != null) { var person = await _personService.GetByIdAsync(model.Id.Value); if (person == null) { throw new Exception("Person Not Found"); } person.FirstName = model.FirstName; person.FirstName_Ku = model.FirstName_Ku; person.FirstName_Ar = model.FirstName_Ar; person.SecondName = model.SecondName; person.SecondName_Ku = model.SecondName_Ku; person.SecondName_Ar = model.SecondName_Ar; person.ThirdName = model.ThirdName; person.ThirdName_Ku = model.ThirdName_Ku; person.ThirdName_Ar = model.ThirdName_Ar; person.Gender = model.Gender; person.Mobile = model.Mobile; person.IsEmployee = model.IsEmployee; _dbContext.Persons.Attach(person); _dbContext.Entry(person).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); if (model.ImageUpload != null) { var(newName, thumbName, dirPath, baseUrl) = _uploadService.GeneratePersonAvatarName(person.Id, model.ImageUpload); person.Avatar = $"{baseUrl}/{thumbName}"; _dbContext.Persons.Attach(person); _dbContext.Entry(person).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); await _uploadService.UploadPersonAvatarAsync(model.ImageUpload, dirPath, newName, thumbName); } message = AN.Core.Resources.EntitiesResources.Messages.ItemUpdatedSuccessFully; } else { var person = _mapper.Map <Person>(model); person.UniqueId = await _personService.GenerateUniqueIdAsync(); await _dbContext.Persons.AddAsync(person); await _dbContext.SaveChangesAsync(); var(newName, thumbName, dirPath, baseUrl) = _uploadService.GeneratePersonAvatarName(person.Id, model.ImageUpload); person.Avatar = $"{baseUrl}/{thumbName}"; _dbContext.Persons.Attach(person); _dbContext.Entry(person).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); await _uploadService.UploadPersonAvatarAsync(model.ImageUpload, dirPath, newName, thumbName); message = Core.Resources.EntitiesResources.Messages.ItemAddedSuccessFully; } transaction.Commit(); success = true; } }); return(Json(new { success, message })); }
public virtual async Task <IActionResult> Create(ClinicViewModel Model) { try { if (ModelState.IsValid) { if (LoginAs == Shared.Enums.LoginAs.HOSPITALMANAGER) { Model.HospitalId = _hospitalService.GetCurrentHospital()?.Id; } var clinic = new Clinic(); //Set New Phones To clinic // :: First:> Delete all pre phones var clinicPhones = new List <ShiftCenterPhoneModel> { new ShiftCenterPhoneModel { PhoneNumber = Model.Phone1, IsForReserve = Model.Phone1IsForReserve, } }; if (Model.Phone2 != null) { clinicPhones.Add(new ShiftCenterPhoneModel { PhoneNumber = Model.Phone2, IsForReserve = Model.Phone2IsForReserve, }); } if (Model.Phone3 != null) { clinicPhones.Add(new ShiftCenterPhoneModel { PhoneNumber = Model.Phone3, IsForReserve = Model.Phone3IsForReserve, }); } if (Model.Id.HasValue) { #region Edit clinic clinic = await _dbContext.Clinics.FindAsync(Model.Id); if (clinic == null) { throw new EntityNotFoundException(); } _dbContext.Entry(clinic).State = EntityState.Modified; if (LoginAs == Shared.Enums.LoginAs.ADMIN) { clinic.HospitalId = Model.HospitalId; clinic.IsIndependent = Model.HospitalId == null; } clinic.Name = Model.Name; clinic.Name_Ku = Model.Name_Ku; clinic.Name_Ar = Model.Name_Ar; clinic.Description = Model.Description; clinic.Description_Ku = Model.Description_Ku; clinic.Description_Ar = Model.Description_Ar; clinic.CityId = Model.CityId; clinic.Address = Model.Address; clinic.Address_Ku = Model.Address_Ku; clinic.Address_Ar = Model.Address_Ar; clinic.FinalBookMessage = Model.FinalBookMessage; clinic.FinalBookMessage_Ku = Model.FinalBookMessage_Ku; clinic.FinalBookMessage_Ar = Model.FinalBookMessage_Ar; clinic.FinalBookSMSMessage = Model.FinalBookSMSMessage; clinic.FinalBookSMSMessage_Ku = Model.FinalBookSMSMessage_Ku; clinic.FinalBookSMSMessage_Ar = Model.FinalBookSMSMessage_Ar; clinic.Notification = Model.Notification; clinic.Notification_Ku = Model.Notification_Ku; clinic.Notification_Ar = Model.Notification_Ar; clinic.IsGovernmental = Model.IsGovernmental; clinic.IsHostelry = Model.IsHostelry; clinic.Type = Model.Type; clinic.UpdatedAt = DateTime.Now; clinic.PhoneNumbers = clinicPhones; double.TryParse(Model.GoogleMap_lng, out double x_longitude); double.TryParse(Model.GoogleMap_lat, out double y_latitude); clinic.Location = new NetTopologySuite.Geometries.Point(x_longitude, y_latitude) { SRID = 4326 // Set the SRID (spatial reference system id) to 4326, which is the spatial reference system used by Google maps (WGS84) }; logger.Info("Clinic with name " + clinic.Name_Ku + " edited by " + CurrentUserName); TempData.Put("message", new MVCResultModel { status = MVCResultStatus.success, message = Core.Resources.EntitiesResources.Messages.ItemUpdatedSuccessFully }); #endregion } else { if (LoginAs == Shared.Enums.LoginAs.CLINICMANAGER) { throw new Exception("You can not create clinic from here"); } double.TryParse(Model.GoogleMap_lng, out double x_longitude); double.TryParse(Model.GoogleMap_lat, out double y_latitude); #region Add New clinic clinic = new Clinic { Name = Model.Name, Name_Ku = Model.Name_Ku, Name_Ar = Model.Name_Ar, Description = Model.Description, Description_Ku = Model.Description_Ku, Description_Ar = Model.Description_Ar, CityId = Model.CityId, Address = Model.Address, Address_Ku = Model.Address_Ku, Address_Ar = Model.Address_Ar, IsIndependent = Model.HospitalId == null, IsApproved = true, IsDeleted = false, HospitalId = Model.HospitalId, FinalBookMessage = Model.FinalBookMessage, FinalBookMessage_Ku = Model.FinalBookMessage_Ku, FinalBookMessage_Ar = Model.FinalBookMessage_Ar, FinalBookSMSMessage = Model.FinalBookSMSMessage, FinalBookSMSMessage_Ku = Model.FinalBookSMSMessage_Ku, FinalBookSMSMessage_Ar = Model.FinalBookSMSMessage_Ar, Notification_Ku = Model.Notification_Ku, Notification = Model.Notification, Notification_Ar = Model.Notification_Ar, IsGovernmental = Model.IsGovernmental, IsHostelry = Model.IsHostelry, Type = Model.Type, PhoneNumbers = clinicPhones, CreatedAt = DateTime.Now, Location = new NetTopologySuite.Geometries.Point(x_longitude, y_latitude) { SRID = 4326 // Set the SRID (spatial reference system id) to 4326, which is the spatial reference system used by Google maps (WGS84) } }; _dbContext.Clinics.Add(clinic); await _dbContext.SaveChangesAsync(); _dbContext.Entry(clinic).State = EntityState.Modified; logger.Info("Clinic with name " + clinic.Name_Ku + " created by " + HttpContext.User.Identity.Name); TempData.Put("message", new MVCResultModel { status = MVCResultStatus.success, message = Core.Resources.EntitiesResources.Messages.ItemAddedSuccessFully }); #endregion } await _dbContext.SaveChangesAsync(); if (LoginAs == Shared.Enums.LoginAs.CLINICMANAGER) { return(RedirectToAction("Index", "Home", new { area = "ClinicManager" })); } return(RedirectToAction("Index", "CommonClinic", new { area = "" })); } } catch (Exception e) { var message = e.Message; } TempData.Put("message", new MVCResultModel { status = MVCResultStatus.danger, message = Model.Id.HasValue ? Core.Resources.EntitiesResources.Messages.AnErrorOccuredWhileUpdateItem : Core.Resources.EntitiesResources.Messages.AnErrorOccuredWhileAddingItem }); if (LoginAs != Shared.Enums.LoginAs.HOSPITALMANAGER) { ViewBag.Hospitals = await GetHospitalsSelectListAsync(); } Model.listCities = _commonUtils.PopulateCitiesList(); return(View(Model)); }
public async Task <ConsultancyMessageDTO> SendMultiMediaMessageAsync(SendMessageDTO model, IFormFile file) { ConsultancyMessageDTO result = null; var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { var msg = new ConsultancyMessage { ConsultancyId = model.ConsultancyId, ServiceSupplyId = model.ServiceSupplyId, PersonId = model.PersonId, CreatedAt = DateTime.Now, Content = "", Status = ConsultancyMessageStatus.NEW, Sender = model.Sender, Type = model.Type, }; await _dbContext.ConsultancyMessages.AddAsync(msg); await _dbContext.SaveChangesAsync(); if (model.Type == ConsultancyMessageType.PHOTO) { var(newName, thumbName, dirPath, baseUrl) = _uploadService.GenerateConsultancyMessageImageName(model.ConsultancyId, msg.Id, file); var url = $"{baseUrl}/{newName}"; var thumbUrl = $"{baseUrl}/{thumbName}"; msg.Content = $"{url},{thumbUrl}"; _dbContext.ConsultancyMessages.Attach(msg); _dbContext.Entry(msg).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); await _uploadService.UploadConsultancyMessageImageAsync(file, dirPath, newName, thumbName); } else if (model.Type == ConsultancyMessageType.VOICE) { var(newName, dirPath, baseUrl) = _uploadService.GenerateConsultancyMessageVoiceName(model.ConsultancyId, msg.Id, file); var url = $"{baseUrl}/{newName}"; msg.Content = $"{url}"; _dbContext.ConsultancyMessages.Attach(msg); _dbContext.Entry(msg).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); await _uploadService.UploadConsultancyMessageVoiceAsync(file, dirPath, newName); } result = new ConsultancyMessageDTO { Id = msg.Id, SenderReceiverType = msg.Sender == ConsultancyMessageSender.CUSTOMER ? MessageSenderReceiverType.SENT : MessageSenderReceiverType.RECEIVED, Message = msg.Content, Time = msg.CreatedAt.ToString("HH:mm"), Type = msg.Type }; transaction.Commit(); } }); await NotifyMessageReceiverAsync(model, result); return(result ?? throw new AwroNoreException("")); }
public async Task <BookingAppointmentResult> BookAppointmentAsync( ServiceSupply serviceSupply, PatientModel patinetModel, string Date, string StartTime, string EndTime, bool _existUser, PaymentStatus paymentStatus, ShiftCenterService polyclinicHealthService, ReservationChannel channel, Lang requestLang, int?offerId = null) { var resultMessage = Messages.ErrorOccuredWhileFinalBookTurn; try { if (serviceSupply == null) { throw new ArgumentNullException(nameof(serviceSupply)); } if (string.IsNullOrEmpty(Date) || string.IsNullOrEmpty(StartTime) || string.IsNullOrEmpty(EndTime)) { throw new ArgumentNullException("Date"); } var tmpStatus = paymentStatus == PaymentStatus.NotPayed ? AppointmentStatus.Unknown : AppointmentStatus.Pending; var startDateTime = DateTime.Parse(Date + " " + StartTime); var endDateTime = DateTime.Parse(Date + " " + EndTime); var date = DateTime.Parse(Date).Date; long appointmentId = -1; string trackingCode = string.Empty; var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { try { if (offerId != null) { var offer = await _dbContext.Offers.FindAsync(offerId.Value); if (offer == null) { throw new AwroNoreException("Offer Not Found"); } if (offer.RemainedCount <= 0) { throw new AwroNoreException("All Offer Appointments Are Reserved"); } offer.RemainedCount -= 1; _dbContext.Entry(offer).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); } #region book appointment for new user if (!_existUser) { var patientUser = new Person { NamePrefix = patinetModel.NamePrefix, FirstName = patinetModel.FirstName, SecondName = patinetModel.SecondName, ThirdName = patinetModel.ThirdName, Age = patinetModel.Age, Gender = patinetModel.Gender, Mobile = patinetModel.Mobile, ZipCode = patinetModel.ZipCode, Address = patinetModel.Address, Description = patinetModel.Description, CreatedAt = DateTime.Now, IsApproved = true, IsDeleted = false, CreatorRole = Shared.Enums.LoginAs.UNKNOWN, CreationPlaceId = null }; _dbContext.Persons.Add(patientUser); _dbContext.SaveChanges(); // TODO: // var createUser = userManager.Create(patientUser, patinetModel.Password); //if (createUser.Succeeded) //{ // var assignPatientRole = userManager.AddToRole(patientUser.Id, UsersRoleName.Patient.ToString()); // if (!assignPatientRole.Succeeded) // { // throw new Exception(Messages.ErrorOccuredWhileAssignRole); // } //} _dbContext.PatientPersonInfo.Add(new PatientPersonInfo { PersonId = patientUser.Id, CreatedAt = DateTime.Now }); #region Set Patient Insurance int?_patientInsuranceId = null; if (patinetModel.InsuranceId != 0 && patinetModel.InsuranceNumber != null) { var _patientInsurance = new PatientInsurance { UserPatientId = patientUser.Id, ServiceSupplyInsuranceId = patinetModel.InsuranceId, InsuranceNumber = patinetModel.InsuranceNumber, CreatedAt = DateTime.Now }; _dbContext.PatientInsurances.Add(_patientInsurance); _dbContext.SaveChanges(); _patientInsuranceId = _patientInsurance.Id; } #endregion var finalBookabeTimePeriods = _doctorServiceManager.CalculateFinalBookableTimePeriods(serviceSupply, startDateTime, polyclinicHealthService); if (finalBookabeTimePeriods == null || finalBookabeTimePeriods.Count() <= 0) { throw new Exception(Messages.ValidEmptyTimePeriodNotFound); } var ipaTimePeriod = finalBookabeTimePeriods.FirstOrDefault(f => f.StartDateTime == startDateTime && f.EndDateTime == endDateTime && f.Type == TimePeriodType.InProgressAppointment); if (ipaTimePeriod == null) { throw new Exception(Messages.ValidEmptyTimePeriodNotFound); } trackingCode = await _appointmentService.GenerateUniqueTrackingNumberAsync(); var appointment = new Appointment { UniqueTrackingCode = trackingCode, Book_DateTime = DateTime.Now, Start_DateTime = startDateTime, End_DateTime = endDateTime, Description = " ", Status = tmpStatus, ServiceSupplyId = serviceSupply.Id, PersonId = patientUser.Id, PatientInsuranceId = _patientInsuranceId, IsAnnounced = false, Paymentstatus = paymentStatus, IsDeleted = false, ShiftCenterServiceId = polyclinicHealthService.Id, ReservationChannel = channel, CreatedAt = DateTime.Now, OfferId = offerId, RequestLang = requestLang }; _dbContext.Appointments.Add(appointment); _dbContext.SaveChanges(); #region Send SMS notification if (channel != ReservationChannel.Kiosk) { try { var doctor_name = serviceSupply.Person.FullName; var persian_dayOfWeek = Utils.ConvertDayOfWeek(startDateTime.DayOfWeek.ToString()); var day_number = startDateTime.ToShortDateString().Split('/')[2]; var persian_month = Utils.GetMonthName(startDateTime); var year_number = startDateTime.ToShortDateString().Split('/')[0]; var time = startDateTime.ToShortTimeString(); var smsBody = $"{Messages.YourAppointmentForDoctor} { doctor_name} ، { persian_dayOfWeek} { day_number} { persian_month} {year_number} ،{Global.Hour}: {time}"; if (channel == ReservationChannel.ClinicManagerSection) { smsBody = smsBody = "Turn for doctor " + doctor_name + ", " + persian_dayOfWeek + " " + day_number + " " + persian_month + " " + year_number; } string[] recepient = { $"964{patinetModel.Mobile}" }; if (serviceSupply.ShiftCenter.IsIndependent) { if (Lng == Lang.KU) { if (serviceSupply.ShiftCenter.FinalBookSMSMessage_Ku != null) { smsBody = serviceSupply.ShiftCenter.FinalBookSMSMessage_Ku; } } else if (Lng == Lang.AR) { if (serviceSupply.ShiftCenter.FinalBookSMSMessage_Ar != null) { smsBody = serviceSupply.ShiftCenter.FinalBookSMSMessage_Ar; } } } else if (serviceSupply.ShiftCenter.Clinic != null && serviceSupply.ShiftCenter.Clinic.IsIndependent) { if (Lng == Lang.KU) { if (serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ku != null) { smsBody = serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ku; } } else if (Lng == Lang.AR) { if (serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ar != null) { smsBody = serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ar; } } } else if (serviceSupply.ShiftCenter.Clinic != null && serviceSupply.ShiftCenter.Clinic.Hospital != null) { if (Lng == Lang.KU) { if (serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ku != null) { smsBody = serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ku; } } else if (Lng == Lang.AR) { if (serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ar != null) { smsBody = serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ar; } } } _plivoService.SendMessage(recepient.ToList(), smsBody); _dbContext.Entry(appointment).State = EntityState.Modified; appointment.IsAnnounced = true; } catch { } } #endregion _iPAsManager.Delete(serviceSupply.Id, startDateTime); _dbContext.SaveChanges(); appointmentId = appointment.Id; } #endregion #region book appointment for existing user else if (_existUser == true) { var user = await _dbContext.Persons.FirstOrDefaultAsync(u => u.Mobile == patinetModel.Mobile); if (user == null) { throw new EntityNotFoundException(); } // TODO //if (!userManager.IsInRole(user.Id, UsersRoleName.Patient.ToString())) //{ // var assignPatientRole = userManager.AddToRole(user.Id, UsersRoleName.Patient.ToString()); // if (!assignPatientRole.Succeeded) // { // throw new Exception(Messages.ErrorOccuredWhileAssignRole); // } //} if (user.PatientPersonInfo == null) { _dbContext.PatientPersonInfo.Add(new PatientPersonInfo { PersonId = user.Id, CreatedAt = DateTime.Now }); } #region Set Patient Insurance //Check if user already used current insurance name and number int?patientInsuranId = null; if (patinetModel.InsuranceId != 0 && patinetModel.InsuranceNumber != null) { var oldInsurance = user.PatientPersonInfo.PatientInsurances.FirstOrDefault(pi => pi.InsuranceNumber == patinetModel.InsuranceNumber && pi.ServiceSupplyInsuranceId == patinetModel.InsuranceId); if (oldInsurance == null) { var _patientInsurance = new PatientInsurance { UserPatientId = user.Id, ServiceSupplyInsuranceId = patinetModel.InsuranceId, InsuranceNumber = patinetModel.InsuranceNumber, CreatedAt = DateTime.Now }; _dbContext.PatientInsurances.Add(_patientInsurance); _dbContext.SaveChanges(); patientInsuranId = _patientInsurance.Id; } else { patientInsuranId = oldInsurance.Id; } } #endregion var finalBookabeTimePeriods = _doctorServiceManager.CalculateFinalBookableTimePeriods(serviceSupply, startDateTime, polyclinicHealthService); if (finalBookabeTimePeriods == null || finalBookabeTimePeriods.Count() <= 0) { throw new Exception(Messages.ValidEmptyTimePeriodNotFound); } var ipaTimePeriod = finalBookabeTimePeriods.FirstOrDefault(f => f.StartDateTime == startDateTime && f.EndDateTime == endDateTime && f.Type == TimePeriodType.InProgressAppointment); if (ipaTimePeriod == null) { throw new Exception(Messages.ValidEmptyTimePeriodNotFound); } trackingCode = await _appointmentService.GenerateUniqueTrackingNumberAsync(); var appointment = new Appointment { UniqueTrackingCode = trackingCode, Book_DateTime = DateTime.Now, Start_DateTime = startDateTime, End_DateTime = endDateTime, Description = " ", Status = tmpStatus, ServiceSupplyId = serviceSupply.Id, PersonId = user.Id, PatientInsuranceId = patientInsuranId, IsAnnounced = false, Paymentstatus = paymentStatus, IsDeleted = false, ShiftCenterServiceId = polyclinicHealthService.Id, ReservationChannel = channel, CreatedAt = DateTime.Now, OfferId = offerId, RequestLang = requestLang }; _dbContext.Appointments.Add(appointment); _dbContext.SaveChanges(); #region Send SMS notification if (channel != ReservationChannel.Kiosk) { try { var doctor_name = serviceSupply.Person.FullName; var persian_dayOfWeek = Utils.ConvertDayOfWeek(startDateTime.DayOfWeek.ToString()); var day_number = startDateTime.ToShortDateString().Split('/')[2]; var persian_month = Utils.GetMonthName(startDateTime); var year_number = startDateTime.ToShortDateString().Split('/')[0]; var time = startDateTime.ToShortTimeString(); var smsBody = $"{Messages.YourAppointmentForDoctor} { doctor_name} ، { persian_dayOfWeek} { day_number} { persian_month} {year_number} ،{Global.Hour}: {time}"; if (channel == ReservationChannel.ClinicManagerSection) { smsBody = smsBody = "Turn for doctor " + doctor_name + ", " + persian_dayOfWeek + " " + day_number + " " + persian_month + " " + year_number; } string[] recepient = { $"964{patinetModel.Mobile}" }; if (serviceSupply.ShiftCenter.IsIndependent) { if (Lng == Lang.KU) { if (serviceSupply.ShiftCenter.FinalBookSMSMessage_Ku != null) { smsBody = serviceSupply.ShiftCenter.FinalBookSMSMessage_Ku; } } else if (Lng == Lang.AR) { if (serviceSupply.ShiftCenter.FinalBookSMSMessage_Ar != null) { smsBody = serviceSupply.ShiftCenter.FinalBookSMSMessage_Ar; } } } else if (serviceSupply.ShiftCenter.Clinic != null && serviceSupply.ShiftCenter.Clinic.IsIndependent) { if (Lng == Lang.KU) { if (serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ku != null) { smsBody = serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ku; } } else if (Lng == Lang.AR) { if (serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ar != null) { smsBody = serviceSupply.ShiftCenter.Clinic.FinalBookSMSMessage_Ar; } } } else if (serviceSupply.ShiftCenter.Clinic != null && serviceSupply.ShiftCenter.Clinic.Hospital != null) { if (Lng == Lang.KU) { if (serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ku != null) { smsBody = serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ku; } } else if (Lng == Lang.AR) { if (serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ar != null) { smsBody = serviceSupply.ShiftCenter.Clinic.Hospital.FinalBookSMSMessage_Ar; } } } _plivoService.SendMessage(recepient.ToList(), smsBody); _dbContext.Entry(appointment).State = EntityState.Modified; appointment.IsAnnounced = true; } catch { } } #endregion _iPAsManager.Delete(serviceSupply.Id, startDateTime); _dbContext.SaveChanges(); appointmentId = appointment.Id; } #endregion transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw ex; } } }); return(new BookingAppointmentResult { Status = BookingAppointmentStatus.Success, Message = Messages.TurnBookedFinally, AppointmentId = appointmentId, TrackingCode = trackingCode }); } catch (Exception ex) { resultMessage = ex.Message; } return(new BookingAppointmentResult { Status = BookingAppointmentStatus.Failure, Message = resultMessage }); }
public async Task <IActionResult> CreateUpdate(ServiceViewModel model) { var message = model.Id != null ? Messages.ItemUpdatedSuccessFully : Messages.ItemAddedSuccessFully; decimal.TryParse(model.Price, out decimal price); var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { if (model.Id != null) { var service = await _dbContext.Services.FindAsync(model.Id); if (service == null) { throw new AwroNoreException("Service Not Found"); } service.Name = model.Name; service.Name_Ar = model.Name_Ar; service.Name_Ku = model.Name_Ku; service.Description = model.Description; service.Description_Ku = model.Description_Ku; service.Description_Ar = model.Description_Ar; service.Price = price; service.Time = model.Time; service.ServiceCategoryId = model.ServiceCategoryId; service.UpdatedAt = DateTime.Now; _dbContext.Services.Attach(service); _dbContext.Entry(service).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); } else { var service = new Service { Name = model.Name, Name_Ku = model.Name_Ku, Name_Ar = model.Name_Ar, Description = model.Description, Description_Ar = model.Description_Ar, Description_Ku = model.Description_Ku, ServiceCategoryId = model.ServiceCategoryId, Price = price, Time = model.Time, CreatedAt = DateTime.Now, }; await _dbContext.Services.AddAsync(service); await _dbContext.SaveChangesAsync(); } transaction.Commit(); } }); return(Json(new { success = true, message })); }
public async Task <IActionResult> AddClinicVocationDay(CMVocationViewModel model) { try { if (ModelState.IsValid) { var fromDate = DateTime.Parse(model.FromDate); var toDate = DateTime.Parse(model.ToDate); var clinic = await _dbContext.Clinics.FindAsync(CurrentClinic.Id); _dbContext.Entry(clinic).State = EntityState.Modified; var vocations = new List <VocationModel>(); if (clinic.Vocations != null) { vocations = clinic.Vocations; } vocations.Add(new VocationModel { F = fromDate, T = toDate }); var specialSchedules = _dbContext.Schedules .Where(s => s.ServiceSupply.ShiftCenter.ClinicId == clinic.Id) .AsEnumerable() .Where(s => s.Start_DateTime.Date >= fromDate.Date && s.Start_DateTime.Date <= toDate.Date).ToList(); foreach (var s in specialSchedules) { _dbContext.Entry(s).State = EntityState.Modified; s.IsAvailable = false; } clinic.Vocations = vocations; await _dbContext.SaveChangesAsync(); TempData.Put("message", new MVCResultModel { status = MVCResultStatus.success, message = Messages.ItemAddedSuccessFully }); return(RedirectToAction("ClinicVocations", "Schedule", new { area = "ClinicManager" })); } TempData.Put("message", new MVCResultModel { status = MVCResultStatus.danger, message = Messages.PleaseEnterAllRequestedData }); } catch (Exception) { TempData.Put("message", new MVCResultModel { status = MVCResultStatus.danger, message = Messages.ErrorOccuredWhileDoneAction }); } return(RedirectToAction("ClinicVocations", new CMVocationViewModel())); }
public async Task <IActionResult> Create(InvoiceViewModel model, InvoiceItemsGridViewModel[] items) { if (model.Id == null && model.AppointmentId != null && model.PatientId != null) { throw new AwroNoreException("Can not create invoice for appointment & patient"); } if (items == null || !items.Any()) { throw new AwroNoreException("Please enter at least one item"); } if (items.Any(x => (x.ShiftCenterServiceId == null || x.ShiftCenterServiceId <= 0) && string.IsNullOrEmpty(x.CustomServiceName))) { throw new AwroNoreException("Please select service for all items"); } bool success = false; var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = _dbContext.Database.BeginTransaction()) { try { if (model.Id != null) { var invoice = await _dbContext.Invoices.FindAsync(model.Id); if (invoice == null || invoice.Patient.ServiceSupply.ShiftCenterId != CurrentBeautyCenter.Id) { throw new AwroNoreException("Invoice Not Found"); } var invoiceItems = await _dbContext.InvoiceItems.Where(x => x.InvoiceId == invoice.Id).ToListAsync(); if (invoiceItems.Any()) { _dbContext.InvoiceItems.RemoveRange(invoiceItems); await _dbContext.SaveChangesAsync(); } if (items != null && items.Any()) { var treats = items.Where(x => !x.IsDeleted && (x.ShiftCenterServiceId != null && x.ShiftCenterServiceId > 0) || !string.IsNullOrEmpty(x.CustomServiceName)).Select(x => new InvoiceItem { InvoiceId = invoice.Id, ShiftCenterCerviceId = x.ShiftCenterServiceId, CustomServiceName = x.CustomServiceName, Price = x.Price, Note = x.Note, CreatedAt = DateTime.Now, }).ToList(); _dbContext.InvoiceItems.AddRange(treats); await _dbContext.SaveChangesAsync(); } invoice.VisitDate = DateTime.Parse(model.VisitDate); invoice.Description = model.Description ?? ""; _dbContext.Invoices.Attach(invoice); _dbContext.Entry(invoice).State = EntityState.Modified; await _dbContext.SaveChangesAsync(); } else { Appointment appointment = null; Patient patient = null; if (model.AppointmentId != null) { appointment = await _dbContext.Appointments.FindAsync(model.AppointmentId); if (appointment == null) { throw new AwroNoreException("Appointment Not Found"); } patient = await _dbContext.Patients.FirstOrDefaultAsync(x => x.ServiceSupplyId == appointment.ServiceSupplyId && x.PersonId == appointment.PersonId); if (patient == null) { patient = new Patient { ServiceSupplyId = appointment.ServiceSupplyId, PersonId = appointment.PersonId, CreatedAt = DateTime.Now }; await _dbContext.Patients.AddAsync(patient); await _dbContext.SaveChangesAsync(); } } else if (model.PatientId != null) { patient = await _dbContext.Patients.FindAsync(model.PatientId.Value) ?? throw new AwroNoreException("Patient Not Found"); } var invoice = new Invoice { PatientId = patient.Id, AppointmentId = model.AppointmentId, CreatedAt = DateTime.Now, Description = model.Description ?? "", VisitDate = DateTime.Parse(model.VisitDate) }; _dbContext.Invoices.Add(invoice); await _dbContext.SaveChangesAsync(); if (items != null && items.Any()) { var treats = items.Where(x => !x.IsDeleted && (x.ShiftCenterServiceId != null && x.ShiftCenterServiceId > 0) || !string.IsNullOrEmpty(x.CustomServiceName)).Select(x => new InvoiceItem { InvoiceId = invoice.Id, ShiftCenterCerviceId = x.ShiftCenterServiceId, CustomServiceName = x.CustomServiceName, Price = x.Price, Note = x.Note, CreatedAt = DateTime.Now, }).ToList(); var oldItems = await _dbContext.InvoiceItems.Where(x => x.InvoiceId == invoice.Id).ToListAsync(); if (oldItems.Any()) { _dbContext.InvoiceItems.RemoveRange(oldItems); } _dbContext.InvoiceItems.AddRange(treats); await _dbContext.SaveChangesAsync(); } if (appointment != null) { _dbContext.Entry(appointment).State = EntityState.Modified; appointment.Status = AppointmentStatus.Done; await _dbContext.SaveChangesAsync(); await SendDoneAppointmentNotificationAsync(appointment, patient); } } transaction.Commit(); success = true; } catch { transaction.Rollback(); throw; } } }); return(Json(new { success, message = success ? Core.Resources.EntitiesResources.Messages.ActionDoneSuccesfully : Core.Resources.EntitiesResources.Messages.ErrorOccuredWhileDoneAction })); }