Exemple #1
0
        internal bool PreAuthorizePaymentMethod(
            string companyKey,
            Guid orderId,
            AccountDetail account,
            bool isFutureBooking,
            decimal?appEstimateWithTip,
            decimal bookingFees,
            string cvv = null)
        {
            if (!_serverSettings.GetPaymentSettings(companyKey).IsPreAuthEnabled || isFutureBooking)
            {
                // preauth will be done later, save the info temporarily
                if (_serverSettings.GetPaymentSettings().AskForCVVAtBooking)
                {
                    _commandBus.Send(new SaveTemporaryOrderPaymentInfo {
                        OrderId = orderId, Cvv = cvv
                    });
                }

                return(true);
            }

            // there's a minimum amount of $50 (warning indicating that on the admin ui)
            // if app returned an estimate, use it, otherwise use the setting (or 0), then use max between the value and 50
            if (appEstimateWithTip.HasValue)
            {
                appEstimateWithTip = appEstimateWithTip.Value + bookingFees;
            }

            var preAuthAmount = Math.Max(appEstimateWithTip ?? (_serverSettings.GetPaymentSettings(companyKey).PreAuthAmount ?? 0), 50);

            var preAuthResponse = _paymentService.PreAuthorize(companyKey, orderId, account, preAuthAmount, cvv: cvv);

            return(preAuthResponse.IsSuccessful);
        }
        public void Handle(OrderStatusChanged @event)
        {
            if (@event.IsCompleted)
            {
                var order       = _orderDao.FindById(@event.SourceId);
                var orderStatus = _orderDao.FindOrderStatusById(@event.SourceId);
                var pairingInfo = _orderDao.FindOrderPairingById(@event.SourceId);
                var account     = _accountDao.FindById(order.AccountId);

                if (_serverSettings.GetPaymentSettings(order.CompanyKey).PaymentMode == PaymentMethod.RideLinqCmt)
                {
                    // Check if card declined
                    InitializeCmtServiceClient();

                    if (CmtErrorCodes.IsTerminalError(orderStatus.PairingError))
                    {
                        // Terminal error, no need to react to paymentFailure.
                        return;
                    }
                    var trip = _cmtTripInfoServiceHelper.CheckForTripEndErrors(pairingInfo.PairingToken);

                    if (trip != null && trip.ErrorCode == CmtErrorCodes.CardDeclined)
                    {
                        _commandBus.Send(new ReactToPaymentFailure
                        {
                            AccountId       = order.AccountId,
                            OrderId         = order.Id,
                            IBSOrderId      = order.IBSOrderId,
                            CreditCardId    = account.DefaultCreditCard.GetValueOrDefault(),
                            TransactionId   = orderStatus.OrderId.ToString().Split('-').FirstOrDefault(), // Use first part of GUID to display to user
                            OverdueAmount   = Convert.ToDecimal(@event.Fare + @event.Tax + @event.Tip + @event.Toll),
                            TransactionDate = @event.EventDate
                        });

                        return;
                    }

                    // Since RideLinqCmt payment is processed automatically by CMT, we have to charge booking fees separately
                    _feeService.ChargeBookingFeesIfNecessary(orderStatus);
                }

                // If the user has decided not to pair (paying the ride in car instead),
                // we have to void the amount that was preauthorized
                if (_serverSettings.GetPaymentSettings(order.CompanyKey).PaymentMode != PaymentMethod.RideLinqCmt &&
                    (order.Settings.ChargeTypeId == ChargeTypes.CardOnFile.Id || order.Settings.ChargeTypeId == ChargeTypes.PayPal.Id) &&
                    (pairingInfo == null || pairingInfo.WasUnpaired) &&
                    !orderStatus.IsPrepaid)    //prepaid order will never have a pairing info
                {
                    // void the preauthorization to prevent misuse fees
                    _paymentService.VoidPreAuthorization(order.CompanyKey, @event.SourceId);
                }
            }
        }
 public void Handle(CreditCardDeactivated @event)
 {
     using (var context = _contextFactory.Invoke())
     {
         if (_serverSettings.GetPaymentSettings().IsPaymentOutOfAppDisabled == OutOfAppPaymentDisabled.None)
         {
             // If pay in taxi is not disable, this becomes the default payment method
             var account = context.Find <AccountDetail>(@event.SourceId);
             account.Settings.ChargeTypeId = ChargeTypes.PaymentInCar.Id;
             context.Save(account);
         }
     }
 }
Exemple #4
0
        public void Post(UpdateServerPaymentSettingsRequest request)
        {
            if (request.ServerPaymentSettings.IsPayInTaxiEnabled &&
                request.ServerPaymentSettings.PaymentMode == PaymentMethod.None)
            {
                throw new ArgumentException("Please Select a payment setting");
            }

            _taxiHailNetworkServiceClient.UpdatePaymentSettings(_serverSettings.ServerData.TaxiHail.ApplicationKey,
                                                                new CompanyPaymentSettings
            {
                PaymentMode = request.ServerPaymentSettings.PaymentMode,
                BraintreePaymentSettings = new BraintreePaymentSettings
                {
                    ClientKey  = request.ServerPaymentSettings.BraintreeClientSettings.ClientKey,
                    IsSandbox  = request.ServerPaymentSettings.BraintreeServerSettings.IsSandbox,
                    MerchantId = request.ServerPaymentSettings.BraintreeServerSettings.MerchantId,
                    PrivateKey = request.ServerPaymentSettings.BraintreeServerSettings.PrivateKey,
                    PublicKey  = request.ServerPaymentSettings.BraintreeServerSettings.PublicKey
                },
                MonerisPaymentSettings = request.ServerPaymentSettings.MonerisPaymentSettings,
                CmtPaymentSettings     = request.ServerPaymentSettings.CmtPaymentSettings
            })
            .HandleErrors();

            SaveConfigurationChanges(request.ServerPaymentSettings, _serverSettings.GetPaymentSettings());

            _commandBus.Send(new UpdatePaymentSettings {
                ServerPaymentSettings = request.ServerPaymentSettings
            });
        }
        private Trip GetTripInfo(string pairingToken)
        {
            var cmtMobileServiceClient   = new CmtMobileServiceClient(_serverSettings.GetPaymentSettings().CmtPaymentSettings, null, null, null);
            var cmtTripInfoServiceHelper = new CmtTripInfoServiceHelper(cmtMobileServiceClient, _logger);

            return(cmtTripInfoServiceHelper.GetTripInfo(pairingToken));
        }
Exemple #6
0
        public object Post(UpdateAutoTipRequest request)
        {
            var orderPairing = _orderDao.FindOrderPairingById(request.OrderId);

            if (orderPairing == null)
            {
                return(new HttpResult(HttpStatusCode.NotFound));
            }

            var order = _orderDao.FindById(request.OrderId);

            var paymentSettings = _serverSettings.GetPaymentSettings(order.CompanyKey);

            if (paymentSettings.PaymentMode == PaymentMethod.RideLinqCmt)
            {
                var result = _paymentService.UpdateAutoTip(order.CompanyKey, request.OrderId, request.AutoTipPercentage);
                if (!result.IsSuccessful)
                {
                    return(new HttpResult(HttpStatusCode.InternalServerError, result.Message));
                }
            }

            _commandBus.Send(new UpdateAutoTip
            {
                OrderId           = request.OrderId,
                AutoTipPercentage = request.AutoTipPercentage
            });

            return(new HttpResult(HttpStatusCode.OK));
        }
Exemple #7
0
        public ActionResult DeleteCreditCardsInfo(AccountManagementModel accountManagementModel)
        {
            var paymentSettings = _serverSettings.GetPaymentSettings();

            var forceUserDisconnect = paymentSettings.CreditCardIsMandatory &&
                                      (paymentSettings.IsPaymentOutOfAppDisabled != OutOfAppPaymentDisabled.None);

            _commandBus.Send(new DeleteCreditCardsFromAccounts
            {
                AccountIds          = new[] { accountManagementModel.Id },
                ForceUserDisconnect = forceUserDisconnect
            });

            TempData["UserMessage"] = "Operation done successfully";

            // needed to feed orders list
            accountManagementModel.OrdersPaged = GetOrders(accountManagementModel.Id, accountManagementModel.OrdersPageIndex, accountManagementModel.OrdersPageSize);

            return(View("Index", accountManagementModel));
        }
        public void Handle(PaymentModeChanged @event)
        {
            var paymentSettings = _serverSettings.GetPaymentSettings();

            var forceUserDisconnect = paymentSettings.CreditCardIsMandatory &&
                                      paymentSettings.IsPaymentOutOfAppDisabled != OutOfAppPaymentDisabled.None;

            _commandBus.Send(new DeleteCreditCardsFromAccounts
            {
                AccountIds          = _accountDao.GetAll().Select(a => a.Id).ToArray(),
                ForceUserDisconnect = forceUserDisconnect
            });
        }
Exemple #9
0
        public void Handle(OrderPairedForPayment @event)
        {
            try
            {
                using (var context = _contextFactory.Invoke())
                {
                    var existingPairing = context.Find <OrderPairingDetail>(@event.SourceId);
                    if (existingPairing != null)
                    {
                        _logger.LogMessage("Order Pairing already existing for Order : " + @event.SourceId);
                    }
                    else
                    {
                        context.Save(new OrderPairingDetail
                        {
                            OrderId      = @event.SourceId,
                            Medallion    = @event.Medallion,
                            DriverId     = @event.DriverId,
                            PairingToken = @event.PairingToken,
                            PairingCode  = @event.PairingCode,
                            TokenOfCardToBeUsedForPayment = @event.TokenOfCardToBeUsedForPayment,
                            AutoTipAmount     = @event.AutoTipAmount,
                            AutoTipPercentage = @event.AutoTipPercentage
                        });

                        var orderStatus = context.Find <OrderStatusDetail>(@event.SourceId);

                        var paymentSettings = _serverSettings.GetPaymentSettings(orderStatus.CompanyKey);
                        if (!paymentSettings.IsUnpairingDisabled)
                        {
                            // Unpair only available if automatic pairing is disabled
                            orderStatus.UnpairingTimeOut = paymentSettings.UnpairingTimeOut == 0
                                ? DateTime.UtcNow.AddHours(12)                                      // Unpair will be available for the duration of the ride (considering ride duration is less than 12 hours)
                                : @event.EventDate.AddSeconds(paymentSettings.UnpairingTimeOut);    // Unpair will be available until timeout reached

                            context.Save(orderStatus);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
                throw;
            }
        }
 private void AddCvvInfo(ResPreauthCC preAuthorizeCommand, string cvv)
 {
     if (_serverSettings.GetPaymentSettings().AskForCVVAtBooking)
     {
         if (!cvv.HasValue())
         {
             _logger.LogMessage("AskForCVVAtBooking setting is enabled but no cvv found for this order, could be from a reauth");
         }
         else
         {
             // Only supported for Visa/MasterCard/Amex
             var cvdCheck = new CvdInfo();
             cvdCheck.SetCvdIndicator("1");
             cvdCheck.SetCvdValue(cvv);
             preAuthorizeCommand.SetCvdInfo(cvdCheck);
         }
     }
 }
Exemple #11
0
 private void AddCvvInfo(TransactionRequest transactionRequest, string cvv)
 {
     if (_serverSettings.GetPaymentSettings().AskForCVVAtBooking)
     {
         if (!cvv.HasValue())
         {
             _logger.LogMessage("AskForCVVAtBooking setting is enabled but no cvv found for this order, could be from a reauth");
         }
         else
         {
             // we pass the cvv to Braintree, but if no cvv rules are configured on the
             // Braintree Gateway of the client, the cvv will not cause a preauth failure
             transactionRequest.CreditCard = new TransactionCreditCardRequest
             {
                 CVV = cvv
             };
         }
     }
 }
Exemple #12
0
        internal bool FetchCompanyPaymentSettings(string companyKey)
        {
            try
            {
                var paymentSettings        = _serverSettings.GetPaymentSettings();
                var companyPaymentSettings = _taxiHailNetworkServiceClient.GetPaymentSettings(companyKey);

                // Mobile will always keep local settings. The only values that needs to be overridden are the payment providers settings.
                paymentSettings.Id                      = Guid.NewGuid();
                paymentSettings.CompanyKey              = companyKey;
                paymentSettings.PaymentMode             = companyPaymentSettings.PaymentMode;
                paymentSettings.BraintreeServerSettings = new BraintreeServerSettings
                {
                    IsSandbox  = companyPaymentSettings.BraintreePaymentSettings.IsSandbox,
                    MerchantId = companyPaymentSettings.BraintreePaymentSettings.MerchantId,
                    PrivateKey = companyPaymentSettings.BraintreePaymentSettings.PrivateKey,
                    PublicKey  = companyPaymentSettings.BraintreePaymentSettings.PublicKey
                };
                paymentSettings.BraintreeClientSettings = new BraintreeClientSettings
                {
                    ClientKey = companyPaymentSettings.BraintreePaymentSettings.ClientKey
                };
                paymentSettings.MonerisPaymentSettings = companyPaymentSettings.MonerisPaymentSettings;
                paymentSettings.CmtPaymentSettings     = companyPaymentSettings.CmtPaymentSettings;

                // Save/update company settings
                _commandBus.Send(new UpdatePaymentSettings
                {
                    ServerPaymentSettings = paymentSettings
                });

                return(companyPaymentSettings.PaymentMode == PaymentMethod.Cmt ||
                       companyPaymentSettings.PaymentMode == PaymentMethod.RideLinqCmt);
            }
            catch (Exception ex)
            {
                _logger.LogMessage(string.Format("An error occurred when trying to get PaymentSettings for company {0}", companyKey));
                _logger.LogError(ex);

                return(false);
            }
        }
Exemple #13
0
        public object Delete(DeleteCreditCardsWithAccountRequest request)
        {
            if (_dao.FindByAccountId(request.AccountID).Count > 0)
            {
                var paymentSettings = _serverSettings.GetPaymentSettings();

                var forceUserDisconnect = paymentSettings.CreditCardIsMandatory &&
                                          paymentSettings.IsPaymentOutOfAppDisabled != OutOfAppPaymentDisabled.None;

                _commandBus.Send(new DeleteCreditCardsFromAccounts
                {
                    AccountIds          = new[] { request.AccountID },
                    ForceUserDisconnect = forceUserDisconnect
                });

                return(new HttpResult(HttpStatusCode.OK));
            }

            return(new HttpError("Cannot find the credit card"));
        }
Exemple #14
0
        public CompanyMarketSettingsResponse GetCompanyMarketSettings(double latitude, double longitude)
        {
            CompanyMarketSettingsResponse response;

            if (_serverSettings.ServerData.Network.Enabled)
            {
                var homeCompanyKey = _serverSettings.ServerData.TaxiHail.ApplicationKey;

                var @params = new Dictionary <string, string>
                {
                    { "companyId", homeCompanyKey },
                    { "latitude", latitude.ToString(CultureInfo.InvariantCulture) },
                    { "longitude", longitude.ToString(CultureInfo.InvariantCulture) }
                };

                var queryString = BuildQueryString(@params);

                response = Client.Get("customer/roaming/marketsettings" + queryString)
                           .Deserialize <CompanyMarketSettingsResponse>()
                           .Result;
            }
            else
            {
                response = new CompanyMarketSettingsResponse();
            }

            response.EnableFutureBooking = !response.Market.HasValue()
                ? !_serverSettings.ServerData.DisableFutureBooking
                : response.EnableFutureBooking;

            response.DisableOutOfAppPayment = !response.Market.HasValue()
                ? _serverSettings.GetPaymentSettings().CancelOrderOnUnpair
                : response.DisableOutOfAppPayment;

            response.ShowCallDriver = !response.Market.HasValue()
                ? _serverSettings.ServerData.ShowCallDriver
                : response.ShowCallDriver;

            return(response);
        }
        // GET: AdminTH/PromoCode
        public ActionResult Index()
        {
            var paymentSettings = _serverSettings.GetPaymentSettings();

            if (paymentSettings.PaymentMode == PaymentMethod.None)
            {
                TempData["Warning"] = "No payment Method has been configured. For users to be able to use promo codes, " +
                                      "go to the Payment Settings section and configure a Payment method.";
            }

            var updatedModel = TempData["Model"];

            if (updatedModel != null)
            {
                return(View(updatedModel));
            }
            else
            {
                var promotions = _promotionDao.GetAll().Select(x => new PromoCodeModel(x));
                return(View(promotions));
            }
        }
        public ManualRidelinqOrderService(
            ICommandBus commandBus,
            IOrderDao orderDao,
            IAccountDao accountDao,
            ICreditCardDao creditCardDao,
            IServerSettings serverSettings,
            ILogger logger,
            INotificationService notificationService)
        {
            _commandBus          = commandBus;
            _orderDao            = orderDao;
            _accountDao          = accountDao;
            _creditCardDao       = creditCardDao;
            _serverSettings      = serverSettings;
            _logger              = logger;
            _notificationService = notificationService;

            // Since CMT will handle the payment on their ends. We do not need to know the actual company of the cab from wich we do the manual pairing.
            _cmtMobileServiceClient   = new CmtMobileServiceClient(_serverSettings.GetPaymentSettings().CmtPaymentSettings, null, null, null);
            _cmtTripInfoServiceHelper = new CmtTripInfoServiceHelper(_cmtMobileServiceClient, logger);

            _resources = new Resources.Resources(_serverSettings);
        }
 public BraintreeClientPaymentService(IServerSettings serverSettings)
 {
     BraintreeGateway = GetBraintreeGateway(serverSettings.GetPaymentSettings().BraintreeServerSettings);
 }
        public object Put(AccountUpdateRequest accountUpdateRequest)
        {
            Guid accountId = accountUpdateRequest.AccountId;
            var  request   = accountUpdateRequest.BookingSettingsRequest;

            AccountDetail existingEmailAccountDetail = _accountDao.FindByEmail(request.Email);
            AccountDetail currentAccountDetail       = _accountDao.FindById(accountId);

            if (currentAccountDetail.Email != request.Email && currentAccountDetail.FacebookId.HasValue())
            {
                throw new HttpError(HttpStatusCode.BadRequest, _resources.Get("EmailChangeWithFacebookAccountErrorMessage"));
            }

            if (existingEmailAccountDetail != null && existingEmailAccountDetail.Email == request.Email && existingEmailAccountDetail.Id != accountId)
            {
                throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.EmailAlreadyUsed.ToString(), _resources.Get("EmailUsedMessage"));
            }

            CountryCode countryCode = CountryCode.GetCountryCodeByIndex(CountryCode.GetCountryCodeIndexByCountryISOCode(request.Country));

            if (PhoneHelper.IsPossibleNumber(countryCode, request.Phone))
            {
                request.Phone = PhoneHelper.GetDigitsFromPhoneNumber(request.Phone);
            }
            else
            {
                throw new HttpError(string.Format(_resources.Get("PhoneNumberFormat"), countryCode.GetPhoneExample()));
            }

            var isChargeAccountEnabled = _serverSettings.GetPaymentSettings().IsChargeAccountPaymentEnabled;

            // Validate account number if charge account is enabled and account number is set.
            if (isChargeAccountEnabled && !string.IsNullOrWhiteSpace(request.AccountNumber))
            {
                if (!request.CustomerNumber.HasValue())
                {
                    throw new HttpError(HttpStatusCode.Forbidden, ErrorCode.AccountCharge_InvalidAccountNumber.ToString());
                }

                // Validate locally that the account exists
                var account = _accountChargeDao.FindByAccountNumber(request.AccountNumber);
                if (account == null)
                {
                    throw new HttpError(HttpStatusCode.Forbidden, ErrorCode.AccountCharge_InvalidAccountNumber.ToString());
                }

                // Validate with IBS to make sure the account/customer is still active
                var ibsChargeAccount = _ibsServiceProvider.ChargeAccount().GetIbsAccount(request.AccountNumber, request.CustomerNumber);
                if (!ibsChargeAccount.IsValid())
                {
                    throw new HttpError(HttpStatusCode.Forbidden, ErrorCode.AccountCharge_InvalidAccountNumber.ToString());
                }
            }

            var command = new UpdateBookingSettings();

            Mapper.Map(request, command);

            command.AccountId = accountId;

            _commandBus.Send(command);

            return(new HttpResult(HttpStatusCode.OK));
        }
Exemple #19
0
        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);
        }
Exemple #20
0
 private ServerPaymentSettings GetPaymentSettings(string companyKey)
 {
     return(_serverSettings.GetPaymentSettings(companyKey));
 }
Exemple #21
0
        private async Task <ServiceStatus> GetServiceStatus()
        {
            // Setup tests variable
            var useGeo = _serverSettings.ServerData.LocalAvailableVehiclesMode == LocalAvailableVehiclesModes.Geo ||
                         _serverSettings.ServerData.ExternalAvailableVehiclesMode == ExternalAvailableVehiclesModes.Geo;

            var useHoneyBadger = _serverSettings.ServerData.LocalAvailableVehiclesMode == LocalAvailableVehiclesModes.HoneyBadger ||
                                 _serverSettings.ServerData.ExternalAvailableVehiclesMode == ExternalAvailableVehiclesModes.HoneyBadger;

            var paymentSettings = _serverSettings.GetPaymentSettings();

            var useCmtPapi = paymentSettings.PaymentMode == PaymentMethod.Cmt ||
                             paymentSettings.PaymentMode == PaymentMethod.RideLinqCmt;

            // Setup tests
            var ibsTest = RunTest(() => Task.Run(() => _ibsProvider.Booking().GetOrdersStatus(new[] { 0 })), "IBS");

            var geoTest = useGeo
                ? RunTest(() => Task.Run(() => RunGeoTest()), "GEO")
                : Task.FromResult(false); // We do nothing here.

            var honeyBadger = useHoneyBadger
                ? RunTest(() => Task.Run(() => RunHoneyBadgerTest()), "HoneyBadger")
                : Task.FromResult(false); // We do nothing here.

            var orderStatusUpdateDetailTest = Task.Run(() => _statusUpdaterDao.GetLastUpdate());

            var sqlTest = RunTest(async() => await orderStatusUpdateDetailTest, "SQL");

            var mapiTest = paymentSettings.PaymentMode == PaymentMethod.RideLinqCmt
                ? RunTest(async() => await RunMapiTest(), "CMT MAPI")
                : Task.FromResult(false);

            var papiTest = useCmtPapi
                ? RunTest(() => Task.Run(() => RunPapiTest(paymentSettings.CmtPaymentSettings)), "CMT PAPI")
                : Task.FromResult(false);

            var customerPortalTest = RunTest(() => Task.Run(() => _networkService.GetCompanyMarketSettings(_serverSettings.ServerData.GeoLoc.DefaultLatitude, _serverSettings.ServerData.GeoLoc.DefaultLongitude)), "Customer Portal");

            // We use ConfigureAwait false here to ensure we are not deadlocking ourselves.
            await Task.WhenAll(ibsTest, geoTest, honeyBadger, sqlTest, mapiTest, papiTest, customerPortalTest).ConfigureAwait(false);

            var orderStatusUpdateDetails = orderStatusUpdateDetailTest.Result;

            var now = DateTime.UtcNow;

            var isUpdaterDeadlocked = orderStatusUpdateDetails.CycleStartDate.HasValue &&
                                      orderStatusUpdateDetails.CycleStartDate + TimeSpan.FromMinutes(10) < now;

            return(new ServiceStatus
            {
                IsIbsAvailable = ibsTest.Result,
                IbsUrl = _serverSettings.ServerData.IBS.WebServicesUrl,
                IsGeoAvailable = useGeo ? geoTest.Result : (bool?)null,
                GeoUrl = useGeo ? _serverSettings.ServerData.CmtGeo.ServiceUrl : null,
                IsHoneyBadgerAvailable = useHoneyBadger ? honeyBadger.Result : (bool?)null,
                HoneyBadgerUrl = _serverSettings.ServerData.HoneyBadger.ServiceUrl,
                IsSqlAvailable = sqlTest.Result,
                IsMapiAvailable = paymentSettings.PaymentMode == PaymentMethod.RideLinqCmt ? mapiTest.Result : (bool?)null,
                MapiUrl = paymentSettings.PaymentMode == PaymentMethod.RideLinqCmt ? GetMapiUrl() : null,
                IsPapiAvailable = useCmtPapi ? papiTest.Result : (bool?)null,
                PapiUrl = useCmtPapi ? GetPapiUrl() :null,
                IsCustomerPortalAvailable = customerPortalTest.Result,
                LastOrderUpdateDate = orderStatusUpdateDetails.LastUpdateDate,
                CycleStartDate = orderStatusUpdateDetails.CycleStartDate,
                LastOrderUpdateId = orderStatusUpdateDetails.Id.ToString(),
                LastOrderUpdateServer = orderStatusUpdateDetails.UpdaterUniqueId,
                IsUpdaterDeadlocked = isUpdaterDeadlocked
            });
        }
        private static void MigratePaymentSettings(IServerSettings serverSettings, ICommandBus commandBus, IDictionary <string, string> appSettings)
        {
            var paymentSettings            = serverSettings.GetPaymentSettings();
            var paymentSettingsNeedsUpdate = false;
            var serverSettingsNeedsUpdate  = false;

            if (paymentSettings.AutomaticPaymentPairing)
            {
                paymentSettings.IsUnpairingDisabled     = true;
                paymentSettings.AutomaticPaymentPairing = false;
                paymentSettingsNeedsUpdate = true;
            }

            if (paymentSettings.NoShowFee.HasValue)
            {
                var noShowFee = paymentSettings.NoShowFee.Value;
                commandBus.Send(new UpdateFees
                {
                    CompanyId = AppConstants.CompanyId,
                    Fees      = new List <Fees>
                    {
                        new Fees
                        {
                            NoShow = noShowFee
                        }
                    }
                });

                paymentSettings.NoShowFee  = null;
                paymentSettingsNeedsUpdate = true;
            }

            if (serverSettings.ServerData.UsePairingCodeWhenUsingRideLinqCmtPayment)
            {
                paymentSettings.CmtPaymentSettings.UsePairingCode        = true;
                appSettings["UsePairingCodeWhenUsingRideLinqCmtPayment"] = "false";
                paymentSettingsNeedsUpdate = true;
                serverSettingsNeedsUpdate  = true;
            }

            if (paymentSettings.CmtPaymentSettings.PairingMethod == RideLinqPairingMethod.NotSet)
            {
                paymentSettings.CmtPaymentSettings.PairingMethod = paymentSettings.CmtPaymentSettings.UsePairingCode
                    ? RideLinqPairingMethod.PairingCode
                    : RideLinqPairingMethod.VehicleMedallion;
                paymentSettingsNeedsUpdate = true;
            }

            if (paymentSettings.IsPaymentOutOfAppDisabled == OutOfAppPaymentDisabled.NotSet)
            {
                paymentSettings.IsPaymentOutOfAppDisabled = paymentSettings.IsOutOfAppPaymentDisabled
                    ? OutOfAppPaymentDisabled.All
                    : OutOfAppPaymentDisabled.None;
                paymentSettingsNeedsUpdate = true;
            }

            if (serverSettings.ServerData.CreditCardIsMandatory)
            {
                paymentSettings.CreditCardIsMandatory = true;
                appSettings["CreditCardIsMandatory"]  = "false";
                paymentSettingsNeedsUpdate            = true;
                serverSettingsNeedsUpdate             = true;
            }

            if (paymentSettingsNeedsUpdate)
            {
                commandBus.Send(new UpdatePaymentSettings
                {
                    CompanyId             = AppConstants.CompanyId,
                    ServerPaymentSettings = paymentSettings
                });
            }

            if (serverSettingsNeedsUpdate)
            {
                AddOrUpdateAppSettings(commandBus, appSettings);
            }
        }
Exemple #23
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);
            }
        }
Exemple #24
0
        private CmtTripInfoServiceHelper GetTripInfoServiceHelper(string companyKey)
        {
            var cmtMobileServiceClient = new CmtMobileServiceClient(_serverSettings.GetPaymentSettings(companyKey).CmtPaymentSettings, null, null, null);

            return(new CmtTripInfoServiceHelper(cmtMobileServiceClient, _logger));
        }
Exemple #25
0
        public async Task <ActionResult> Fees()
        {
            var fees            = _feesDao.GetAll();
            var feesPreferences = new MarketFeesModel();

            var localFees = fees.FirstOrDefault(f => !f.Market.HasValue());

            if (localFees == null)
            {
                // Create empty entry
                feesPreferences.Fees.Add("Local",
                                         new FeeStructure
                {
                    Booking      = 0.00m,
                    Cancellation = 0.00m,
                    NoShow       = 0.00m
                });
            }
            else
            {
                feesPreferences.Fees.Add("Local", localFees.SelectOrDefault(f =>
                                                                            new FeeStructure
                {
                    Booking      = f.Booking,
                    Cancellation = f.Cancellation,
                    NoShow       = f.NoShow
                }));
            }

            // Fetch only market fees for markets that are available to the company
            var roamingCompaniesPreferences = await _taxiHailNetworkService.GetRoamingCompanyPreferences(_serverSettings.ServerData.TaxiHail.ApplicationKey);

            if (roamingCompaniesPreferences != null)
            {
                foreach (var market in roamingCompaniesPreferences.Keys)
                {
                    var marketFee = fees.FirstOrDefault(f => f.Market == market);
                    if (marketFee == null)
                    {
                        // Create empty entry
                        feesPreferences.Fees.Add(market,
                                                 new FeeStructure
                        {
                            Booking      = 0.00m,
                            Cancellation = 0.00m,
                            NoShow       = 0.00m
                        });
                    }
                    else
                    {
                        feesPreferences.Fees.Add(market,
                                                 new FeeStructure
                        {
                            Booking      = marketFee.Booking,
                            Cancellation = marketFee.Cancellation,
                            NoShow       = marketFee.NoShow
                        });
                    }
                }
            }

            var paymentSettings = _serverSettings.GetPaymentSettings();

            if (paymentSettings.PaymentMode != PaymentMethod.Cmt &&
                paymentSettings.PaymentMode != PaymentMethod.RideLinqCmt)
            {
                TempData["Info"] = "Fees will only be processed if payment is configured for CMT or CMT RideLinQ";
            }

            return(View(feesPreferences));
        }
Exemple #26
0
        private void InitializeCmtServiceClient(string companyKey)
        {
            var cmtMobileServiceClient = new CmtMobileServiceClient(_serverSettings.GetPaymentSettings(companyKey).CmtPaymentSettings, null, null, null);

            _cmtTripInfoServiceHelper = new CmtTripInfoServiceHelper(cmtMobileServiceClient, _logger);
        }