public async Task Should_send_correct_data() { InitializeMock(); var service = CreateService(); var(account, chargeAmount) = CreateAccountAndAmount(10000, 9943, 1, 1); AccountBalanceManagementNotificationData actualMailData = null; SaveMailData(); await service.SendNotificationIfRequired(account, chargeAmount); Assert.Equal(1, actualMailData.AgencyAccountId); Assert.Equal(1, actualMailData.AgencyId); Assert.Equal("AgencyName1", actualMailData.AgencyName); Assert.Equal(EnumFormatters.FromDescription(Currencies.USD), actualMailData.Currency); Assert.Equal(MoneyFormatter.ToCurrencyString(57, Currencies.USD), actualMailData.NewAmount); void SaveMailData() => _notificationServiceMock .Setup(x => x.Send(It.IsAny <DataWithCompanyInfo>(), It.IsAny <NotificationTypes>(), It.IsAny <string>())) .Callback <DataWithCompanyInfo, NotificationTypes, string>((data, _, _) => actualMailData = (AccountBalanceManagementNotificationData)data); }
private void SetContent() { if (ShowHotKeyInTitle && HotKey != Key.None) { Content = string.Format("{0} {1}", EnumFormatters.Format(HotKey), Text); } else { Content = Text; } }
public Task <Result> SendInvoice(Booking booking, string email, bool sendCopyToAdmins, SlimAgentContext agent) { // TODO: hardcoded to be removed with UEDA-20 var addresses = new List <string> { email }; if (sendCopyToAdmins) { addresses.AddRange(_options.CcNotificationAddresses); } return(_documentsService.GetActualInvoice(booking) .Bind(async invoice => { var(registrationInfo, data) = invoice; var invoiceData = new InvoiceData { Number = registrationInfo.Number, BuyerDetails = data.BuyerDetails, InvoiceDate = DateTimeFormatters.ToDateString(registrationInfo.Date), InvoiceItems = data.InvoiceItems .Select(i => new InvoiceData.InvoiceItem { Number = i.Number, Price = FormatPrice(i.Price), Total = FormatPrice(i.Total), AccommodationName = i.AccommodationName, RoomDescription = i.RoomDescription, RoomType = EnumFormatters.FromDescription <RoomTypes>(i.RoomType), DeadlineDate = DateTimeFormatters.ToDateString(i.DeadlineDate), MainPassengerName = PersonNameFormatters.ToMaskedName(i.MainPassengerFirstName, i.MainPassengerLastName) }) .ToList(), TotalPrice = FormatPrice(data.TotalPrice), CurrencyCode = EnumFormatters.FromDescription(data.TotalPrice.Currency), ReferenceCode = data.ReferenceCode, SupplierReferenceCode = data.SupplierReferenceCode, SellerDetails = data.SellerDetails, PayDueDate = DateTimeFormatters.ToDateString(data.PayDueDate), CheckInDate = DateTimeFormatters.ToDateString(data.CheckInDate), CheckOutDate = DateTimeFormatters.ToDateString(data.CheckOutDate), PaymentStatus = EnumFormatters.FromDescription(data.PaymentStatus), DeadlineDate = DateTimeFormatters.ToDateString(data.DeadlineDate) }; return await _notificationsService.Send(agent: agent, messageData: invoiceData, notificationType: NotificationTypes.BookingInvoice, emails: addresses); })); }
public async Task <Result> ChangeStatus(Booking booking, BookingStatuses status, DateTime date, ApiCaller apiCaller, BookingChangeReason reason) { if (booking.Status == status) { return(Result.Success()); } await SetStatus(booking, status); var message = new BookingStatusChangeInfo { BookingId = booking.Id, ReferenceCode = booking.ReferenceCode, Status = EnumFormatters.FromDescription(status), ChangeTime = _dateTimeProvider.UtcNow(), AccommodationName = booking.AccommodationName, AccommodationPhoto = booking.AccommodationInfo?.Photo, CheckInDate = booking.CheckInDate.DateTime, CheckOutDate = booking.CheckOutDate.DateTime }; await _notificationsService.Send(apiCaller, JsonDocument.Parse(JsonSerializer.SerializeToUtf8Bytes(message, new JsonSerializerOptions(JsonSerializerDefaults.Web))), Notifications.Enums.NotificationTypes.BookingStatusChanged); // Temporary hot-fix for notifying admins about bookings statuses changed to "Pending" or "Waiting for response" // TODO: remove when we have appropriate admin panel booking monitoring if (status == BookingStatuses.Pending || status == BookingStatuses.WaitingForResponse) { var(isSuccess, _, bookingInfo, _) = await GetBookingInfo(booking.ReferenceCode); if (isSuccess) { await _bookingNotificationService.NotifyAdminsStatusChanged(bookingInfo); } } await _bookingChangeLogService.Write(booking, status, date, apiCaller, reason); return(status switch { BookingStatuses.Confirmed => await ProcessConfirmation(booking, date), BookingStatuses.Cancelled => await ProcessCancellation(booking, date, apiCaller), BookingStatuses.Rejected => await ProcessDiscarding(booking, apiCaller), BookingStatuses.Invalid => await ProcessDiscarding(booking, apiCaller), BookingStatuses.Discarded => await ProcessDiscarding(booking, apiCaller), BookingStatuses.ManualCorrectionNeeded => await ProcessManualCorrectionNeeding(booking, apiCaller), BookingStatuses.PendingCancellation => Result.Success(), BookingStatuses.WaitingForResponse => Result.Success(), BookingStatuses.Pending => Result.Success(), _ => throw new ArgumentOutOfRangeException(nameof(status), status, "Invalid status value") });
public VccBookingRow Convert(VccBookingData data) => new VccBookingRow { GuestName = data.GuestName, ReferenceCode = data.ReferenceCode, CheckInDate = DateTimeFormatters.ToDateString(data.CheckInDate), CheckOutDate = DateTimeFormatters.ToDateString(data.CheckOutDate), Amount = data.Amount, Currency = EnumFormatters.FromDescription(data.Currency), CardActivationDate = DateTimeFormatters.ToDateString(data.CardActivationDate), CardDueDate = DateTimeFormatters.ToDateString(data.CardDueDate), CardNumber = data.CardNumber, CardAmount = data.CardAmount };
static BookingSummaryNotificationData.BookingData CreateBookingData(Booking booking) => new BookingSummaryNotificationData.BookingData { ReferenceCode = booking.ReferenceCode, Accommodation = booking.AccommodationName, Location = $"{booking.Location.Country}, {booking.Location.Locality}", LeadingPassenger = booking.GetLeadingPassengerFormattedName(), Amount = MoneyFormatter.ToCurrencyString(booking.TotalPrice, booking.Currency), DeadlineDate = DateTimeFormatters.ToDateString(booking.DeadlineDate), CheckInDate = DateTimeFormatters.ToDateString(booking.CheckInDate), CheckOutDate = DateTimeFormatters.ToDateString(booking.CheckOutDate), Status = EnumFormatters.FromDescription(booking.Status), PaymentType = EnumFormatters.FromDescription(booking.PaymentType) };
private async Task SetVerificationState(Agency agency, AgencyVerificationStates state, string verificationReason) { var now = _dateTimeProvider.UtcNow(); string reason; if (string.IsNullOrEmpty(agency.VerificationReason)) { reason = verificationReason; } else { reason = agency.VerificationReason + Environment.NewLine + verificationReason; } agency.VerificationState = state; agency.VerificationReason = reason; agency.Verified = now; agency.Modified = now; _context.Update(agency); await _context.SaveChangesAsync(); await SendNotificationToMaster(); async Task <Result> SendNotificationToMaster() { var(_, isFailure, master, error) = await _agentService.GetMasterAgent(agency.Id); if (isFailure) { return(Result.Failure(error)); } var messageData = new AgencyVerificationStateChangedData { AgentName = $"{master.FirstName} {master.LastName}", AgencyName = agency.Name, State = EnumFormatters.FromDescription(state), }; return(await _notificationService.Send(agent : new SlimAgentContext(master.Id, agency.Id), messageData : messageData, notificationType : NotificationTypes.AgencyVerificationChanged, email : master.Email)); } }
protected void UpdateItemProperty(List <SelectListItem> itemsSource) { if (itemsSource == null) { return; } foreach (var p in itemsSource.Where(p => p != null && p.Value != null)) { var index = itemsSource.IndexOf(p) + 1; if (p.HotKey == Key.None) { p.HotKey = string.Format("{0}{1}", UseFunctionKeys ? "F" : "D", index).To(Key.None); } p.DisplayText = string.Format("{0} {1}", EnumFormatters.Format(p.HotKey), p.Value.Name); } }
public static string GetLeadingPassengerFormattedName(this Booking booking) { var leadingPassengersList = booking.Rooms .SelectMany(r => { if (r.Passengers == null) { return(new List <Passenger>(0)); } return(r.Passengers.Where(p => p.IsLeader)); }) .ToList(); if (leadingPassengersList.Any()) { var leadingPassenger = leadingPassengersList.First(); return(PersonNameFormatters.ToMaskedName(leadingPassenger.FirstName, leadingPassenger.LastName, EnumFormatters.FromDescription(leadingPassenger.Title))); } return(PersonNameFormatters.ToMaskedName("*", string.Empty)); }
public async Task SendNotificationIfRequired(AgencyAccount account, MoneyAmount chargedAmount) { var resultingBalance = account.Balance - chargedAmount.Amount; var(_, isFailure, setting, _) = await _balanceNotificationsManagementService.Get(account.Id); if (isFailure || !setting.Thresholds.Any(t => account.Balance >= t && resultingBalance < t)) { return; } var(_, isAgencyFailure, agency, _) = await _adminAgencyManagementService.Get(account.AgencyId); if (isAgencyFailure) { return; } var lowestThreshold = setting.Thresholds .Where(t => account.Balance >= t && resultingBalance < t) .OrderBy(t => t) .First(); var messageData = new AccountBalanceManagementNotificationData { AgencyAccountId = account.Id, AgencyId = agency.Id ?? 0, AgencyName = agency.Name, Currency = EnumFormatters.FromDescription(account.Currency), Threshold = lowestThreshold, NewAmount = MoneyFormatter.ToCurrencyString(resultingBalance, account.Currency) }; await _notificationService.Send(messageData : messageData, notificationType : NotificationTypes.AccountBalanceManagementNotification, email : _options.AccountsEmail); }
public Task <Result> RegisterWithAgency(UserDescriptionInfo agentData, RegistrationAgencyInfo registrationAgencyInfo, string externalIdentity, string email) { return(Result.Success() .Ensure(IsIdentityPresent, "User should have identity") .Bind(Validate) .BindWithTransaction(_context, () => Result.Success() .Bind(CreateRootAgency) .Bind(CreateAgent) .Tap(AddMasterAgentAgencyRelation)) .Bind(LogSuccess) .Bind(SendRegistrationMailToAdmins) .OnFailure(LogFailure)); bool IsIdentityPresent() => !string.IsNullOrWhiteSpace(externalIdentity); Result Validate() => AgencyValidator.Validate(registrationAgencyInfo); Task <Result <AgencyInfo> > CreateRootAgency() => _agencyService.Create(registrationAgencyInfo, parentAgencyId: null); async Task <Result <(AgencyInfo, Agent)> > CreateAgent(AgencyInfo agency) { var(_, isFailure, agent, error) = await _agentService.Add(agentData, externalIdentity, email); return(isFailure ? Result.Failure <(AgencyInfo, Agent)>(error) : Result.Success((agency, agent))); } async Task AddMasterAgentAgencyRelation((AgencyInfo agency, Agent agent) agencyAgentInfo) { var(agency, agent) = agencyAgentInfo; // assign all roles to master agent var roleIds = await _context.AgentRoles.Select(x => x.Id).ToArrayAsync(); await AddAgentAgencyRelation(agent, AgentAgencyRelationTypes.Master, agency.Id.Value, roleIds); } async Task <Result> SendRegistrationMailToAdmins(AgencyInfo agency) { var agent = $"{agentData.Title} {agentData.FirstName} {agentData.LastName}"; if (!string.IsNullOrWhiteSpace(agentData.Position)) { agent += $" ({agentData.Position})"; } var messageData = new RegistrationDataForAdmin { Agency = new RegistrationDataForAdmin.RootAgencyRegistrationMailData { Id = agency.Id.ToString(), Name = agency.Name, CountryCode = agency.CountryCode, City = agency.City, Address = agency.Address, Phone = agency.Phone, PostalCode = agency.PostalCode, Fax = agency.Fax, PreferredCurrency = EnumFormatters.FromDescription(agency.PreferredCurrency), PreferredPaymentMethod = EnumFormatters.FromDescription(agency.PreferredPaymentMethod), Website = agency.Website }, AgentEmail = email, AgentName = agent }; return(await _notificationService.Send(messageData : messageData, notificationType : NotificationTypes.MasterAgentSuccessfulRegistration, emails : _notificationOptions.AdministratorsEmails)); } Result <AgencyInfo> LogSuccess((AgencyInfo, Agent) registrationData) { var(agency, agent) = registrationData; _logger.LogAgentRegistrationSuccess(agent.Email); return(Result.Success(agency)); } void LogFailure(string error) { _logger.LogAgentRegistrationFailed(error); } }
private Task <Result> ChangeActivityStatus(Agency agency, ActivityStatus status) { var isActive = ToBoolean(status); if (isActive == agency.IsActive) { return(Task.FromResult(Result.Success())); } return(ChangeAgencyActivityStatus() .Tap(ChangeAgencyAccountsActivityStatus) .Bind(SendNotificationToMaster)); async Task <Result> ChangeAgencyActivityStatus() { agency.IsActive = isActive; agency.Modified = _dateTimeProvider.UtcNow(); _context.Update(agency); await _context.SaveChangesAsync(); return(Result.Success()); } async Task ChangeAgencyAccountsActivityStatus() { var agencyAccounts = await _context.AgencyAccounts .Where(ac => ac.AgencyId == agency.Id) .ToListAsync(); foreach (var account in agencyAccounts) { account.IsActive = isActive; } _context.UpdateRange(agencyAccounts); await _context.SaveChangesAsync(); } async Task <Result> SendNotificationToMaster() { var(_, isFailure, master, error) = await _agentService.GetMasterAgent(agency.Id); if (isFailure) { return(Result.Failure(error)); } var messageData = new AgencyIsActiveStatusChangedData { AgentName = $"{master.FirstName} {master.LastName}", AgencyName = agency.Name, Status = EnumFormatters.FromDescription <ActivityStatus>(status) }; return(await _notificationService.Send(agent : new SlimAgentContext(master.Id, agency.Id), messageData : messageData, notificationType : NotificationTypes.AgencyActivityChanged, email : master.Email)); } }
public async Task <Result <BookingVoucherData> > GenerateVoucher(int bookingId, AgentContext agent, string languageCode) { var(_, isBookingFailure, booking, bookingError) = await _bookingRecordsManager.Get(bookingId); if (isBookingFailure) { return(Result.Failure <BookingVoucherData>(bookingError)); } var(_, isAccommodationFailure, accommodationDetails, accommodationError) = await _accommodationService.Get(booking.Supplier, booking.AccommodationId, languageCode); if (isAccommodationFailure) { return(Result.Failure <BookingVoucherData>(accommodationError.Detail)); } var(isBannerSuccess, _, bannerImage, _) = await _imageFileService.GetBanner(agent); var(isLogoSuccess, _, logoImage, _) = await _imageFileService.GetLogo(agent); if (!AvailableForVoucherBookingStatuses.Contains(booking.Status)) { return(Result.Failure <BookingVoucherData>($"Voucher is not allowed for booking status '{EnumFormatters.FromDescription(booking.Status)}'")); } if (!AvailableForVoucherPaymentStatuses.Contains(booking.PaymentStatus)) { return(Result.Failure <BookingVoucherData>($"Voucher is not allowed for payment status '{EnumFormatters.FromDescription(booking.PaymentStatus)}'")); } return(Result.Success(new BookingVoucherData ( $"{agent.FirstName} {agent.LastName}", booking.Id, GetAccommodationInfo(in accommodationDetails), (booking.CheckOutDate - booking.CheckInDate).Days, booking.CheckInDate, booking.CheckOutDate, booking.DeadlineDate, booking.MainPassengerName, booking.ReferenceCode, isBannerSuccess ? bannerImage.Url : null, isLogoSuccess ? logoImage.Url : null, booking.Rooms.Select(r => new BookingVoucherData.RoomInfo(r.Type, r.BoardBasis, r.MealPlan, r.DeadlineDate, r.ContractDescription, r.Passengers, r.Remarks, r.SupplierRoomReferenceCode)) .ToList() ))); }
public async Task <Result <BookingVoucherData> > GenerateVoucher(Booking booking, string languageCode) { var(_, isAccommodationFailure, accommodationDetails, accommodationError) = await _accommodationMapperClient.GetAccommodation(booking.HtId, languageCode); if (isAccommodationFailure) { return(Result.Failure <BookingVoucherData>(accommodationError.Detail)); } var bannerMaybe = await _imageFileService.GetBanner(booking.AgencyId); var logoMaybe = await _imageFileService.GetLogo(booking.AgencyId); var agent = await _context.Agents.SingleOrDefaultAsync(a => a.Id == booking.AgentId); if (agent == default) { return(Result.Failure <BookingVoucherData>("Could not find agent")); } if (!AvailableForVoucherBookingStatuses.Contains(booking.Status)) { return(Result.Failure <BookingVoucherData>($"Voucher is not allowed for booking status '{EnumFormatters.FromDescription(booking.Status)}'")); } if (!AvailableForVoucherPaymentStatuses.Contains(booking.PaymentStatus)) { return(Result.Failure <BookingVoucherData>($"Voucher is not allowed for payment status '{EnumFormatters.FromDescription(booking.PaymentStatus)}'")); } return(new BookingVoucherData ( agentName: $"{agent.FirstName} {agent.LastName}", bookingId: booking.Id, accommodation: GetAccommodationInfo(accommodationDetails.ToEdoContract()), nightCount: (booking.CheckOutDate - booking.CheckInDate).Days, checkInDate: booking.CheckInDate.DateTime, checkOutDate: booking.CheckOutDate.DateTime, deadlineDate: booking.DeadlineDate?.DateTime, mainPassengerName: booking.MainPassengerName, referenceCode: booking.ReferenceCode, supplierReferenceCode: booking.SupplierReferenceCode, propertyOwnerConfirmationCode: booking.PropertyOwnerConfirmationCode, bannerUrl: bannerMaybe.HasValue ? bannerMaybe.Value.Url : null, logoUrl: logoMaybe.HasValue ? logoMaybe.Value.Url : null, roomDetails: booking.Rooms.Select(r => new BookingVoucherData.RoomInfo(r.ContractDescription, r.BoardBasis, r.MealPlan, r.DeadlineDate?.DateTime, r.ContractDescription, r.Passengers, r.Remarks, r.SupplierRoomReferenceCode)) .ToList() )); }