public async void can_cancel_it()
        {
            var sut = new OrderServiceClient(BaseUrl, SessionId, new DummyPackageInfo(), null, null);
            await sut.CancelOrder(_orderId);

            OrderStatusDetail status = null;

            for (var i = 0; i < 10; i++)
            {
                status = await sut.GetOrderStatus(_orderId);

                if (string.IsNullOrEmpty(status.IBSStatusId))
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    break;
                }
            }

            Assert.NotNull(status);
            Assert.AreEqual(OrderStatus.Canceled, status.Status);
            Assert.AreEqual(VehicleStatuses.Common.CancelledDone, status.IBSStatusId);
        }
Esempio n. 2
0
        public void ChangeStatus(OrderStatusDetail status, double?fare, double?tip, double?toll, double?tax, double?surcharge)
        {
            if (status == null)
            {
                throw new InvalidOperationException();
            }

            if (_status == OrderStatus.Canceled)
            {
                // Order was cancelled, we might have a race condition where OrderStatusUpdater would overwrite
                // the cancel status and continue polling the order forever
                return;
            }

            if (status.Status != _status || status.IBSStatusId != _ibsStatus || _fare != fare)
            {
                Update(new OrderStatusChanged
                {
                    Status              = status,
                    Fare                = fare,
                    Tip                 = tip,
                    Toll                = toll,
                    Tax                 = tax,
                    Surcharge           = surcharge,
                    IsCompleted         = status.Status == OrderStatus.Completed,
                    PreviousIBSStatusId = _ibsStatus,
                });
            }
        }
Esempio n. 3
0
        public Address TryToGetExactDropOffAddress(OrderStatusDetail orderStatusDetail, double?manualRideLinqLastLatitudeOfVehicle, double?manualRideLinqLastLongitudeOfVehicle, Address dropOffAddress, string clientLanguageCode)
        {
            if ((orderStatusDetail == null ||
                 !orderStatusDetail.VehicleLatitude.HasValue ||
                 !orderStatusDetail.VehicleLongitude.HasValue) ||
                !manualRideLinqLastLatitudeOfVehicle.HasValue ||
                !manualRideLinqLastLongitudeOfVehicle.HasValue)
            {
                return(dropOffAddress);
            }

            double latitude;
            double longitude;

            if (manualRideLinqLastLatitudeOfVehicle.HasValue &&
                manualRideLinqLastLongitudeOfVehicle.HasValue)
            {
                latitude  = manualRideLinqLastLatitudeOfVehicle.Value;
                longitude = manualRideLinqLastLongitudeOfVehicle.Value;
            }
            else
            {
                latitude  = orderStatusDetail.VehicleLatitude.Value;
                longitude = orderStatusDetail.VehicleLongitude.Value;
            }

            // Find the exact dropoff address using the last vehicle position
            var exactDropOffAddress = Search(latitude, longitude, clientLanguageCode).FirstOrDefault();

            return(exactDropOffAddress ?? dropOffAddress);
        }
 public bool IsOrderCancellable(OrderStatusDetail status)
 {
     return(status.IBSStatusId == VehicleStatuses.Common.Assigned ||
            status.IBSStatusId == VehicleStatuses.Common.Waiting ||
            status.IBSStatusId == VehicleStatuses.Common.Arrived ||
            status.IBSStatusId == VehicleStatuses.Common.Scheduled ||
            !status.IBSStatusId.HasValue());
 }
Esempio n. 5
0
 protected void EnsureVoidPreAuthForFeeWasCalled(OrderStatusDetail status)
 {
     PaymentServiceMock
     .Setup(x => x.VoidPreAuthorization(
                It.Is <string>(o => o == null),
                It.Is <Guid>(o => o == status.OrderId),
                It.IsAny <bool>()))
     .Verifiable();
 }
Esempio n. 6
0
 private DateTime?GetChargeAmountsTimeoutIfNecessary(OrderStatusDetail details, DateTime eventDate)
 {
     if (details.IBSStatusId.SoftEqual(VehicleStatuses.Common.Unloaded) &&
         !details.ChargeAmountsTimeOut.HasValue)
     {
         // First timeout
         return(eventDate.AddSeconds(_serverSettings.ServerData.ChargeAmountsTimeOut));
     }
     return(details.ChargeAmountsTimeOut);
 }
Esempio n. 7
0
        public override void Update(IBSOrderInformation orderFromIbs, OrderStatusDetail orderStatusDetail)
        {
            //eHail Order
            Thread.Sleep(500);

            //Call Geo
            Thread.Sleep(500);

            //Process Geo
            Thread.Sleep(500);
        }
        public void when_ibs_fare_changed()
        {
            var status = new OrderStatusDetail
            {
                OrderId = _orderId
            };

            _sut.When(new ChangeOrderStatus
            {
                Status = status,
                Fare   = 12
            });

            var @event = _sut.ThenHasSingle <OrderStatusChanged>();

            Assert.AreEqual(12, @event.Fare);
        }
        public bool IsStatusCompleted(OrderStatusDetail status)
        {
            if (status.IsManualRideLinq)
            {
                return(status.Status == OrderStatus.Completed ||
                       status.Status == OrderStatus.Canceled);
            }

            return(status.IBSStatusId.IsNullOrEmpty() ||
                   status.IBSStatusId.SoftEqual(VehicleStatuses.Common.Cancelled) ||
                   status.IBSStatusId.SoftEqual(VehicleStatuses.Common.Done) ||
                   status.IBSStatusId.SoftEqual(VehicleStatuses.Common.NoShow) ||
                   status.IBSStatusId.SoftEqual(VehicleStatuses.Common.CancelledDone) ||
                   status.IBSStatusId.SoftEqual(VehicleStatuses.Common.MeterOffNotPayed) ||
                   (status.IBSStatusId.SoftEqual(VehicleStatuses.Unknown.None) && status.Status == OrderStatus.Canceled) ||
                   (status.IBSStatusId.SoftEqual(VehicleStatuses.Common.Timeout) && status.Status == OrderStatus.Canceled));
        }
Esempio n. 10
0
        private async Task <OrderRepresentation> GetOrderInfos(Guid pendingOrderId)
        {
            var order = await _accountService.GetHistoryOrderAsync(pendingOrderId);

            var orderStatus = new OrderStatusDetail
            {
                IBSOrderId           = order.IBSOrderId,
                IBSStatusDescription = this.Services().Localize["LoadingMessage"],
                IBSStatusId          = string.Empty,
                OrderId          = pendingOrderId,
                Status           = OrderStatus.Unknown,
                VehicleLatitude  = null,
                VehicleLongitude = null
            };

            return(new OrderRepresentation(order, orderStatus));
        }
Esempio n. 11
0
        protected void EnsurePreAuthPaymentForTripWasCalled(OrderStatusDetail status, decimal amount)
        {
            var isReAuth = false;

            PaymentServiceMock
            .Setup(x => x.PreAuthorize(
                       It.Is <string>(o => o == status.CompanyKey),
                       It.Is <Guid>(o => o == status.OrderId),
                       It.Is <AccountDetail>(o => o.Id == status.AccountId),
                       It.Is <decimal>(o => o == amount),
                       It.Is <bool>(o => o == isReAuth),
                       It.IsAny <bool>(),
                       It.IsAny <bool>(),
                       It.IsAny <string>()))
            .Returns <string, Guid, AccountDetail, decimal, bool, bool, bool, string>(PreAuth)
            .Verifiable();
        }
Esempio n. 12
0
 private DateTime?GetNetworkPairingTimeoutIfNecessary(OrderStatusDetail details, DateTime eventDate)
 {
     if (details.IBSStatusId.SoftEqual(VehicleStatuses.Common.Waiting) &&
         !details.NetworkPairingTimeout.HasValue &&
         _serverSettings.ServerData.Network.Enabled)
     {
         if (!details.CompanyKey.HasValue() ||
             (details.Market.HasValue() && !details.NextDispatchCompanyKey.HasValue()))
         {
             // First timeout
             return(eventDate.AddSeconds(_serverSettings.ServerData.Network.PrimaryOrderTimeout));
         }
         // Subsequent timeouts
         return(eventDate.AddSeconds(_serverSettings.ServerData.Network.SecondaryOrderTimeout));
     }
     return(null);
 }
Esempio n. 13
0
 protected void EnsureCommitForFeeWasCalled(OrderStatusDetail status, decimal feeAmount, decimal preAuthAmount)
 {
     PaymentServiceMock
     .Setup(x => x.CommitPayment(
                It.Is <string>(o => o == null),
                It.Is <Guid>(o => o == status.OrderId),
                It.Is <AccountDetail>(o => o.Id == status.AccountId),
                It.Is <decimal>(o => o == preAuthAmount),
                It.Is <decimal>(o => o == feeAmount),
                It.Is <decimal>(o => o == feeAmount),
                It.Is <decimal>(o => o == 0),
                It.IsAny <string>(),
                It.IsAny <string>(),
                It.IsAny <bool>(),
                It.IsAny <string>(),
                It.IsAny <string>()))
     .Returns <string, Guid, AccountDetail, decimal, decimal, decimal, decimal, string, string, bool, string, string>(Commit)
     .Verifiable();
 }
Esempio n. 14
0
        private void RaiseOrderStatusChanged(OrderStatus orderStatus)
        {
            var fakeOrderStatus = new OrderStatusDetail()
            {
                CompanyName = TaxiCompanyChanged,
                Status      = orderStatus,
                DriverInfos = new DriverInfos()
                {
                    VehicleColor = VehicleColor,
                }
            };

            _reportDetailGenerator.Handle(new OrderStatusChanged
            {
                Status      = fakeOrderStatus,
                SourceId    = _orderId,
                IsCompleted = (orderStatus == OrderStatus.Completed),
            });
        }
Esempio n. 15
0
 protected void EnsureCommitWasCalled(OrderStatusDetail status, decimal preauthAmount, decimal totalAmount, decimal meterAmount, decimal tipAmount)
 {
     PaymentServiceMock
     .Setup(x => x.CommitPayment(
                It.Is <string>(o => o == status.CompanyKey),
                It.Is <Guid>(o => o == status.OrderId),
                It.Is <AccountDetail>(o => o.Id == status.AccountId),
                It.Is <decimal>(o => o == preauthAmount),
                It.Is <decimal>(o => o == totalAmount),
                It.Is <decimal>(o => o == meterAmount),
                It.Is <decimal>(o => o == tipAmount),
                It.IsAny <string>(),
                It.IsAny <string>(),
                It.IsAny <bool>(),
                It.IsAny <string>(),
                It.IsAny <string>()))
     .Returns <string, Guid, AccountDetail, decimal, decimal, decimal, decimal, string, string, bool, string, string>(Commit)
     .Verifiable();
 }
        public void when_ibs_status_has_not_changed_then_no_event()
        {
            var status = new OrderStatusDetail
            {
                OrderId     = _orderId,
                IBSStatusId = Guid.NewGuid().ToString()
            };

            _sut.Given(new OrderStatusChanged
            {
                SourceId = _orderId,
                Status   = status
            });

            _sut.When(new ChangeOrderStatus
            {
                Status = status,
            });

            Assert.AreEqual(0, _sut.Events.Count);
        }
        public List <OrderStatusDetail> GetForOrder(string OrderThumbprint)
        {
            List <OrderStatusDetail> returnMe = new List <OrderStatusDetail>();

            using (SqlConnection connection = new SqlConnection(_dbConnection.ConnectionString))
            {
                using (SqlCommand sqlCommand = new SqlCommand
                {
                    Connection = connection,
                    CommandType = CommandType.Text,
                    CommandText = "SELECT * FROM OrderStatusDetails WHERE OrderThumbprint=@ORDERID"
                })
                {
                    sqlCommand.Parameters.AddWithValue("ORDERID", OrderThumbprint);
                    sqlCommand.Connection.Open();

                    SqlDataReader dbDataReader = sqlCommand.ExecuteReader();

                    if (dbDataReader.HasRows)
                    {
                        while (dbDataReader.Read())
                        {
                            OrderStatusDetail product = dataReaderToObject(dbDataReader);

                            if (product != null)
                            {
                                returnMe.Add(product);
                            }
                        }
                    }

                    sqlCommand.Connection.Close();
                }
            }

            return(returnMe);
        }
        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_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());
        }
Esempio n. 20
0
 public override void HandleManualRidelinqFlow(OrderStatusDetail orderStatusDetail)
 {
     Thread.Sleep(120);
 }
Esempio n. 21
0
        public void GotoBookingStatus(Order order, OrderStatusDetail orderStatusDetail)
        {
            CurrentViewState = HomeViewModelState.BookingStatus;

            BookingStatus.StartBookingStatus(order, orderStatusDetail);
        }
Esempio n. 22
0
        public decimal?ChargeCancellationFeeIfNecessary(OrderStatusDetail orderStatusDetail)
        {
            var paymentSettings = _serverSettings.GetPaymentSettings();

            if (orderStatusDetail.IsPrepaid ||
                (paymentSettings.PaymentMode != PaymentMethod.Cmt &&
                 paymentSettings.PaymentMode != PaymentMethod.RideLinqCmt))
            {
                return(null);
            }

            var wasOrderUnpaired = false;

            var pairingDetail = _orderDao.FindOrderPairingById(orderStatusDetail.OrderId);

            if (pairingDetail != null)
            {
                wasOrderUnpaired = pairingDetail.WasUnpaired;
            }

            var isPastNoFeeCancellationWindow = orderStatusDetail.TaxiAssignedDate.HasValue &&
                                                orderStatusDetail.TaxiAssignedDate.Value.AddSeconds(_serverSettings.ServerData.CancellationFeesWindow) < DateTime.UtcNow;

            var bookingFees     = _orderDao.FindById(orderStatusDetail.OrderId).BookingFees;
            var feesForMarket   = _feesDao.GetMarketFees(orderStatusDetail.Market);
            var cancellationFee = feesForMarket != null
                ? feesForMarket.Cancellation + bookingFees
                : 0;

            if (cancellationFee <= 0 || !isPastNoFeeCancellationWindow || wasOrderUnpaired)
            {
                // No cancellation fee for unpaired rides because the rider is either: already in the car (pay cash) or had his car hijacked
                return(null);
            }

            _logger.LogMessage("Cancellation fee of {0} will be charged for order {1}{2}.",
                               cancellationFee,
                               orderStatusDetail.IBSOrderId,
                               string.Format(orderStatusDetail.Market.HasValue()
                        ? "in market {0}"
                        : string.Empty,
                                             orderStatusDetail.Market));

            var account = _accountDao.FindById(orderStatusDetail.AccountId);

            if (!account.HasValidPaymentInformation)
            {
                _logger.LogMessage("Cancellation fee cannot be charged for order {0} because the user has no payment method configured.", orderStatusDetail.IBSOrderId);
                return(null);
            }

            try
            {
                // PreAuthorization
                var preAuthResponse = PreauthorizePaymentIfNecessary(orderStatusDetail.OrderId, cancellationFee, FeeTypes.Cancellation);
                if (preAuthResponse.IsSuccessful)
                {
                    // Commit
                    var paymentResult = CommitPayment(cancellationFee, bookingFees, orderStatusDetail.OrderId, FeeTypes.Cancellation);
                    if (paymentResult.IsSuccessful)
                    {
                        _logger.LogMessage("Cancellation fee of amount {0} was charged for order {1}.", cancellationFee, orderStatusDetail.IBSOrderId);
                        return(cancellationFee);
                    }
                    throw new Exception(paymentResult.Message);
                }
                throw new Exception(preAuthResponse.Message);
            }
            catch (Exception ex)
            {
                _logger.LogMessage("Could not process cancellation fee for order {0}: {1}.", orderStatusDetail.IBSOrderId, ex.Message);
                return(null);
            }
        }
Esempio n. 23
0
        private CmtPairingResponse PairWithVehicleUsingRideLinq(RideLinqPairingMethod pairingMethod, OrderStatusDetail orderStatusDetail, string cardToken, int autoTipPercentage)
        {
            InitializeServiceClient();

            try
            {
                var accountDetail    = _accountDao.FindById(orderStatusDetail.AccountId);
                var creditCardDetail = _creditCardDao.FindByToken(cardToken);
                var orderDetail      = _orderDao.FindById(orderStatusDetail.OrderId);

                // send pairing request
                var cmtPaymentSettings = _serverPaymentSettings.CmtPaymentSettings;
                var pairingRequest     = new ManualRideLinqCoFPairingRequest
                {
                    AutoTipPercentage   = autoTipPercentage,
                    AutoCompletePayment = true,
                    CallbackUrl         = string.Empty,
                    CustomerId          = orderStatusDetail.AccountId.ToString(),
                    CustomerName        = accountDetail.Name,
                    DriverId            = orderStatusDetail.DriverInfos.DriverId,
                    Latitude            = orderStatusDetail.VehicleLatitude.GetValueOrDefault(),
                    Longitude           = orderStatusDetail.VehicleLongitude.GetValueOrDefault(),
                    CardOnFileId        = cardToken,
                    Market            = cmtPaymentSettings.Market,
                    TripRequestNumber = orderStatusDetail.IBSOrderId.GetValueOrDefault().ToString(),
                    LastFour          = creditCardDetail.Last4Digits,
                    TipIncentive      = orderDetail.TipIncentive,
                    ZipCode           = creditCardDetail.ZipCode,
                    Email             = accountDetail.Email,
                    CustomerIpAddress = orderDetail.OriginatingIpAddress,
                    BillingFullName   = creditCardDetail.NameOnCard,
                    SessionId         = orderDetail.KountSessionId
                };

                switch (pairingMethod)
                {
                case RideLinqPairingMethod.VehicleMedallion:
                    _logger.LogMessage("OrderPairingManager RideLinq with VehicleMedallion : " + (orderStatusDetail.VehicleNumber.HasValue() ? orderStatusDetail.VehicleNumber : "No vehicle number"));
                    pairingRequest.Medallion = orderStatusDetail.VehicleNumber;
                    break;

                case RideLinqPairingMethod.PairingCode:
                    _logger.LogMessage("OrderPairingManager RideLinq with PairingCode : " + (orderStatusDetail.RideLinqPairingCode.HasValue() ? orderStatusDetail.RideLinqPairingCode : "No code"));
                    pairingRequest.PairingCode = orderStatusDetail.RideLinqPairingCode;
                    break;

                case RideLinqPairingMethod.DeviceName:
                    throw new Exception("RideLinq PairingMethod DeviceName not supported on non Arro Servers.  Since we do not do the dispatcher, we have no idea of the device name and can't pair using this.");

                default:
                    throw new Exception("CmtPaymentSetting.PairingMethod not set and trying to use RideLinq pairing.");
                }

                _logger.LogMessage("Pairing request : " + pairingRequest.ToJson());
                _logger.LogMessage("PaymentSettings request : " + cmtPaymentSettings.ToJson());

                var response = _cmtMobileServiceClient.Post(pairingRequest);

                _logger.LogMessage("Pairing response : " + response.ToJson());

                // Wait for trip to be updated to check if pairing was successful
                var trip = _cmtTripInfoServiceHelper.WaitForTripInfo(response.PairingToken, response.TimeoutSeconds);

                response.ErrorCode = trip != null ? trip.ErrorCode : CmtErrorCodes.UnableToPair;

                return(response);
            }
            catch (Exception ex)
            {
                var aggregateException = ex as AggregateException;
                if (aggregateException == null)
                {
                    throw;
                }

                var webServiceException = aggregateException.InnerException as WebServiceException;
                if (webServiceException == null)
                {
                    throw;
                }

                var response = JsonConvert.DeserializeObject <AuthorizationResponse>(webServiceException.ResponseBody);

                _logger.LogMessage(string.Format("Error when trying to pair using RideLinQ. Code: {0} - {1}"), response.ResponseCode, response.ResponseMessage);

                throw;
            }
        }
Esempio n. 24
0
        public decimal?ChargeNoShowFeeIfNecessary(OrderStatusDetail orderStatusDetail)
        {
            var paymentSettings = _serverSettings.GetPaymentSettings();

            if (orderStatusDetail.IsPrepaid ||
                (paymentSettings.PaymentMode != PaymentMethod.Cmt &&
                 paymentSettings.PaymentMode != PaymentMethod.RideLinqCmt))
            {
                // If order is prepaid, if the user prepaid and decided not to show up, the fee is his fare already charged
                return(null);
            }

            // As requested by MK, we need to charge booking fees on top of cancellation fees
            var bookingFees   = _orderDao.FindById(orderStatusDetail.OrderId).BookingFees;
            var feesForMarket = _feesDao.GetMarketFees(orderStatusDetail.Market);
            var noShowFee     = feesForMarket != null
                ? feesForMarket.NoShow + bookingFees
                : 0;

            if (noShowFee <= 0)
            {
                return(null);
            }

            _logger.LogMessage("No show fee of {0} will be charged for order {1}{2}.",
                               noShowFee,
                               orderStatusDetail.IBSOrderId,
                               string.Format(orderStatusDetail.Market.HasValue()
                        ? "in market {0}"
                        : string.Empty,
                                             orderStatusDetail.Market));

            var account = _accountDao.FindById(orderStatusDetail.AccountId);

            if (!account.HasValidPaymentInformation)
            {
                _logger.LogMessage("No show fee cannot be charged for order {0} because the user has no payment method configured.", orderStatusDetail.IBSOrderId);
                return(null);
            }

            try
            {
                // PreAuthorization
                var preAuthResponse = PreauthorizePaymentIfNecessary(orderStatusDetail.OrderId, noShowFee, FeeTypes.NoShow);
                if (preAuthResponse.IsSuccessful)
                {
                    // Commit
                    var paymentResult = CommitPayment(noShowFee, bookingFees, orderStatusDetail.OrderId, FeeTypes.NoShow);
                    if (paymentResult.IsSuccessful)
                    {
                        _logger.LogMessage("No show fee of amount {0} was charged for order {1}.", noShowFee, orderStatusDetail.IBSOrderId);
                        return(noShowFee);
                    }

                    throw new Exception(paymentResult.Message);
                }

                throw new Exception(preAuthResponse.Message);
            }
            catch (Exception ex)
            {
                _logger.LogMessage("Could not process no show fee for order {0}: {1}.", orderStatusDetail.IBSOrderId, ex.Message);
                return(null);
            }
        }
        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 CallboxOrderCreated(object sender, Order order, OrderStatusDetail orderStatus) : base(sender)
 {
     Order       = order;
     OrderStatus = orderStatus;
 }
Esempio n. 27
0
        public decimal?ChargeBookingFeesIfNecessary(OrderStatusDetail orderStatusDetail)
        {
            var paymentSettings = _serverSettings.GetPaymentSettings();

            if (orderStatusDetail.IsPrepaid ||
                orderStatusDetail.CompanyKey == null || // If booking is made on home company, booking fees will be included in same trip receipt
                (paymentSettings.PaymentMode != PaymentMethod.Cmt &&
                 paymentSettings.PaymentMode != PaymentMethod.RideLinqCmt))
            {
                return(null);
            }

            var feesForMarket = _feesDao.GetMarketFees(orderStatusDetail.Market);
            var bookingFees   = feesForMarket != null
                ? feesForMarket.Booking
                : 0;

            if (bookingFees <= 0)
            {
                return(null);
            }

            _logger.LogMessage("Booking fee of {0} will be charged for order {1}{2}.",
                               bookingFees,
                               orderStatusDetail.IBSOrderId,
                               string.Format(orderStatusDetail.Market.HasValue()
                        ? "in market {0}"
                        : string.Empty,
                                             orderStatusDetail.Market));

            var account = _accountDao.FindById(orderStatusDetail.AccountId);

            if (!account.HasValidPaymentInformation)
            {
                _logger.LogMessage("Booking fee cannot be charged for order {0} because the user has no payment method configured.", orderStatusDetail.IBSOrderId);
                return(null);
            }

            try
            {
                // PreAuthorization
                var preAuthResponse = PreauthorizePaymentIfNecessary(orderStatusDetail.OrderId, bookingFees, FeeTypes.Booking);
                if (preAuthResponse.IsSuccessful)
                {
                    // Commit
                    var paymentResult = CommitPayment(bookingFees, bookingFees, orderStatusDetail.OrderId, FeeTypes.Booking);
                    if (paymentResult.IsSuccessful)
                    {
                        _logger.LogMessage("No show fee of amount {0} was charged for order {1}.", bookingFees, orderStatusDetail.IBSOrderId);
                        return(bookingFees);
                    }

                    throw new Exception(paymentResult.Message);
                }

                throw new Exception(preAuthResponse.Message);
            }
            catch (Exception ex)
            {
                _logger.LogMessage("Could not process no show fee for order {0}: {1}.", orderStatusDetail.IBSOrderId, ex.Message);
                return(null);
            }
        }
Esempio n. 28
0
 public OrderRepresentation(Order order, OrderStatusDetail status)
 {
     Order       = order;
     OrderStatus = status;
 }
        public Order CreateOrder(IEnumerable <ShoppingCartItem> items, string BudgetAccountNumber, string SubmittedByName, string SubmittdByEmail, UserThumbprint userThumbprint, string customerNotes)
        {
            OrderStatusDetailRepository orderStatusDetailRepository = new OrderStatusDetailRepository(this._dbContext);
            OrderItemRepository         orderItemRepository         = new OrderItemRepository(this._dbContext);

            // We need to get a new OrderID or make one somehow
            // Hash the user thumbprint and the date and time together, and it should be fairly unique...

            List <OrderItem> newOrderItems = new List <OrderItem>();

            foreach (ShoppingCartItem scitem in items)
            {
                if (scitem.Quantity > 0)
                {
                    newOrderItems.Add(new OrderItem()
                    {
                        OrderThumbprint   = "WILL-GET-REPLACED",
                        Name              = scitem.Product.Name,
                        ItemBasePrice     = scitem.Product.BasePrice,
                        ItemGST           = scitem.Product.GSTAmount,
                        ItemPST           = scitem.Product.PSTAmount,
                        ItemEHF           = scitem.Product.RecyclingFee,
                        ItemPriceWithTax  = scitem.Product.TotalPrice,
                        TotalBasePrice    = (decimal)(scitem.Product.BasePrice * scitem.Quantity),
                        TotalEHF          = (decimal)(scitem.Product.RecyclingFee * scitem.Quantity),
                        TotalPST          = (decimal)(scitem.Product.PSTAmount * scitem.Quantity),
                        TotalGST          = (decimal)(scitem.Product.GSTAmount * scitem.Quantity),
                        TotalPriceWithTax = (decimal)(scitem.Product.TotalPrice * scitem.Quantity),
                        ProductId         = scitem.ProductId,
                        Quantity          = scitem.Quantity,
                    });
                }
            }

            OrderStatusDetail newOrderStatusDetail = new OrderStatusDetail()
            {
                OrderThumbprint = "WILL-GET-REPLACED",
                Status          = "Order Submitted",
                Timestamp       = DateTime.Now,
                UpdatedBy       = SubmittedByName,
                Notes           = string.Empty
            };


            Order newOrder = new Order()
            {
                OrderThumbprint      = "WILL-GET-REPLACED",
                UserThumbprint       = userThumbprint.Value,
                OrderDate            = DateTime.Now,
                CustomerFullName     = SubmittedByName,
                CustomerEmailAddress = SubmittdByEmail,
                BudgetAccountNumber  = BudgetAccountNumber,
                CustomerNotes        = customerNotes,
                StatusDetails        = new List <OrderStatusDetail>()
                {
                    newOrderStatusDetail
                },
                Items           = newOrderItems,
                OrderTotalItems = newOrderItems.Sum(x => x.Quantity),
                OrderSubTotal   = newOrderItems.Sum(x => x.TotalBasePrice),
                OrderGrandTotal = newOrderItems.Sum(x => x.TotalPriceWithTax),
                TotalEHF        = newOrderItems.Sum(x => x.TotalEHF),
                TotalGST        = newOrderItems.Sum(x => x.TotalGST),
                TotalPST        = newOrderItems.Sum(x => x.TotalPST)
            };

            string orderThumbprint = _orderRepository.Create(newOrder);

            // Update the order thumbprint for things that need it
            newOrder.OrderThumbprint = orderThumbprint;
            newOrder.StatusDetails.ForEach(x => x.OrderThumbprint = orderThumbprint);
            newOrder.Items.ForEach(x => x.OrderThumbprint         = orderThumbprint);

            orderItemRepository.Create(newOrder.Items);
            orderStatusDetailRepository.Create(newOrder.StatusDetails);

            return(newOrder);
        }