public async Task <List <GetAllRiderTransactionsDto> > Handle(GetAllRiderTransactionsQuery request, CancellationToken cancellationToken) { // filter by status ready. only ready status will be retrieved. var bookingStatus = await context.BookingStatus.SingleOrDefaultAsync(o => o.BookingStatusName.ToLower() == "ready"); if (bookingStatus == null) { throw new NotFoundException(); } var result = await context.Bookings.Where(o => o.BookingStatusId == bookingStatus.BookingStatusId).ToListAsync(); if (result == null) { throw new BookingsWithStatusReadyNotFoundException(); } var bookings = mapper.Map <List <GetAllRiderTransactionsDto> >(result); foreach (var booking in bookings) { var status = await context.BookingStatus.FindAsync(booking.BookingStatusId); if (status != null) { booking.BookingStatusName = status.BookingStatusName; } var customer = await context.Customers.FindAsync(booking.CustomerId); if (customer != null) { booking.CustomerName = $"{ customer.LastName }, {customer.FirstName}"; } var rider = await context.Riders.FindAsync(booking.RiderId); if (rider != null) { booking.RiderName = $"{ rider.LastName }, {rider.FirstName}"; } booking.BookingDateFormatted = booking.BookingDate.ToString("MM/dd/yyyy"); booking.PickupTimeFormatted = booking.PickupTime.GetValueOrDefault().ToString("hh:mm tt"); booking.DropOffTimeFormatted = booking.DropOffTime.GetValueOrDefault().ToString("hh:mm tt"); var fare = await context.Fares.FindAsync(booking.FareId); if (fare != null) { booking.TotalFare = FareHelper.Compute(fare.PricePerKilometer, fare.BaseFare, fare.Surcharge, GetKilometer(booking.TotalKilometers)); } } return(bookings); }
public async Task <string> Handle(ComputeFare request, CancellationToken cancellationToken) { var fare = await context.Fares.SingleOrDefaultAsync(o => o.IsDefault == true); if (fare == null) { throw new NotFoundException(); } return(FareHelper.ComputeRiderFare(fare.PricePerKilometer, fare.BaseFare, fare.Surcharge, request.TotalKilometers)); }
public async Task <List <GetAllBookingsDto> > Handle(GetAllBookingsQuery request, CancellationToken cancellationToken) { var bookings = mapper.Map <List <GetAllBookingsDto> >(await context.Bookings.ToListAsync()); foreach (var booking in bookings) { var status = await context.BookingStatus.FindAsync(booking.BookingStatusId); if (status != null) { booking.BookingStatusName = status.BookingStatusName; booking.BookingStatusColor = status.StatusColor; } var customer = await context.Customers.SingleOrDefaultAsync(o => o.UserId == booking.CustomerId); if (customer != null) { booking.CustomerName = $"{ customer.LastName }, {customer.FirstName}"; } var rider = await context.Riders.FindAsync(booking.RiderId); if (rider != null) { booking.RiderName = $"{ rider.LastName }, {rider.FirstName}"; } booking.BookingDateFormatted = booking.BookingDate.ToString("MM/dd/yyyy"); booking.PickupTimeFormatted = booking.PickupTime.GetValueOrDefault().ToString("hh:mm tt"); booking.DropOffTimeFormatted = booking.DropOffTime.GetValueOrDefault().ToString("hh:mm tt"); var fare = await context.Fares.FindAsync(booking.FareId); if (fare != null) { booking.TotalFare = FareHelper.Compute(fare.PricePerKilometer, fare.BaseFare, fare.Surcharge, GetKilometer(booking.TotalKilometers)); } } return(bookings); }
private CreditCardPaymentCaptured_V2 Convert(CreditCardPaymentCaptured oldEvent) { var fareObject = FareHelper.GetFareFromAmountInclTax(System.Convert.ToDouble(oldEvent.Meter), _serverSettings.ServerData.VATIsEnabled ? _serverSettings.ServerData.VATPercentage : 0); return(new CreditCardPaymentCaptured_V2 { EventDate = oldEvent.EventDate, SourceId = oldEvent.SourceId, Version = oldEvent.Version, TransactionId = oldEvent.TransactionId, AuthorizationCode = oldEvent.AuthorizationCode, Amount = oldEvent.Amount, Tip = oldEvent.Tip, Provider = oldEvent.Provider, OrderId = oldEvent.OrderId, IsNoShowFee = oldEvent.IsNoShowFee, PromotionUsed = oldEvent.PromotionUsed, AmountSavedByPromotion = oldEvent.AmountSavedByPromotion, Meter = System.Convert.ToDecimal(fareObject.AmountExclTax), Tax = System.Convert.ToDecimal(fareObject.TaxAmount) }); }
public void when_order_is_paired_and_received_fare_with_preauth_enabled_and_commit_fails_with_card_declined() { // Prepare var accountId = Guid.NewGuid(); var orderId = Guid.NewGuid(); var creditCardId = Guid.NewGuid(); string companyKey = null; var orderAmount = 100.85m; var preAuthAmount = 50m; using (var context = new BookingDbContext(DbName)) { context.Save(new AccountDetail { Id = accountId, CreationDate = DateTime.Now, IBSAccountId = 123, DefaultCreditCard = creditCardId }); context.Save(new CreditCardDetails { AccountId = accountId, CreditCardId = creditCardId, Token = "token" }); context.Save(new OrderDetail { Id = orderId, AccountId = accountId, PickupDate = DateTime.Now, CreatedDate = DateTime.Now, IBSOrderId = 12345, CompanyKey = companyKey }); context.Save(new OrderPaymentDetail { PaymentId = Guid.NewGuid(), OrderId = orderId, CompanyKey = companyKey, PreAuthorizedAmount = preAuthAmount, FirstPreAuthTransactionId = "asdasdnasd", TransactionId = "asdasdnasd" }); context.Save(new OrderPairingDetail { OrderId = orderId }); } var tip = FareHelper.CalculateTipAmount(orderAmount, ConfigurationManager.ServerData.DefaultTipPercentage); var ibsOrder = new IBSOrderInformation { Fare = Convert.ToDouble(orderAmount) }; var status = new OrderStatusDetail { OrderId = orderId, CompanyKey = companyKey, AccountId = accountId, IBSOrderId = 12345 }; ConfigurationManager.SetPaymentSettings(null, new ServerPaymentSettings { PaymentMode = PaymentMethod.Braintree }); EnsureCommitWasCalled(status, preAuthAmount, orderAmount + tip, orderAmount, tip); EnsureVoidPreAuthWasCalled(status); // Act Sut.Update(ibsOrder, status); // Assert PaymentServiceMock.Verify(); Assert.AreEqual(3, Commands.Count); Assert.AreEqual(typeof(LogCreditCardError), Commands.First().GetType()); Assert.AreEqual(typeof(ReactToPaymentFailure), Commands.Skip(1).First().GetType()); Assert.AreEqual(typeof(ChangeOrderStatus), Commands.Skip(2).First().GetType()); }
private bool SettleOverduePayment(Guid orderId, AccountDetail accountDetail, decimal amount, string companyKey, bool isFee, string kountSessionId, string customerIpAddress) { var payment = _orderPaymentDao.FindByOrderId(orderId, companyKey); var reAuth = payment != null; var preAuthResponse = _paymentService.PreAuthorize(companyKey, orderId, accountDetail, amount, reAuth, isSettlingOverduePayment: true); if (preAuthResponse.IsSuccessful) { // Wait for payment to be created Thread.Sleep(500); var commitResponse = _paymentService.CommitPayment( companyKey, orderId, accountDetail, amount, amount, amount, 0, preAuthResponse.TransactionId, preAuthResponse.ReAuthOrderId, false, kountSessionId, customerIpAddress); if (commitResponse.IsSuccessful) { // Go fetch declined order, and send its receipt var paymentDetail = _orderPaymentDao.FindByOrderId(orderId, companyKey); var promotion = _promotionDao.FindByOrderId(orderId); var orderDetail = _orderDao.FindById(orderId); decimal tipAmount = 0; decimal meterAmountWithoutTax = amount; decimal taxAmount = 0; if (!isFee) { if (!orderDetail.IsManualRideLinq) { var pairingInfo = _orderDao.FindOrderPairingById(orderId); tipAmount = FareHelper.GetTipAmountFromTotalIncludingTip(amount, pairingInfo.AutoTipPercentage ?? _serverSettings.ServerData.DefaultTipPercentage); var meterAmount = amount - tipAmount; var fareObject = FareHelper.GetFareFromAmountInclTax(meterAmount, _serverSettings.ServerData.VATIsEnabled ? _serverSettings.ServerData.VATPercentage : 0); meterAmountWithoutTax = fareObject.AmountExclTax; taxAmount = fareObject.TaxAmount; } else { var ridelinqOrderDetail = _orderDao.GetManualRideLinqById(orderId); taxAmount = Convert.ToDecimal(ridelinqOrderDetail.Tax ?? 0); meterAmountWithoutTax = amount - taxAmount; tipAmount = Convert.ToDecimal(ridelinqOrderDetail.Tip); } } _commandBus.Send(new CaptureCreditCardPayment { IsSettlingOverduePayment = true, NewCardToken = paymentDetail.CardToken, AccountId = accountDetail.Id, PaymentId = paymentDetail.PaymentId, Provider = _paymentService.ProviderType(companyKey, orderId), TotalAmount = amount, MeterAmount = meterAmountWithoutTax, TipAmount = tipAmount, TaxAmount = taxAmount, TollAmount = Convert.ToDecimal(orderDetail.Toll ?? 0), SurchargeAmount = Convert.ToDecimal(orderDetail.Surcharge ?? 0), AuthorizationCode = commitResponse.AuthorizationCode, TransactionId = commitResponse.TransactionId, PromotionUsed = promotion != null ? promotion.PromoId : default(Guid?), AmountSavedByPromotion = promotion != null ? promotion.AmountSaved : 0, FeeType = isFee ? FeeTypes.Booking : FeeTypes.None }); _commandBus.Send(new SettleOverduePayment { AccountId = accountDetail.Id, OrderId = orderId, CreditCardId = accountDetail.DefaultCreditCard.GetValueOrDefault() }); return(true); } // Payment failed, void preauth _paymentService.VoidPreAuthorization(companyKey, orderId); } return(false); }
private void ValidatePayment(string companyKey, CreateOrderRequest request, Guid orderId, AccountDetail account, bool isFutureBooking, double?appEstimate, decimal bookingFees, bool isPrepaid, CreateReportOrder createReportOrder) { var tipPercent = account.DefaultTipPercent ?? _serverSettings.ServerData.DefaultTipPercentage; // If there's an estimate, add tip to that estimate if (appEstimate.HasValue) { appEstimate = appEstimate.Value + FareHelper.CalculateTipAmount(appEstimate.Value, tipPercent); } var appEstimateWithTip = appEstimate.HasValue ? Convert.ToDecimal(appEstimate.Value) : (decimal?)null; if (isPrepaid) { // Verify that prepaid is enabled on the server if (!_serverSettings.GetPaymentSettings(companyKey).IsPrepaidEnabled) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_PrepaidButPrepaidNotEnabled", request.ClientLanguageCode)); } // Payment mode is CardOnFile if (request.Settings.ChargeTypeId.HasValue && request.Settings.ChargeTypeId.Value == ChargeTypes.CardOnFile.Id) { if (!appEstimateWithTip.HasValue) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_PrepaidNoEstimate", request.ClientLanguageCode)); } ValidateCreditCard(account, request.ClientLanguageCode, request.Cvv, createReportOrder); var result = PaymentHelper.CapturePaymentForPrepaidOrder(companyKey, orderId, account, Convert.ToDecimal(appEstimateWithTip), tipPercent, bookingFees, request.Cvv); if (!result.IsSuccessful) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, result.Message); } } } else { // Payment mode is CardOnFile if (request.Settings.ChargeTypeId.HasValue && request.Settings.ChargeTypeId.Value == ChargeTypes.CardOnFile.Id) { ValidateCreditCard(account, request.ClientLanguageCode, request.Cvv, createReportOrder); var isSuccessful = PaymentHelper.PreAuthorizePaymentMethod(companyKey, orderId, account, isFutureBooking, appEstimateWithTip, bookingFees, request.Cvv); if (!isSuccessful) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_CreditCardWasDeclined", request.ClientLanguageCode)); } } // Payment mode is PayPal if (request.Settings.ChargeTypeId.HasValue && request.Settings.ChargeTypeId.Value == ChargeTypes.PayPal.Id) { ValidatePayPal(companyKey, orderId, account, request.ClientLanguageCode, isFutureBooking, appEstimateWithTip, bookingFees, createReportOrder); } } }
protected CreateOrder BuildCreateOrderCommand(CreateOrderRequest request, AccountDetail account, CreateReportOrder createReportOrder) { _logger.LogMessage("Create order request : " + request); if (request.Settings.Country == null || !request.Settings.Country.Code.HasValueTrimmed()) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, string.Format(_resources.Get("PhoneNumberCountryNotProvided", request.ClientLanguageCode))); } var countryCode = CountryCode.GetCountryCodeByIndex(CountryCode.GetCountryCodeIndexByCountryISOCode(request.Settings.Country)); if (PhoneHelper.IsPossibleNumber(countryCode, request.Settings.Phone)) { request.Settings.Phone = PhoneHelper.GetDigitsFromPhoneNumber(request.Settings.Phone); } else { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, string.Format(_resources.Get("PhoneNumberFormat", request.ClientLanguageCode), countryCode.GetPhoneExample())); } // TODO MKTAXI-3576: Find a better way to do this... var isFromWebApp = request.FromWebApp; if (!isFromWebApp) { ValidateAppVersion(request.ClientLanguageCode, createReportOrder); } // Find market var marketSettings = _taxiHailNetworkServiceClient.GetCompanyMarketSettings(request.PickupAddress.Latitude, request.PickupAddress.Longitude); var market = marketSettings.Market.HasValue() ? marketSettings.Market : null; createReportOrder.Market = market; var isFutureBooking = IsFutureBooking(request.PickupDate, marketSettings); if (!marketSettings.EnableFutureBooking && isFutureBooking) { // future booking not allowed ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_FutureBookingNotAllowed", request.ClientLanguageCode)); } BestAvailableCompany bestAvailableCompany; if (request.OrderCompanyKey.HasValue() || request.OrderFleetId.HasValue) { // For API user, it's possible to manually specify which company to dispatch to by using a fleet id bestAvailableCompany = _taxiHailNetworkHelper.FindSpecificCompany(market, createReportOrder, request.OrderCompanyKey, request.OrderFleetId, request.PickupAddress.Latitude, request.PickupAddress.Longitude); } else { bestAvailableCompany = _taxiHailNetworkHelper.FindBestAvailableCompany(marketSettings, request.PickupAddress.Latitude, request.PickupAddress.Longitude, isFutureBooking); } _logger.LogMessage("Best available company determined: {0}, in {1}", bestAvailableCompany.CompanyKey.HasValue() ? bestAvailableCompany.CompanyKey : "local company", market.HasValue() ? market : "local market"); createReportOrder.CompanyKey = bestAvailableCompany.CompanyKey; createReportOrder.CompanyName = bestAvailableCompany.CompanyName; if (market.HasValue()) { if (!bestAvailableCompany.CompanyKey.HasValue()) { // No companies available that are desserving this region for the company ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_NoCompanies", request.ClientLanguageCode)); } _taxiHailNetworkHelper.UpdateVehicleTypeFromMarketData(request.Settings, bestAvailableCompany.CompanyKey); var isConfiguredForCmtPayment = _taxiHailNetworkHelper.FetchCompanyPaymentSettings(bestAvailableCompany.CompanyKey); if (!isConfiguredForCmtPayment) { // Only companies configured for CMT payment can support CoF orders outside of home market request.Settings.ChargeTypeId = ChargeTypes.PaymentInCar.Id; } if (marketSettings.DisableOutOfAppPayment && request.Settings.ChargeTypeId == ChargeTypes.PaymentInCar.Id) { // No payment method available since we can't pay in car ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_NoChargeType, _resources.Get("CannotCreateOrder_NoChargeType", request.ClientLanguageCode)); } } var isPaypal = request.Settings.ChargeTypeId == ChargeTypes.PayPal.Id; var isBraintree = (request.Settings.ChargeTypeId == ChargeTypes.CardOnFile.Id) && (_serverSettings.GetPaymentSettings().PaymentMode == PaymentMethod.Braintree); var isPrepaid = isFromWebApp && (isPaypal || isBraintree); createReportOrder.IsPrepaid = isPrepaid; account.IBSAccountId = CreateIbsAccountIfNeeded(account, bestAvailableCompany.CompanyKey); var pickupDate = request.PickupDate ?? GetCurrentOffsetedTime(bestAvailableCompany.CompanyKey); createReportOrder.PickupDate = pickupDate; // User can still create future order, but we allow only one active Book now order. if (!isFutureBooking) { var pendingOrderId = GetPendingOrder(); // We don't allow order creation if there's already an order scheduled if (!_serverSettings.ServerData.AllowSimultaneousAppOrders && pendingOrderId != null && !isFromWebApp) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_PendingOrder, pendingOrderId.ToString()); } } var rule = _ruleCalculator.GetActiveDisableFor( isFutureBooking, pickupDate, () => _ibsServiceProvider.StaticData(bestAvailableCompany.CompanyKey) .GetZoneByCoordinate( request.Settings.ProviderId, request.PickupAddress.Latitude, request.PickupAddress.Longitude), () => request.DropOffAddress != null ? _ibsServiceProvider.StaticData(bestAvailableCompany.CompanyKey) .GetZoneByCoordinate( request.Settings.ProviderId, request.DropOffAddress.Latitude, request.DropOffAddress.Longitude) : null, market, new Position(request.PickupAddress.Latitude, request.PickupAddress.Longitude)); if (rule != null) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, rule.Message); } // We need to validate the rules of the roaming market. if (market.HasValue()) { // External market, query company site directly to validate their rules var orderServiceClient = new RoamingValidationServiceClient(bestAvailableCompany.CompanyKey, _serverSettings.ServerData.Target); _logger.LogMessage(string.Format("Validating rules for company in external market... Target: {0}, Server: {1}", _serverSettings.ServerData.Target, orderServiceClient.Url)); var validationResult = orderServiceClient.ValidateOrder(request, true); if (validationResult.HasError) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, validationResult.Message); } } if (Params.Get(request.Settings.Name, request.Settings.Phone).Any(p => p.IsNullOrEmpty())) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_SettingsRequired); } var referenceData = (ReferenceData)_referenceDataService.Get(new ReferenceDataRequest { CompanyKey = bestAvailableCompany.CompanyKey }); request.PickupDate = pickupDate; request.Settings.Passengers = request.Settings.Passengers <= 0 ? 1 : request.Settings.Passengers; if (_serverSettings.ServerData.Direction.NeedAValidTarif && (!request.Estimate.Price.HasValue || request.Estimate.Price == 0)) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_NoFareEstimateAvailable, GetCreateOrderServiceErrorMessage(ErrorCode.CreateOrder_NoFareEstimateAvailable, request.ClientLanguageCode)); } // IBS provider validation ValidateProvider(request, referenceData, market.HasValue(), createReportOrder); // Map the command to obtain a OrderId (web doesn't prepopulate it in the request) var orderCommand = Mapper.Map <Commands.CreateOrder>(request); _logger.LogMessage("MarketSettings for order {0}: {1}", orderCommand.OrderId, marketSettings.ToJson()); var marketFees = _feesDao.GetMarketFees(market); orderCommand.BookingFees = marketFees != null ? marketFees.Booking : 0; createReportOrder.BookingFees = orderCommand.BookingFees; createReportOrder.AssignVehicleId = orderCommand.AssignVehicleId; // Promo code validation var promotionId = ValidatePromotion(bestAvailableCompany.CompanyKey, request.PromoCode, request.Settings.ChargeTypeId, account.Id, pickupDate, isFutureBooking, request.ClientLanguageCode, createReportOrder); // Charge account validation var accountValidationResult = ValidateChargeAccountIfNecessary(bestAvailableCompany.CompanyKey, request, orderCommand.OrderId, account, isFutureBooking, isFromWebApp, orderCommand.BookingFees, createReportOrder); createReportOrder.IsChargeAccountPaymentWithCardOnFile = accountValidationResult.IsChargeAccountPaymentWithCardOnFile; // if ChargeAccount uses payment with card on file, payment validation was already done if (!accountValidationResult.IsChargeAccountPaymentWithCardOnFile) { // Payment method validation ValidatePayment(bestAvailableCompany.CompanyKey, request, orderCommand.OrderId, account, isFutureBooking, request.Estimate.Price, orderCommand.BookingFees, isPrepaid, createReportOrder); } var chargeTypeIbs = string.Empty; var chargeTypeEmail = string.Empty; var chargeTypeKey = ChargeTypes.GetList() .Where(x => x.Id == request.Settings.ChargeTypeId) .Select(x => x.Display) .FirstOrDefault(); chargeTypeKey = accountValidationResult.ChargeTypeKeyOverride ?? chargeTypeKey; if (chargeTypeKey != null) { // this must be localized with the priceformat to be localized in the language of the company // because it is sent to the driver chargeTypeIbs = _resources.Get(chargeTypeKey, _serverSettings.ServerData.PriceFormat); chargeTypeEmail = _resources.Get(chargeTypeKey, request.ClientLanguageCode); } // Get Vehicle Type from reference data var vehicleType = referenceData.VehiclesList .Where(x => x.Id == request.Settings.VehicleTypeId) .Select(x => x.Display) .FirstOrDefault(); // Use address alias if present. var addressAlias = request.PickupAddress.FriendlyName.HasValueTrimmed() ? request.PickupAddress.FriendlyName : request.PickupAddress.BuildingName; var ibsInformationNote = IbsHelper.BuildNote( _serverSettings.ServerData.IBS.NoteTemplate, chargeTypeIbs, request.Note, addressAlias, request.Settings.LargeBags, _serverSettings.ServerData.IBS.HideChargeTypeInUserNote); var fare = FareHelper.GetFareFromEstimate(request.Estimate); orderCommand.AccountId = account.Id; orderCommand.UserAgent = Request.UserAgent; orderCommand.ClientVersion = Request.Headers.Get("ClientVersion"); orderCommand.IsChargeAccountPaymentWithCardOnFile = accountValidationResult.IsChargeAccountPaymentWithCardOnFile; orderCommand.CompanyKey = bestAvailableCompany.CompanyKey; orderCommand.CompanyName = bestAvailableCompany.CompanyName; orderCommand.CompanyFleetId = bestAvailableCompany.FleetId; orderCommand.Market = market; orderCommand.IsPrepaid = isPrepaid; orderCommand.Settings.ChargeType = chargeTypeIbs; orderCommand.Settings.VehicleType = vehicleType; orderCommand.IbsAccountId = account.IBSAccountId.Value; orderCommand.ReferenceDataCompanyList = referenceData.CompaniesList.ToArray(); orderCommand.IbsInformationNote = ibsInformationNote; orderCommand.Fare = fare; orderCommand.Prompts = accountValidationResult.Prompts; orderCommand.PromptsLength = accountValidationResult.PromptsLength; orderCommand.PromotionId = promotionId; orderCommand.ChargeTypeEmail = chargeTypeEmail; orderCommand.OriginatingIpAddress = createReportOrder.OriginatingIpAddress = request.CustomerIpAddress; orderCommand.KountSessionId = createReportOrder.OriginatingIpAddress = request.KountSessionId; orderCommand.IsFutureBooking = createReportOrder.IsFutureBooking = isFutureBooking; orderCommand.AssignVehicleId = createReportOrder.AssignVehicleId; Debug.Assert(request.PickupDate != null, "request.PickupDate != null"); return(orderCommand); }
public InitializePayPalCheckoutResponse InitializeWebPayment(Guid accountId, Guid orderId, string baseUri, double?estimatedFare, decimal bookingFees, string clientLanguageCode) { if (!estimatedFare.HasValue) { return(new InitializePayPalCheckoutResponse { IsSuccessful = false, Message = _resources.Get("CannotCreateOrder_PrepaidNoEstimate", clientLanguageCode) }); } var regionName = _serverSettings.ServerData.PayPalRegionInfoOverride; var conversionRate = _serverSettings.ServerData.PayPalConversionRate; _logger.LogMessage("PayPal Conversion Rate: {0}", conversionRate); // Fare amount var fareAmount = Math.Round(Convert.ToDecimal(estimatedFare.Value) * conversionRate, 2); var currency = conversionRate != 1 ? CurrencyCodes.Main.UnitedStatesDollar : _resources.GetCurrencyCode(); // Need the fare object because tip amount should be calculated on the fare excluding taxes var fareObject = FareHelper.GetFareFromAmountInclTax(Convert.ToDouble(fareAmount), _serverSettings.ServerData.VATIsEnabled ? _serverSettings.ServerData.VATPercentage : 0); // Tip amount (on fare amount excl. taxes) var defaultTipPercentage = _accountDao.FindById(accountId).DefaultTipPercent; var tipPercentage = defaultTipPercentage ?? _serverSettings.ServerData.DefaultTipPercentage; var tipAmount = FareHelper.CalculateTipAmount(fareObject.AmountInclTax, tipPercentage); // Booking Fees with conversion rate if necessary var bookingFeesAmount = Math.Round(bookingFees * conversionRate, 2); // Fare amount with tip and booking fee var totalAmount = fareAmount + tipAmount + bookingFeesAmount; var redirectUrl = baseUri + string.Format("/{0}/proceed", orderId); _logger.LogMessage("PayPal Web redirect URL: {0}", redirectUrl); var redirUrls = new RedirectUrls { cancel_url = redirectUrl + "?cancel=true", return_url = redirectUrl }; // Create transaction var transactionList = new List <Transaction> { new Transaction { amount = new Amount { currency = currency, total = totalAmount.ToString("N", CultureInfo.InvariantCulture) }, description = string.Format( _resources.Get("PayPalWebPaymentDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), totalAmount), item_list = new ItemList { items = new List <Item> { new Item { name = _resources.Get("PayPalWebFareItemDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), currency = currency, price = fareAmount.ToString("N", CultureInfo.InvariantCulture), quantity = "1" }, new Item { name = string.Format(_resources.Get("PayPalWebTipItemDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), tipPercentage), currency = currency, price = tipAmount.ToString("N", CultureInfo.InvariantCulture), quantity = "1" } } } } }; if (bookingFeesAmount > 0) { transactionList.First().item_list.items.Add(new Item { name = _resources.Get("PayPalWebBookingFeeItemDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), currency = currency, price = bookingFeesAmount.ToString("N", CultureInfo.InvariantCulture), quantity = "1" }); } // Create web experience profile var profile = new WebProfile { name = Guid.NewGuid().ToString(), flow_config = new FlowConfig { landing_page_type = _serverPaymentSettings.PayPalServerSettings.LandingPageType.ToString() } }; try { var webExperienceProfile = profile.Create(GetAPIContext(GetAccessToken())); // Create payment var payment = new Payment { intent = Intents.Sale, payer = new Payer { payment_method = "paypal" }, transactions = transactionList, redirect_urls = redirUrls, experience_profile_id = webExperienceProfile.id }; var createdPayment = payment.Create(GetAPIContext(GetAccessToken())); var links = createdPayment.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { return(new InitializePayPalCheckoutResponse { IsSuccessful = true, PaymentId = createdPayment.id, PayPalCheckoutUrl = link.href // Links that give the user the option to redirect to PayPal to approve the payment }); } } _logger.LogMessage("Error when creating PayPal Web payment: no approval_urls found"); // No approval_url found return(new InitializePayPalCheckoutResponse { IsSuccessful = false, Message = "No approval_url found" }); } catch (Exception ex) { var exceptionMessage = ex.Message; var paymentException = ex as PaymentsException; if (paymentException != null && paymentException.Details != null) { exceptionMessage = paymentException.Details.message; } _logger.LogMessage("Initialization of PayPal Web Store failed: {0}", exceptionMessage); return(new InitializePayPalCheckoutResponse { IsSuccessful = false, Message = exceptionMessage }); } }
public object Post(SwitchOrderToNextDispatchCompanyRequest request) { _logger.LogMessage("Switching order to another IBS : " + request.ToJson()); var account = _accountDao.FindById(new Guid(this.GetSession().UserAuthId)); var order = _orderDao.FindById(request.OrderId); var orderStatusDetail = _orderDao.FindOrderStatusById(request.OrderId); if (orderStatusDetail.Status != OrderStatus.TimedOut) { // Only switch companies if order is timedout return(orderStatusDetail); } // We are in a network timeout situation. if (orderStatusDetail.CompanyKey == request.NextDispatchCompanyKey) { _ibsCreateOrderService.CancelIbsOrder(order.IBSOrderId, order.CompanyKey, order.Settings.Phone, account.Id); orderStatusDetail.IBSStatusId = VehicleStatuses.Common.Timeout; orderStatusDetail.IBSStatusDescription = _resources.Get("OrderStatus_" + VehicleStatuses.Common.Timeout); return(orderStatusDetail); } var market = _taxiHailNetworkServiceClient.GetCompanyMarket(order.PickupAddress.Latitude, order.PickupAddress.Longitude); var isConfiguredForCmtPayment = _taxiHailNetworkHelper.FetchCompanyPaymentSettings(request.NextDispatchCompanyKey); var chargeTypeId = order.Settings.ChargeTypeId; var chargeTypeDisplay = order.Settings.ChargeType; if (!isConfiguredForCmtPayment) { // Only companies configured for CMT payment can support CoF orders outside of home market chargeTypeId = ChargeTypes.PaymentInCar.Id; chargeTypeDisplay = ChargeTypes.PaymentInCar.Display; } var newOrderRequest = new CreateOrderRequest { PickupDate = GetCurrentOffsetedTime(request.NextDispatchCompanyKey), PickupAddress = order.PickupAddress, DropOffAddress = order.DropOffAddress, Settings = new BookingSettings { LargeBags = order.Settings.LargeBags, Name = order.Settings.Name, NumberOfTaxi = order.Settings.NumberOfTaxi, Passengers = order.Settings.Passengers, Phone = order.Settings.Phone, ProviderId = null, ChargeType = chargeTypeDisplay, ChargeTypeId = chargeTypeId, // Reset vehicle type VehicleType = null, VehicleTypeId = null }, Note = order.UserNote, ClientLanguageCode = account.Language }; var fare = FareHelper.GetFareFromEstimate(new RideEstimate { Price = order.EstimatedFare }); var newReferenceData = (ReferenceData)_referenceDataService.Get(new ReferenceDataRequest { CompanyKey = request.NextDispatchCompanyKey }); // This must be localized with the priceformat to be localized in the language of the company // because it is sent to the driver var chargeTypeIbs = _resources.Get(chargeTypeDisplay, _serverSettings.ServerData.PriceFormat); var ibsInformationNote = IbsHelper.BuildNote( _serverSettings.ServerData.IBS.NoteTemplate, chargeTypeIbs, order.UserNote, order.PickupAddress.BuildingName, newOrderRequest.Settings.LargeBags, _serverSettings.ServerData.IBS.HideChargeTypeInUserNote); var networkErrorMessage = string.Format(_resources.Get("Network_CannotCreateOrder", order.ClientLanguageCode), request.NextDispatchCompanyName); int ibsAccountId; try { // Recreate order on next dispatch company IBS ibsAccountId = CreateIbsAccountIfNeeded(account, request.NextDispatchCompanyKey); } catch (Exception ex) { _logger.LogMessage(networkErrorMessage); _logger.LogError(ex); throw new HttpError(HttpStatusCode.InternalServerError, networkErrorMessage); } ValidateProvider(newOrderRequest, newReferenceData, market.HasValue(), null); var newOrderCommand = Mapper.Map <CreateOrder>(newOrderRequest); newOrderCommand.OrderId = request.OrderId; newOrderCommand.ReferenceDataCompanyList = newReferenceData.CompaniesList.ToArray(); newOrderCommand.Market = market; newOrderCommand.CompanyKey = request.NextDispatchCompanyKey; newOrderCommand.CompanyName = request.NextDispatchCompanyName; newOrderCommand.Fare = fare; newOrderCommand.IbsInformationNote = ibsInformationNote; _commandBus.Send(new InitiateIbsOrderSwitch { NewIbsAccountId = ibsAccountId, NewOrderCommand = newOrderCommand }); return(new OrderStatusDetail { OrderId = request.OrderId, Status = OrderStatus.Created, CompanyKey = request.NextDispatchCompanyKey, CompanyName = request.NextDispatchCompanyName, NextDispatchCompanyKey = null, NextDispatchCompanyName = null, IBSStatusId = string.Empty, IBSStatusDescription = string.Format(_resources.Get("OrderStatus_wosWAITINGRoaming", order.ClientLanguageCode), request.NextDispatchCompanyName), }); }
public async Task <Unit> Handle(UpdateBookingCommand request, CancellationToken cancellationToken) { var entity = mapper.Map <Booking>(request.Dto); var booking = await context.Bookings.FindAsync(request.BookingId); if (booking == null) { throw new NotFoundException(); } // update booking properties booking.BookingStatusId = entity.BookingStatusId; booking.BookingDate = entity.BookingDate; booking.ContactName = entity.ContactName; booking.ContactNumber = entity.ContactNumber; booking.DropOffLocation = entity.DropOffLocation; booking.DropOffLatitude = entity.DropOffLatitude; booking.DropOffLongitude = entity.DropOffLongitude; booking.DropOffTime = entity.DropOffTime; booking.Items = entity.Items; booking.Notes = entity.Notes; booking.TotalEstimatedWeight = entity.TotalEstimatedWeight; booking.IsActive = entity.IsActive; booking.PickupLocation = entity.PickupLocation; booking.PickupLongitude = entity.PickupLongitude; booking.PickupLatitude = entity.PickupLatitude; booking.PickupTime = entity.PickupTime; booking.FareId = entity.FareId; booking.RiderId = entity.RiderId; booking.PhotoUrl = entity.PhotoUrl; context.Update(booking); context.SaveChanges(); // log in booking history var customerBookingHistory = new CustomerBookingHistory(); customerBookingHistory.CustomerId = booking.CustomerId; customerBookingHistory.BookingStatusId = booking.BookingStatusId; customerBookingHistory.ReceiverCompleteName = booking.ContactName; customerBookingHistory.ReceiverCompleteAddress = booking.DropOffLocation; customerBookingHistory.EstimatedTime = booking.EstimatedTime; customerBookingHistory.ItemDetails = booking.Items; customerBookingHistory.TotalKilometers = booking.TotalKilometers; customerBookingHistory.Receipt = booking.ReceiptNumber; customerBookingHistory.BookingDate = booking.BookingDate; var fare = await context.Fares.FindAsync(booking.FareId); if (fare != null) { if (!string.IsNullOrEmpty(entity.TotalKilometers)) { customerBookingHistory.TotalFare = FareHelper.Compute(fare.PricePerKilometer, fare.BaseFare, fare.Surcharge, GetKilometer(booking.TotalKilometers)); } } context.CustomerBookingHistories.Add(customerBookingHistory); await context.SaveChangesAsync(); return(await Task.FromResult(Unit.Value)); }
public object Get(ExecuteWebPaymentAndProceedWithOrder request) { _logger.LogMessage("ExecuteWebPaymentAndProceedWithOrder request : " + request.ToJson()); var temporaryInfo = _orderDao.GetTemporaryInfo(request.OrderId); var orderInfo = JsonSerializer.DeserializeFromString <TemporaryOrderCreationInfo>(temporaryInfo.SerializedOrderCreationInfo); if (request.Cancel || orderInfo == null) { var clientLanguageCode = orderInfo == null ? SupportedLanguages.en.ToString() : orderInfo.Request.ClientLanguageCode; _commandBus.Send(new CancelOrderBecauseOfError { OrderId = request.OrderId, ErrorDescription = _resources.Get("CannotCreateOrder_PrepaidPayPalPaymentCancelled", clientLanguageCode) }); } else { // Execute PayPal payment var response = _payPalServiceFactory.GetInstance(orderInfo.BestAvailableCompany.CompanyKey).ExecuteWebPayment(request.PayerId, request.PaymentId); if (response.IsSuccessful) { var account = _accountDao.FindById(orderInfo.AccountId); var tipPercentage = account.DefaultTipPercent ?? _serverSettings.ServerData.DefaultTipPercentage; var tipAmount = FareHelper.CalculateTipAmount(orderInfo.Request.Fare.AmountInclTax, tipPercentage); _commandBus.Send(new MarkPrepaidOrderAsSuccessful { OrderId = request.OrderId, TotalAmount = orderInfo.Request.Fare.AmountInclTax + tipAmount, MeterAmount = orderInfo.Request.Fare.AmountExclTax, TaxAmount = orderInfo.Request.Fare.TaxAmount, TipAmount = tipAmount, TransactionId = response.TransactionId, Provider = PaymentProvider.PayPal, Type = PaymentType.PayPal }); } else { _commandBus.Send(new CancelOrderBecauseOfError { OrderId = request.OrderId, ErrorDescription = response.Message }); } } // Build url used to redirect the web client to the booking status view string baseUrl; if (_serverSettings.ServerData.BaseUrl.HasValue()) { baseUrl = _serverSettings.ServerData.BaseUrl; } else { baseUrl = Request.AbsoluteUri .Replace(Request.PathInfo, string.Empty) .Replace(GetAppHost().Config.ServiceStackHandlerFactoryPath, string.Empty) .Replace(Request.QueryString.ToString(), string.Empty) .Replace("?", string.Empty); } var redirectUrl = string.Format("{0}#status/{1}", baseUrl, request.OrderId); return(new HttpResult { StatusCode = HttpStatusCode.Redirect, Headers = { { HttpHeaders.Location, redirectUrl } } }); }
private CommitPreauthorizedPaymentResponse CommitPayment(decimal totalFeeAmount, decimal bookingFees, Guid orderId, FeeTypes feeType, string companyKey = null) { var orderDetail = _orderDao.FindById(orderId); if (orderDetail == null) { throw new Exception("Order not found"); } if (orderDetail.IBSOrderId == null) { throw new Exception("Order has no IBSOrderId"); } var account = _accountDao.FindById(orderDetail.AccountId); var paymentDetail = _paymentDao.FindByOrderId(orderId, companyKey); if (paymentDetail == null) { throw new Exception("Payment not found"); } var paymentProviderServiceResponse = new CommitPreauthorizedPaymentResponse { TransactionId = paymentDetail.TransactionId }; try { var message = string.Empty; if (paymentDetail.IsCompleted) { message = "Order already paid or payment currently processing"; } else { if (totalFeeAmount > 0) { // Fees are collected by the local company paymentProviderServiceResponse = _paymentService.CommitPayment(null, orderId, account, paymentDetail.PreAuthorizedAmount, totalFeeAmount, totalFeeAmount, 0, paymentDetail.TransactionId); message = paymentProviderServiceResponse.Message; } else { // void preauth if it exists _paymentService.VoidPreAuthorization(null, orderId); paymentProviderServiceResponse.IsSuccessful = true; } } if (paymentProviderServiceResponse.IsSuccessful) { // Payment completed var fareObject = FareHelper.GetFareFromAmountInclTax(Convert.ToDouble(totalFeeAmount), _serverSettings.ServerData.VATIsEnabled ? _serverSettings.ServerData.VATPercentage : 0); _commandBus.Send(new CaptureCreditCardPayment { AccountId = account.Id, PaymentId = paymentDetail.PaymentId, Provider = _paymentService.ProviderType(companyKey, orderDetail.Id), TotalAmount = totalFeeAmount, MeterAmount = Convert.ToDecimal(fareObject.AmountExclTax), TipAmount = Convert.ToDecimal(0), TaxAmount = Convert.ToDecimal(fareObject.TaxAmount), AuthorizationCode = paymentProviderServiceResponse.AuthorizationCode, TransactionId = paymentProviderServiceResponse.TransactionId, FeeType = feeType, BookingFees = bookingFees }); } else { // Void PreAuth because commit failed _paymentService.VoidPreAuthorization(null, orderId); // Payment error _commandBus.Send(new LogCreditCardError { PaymentId = paymentDetail.PaymentId, Reason = message }); if (paymentProviderServiceResponse.IsDeclined) { _commandBus.Send(new ReactToPaymentFailure { AccountId = account.Id, OrderId = orderId, IBSOrderId = orderDetail.IBSOrderId, CreditCardId = account.DefaultCreditCard.GetValueOrDefault(), OverdueAmount = totalFeeAmount, TransactionId = paymentProviderServiceResponse.TransactionId, TransactionDate = paymentProviderServiceResponse.TransactionDate, FeeType = feeType }); } } return(new CommitPreauthorizedPaymentResponse { AuthorizationCode = paymentProviderServiceResponse.AuthorizationCode, TransactionId = paymentProviderServiceResponse.TransactionId, IsSuccessful = paymentProviderServiceResponse.IsSuccessful, Message = paymentProviderServiceResponse.IsSuccessful ? "Success" : message }); } catch (Exception e) { _logger.LogMessage("Error during fee payment " + e); _logger.LogError(e); return(new CommitPreauthorizedPaymentResponse { IsSuccessful = false, TransactionId = paymentProviderServiceResponse.TransactionId, Message = e.Message }); } }
internal BasePaymentResponse CapturePaymentForPrepaidOrder( string companyKey, Guid orderId, AccountDetail account, decimal appEstimateWithTip, int tipPercentage, decimal bookingFees, string cvv) { // Note: No promotion on web var tipAmount = FareHelper.GetTipAmountFromTotalIncludingTip(appEstimateWithTip, tipPercentage); var totalAmount = appEstimateWithTip + bookingFees; var meterAmount = appEstimateWithTip - tipAmount; var preAuthResponse = _paymentService.PreAuthorize(companyKey, orderId, account, totalAmount, isForPrepaid: true, cvv: cvv); if (preAuthResponse.IsSuccessful) { // Wait for payment to be created Thread.Sleep(500); var commitResponse = _paymentService.CommitPayment( companyKey, orderId, account, totalAmount, totalAmount, meterAmount, tipAmount, preAuthResponse.TransactionId, preAuthResponse.ReAuthOrderId, isForPrepaid: true); if (commitResponse.IsSuccessful) { var paymentDetail = _orderPaymentDao.FindByOrderId(orderId, companyKey); var fareObject = FareHelper.GetFareFromAmountInclTax(meterAmount, _serverSettings.ServerData.VATIsEnabled ? _serverSettings.ServerData.VATPercentage : 0); _commandBus.Send(new CaptureCreditCardPayment { AccountId = account.Id, PaymentId = paymentDetail.PaymentId, Provider = _paymentService.ProviderType(companyKey, orderId), TotalAmount = totalAmount, MeterAmount = fareObject.AmountExclTax, TipAmount = tipAmount, TaxAmount = fareObject.TaxAmount, AuthorizationCode = commitResponse.AuthorizationCode, TransactionId = commitResponse.TransactionId, IsForPrepaidOrder = true, BookingFees = bookingFees }); } else { // Payment failed, void preauth _paymentService.VoidPreAuthorization(companyKey, orderId, true); return(new BasePaymentResponse { IsSuccessful = false, Message = commitResponse.Message }); } } else { return(new BasePaymentResponse { IsSuccessful = false, Message = preAuthResponse.Message }); } return(new BasePaymentResponse { IsSuccessful = true }); }
public object Post(TestEmailAdministrationRequest request) { try { switch (request.TemplateName) { case NotificationService.EmailConstant.Template.AccountConfirmation: _notificationService.SendAccountConfirmationEmail(new Uri("http://www.google.com"), request.EmailAddress, request.Language); break; case NotificationService.EmailConstant.Template.BookingConfirmation: _notificationService.SendBookingConfirmationEmail(12345, "This is a standard note", _pickupAddress, _dropOffAddress, DateTime.Now, _bookingSettings, request.EmailAddress, request.Language, true); break; case NotificationService.EmailConstant.Template.PasswordReset: _notificationService.SendPasswordResetEmail("N3wp@s5w0rd", request.EmailAddress, request.Language); break; case NotificationService.EmailConstant.Template.CancellationFeesReceipt: _notificationService.SendCancellationFeesReceiptEmail(1234, 24.42, "1111", request.EmailAddress, request.Language); break; case NotificationService.EmailConstant.Template.NoShowFeesReceipt: _notificationService.SendNoShowFeesReceiptEmail(1234, 10.00, _pickupAddress, "1111", request.EmailAddress, request.Language); break; case NotificationService.EmailConstant.Template.Receipt: var fareObject = _serverSettings.ServerData.VATIsEnabled ? FareHelper.GetFareFromAmountInclTax(45m, _serverSettings.ServerData.VATPercentage) : FareHelper.GetFareFromAmountInclTax(45m, 0); var toll = 3; var tip = (double)45 * ((double)15 / (double)100); var amountSavedByPromo = 10; var extra = 2; var surcharge = 5; var bookingFees = 7; var tipIncentive = 10; var driverInfos = new DriverInfos { DriverId = "7009", FirstName = "Alex", LastName = "Proteau", MobilePhone = "5551234567", VehicleColor = "Silver", VehicleMake = "DMC", VehicleModel = "Delorean", VehicleRegistration = "OUTATIME", VehicleType = "Time Machine" }; var fare = Convert.ToDouble(fareObject.AmountExclTax); var tax = Convert.ToDouble(fareObject.TaxAmount); _notificationService.SendTripReceiptEmail(Guid.NewGuid(), 12345, "9007", driverInfos, fare, toll, tip, tax, extra, surcharge, bookingFees, fare + toll + tip + tax + bookingFees + extra + tipIncentive - amountSavedByPromo, _payment, _pickupAddress, _dropOffAddress, DateTime.Now.AddMinutes(-15), DateTime.UtcNow, request.EmailAddress, request.Language, amountSavedByPromo, "PROMO10", new SendReceipt.CmtRideLinqReceiptFields { Distance = 13, DriverId = "D1337", DropOffDateTime = DateTime.Now, AccessFee = 0.3, LastFour = "1114", TripId = 9874, RateAtTripStart = 1, RateAtTripEnd = 4, FareAtAlternateRate = 23.45, LastLatitudeOfVehicle = 45.546571, LastLongitudeOfVehicle = -73.586309, Tolls = new[] { new TollDetail { TollName = "Toll 1", TollAmount = 95 }, new TollDetail { TollName = "Toll 2", TollAmount = 5 }, new TollDetail { TollName = "Toll 3", TollAmount = 30 }, new TollDetail { TollName = "Toll 4", TollAmount = 35 } }, TipIncentive = tipIncentive }, true); break; case NotificationService.EmailConstant.Template.PromotionUnlocked: _notificationService.SendPromotionUnlockedEmail("10% Off your next ride", "PROMO123", DateTime.Now.AddMonths(1), request.EmailAddress, request.Language, true); break; case NotificationService.EmailConstant.Template.CreditCardDeactivated: _notificationService.SendCreditCardDeactivatedEmail("Visa", "1234", request.EmailAddress, request.Language, true); break; default: throw new Exception("sendTestEmailErrorNoMatchingTemplate"); } } catch (Exception e) { _logger.LogError(e); throw new HttpError(HttpStatusCode.InternalServerError, e.Message); } return(new HttpResult(HttpStatusCode.OK)); }
public void when_order_on_external_company_has_booking_fees_configured_with_cmt_and_card_is_declined() { // Prepare var creditCardId = Guid.NewGuid(); var accountId = Guid.NewGuid(); var orderId = Guid.NewGuid(); string companyKey = "ext"; var orderAmount = 100.85m; var bookingFees = 40.85m; using (var context = new BookingDbContext(DbName)) { context.RemoveAll <FeesDetail>(); context.SaveChanges(); context.Save(new AccountDetail { Id = accountId, CreationDate = DateTime.Now, IBSAccountId = 123, DefaultCreditCard = creditCardId }); context.Save(new AccountIbsDetail { CompanyKey = companyKey, AccountId = accountId, IBSAccountId = 123 }); context.Save(new CreditCardDetails { AccountId = accountId, CreditCardId = creditCardId, Token = "token" }); context.Save(new OrderDetail { Id = orderId, AccountId = accountId, PickupDate = DateTime.Now, CreatedDate = DateTime.Now, IBSOrderId = 12345, CompanyKey = companyKey, BookingFees = bookingFees }); context.Save(new OrderPairingDetail { OrderId = orderId }); context.Save(new FeesDetail { Market = null, Booking = bookingFees, Id = Guid.NewGuid() }); } var tip = FareHelper.CalculateTipAmount(orderAmount, ConfigurationManager.ServerData.DefaultTipPercentage); var ibsOrder = new IBSOrderInformation { Fare = Convert.ToDouble(orderAmount) }; var status = new OrderStatusDetail { OrderId = orderId, CompanyKey = companyKey, AccountId = accountId, IBSOrderId = 12345 }; ConfigurationManager.SetPaymentSettings(null, new ServerPaymentSettings { PaymentMode = PaymentMethod.Cmt }); ConfigurationManager.SetPaymentSettings(companyKey, new ServerPaymentSettings { PaymentMode = PaymentMethod.Cmt }); EnsurePreAuthForFeeWasCalled(status, bookingFees); EnsurePreAuthPaymentForTripWasCalled(status, orderAmount + tip); // Act Sut.Update(ibsOrder, status); // Wait for commands to be sent properly Thread.Sleep(5000); // Assert PaymentServiceMock.Verify(); Assert.AreEqual(3, Commands.Count); Assert.AreEqual(typeof(ReactToPaymentFailure), Commands.First().GetType()); Assert.AreEqual(typeof(ReactToPaymentFailure), Commands.Skip(1).First().GetType()); Assert.AreEqual(typeof(ChangeOrderStatus), Commands.Skip(2).First().GetType()); }
public void when_order_is_paired_and_received_fare_with_preauth_disabled_and_preauth_fails() { // Prepare var accountId = Guid.NewGuid(); var orderId = Guid.NewGuid(); string companyKey = null; var orderAmount = 100.55m; var creditCardId = Guid.NewGuid(); using (var context = new BookingDbContext(DbName)) { context.Save(new AccountDetail { Id = accountId, CreationDate = DateTime.Now, IBSAccountId = 123, DefaultCreditCard = creditCardId }); context.Save(new CreditCardDetails { AccountId = accountId, CreditCardId = creditCardId, Token = "token" }); context.Save(new OrderDetail { Id = orderId, AccountId = accountId, PickupDate = DateTime.Now, CreatedDate = DateTime.Now, IBSOrderId = 12345, CompanyKey = companyKey }); context.Save(new OrderPairingDetail { OrderId = orderId }); } var tip = FareHelper.CalculateTipAmount(orderAmount, ConfigurationManager.ServerData.DefaultTipPercentage); var ibsOrder = new IBSOrderInformation { Fare = Convert.ToDouble(orderAmount) }; var status = new OrderStatusDetail { OrderId = orderId, CompanyKey = companyKey, AccountId = accountId, IBSOrderId = 12345 }; ConfigurationManager.SetPaymentSettings(null, new ServerPaymentSettings { PaymentMode = PaymentMethod.Braintree }); EnsurePreAuthPaymentForTripWasCalled(status, orderAmount + tip); // Act Sut.Update(ibsOrder, status); // Assert PaymentServiceMock.Verify(); Assert.AreEqual(1, Commands.Count); Assert.AreEqual(typeof(ChangeOrderStatus), Commands.First().GetType()); }
public object Post(SendReceiptAdmin request) { var order = _orderDao.FindById(request.OrderId); if (order == null || !(order.IsManualRideLinq || order.IBSOrderId.HasValue)) { throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.OrderNotInIbs.ToString()); } AccountDetail account; // if the admin is requesting the receipt then it won't be for the logged in user if (!request.RecipientEmail.IsNullOrEmpty()) { account = _accountDao.FindById(order.AccountId); } else { account = _accountDao.FindById(new Guid(this.GetSession().UserAuthId)); if (account.Id != order.AccountId) { throw new HttpError(HttpStatusCode.Unauthorized, "Not your order"); } } // If the order was created in another company, need to fetch the correct IBS account var ibsAccountId = _accountDao.GetIbsAccountId(account.Id, order.CompanyKey); if (!(ibsAccountId.HasValue || order.IsManualRideLinq)) { throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.IBSAccountNotFound.ToString()); } var ibsOrder = !order.IsManualRideLinq ? _ibsServiceProvider.Booking(order.CompanyKey).GetOrderDetails(order.IBSOrderId.Value, ibsAccountId.Value, order.Settings.Phone) : null; var orderPayment = _orderPaymentDao.FindByOrderId(order.Id, order.CompanyKey); var pairingInfo = _orderDao.FindOrderPairingById(order.Id); var orderStatus = _orderDao.FindOrderStatusById(request.OrderId); double?fareAmount; double?tollAmount = null; double?tipAmount; double?taxAmount; double?surcharge; double?bookingFees = null; double?extraAmount = null; PromotionUsageDetail promotionUsed = null; ReadModel.CreditCardDetails creditCard = null; var ibsOrderId = orderStatus.IBSOrderId; Commands.SendReceipt.CmtRideLinqReceiptFields cmtRideLinqFields = null; if (orderPayment != null && orderPayment.IsCompleted) { fareAmount = Convert.ToDouble(orderPayment.Meter); tipAmount = Convert.ToDouble(orderPayment.Tip); taxAmount = Convert.ToDouble(orderPayment.Tax); surcharge = Convert.ToDouble(orderPayment.Surcharge); bookingFees = Convert.ToDouble(orderPayment.BookingFees); // promotion can only be used with in app payment promotionUsed = _promotionDao.FindByOrderId(request.OrderId); creditCard = orderPayment.CardToken.HasValue() ? _creditCardDao.FindByToken(orderPayment.CardToken) : null; } else if (order.IsManualRideLinq) { var manualRideLinqDetail = _orderDao.GetManualRideLinqById(order.Id); fareAmount = manualRideLinqDetail.Fare; ibsOrderId = manualRideLinqDetail.TripId; tollAmount = manualRideLinqDetail.Toll; extraAmount = manualRideLinqDetail.Extra; tipAmount = manualRideLinqDetail.Tip; taxAmount = manualRideLinqDetail.Tax; surcharge = manualRideLinqDetail.Surcharge; orderStatus.DriverInfos.DriverId = manualRideLinqDetail.DriverId.ToString(); order.DropOffAddress = _geocoding.TryToGetExactDropOffAddress(orderStatus, manualRideLinqDetail.LastLatitudeOfVehicle, manualRideLinqDetail.LastLongitudeOfVehicle, order.DropOffAddress, order.ClientLanguageCode); cmtRideLinqFields = new Commands.SendReceipt.CmtRideLinqReceiptFields { TripId = manualRideLinqDetail.TripId, DriverId = manualRideLinqDetail.DriverId.ToString(), Distance = manualRideLinqDetail.Distance, AccessFee = manualRideLinqDetail.AccessFee, PickUpDateTime = manualRideLinqDetail.StartTime, DropOffDateTime = manualRideLinqDetail.EndTime, LastFour = manualRideLinqDetail.LastFour, FareAtAlternateRate = manualRideLinqDetail.FareAtAlternateRate, RateAtTripEnd = (int)(manualRideLinqDetail.RateAtTripEnd.GetValueOrDefault()), RateAtTripStart = (int)(manualRideLinqDetail.RateAtTripStart.GetValueOrDefault()), LastLatitudeOfVehicle = order.DropOffAddress.Latitude, LastLongitudeOfVehicle = order.DropOffAddress.Longitude, TipIncentive = order.TipIncentive ?? 0 }; } else if (pairingInfo != null && pairingInfo.AutoTipPercentage.HasValue) { var tripInfo = GetTripInfo(pairingInfo.PairingToken); if (tripInfo != null && !tripInfo.ErrorCode.HasValue && tripInfo.EndTime.HasValue) { // this is for CMT RideLinq only, no VAT fareAmount = Math.Round(((double)tripInfo.Fare / 100), 2); var tollHistory = tripInfo.TollHistory != null ? tripInfo.TollHistory.Sum(p => p.TollAmount) : 0; tollAmount = Math.Round(((double)tollHistory / 100), 2); extraAmount = Math.Round(((double)tripInfo.Extra / 100), 2); tipAmount = Math.Round(((double)tripInfo.Tip / 100), 2); taxAmount = Math.Round(((double)tripInfo.Tax / 100), 2); surcharge = Math.Round(((double)tripInfo.Surcharge / 100), 2); orderStatus.DriverInfos.DriverId = tripInfo.DriverId.ToString(); cmtRideLinqFields = new Commands.SendReceipt.CmtRideLinqReceiptFields { TripId = tripInfo.TripId, DriverId = tripInfo.DriverId.ToString(), Distance = tripInfo.Distance, AccessFee = Math.Round(((double)tripInfo.AccessFee / 100), 2), PickUpDateTime = tripInfo.StartTime, DropOffDateTime = tripInfo.EndTime, LastFour = tripInfo.LastFour, FareAtAlternateRate = Math.Round(((double)tripInfo.FareAtAlternateRate / 100), 2), RateAtTripEnd = tripInfo.RateAtTripEnd, RateAtTripStart = tripInfo.RateAtTripStart, Tolls = tripInfo.TollHistory, TipIncentive = (order.TipIncentive.HasValue) ? order.TipIncentive.Value : 0 }; } else { fareAmount = ibsOrder.Fare; tollAmount = ibsOrder.Toll; tipAmount = FareHelper.CalculateTipAmount(ibsOrder.Fare.GetValueOrDefault(0), pairingInfo.AutoTipPercentage.Value); taxAmount = ibsOrder.VAT; surcharge = order.Surcharge; } orderPayment = null; creditCard = pairingInfo.TokenOfCardToBeUsedForPayment.HasValue() ? _creditCardDao.FindByToken(pairingInfo.TokenOfCardToBeUsedForPayment) : null; } else { fareAmount = ibsOrder.Fare; tollAmount = ibsOrder.Toll; tipAmount = ibsOrder.Tip; taxAmount = ibsOrder.VAT; surcharge = order.Surcharge; orderPayment = null; } var orderReport = _reportDao.GetOrderReportWithOrderId(order.Id); var sendReceiptCommand = SendReceiptCommandBuilder.GetSendReceiptCommand( order, account, ibsOrderId, (orderReport != null ? orderReport.VehicleInfos.Number : ibsOrder.VehicleNumber), orderStatus.DriverInfos, fareAmount, tollAmount, extraAmount, surcharge, bookingFees, tipAmount, taxAmount, orderPayment, promotionUsed != null ? Convert.ToDouble(promotionUsed.AmountSaved) : (double?)null, promotionUsed, creditCard, cmtRideLinqFields); // Since the user or an admin requested the receipt, we should bypass the normal notification settings. sendReceiptCommand.BypassNotificationSettings = true; if (!request.RecipientEmail.IsNullOrEmpty()) { sendReceiptCommand.EmailAddress = request.RecipientEmail; } _commandBus.Send(sendReceiptCommand); return(new HttpResult(HttpStatusCode.OK, "OK")); }