public static Status CheckUserStatus(UserDto user) { if (Status.Expired.Equals(user.Status)) { return user.Status; } bool finalStep = false; switch (user.Role) { case Role.Customer: if (CUSTOMER_FINISHED_REGISTER_STEP.Equals(user.CompletedStep)) finalStep = true; break; case Role.Specialist: if (SPECIALIST_FINISHED_REGISTER_STEP.Equals(user.CompletedStep)) finalStep = true; break; default: finalStep = false; break; } if (user.IsEmailConfirmed && user.IsPhoneConfirmed && finalStep) { return Status.Active; } return Status.InActive; }
/// <summary> /// Remove password and security stamp in user model before send it to client /// </summary> public static UserDto RemoveUnusedAttr(UserDto user) { user.Password = string.Empty; user.SecurityStamp = string.Empty; return user; }
//public static bool IsSpecialistStandardHour(int specialistID, DateTime startTime, DateTime endTime, IServices service) //{ // bool isStandardHour = false; // isStandardHour = service.StandardHour.IsStandardHour(specialistID, startTime, endTime); // return isStandardHour; //} /// <summary> /// calculate fee for customer and speclist when book time or reschedule /// </summary> /// <param name="specialistId"></param> /// <param name="IsSpecialist"></param> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <param name="service"></param> /// <param name="specializationId"></param> /// <returns></returns> public static decimal GetbookingRateByBookDate(Guid bookingId, UserDto specialist, bool IsSpecialist, DateTime startTime, DateTime endTime, IServices services) { decimal rate = 0; //TODO: will use function check standardhour when branch 226369 merged bool isStandardHour = services.Users.IsStandardHour(specialist.Id, startTime, endTime); return rate; }
public void Add(UserDto user) { var searchDocument = BuidDocument(user); if (searchDocument != null) { var result = _cloudSearch.Add(searchDocument); if (result.IsError) { Log.WarnFormat("Cannot add to search index. Error: {0}", result.errors); } else { Log.InfoFormat("Adding documents index: ", searchDocument.Id); } } }
public void Delete(UserDto user) { var searchDocument = new SearchDocument { Id = user.Id.ToString() }; var result = _cloudSearch.Delete(searchDocument); if (result.IsError) { Log.WarnFormat("Cannot delete to search index. Error: {0}", result.errors); } else { Log.InfoFormat("Deleting documents index: ", searchDocument.Id); } }
public void CheckBookingEventExist_ExistedEventInfo_MatchedEvent() { // Setup dependency var settingsMock = new Mock<ISettings>(); var uowMock = new Mock<IUnitOfWork>(); var repositoryMock = new Mock<IRepository>(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRepository>()) .Returns(repositoryMock.Object); ServiceLocator.SetLocatorProvider(() => serviceLocatorMock.Object); // Arrange Guid sourceUserId = Guid.NewGuid(); Guid targetUserId = Guid.NewGuid(); UserDto sourceUser = new UserDto { Id = sourceUserId }; UserDto targetUser = new UserDto { Id = targetUserId }; string shortDescription = "Test description"; BookingEvent bookingEvent = new BookingEvent { Id = Guid.NewGuid(), SourceUser = new User { Id = sourceUserId }, TargetUser = new User { Id = targetUserId }, ShortDescription = shortDescription }; BookingEvent[] bookingEvents = new BookingEvent[] { bookingEvent }; repositoryMock.Setup(r => r.Query<BookingEvent>()).Returns(bookingEvents.AsQueryable()); BookingEventDto actualBookingEventDto; // Act var bookingService = new BookingService(uowMock.Object, repositoryMock.Object, settingsMock.Object); actualBookingEventDto = bookingService.CheckBookingEventExist( sourceUser, targetUser, shortDescription); // Assert Assert.AreEqual(bookingEvent.Id, actualBookingEventDto.Id); }
private static void CreateUnsuccessInvoice(UserDto user, BookingDto booking, IServices Services, decimal amount) { ConsultationType consultType; switch (booking.Type) { case BookingType.ASAP: consultType = ConsultationType.StandardHour; break; default: Enum.TryParse(booking.Type.ToString(), out consultType); break; } var call = Services.Call.GetByBookingId(booking.Id); InvoiceDto unsuccessInvoice = new InvoiceDto() { Amount = amount, CreatedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, Type = InvoiceType.Consultation, PaymentStatus = false, InvoiceNumber = Services.Invoices.GetInvoiceNumber(), Booking = Services.Booking.GetById(booking.Id), User = user, Description = InvoiceType.Consultation.ToString(), RatePerMinute = booking.CostPerMinute, ConsultationType = consultType, }; if (call != null) { unsuccessInvoice.Duration = 0; } Services.Invoices.Create(unsuccessInvoice); }
public TwiMLResult VoiceMailStatusCallBack(CallContextModel model) { var response = new TwilioResponse(); try { // Get specialist var specialist = new UserDto(); if (model.IsCustomer) // Caller is customer { specialist = Services.Users.GetUserById(model.ReceiverId); } else { specialist = Services.Users.GetUserById(model.CallerId); } string recordUrl = Request["RecordingUrl"]; int recordDuration = Convert.ToInt32(Request["RecordingDuration"]); var booking = Services.Call.Get(model.CallId).Booking; // Send transcript request int transcriptSuccess = SendTranscriptionRequest(specialist.Id.ToString(), specialist.UserName, specialist.Email, recordUrl, recordDuration, booking); switch (transcriptSuccess) { case 0: response.Say(ConferenceConst.BalanceNotEnoughForTranscript); break; case 2: response.Say(ConferenceConst.DictateFollowUpActionCompleted); break; default: response.Say(ConferenceConst.TranscriptError); break; } } catch (Exception e) { // Log Log.Error("Voice email. Error: ", e); // Error response.Say(ConferenceConst.ErrorMessage, new { voice = VoiceInConference, language = LanguageInConference }); response.Hangup(); } response.Redirect(Url.Action("ConsultantAfterCall", model)); return new TwiMLResult(response); }
public TwiMLResult ConsultantAfterCallResponse(CallContextModel model, string digits) { var response = new TwilioResponse(); var message = ConferenceConst.AcctionCompleted; var specialist = new UserDto(); var call = new CallDto(); bool canWaiveFee = true; int transcriptSuccess = 2; try { if (digits.Equals("2") || digits.Equals("3") || digits.Equals("4") || digits.Equals("5")) { call = Services.Call.GetByCallSid(Request["CallSid"]); if (string.IsNullOrWhiteSpace(model.RecordUrl)) { model.RecordSid = call.RecordSid; model.RecordDuration = call.RecordDuration; model.RecordUrl = call.RecordUrl; } // Get specialist if (model.IsCustomer) // Caller is customer { specialist = Services.Users.GetUserById(model.ReceiverId); } else { specialist = Services.Users.GetUserById(model.CallerId); } int startingTime = Convert.ToInt32(Services.SystemConfig.GetByKey(ParamatricBusinessRules.STARTING_TIME.ToString()).Value); if (call.Duration <= startingTime) { canWaiveFee = false; } } switch (digits) { case "1": // Dictate your follow up action var statusCallBack = Utilities.FormatLink(Url.Action("VoiceMail", "Conference", model)); Services.Call.RedirectToVoiceMail(Request["CallSid"], statusCallBack); break; case "2": // Transcript consultation // Send transcription request transcriptSuccess = SendTranscriptionRequest(specialist.Id.ToString(), specialist.UserName, specialist.Email, call.RecordUrl, call.RecordDuration, call.Booking); if (transcriptSuccess == 0) { message = ConferenceConst.BalanceNotEnoughForTranscript; } else if (transcriptSuccess == 1) { message = ConferenceConst.TranscriptError; } break; case "3": // Play consultation record response.Pause(5); response.Play(model.RecordUrl); break; case "4": // Play consultation record and transcription // Play consultation record response.Pause(5); response.Play(model.RecordUrl); // Send transcription request transcriptSuccess = SendTranscriptionRequest(specialist.Id.ToString(), specialist.UserName, specialist.Email, call.RecordUrl, call.RecordDuration, call.Booking); if (transcriptSuccess == 0) { message = ConferenceConst.BalanceNotEnoughForTranscript; } else if (transcriptSuccess == 1) { message = ConferenceConst.TranscriptError; } break; case "5": // Waive consultation fee if (canWaiveFee) { response.Redirect(Url.Action("WaiveFeeAction", model)); } else { response.Redirect(Url.Action("ConsultantAfterCall", model)); } break; default: response.Redirect(Url.Action("ConsultantAfterCall", model)); return new TwiMLResult(response); } } catch (Exception e) { // Log Log.Error("Consultant after call response. Error: ", e); // Error response.Say(ConferenceConst.ErrorMessage, new { voice = VoiceInConference, language = LanguageInConference }); response.Hangup(); } response.Say(message, new { voice = VoiceInConference, language = LanguageInConference }); response.Redirect(Url.Action("ConsultantAfterCall", model)); return new TwiMLResult(response); }
public void UpdateUserInfo_Anyuser_CallsUpdateUserInfoMethodOfRepository() { var settingsMock = new Mock<ISettings>(); var componentsMock = new Mock<IComponents>(); var repositoryMock = new Mock<IRepository>(); var uowMock = new Mock<IUnitOfWork>(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRepository>()) .Returns(repositoryMock.Object); serviceLocatorMock.Setup(x => x.GetInstance<IUnitOfWork>()) .Returns(uowMock.Object); ServiceLocator.SetLocatorProvider(() => serviceLocatorMock.Object); // Arrange Guid id = Guid.NewGuid(); UserDto user = new UserDto { Id = id, UserName = "******", Email = "*****@*****.**", MobilePhoneCode = "12345678x@X" }; repositoryMock.Setup(r => r.Query<UserDto>()); repositoryMock.Setup(r => r.CreateUnitOfWork()).Returns(uowMock.Object); // Act var userService = new UserService(uowMock.Object,repositoryMock.Object, settingsMock.Object, componentsMock.Object); userService.UpdateUserInfo(user); // Assert repositoryMock.Verify(repo => repo.Update<User>( It.Is<User>(u => u.Id == id))); uowMock.Verify(uow => uow.Save()); }
public void CreateUserConfirmationDto_Any_CallsCreateMethodOfRepository() { var settingsMock = new Mock<ISettings>(); var componentsMock = new Mock<IComponents>(); var repositoryMock = new Mock<IRepository>(); var uowMock = new Mock<IUnitOfWork>(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRepository>()) .Returns(repositoryMock.Object); serviceLocatorMock.Setup(x => x.GetInstance<IUnitOfWork>()) .Returns(uowMock.Object); ServiceLocator.SetLocatorProvider(() => serviceLocatorMock.Object); // Arrange Guid id = Guid.NewGuid(); UserDto user = new UserDto() { Id = Guid.NewGuid() }; UserConfirmationDto userConfirmationDto = new UserConfirmationDto { Id = id, Type= ConfirmedType.ChangeEmail, User=user }; repositoryMock.Setup(r => r.FindById<User>(user.Id)); repositoryMock.Setup(r => r.CreateUnitOfWork()).Returns(uowMock.Object); // Act var userService = new UserService(uowMock.Object,repositoryMock.Object, settingsMock.Object, componentsMock.Object); UserConfirmationDto actualUser= userService.Create(userConfirmationDto); // Assert repositoryMock.Verify(repo => repo.Insert<UserConfirmation>( It.Is<UserConfirmation>(u => u.Id == id))); uowMock.Verify(uow => uow.Save()); Assert.AreEqual(actualUser.Id, id); }
/// <summary> /// Push start/stop for calltimer to client /// </summary> /// <param name="UserName"></param> /// <param name="callLog"></param> /// <param name="costPerMinute"></param> /// <param name="isBegin"></param> public static void CallDurationForUser(string UserName, UserDto userForLoadCallTimer, CallDto callDto, decimal costPerMinute, bool isBegin, int startingTime) { var context = GlobalHost.ConnectionManager.GetHubContext<CallTimerHub>(); foreach (var connectionId in CallTimerHub.connections.GetConnections(UserName)) { if (isBegin && callDto.StartTime.HasValue) { decimal minimumCost = Role.Specialist.Equals(userForLoadCallTimer.Role) ? callDto.Booking.CustomerMinCharge : callDto.Booking.SpecialistMinCharge; //load user information for calltimer context.Clients.Client(connectionId).loadCallTimer(userForLoadCallTimer.Id); //start call timer context.Clients.Client(connectionId).callDurationWeb( callDto.StartTime.Value.ToString(Code.Constants.DateTimeFormatTimeZone), DateTime.UtcNow.ToString(Code.Constants.DateTimeFormatTimeZone), costPerMinute, minimumCost, startingTime, callDto.Booking.IsApplyNoMinimumCharge); //start call timer for mobile context.Clients.Client(connectionId).callDuration(new { BookingId = callDto.Booking.Id, ReferenceNo = callDto.Booking.ReferenceNo, StartTime = callDto.StartTime.Value.ToString(Code.Constants.DateTimeFormatTimeZone), currentTimeServerSend = DateTime.UtcNow.ToString(Code.Constants.DateTimeFormatTimeZone), CostPerMinute = costPerMinute, UserTitleGender = !string.IsNullOrWhiteSpace(userForLoadCallTimer.Title) ? userForLoadCallTimer.Title : string.Empty, UserFirstName = userForLoadCallTimer.FirstName, UserLastName = userForLoadCallTimer.LastName, UserFullName = userForLoadCallTimer.Name, AvatarPath = S3ReaderHelper.CombineS3Root(userForLoadCallTimer.Avatar), MinimumCost = minimumCost, FreeTime = startingTime, UserPostNominal = Role.Specialist.Equals(userForLoadCallTimer.Role) && !string.IsNullOrWhiteSpace(userForLoadCallTimer.PostNominal) ? userForLoadCallTimer.PostNominal : string.Empty, IsApplyNoMinimumCharge = callDto.Booking.IsApplyNoMinimumCharge }); } else if (!isBegin && callDto.EndTime.HasValue) { //stop call timer context.Clients.Client(connectionId).stopCall( callDto.EndTime.Value.ToString(Code.Constants.DateTimeFormatTimeZone)); } } }
/// <summary> /// Add user to cloud search indexer /// </summary> /// <param name="user"></param> public void AddToCloudIndexer(UserDto user) { var indexer = new AmazonCloudIndexer(); indexer.Add(user); }
private bool HasPassword(UserDto account) { var user = _userManager.FindById(account.Id); if (user != null) { return user.PasswordHash != null; } return false; }
/// <summary> /// tranform invoice object into Invoice email template /// </summary> /// <param name="user"></param> /// <param name="invoice"></param> /// <param name="unit">months, minutes, hours,...</param> /// <returns></returns> public string TranformToInvoiceTemplate(UserDto user, InvoiceDto invoice, string unit, string mailTemplateKey, List<InvoiceDto> listConsultationInvoiceForWalvedFee) { try { LocationDto location = user.Locations.First(); bool hasDisplayMinimum = true; decimal originAmount = invoice.Amount - invoice.GST; decimal invoiceTotal = invoice.Amount; decimal walvedFee = 0; decimal subTotal = 0; int duration = invoice.Duration; decimal GST = invoice.GST; decimal ratePerMinute = GST > 0 ? invoice.RatePerMinute - SubtractGSTCalculator(invoice.RatePerMinute) : invoice.RatePerMinute; if (InvoiceType.OrderTranscript.Equals(invoice.Type) || InvoiceType.Prepayment.Equals(invoice.Type)) { hasDisplayMinimum = false; } else if (InvoiceType.WaiveFee.Equals(invoice.Type) && listConsultationInvoiceForWalvedFee != null) { var customerInvoice = listConsultationInvoiceForWalvedFee.First(x => x.Booking.Customer.Id == x.User.Id && x.Type == InvoiceType.Consultation); var specialistInvoice = listConsultationInvoiceForWalvedFee.First(x => x.Booking.Specialist.Id == x.User.Id && x.Type == InvoiceType.Consultation); duration = customerInvoice.Duration; originAmount = customerInvoice.Amount - customerInvoice.GST; walvedFee = specialistInvoice.Amount - specialistInvoice.GST; subTotal = originAmount - walvedFee; GST = customerInvoice.GST > 0 ? SubtractGSTCalculator(customerInvoice.Amount - specialistInvoice.Amount) : 0; ratePerMinute = GST > 0 ? customerInvoice.RatePerMinute - SubtractGSTCalculator(customerInvoice.RatePerMinute) : customerInvoice.RatePerMinute; invoiceTotal = subTotal + GST; } object transformWith = new { BaseUrl = baseUrl, //- XXXXXXXX-X InvoiceNumber = invoice.InvoiceNumber, //- 27/02/2015 CreatedDate = invoice.CreatedDate.ToString(Infrastructure.Core.Const.SystemConfig.GlobalDateFormat), Name = user.Name, Street = string.Format("{0} {1}", location.StreetNumber, location.Street), Country = string.Format("{0} {1} {2}", location.Country, location.Suburb, location.Postcode), MobileNumber = user.MobileCountryCode + user.MobilePhone, //- AUD USD VND ... Currency = invoice.Currency, Description = invoice.Description, //- 1 (minutes) or 12 (months) Duration = invoice.Type != InvoiceType.Subscription ? TimeSpan.FromSeconds(duration).ToString() : duration.ToString(), Unit = unit, //- $XX Cost = invoice.Type == InvoiceType.Subscription ? (originAmount - GST).ToString("C", new CultureInfo("en-Us")) : ratePerMinute.ToString("C", new CultureInfo("en-Us")), Amount = originAmount.ToString("C", new CultureInfo("en-Us")), Total = invoiceTotal.ToString("C", new CultureInfo("en-Us")), //WaivedFeeDescription = string.IsNullOrWhiteSpace(waiveFeeDescription) ? null : "*" + waiveFeeDescription, IsWavedFee = InvoiceType.WaiveFee.Equals(invoice.Type) ? string.Empty : "display:none;", WaivedFee = walvedFee.ToString("C", new CultureInfo("en-Us")), Subtotal = subTotal.ToString("C", new CultureInfo("en-Us")), IsGST = GST > 0 ? string.Empty : "display:none;", GST = GST.ToString("C", new CultureInfo("en-Us")), Minimum = (hasDisplayMinimum && invoice.Booking != null) ? string.Format(InvoiceConst.InvoiceMinimumDescription, invoice.Booking.CustomerMinCharge.ToString("C", new CultureInfo("en-Us"))) : string.Empty }; var mailTemplate = ConfigurationManager.AppSettings[mailTemplateKey]; var transformWithDynamic = transformWith.ToDynamic(); //- Generate mail content from mail template and object transformWith (invoice information) string mailContent = StringExtend.TransformWithDynamic(File.ReadAllText(HostingEnvironment.MapPath(mailTemplate)), transformWithDynamic); return mailContent; } catch (Exception e) { Log.Error("Tranform to invoice template", e); return null; } }
/// <summary> /// Change css when dial to phone in step 2 /// </summary> /// <param name="user"></param> /// <param name="title"></param> /// <param name="content"></param> public static void ChangeCssDialToPhone(UserDto user) { if (user != null) { var context = GlobalHost.ConnectionManager.GetHubContext<CallTimerHub>(); foreach (var connectionId in CallTimerHub.connections.GetConnections(user.UserName)) { context.Clients.Client(connectionId).changeCssDialToPhone(); } } }
/// <summary> /// Build confirm message /// </summary> /// <param name="confirmType"></param> /// <param name="specialist"></param> /// <param name="bookingRate"></param> /// <param name="minCharge"></param> /// <returns></returns> public string BuildConfirmMessage(string confirmType, UserDto specialist, decimal bookingRate, decimal minCharge, bool IsApplynoMinimumCharge) { string contentMinimumCharge = string.Empty; if (!IsApplynoMinimumCharge) { contentMinimumCharge = string.Format(BookingConst.ContentMinimumCharge, minCharge.ToString("#,##0.00")); } string confirmMessage = String.Format(BookingConst.ConsultantConfirm, confirmType, specialist.Name, bookingRate.ToString("#,##0.00"), contentMinimumCharge, Enums.GetDescriptionEnum(CurrentUser.PaymentMethod)); return confirmMessage; }
/// <summary> /// Show popup notify in conference /// </summary> /// <param name="user"></param> /// <param name="title"></param> /// <param name="content"></param> public static void ShowPopupNotifyInConference(UserDto user, string title, string content) { if (user != null) { var context = GlobalHost.ConnectionManager.GetHubContext<FollowUpActionHub>(); foreach (var connectionId in FollowUpActionHub.connections.GetConnections(user.UserName)) { context.Clients.Client(connectionId).showPopupNotifyInConference(title, content); } } }
/// <summary> /// Buid search document /// </summary> /// <param name="user"></param> /// <returns></returns> private SearchDocument BuidDocument(UserDto user) { try { var doc = new SearchDocument { Id = user.Id.ToString(), FirstName = GetValueOrDefault(user.FirstName), LastName = GetValueOrDefault(user.LastName), BusinessName = GetValueOrDefault(user.Profile.BusinessName), Specialization = GetValueOrDefault(user.Profile.Specializations.FirstOrDefault().Name), State = GetValueOrDefault(user.Locations.FirstOrDefault().State), Postcode = GetValueOrDefault(user.Locations.FirstOrDefault().Postcode), Suburb = GetValueOrDefault(user.Locations.FirstOrDefault().Suburb), Language = GetValueOrDefault(user.Profile.Languages), Country = GetValueOrDefault(user.Locations.FirstOrDefault().Country), Profession = GetValueOrDefault(user.Profile.Specializations.FirstOrDefault().ProfessionalOrTrade) }; return doc; } catch (Exception e) { Log.Error("Buil document error. UserId: " + user.Id, e); return null; } }
public bool UpdateUserInfo(UserDto user) { if (user != null) { //User account = Mapper.Map<UserDto, User>(user); Repository.Update<User>(user.ExposedAs<User>(Repository)); UnitOfWork.Save(); return true; } else { return false; } }
/// <summary> /// Get template of the confirm booking time message /// </summary> /// <param name="specialistDto"></param> /// <returns></returns> protected string GetBookingConfirmMessage(UserDto specialistDto, BookingType type, SpecializationDto specializationDto, DateTime startTime, DateTime endTime) { decimal bookingRate = Services.Booking.GetCustomerPrice(specializationDto.Id, type); decimal minCharge = Services.Booking.GetCustomerMinimumPrice(specializationDto.Id); string confirmMessage = string.Empty; switch (type) { case BookingType.ASAP: confirmMessage = BuildConfirmMessage("a consultation as soon as possible", specialistDto, bookingRate, minCharge, specializationDto.IsApplyNoMinimumCharge); break; case BookingType.StandardHour: confirmMessage = BuildConfirmMessage("a consultation between " + startTime.ToString(Constants.GlobalDateTimeFormat) + " and " + endTime.ToString(Constants.GlobalDateTimeFormat), specialistDto, bookingRate, minCharge, specializationDto.IsApplyNoMinimumCharge); break; case BookingType.OutOfHour: confirmMessage = BuildConfirmMessage("a consultation between " + startTime.ToString(Constants.GlobalDateTimeFormat) + " and " + endTime.ToString(Constants.GlobalDateTimeFormat), specialistDto, bookingRate, minCharge, specializationDto.IsApplyNoMinimumCharge); break; case BookingType.TalkNow: confirmMessage = BuildConfirmMessage("to talk now", specialistDto, bookingRate, minCharge, specializationDto.IsApplyNoMinimumCharge); break; } return confirmMessage; }
/// <summary> /// Get user location follow address or geeperId /// </summary> /// <param name="user"></param> /// <returns></returns> public static Coordinates GetLocationByUserAddress(UserDto user) { var geoIp = new GeoIpService(); LocationDto location = user.Locations.FirstOrDefault(); Coordinates coordinates = new Coordinates(); if (location != null) { if (string.IsNullOrWhiteSpace(location.GeepersName)) { coordinates = geoIp.GetByAddress(location.StreetNumber, location.Street, location.Postcode, location.Country, location.State); } else { coordinates = geoIp.GetByGeepers(location.GeepersName); if (coordinates == null) { coordinates = geoIp.GetByAddress(location.StreetNumber, location.Street, location.Postcode, location.Country, location.State); } } } return coordinates; }
public void CreateBookingEvent_BookingEventDto_BookingEventDto() { var settingsMock = new Mock<ISettings>(); var repositoryMock = new Mock<IRepository>(); var uowMock = new Mock<IUnitOfWork>(); var serviceLocatorMock = new Mock<IServiceLocator>(); serviceLocatorMock.Setup(x => x.GetInstance<IRepository>()) .Returns(repositoryMock.Object); serviceLocatorMock.Setup(x => x.GetInstance<IUnitOfWork>()) .Returns(uowMock.Object); ServiceLocator.SetLocatorProvider(() => serviceLocatorMock.Object); repositoryMock.Setup(r => r.CreateUnitOfWork()).Returns(uowMock.Object); UserDto user = new UserDto() { Email = "*****@*****.**" }; // Act var bookingService = new BookingService(uowMock.Object, repositoryMock.Object, settingsMock.Object); bookingService.CreateBookingEvent(new BookingEventDto() { TargetUser = user }); // Assert repositoryMock.Verify(repo => repo .Insert<BookingEvent>(It.IsAny<BookingEvent>())); uowMock.Verify(repo => repo.Save()); }
/// <summary> /// Get Position of Searcher By IP, address or gepperid /// </summary> /// <param name="searcher"></param> /// <returns></returns> public static Coordinates GetPositionSearcher(UserDto searcher) { var geoip = new GeoIpService(); Coordinates searcherCoordinates = geoip.GetByIp(); if (searcherCoordinates == null && searcher != null) { searcherCoordinates = GetLocationByUserAddress(searcher); } return searcherCoordinates; }
public InvoiceDto CreateTranscriptionInvoice(decimal amount, int duration, decimal ratePerMinute, BookingDto booking, UserDto user, string transactionId) { Invoice invoice = new Invoice { InvoiceNumber = GetInvoiceNumber(), Amount = amount, GST = SubtractGSTCalculator(amount), RatePerMinute = ratePerMinute, Duration = duration, Type = InvoiceType.OrderTranscript, CreatedDate = DateTime.UtcNow, ModifiedDate = DateTime.UtcNow, SentDate = DateTime.UtcNow, User = user.ExposedAs<User>(Repository), Currency = Currency.AUD.ToString(), PaymentStatus = true, Booking = booking.ExposedAs<Booking>(Repository) }; invoice.Description = string.Format(InvoiceConst.InvoiceCallRecordDescription, invoice.Booking.ReferenceNo); Repository.Insert<Invoice>(invoice); UnitOfWork.Save(); if (!invoice.Id.Equals(Guid.Empty)) { var mailContent = GetEmailContentOfInvoice(invoice.ExposedAs<InvoiceDto>()); var mailPdfContent = TranformToInvoiceTemplate(user, invoice.ExposedAs<InvoiceDto>(), null, ConstEmailTemplateKey.ConsultationInvoiceTemplate, null); System.Threading.Tasks.Task.Factory.StartNew(() => { byte[] pdfAsByte = HtmlToPdf.GetPdfData(mailPdfContent, baseUrl); string fileName = GenerateInvoiceName(invoice.InvoiceNumber); SendInvoice(fileName, pdfAsByte, mailContent, user.Email, ConstEmailSubject.TranscriptionInvoice); }); } else { throw new ArgumentException("Cannot save transcription invoice to database"); } return invoice.ExposedAs<InvoiceDto>(); }
/// <summary> /// Get distance of an specialist /// </summary> /// <param name="searcherCoordinates"></param> /// <param name="specialist"></param> /// <returns></returns> public static double GetDistance(Coordinates searcherCoordinates, UserDto specialist) { double distance = 999999; if (searcherCoordinates != null) { var geoIp = new GeoIpService(); LocationDto location = specialist.Locations.FirstOrDefault(); Coordinates responseSpecialist = GetLocationByUserAddress(specialist); if (responseSpecialist != null) { distance = GeoHelper.Distance(searcherCoordinates, new Coordinates { Latitude = responseSpecialist.Latitude, Longitude = responseSpecialist.Longitude }, UnitsOfLength.Kilometer); } } return distance; }
/// <summary> /// Mapping from Specialist profile, country permitted, standard hour and user informatiom to SpecialistProfileViewModel /// </summary> /// <param name="specialization"></param> /// <param name="specProfile"></param> /// <param name="standardHour"></param> /// <returns></returns> public static SpecialistProfileViewModel ModelMapper( UserDto account, Guid? currentUserId, IServices Services) { SpecialistProfileViewModel model = new SpecialistProfileViewModel(); model.Account = Mapper.Map<UserDto, UserViewModel>(account); SpecialistRegisterStep3ViewModel step3Model = new SpecialistRegisterStep3ViewModel(); step3Model = Mapper.Map<ProfileDto, SpecialistRegisterStep3ViewModel>(account.Profile); step3Model.ListStandardHour = Mapper.Map<List<WorkingScheduleDto>, List<WorkingScheduleDto>>(account.Profile.WorkingSchedules.ToList()); step3Model.Specializations = Mapper.Map<List<SpecializationDto>, List<SpecializationViewModel>>(account.Profile.Specializations.ToList()); List<PermittedCountryViewModel> lstCountryPermitted = new List<PermittedCountryViewModel>(); List<StateAndRegulatory> lstStateAndRegulatory = new List<StateAndRegulatory>(); foreach (var spec in step3Model.Specializations) { foreach (var country in spec.PermittedCountries) { var tempState = country.State.Split('_').ToList(); var tempRegulatory = country.RegulatoryAuthority.Split('_').ToList(); lstStateAndRegulatory = new List<StateAndRegulatory>(); for (int i = 0; i < tempState.Count(); i++) { if (!string.IsNullOrEmpty(tempState[i]) && !string.IsNullOrEmpty(tempRegulatory[i])) { lstStateAndRegulatory.Add( new StateAndRegulatory { State = tempState[i], Regulatory = tempRegulatory[i] }); } } lstCountryPermitted.Add(new PermittedCountryViewModel { Name = country.Name, StatesAndRegulatories = lstStateAndRegulatory }); } spec.lstCountryPermitted = lstCountryPermitted; spec.CustomerPricing = Services.Booking.GetCustomerPricing(spec.Id); // Format S3 link for (int i = 0; i < spec.POCs.Count; i++) { spec.POCs[i].S3FileName = TeleConsult.Web.Code.Helpers.S3ReaderHelper.CombineFileS3Root(spec.POCs[i].S3FileName); } } if (string.IsNullOrEmpty(model.Account.AvatarPath)) { model.Account.AvatarPath = ConstPath.DefaulAvatar; } else { var s3Root = BlueChilli.Web.Helpers.S3PathWithoutQuery("").Substring(1); model.Account.AvatarPath = Path.Combine(s3Root, account.Avatar); } model.SpecialistDetail = step3Model; model.IsFavourite = Services.Users.IsFavourite(model.Account.Id, currentUserId); model.SpecialistDetail.RatingRatio = (int)Math.Round(Services.Booking.RatingCalculator(account.Id), 0, MidpointRounding.AwayFromZero); //check current status is not "Not Available". if It is yes, it access db to check call if (!AvailabilityStatus.NotAvailable.Equals(model.Account.CurrentAvailabilityStatus) && Services.Call.CheckCallInProgressBySpecialistId(model.Account.Id)) { model.Account.CurrentAvailabilityStatus = AvailabilityStatus.NotAvailable; } return model; }
/// <summary> /// Check booking event exist /// </summary> /// <param name="sourceUser"></param> /// <param name="targetUser"></param> /// <param name="shortDescription"></param> /// <returns></returns> public BookingEventDto CheckBookingEventExist(UserDto sourceUser, UserDto targetUser, string shortDescription) { return Repository.Query<BookingEvent>() .Where(x => x.SourceUser.Id == sourceUser.Id && x.TargetUser.Id == targetUser.Id && x.ShortDescription == shortDescription) .FirstOrDefault() .ExposedAs<BookingEventDto>(); }
public async Task<string> SendCodeSMS(UserDto user) { string codeSMS = string.Empty; if (user != null) { codeSMS = await _userManager.GenerateChangePhoneNumberTokenAsync(user.Id, !string.IsNullOrWhiteSpace(user.MobilePhone) ? user.MobileCountryCode + user.MobilePhone : user.HomePhoneCountryCode + user.HomePhone); user.MobilePhoneCode = codeSMS; if (Services.Users.UpdateUserInfo(user) && !string.IsNullOrWhiteSpace(user.MobilePhone)) { try { new CommonService().SendSMS(user.MobileCountryCode + user.MobilePhone, string.Format(SMSConst.VerifyContent, codeSMS)); } catch (Exception ex) { Log.Error("System encountered error when trying sending SMS with error", ex); } } } return codeSMS; }
/// <summary> /// Update user to cloud search indexer /// </summary> /// <param name="user"></param> public void UpdateToCloudIndexer(UserDto user) { var indexer = new AmazonCloudIndexer(); indexer.Update(user); }