public void SendPaymentNotification(double totalAmount, double meterAmount, double tipAmount, string authorizationCode, string vehicleNumber, string companyKey) { if (companyKey.HasValue()) { _logger.LogMessage(string.Format("Sending payment notification on external company '{0}'", companyKey)); } var amountString = _resources.FormatPrice(totalAmount); var meterString = _resources.FormatPrice(meterAmount); var tipString = _resources.FormatPrice(tipAmount); // Padded with 32 char because the MDT displays line of 32 char. This will cause to write each string on a new line var line1 = string.Format(_resources.Get("PaymentConfirmationToDriver1")); line1 = line1.PadRight(32, ' '); var line2 = string.Format(_resources.Get("PaymentConfirmationToDriver2"), meterString, tipString); line2 = line2.PadRight(32, ' '); var line3 = string.Format(_resources.Get("PaymentConfirmationToDriver3"), amountString); line3 = line3.PadRight(32, ' '); var line4 = string.IsNullOrWhiteSpace(authorizationCode) ? string.Empty : string.Format(_resources.Get("PaymentConfirmationToDriver4"), authorizationCode); if (!_ibsServiceProvider.Booking(companyKey).SendMessageToDriver(line1 + line2 + line3 + line4, vehicleNumber)) { throw new Exception("Cannot send the payment notification."); } }
public bool SendOrderCreationCommands(Guid orderId, int?ibsOrderId, bool isPrepaid, string clientLanguageCode, bool switchedCompany = false, string newCompanyKey = null, string newCompanyName = null, string market = null) { if (!ibsOrderId.HasValue || ibsOrderId <= 0) { var code = !ibsOrderId.HasValue || (ibsOrderId.Value >= -1) ? string.Empty : "_" + Math.Abs(ibsOrderId.Value); var errorCode = "CreateOrder_CannotCreateInIbs" + code; var errorCommand = new CancelOrderBecauseOfError { OrderId = orderId, ErrorCode = errorCode, ErrorDescription = _resources.Get(errorCode, clientLanguageCode) }; _commandBus.Send(errorCommand); return(false); } else if (switchedCompany) { var orderDetail = _orderDao.FindById(orderId); // Cancel order on current company IBS _ibsCreateOrderService.CancelIbsOrder(orderDetail.IBSOrderId, orderDetail.CompanyKey, orderDetail.Settings.Phone, orderDetail.AccountId); _commandBus.Send(new SwitchOrderToNextDispatchCompany { OrderId = orderId, IBSOrderId = ibsOrderId.Value, CompanyKey = newCompanyKey, CompanyName = newCompanyName, Market = market }); return(true); } else { _logger.LogMessage(string.Format("Adding IBSOrderId {0} to order {1}", ibsOrderId, orderId)); var ibsCommand = new AddIbsOrderInfoToOrder { OrderId = orderId, IBSOrderId = ibsOrderId.Value }; _commandBus.Send(ibsCommand); return(true); } }
public void Unpair(Guid orderId) { var orderPairingDetail = _orderDao.FindOrderPairingById(orderId); if (orderPairingDetail == null) { throw new Exception("Order Pairing not found"); } var orderStatusDetail = _orderDao.FindOrderStatusById(orderId); if (orderStatusDetail == null) { throw new Exception("Order not found"); } // send a message to driver, if it fails we abort the unpairing _ibs.SendMessageToDriver(_resources.Get("UnpairingConfirmationToDriver"), orderStatusDetail.VehicleNumber, orderStatusDetail.CompanyKey); // send a command to delete the pairing pairing info for this order _commandBus.Send(new UnpairForPayment { OrderId = orderId }); }
private void UpdateIBSStatusDescription(Guid orderId, string language, string resourceName) { using (var context = _contextFactory.Invoke()) { var details = context.Find <OrderStatusDetail>(orderId); if (details != null) { details.IBSStatusDescription = _resources.Get(resourceName, language ?? SupportedLanguages.en.ToString()); context.Save(details); } } }
public void Handle(OrderCancelled @event) { using (var context = _contextFactory.Invoke()) { var order = context.Find <OrderDetail>(@event.SourceId); if (order != null) { order.Status = (int)OrderStatus.Canceled; context.Save(order); } var details = context.Find <OrderStatusDetail>(@event.SourceId); if (details != null) { details.Status = OrderStatus.Canceled; details.IBSStatusId = VehicleStatuses.Common.CancelledDone; details.IBSStatusDescription = _resources.Get("OrderStatus_wosCANCELLED", order != null ? order.ClientLanguageCode : "en"); context.Save(details); } RemoveTemporaryPaymentInfo(context, @event.SourceId); } }
public object Post(ConfirmHailRequest request) { if (request.OrderKey.IbsOrderId < 0) { throw new HttpError(string.Format("Cannot confirm hail because IBS returned error code {0}", request.OrderKey.IbsOrderId)); } if (request.VehicleCandidate == null) { throw new HttpError("You need to specify a vehicle in order to confirm the hail."); } var orderDetail = _orderDao.FindById(request.OrderKey.TaxiHailOrderId); if (orderDetail == null) { throw new HttpError(string.Format("Order {0} doesn't exist", request.OrderKey.TaxiHailOrderId)); } _logger.LogMessage(string.Format("Trying to confirm Hail. Request : {0}", request.ToJson())); var ibsOrderKey = Mapper.Map <IbsOrderKey>(request.OrderKey); var ibsVehicleCandidate = Mapper.Map <IbsVehicleCandidate>(request.VehicleCandidate); var confirmHailResult = _ibsServiceProvider.Booking(orderDetail.CompanyKey).ConfirmHail(ibsOrderKey, ibsVehicleCandidate); if (confirmHailResult == null || confirmHailResult < 0) { var errorMessage = string.Format("Error while trying to confirm the hail. IBS response code : {0}", confirmHailResult); _logger.LogMessage(errorMessage); return(new HttpResult(HttpStatusCode.InternalServerError, errorMessage)); } _logger.LogMessage("Hail request confirmed"); return(new OrderStatusDetail { OrderId = request.OrderKey.TaxiHailOrderId, Status = OrderStatus.Created, IBSStatusId = VehicleStatuses.Common.Assigned, IBSStatusDescription = string.Format( _resources.Get("OrderStatus_CabDriverNumberAssigned", orderDetail.ClientLanguageCode), request.VehicleCandidate.VehicleId) }); }
public virtual OrderStatusDetail GetOrderStatus(Guid orderId, IAuthSession session) { var order = _orderDao.FindById(orderId); if (order == null) { //Order could be null if creating the order takes a lot of time and this method is called before the create finishes return(new OrderStatusDetail { OrderId = orderId, Status = OrderStatus.Created, IBSOrderId = 0, IBSStatusId = "", IBSStatusDescription = _resources.Get("OrderStatus_wosWAITING"), }); } ThrowIfUnauthorized(order, session); var o = _orderDao.FindOrderStatusById(orderId); return(o); }
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)); }
protected CreateOrder BuildCreateOrderCommand(CreateOrderRequest request, AccountDetail account, CreateReportOrder createReportOrder) { _logger.LogMessage("Create order request : " + request); if (request.Settings.Country == null || !request.Settings.Country.Code.HasValueTrimmed()) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, string.Format(_resources.Get("PhoneNumberCountryNotProvided", request.ClientLanguageCode))); } var countryCode = CountryCode.GetCountryCodeByIndex(CountryCode.GetCountryCodeIndexByCountryISOCode(request.Settings.Country)); if (PhoneHelper.IsPossibleNumber(countryCode, request.Settings.Phone)) { request.Settings.Phone = PhoneHelper.GetDigitsFromPhoneNumber(request.Settings.Phone); } else { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, string.Format(_resources.Get("PhoneNumberFormat", request.ClientLanguageCode), countryCode.GetPhoneExample())); } // TODO MKTAXI-3576: Find a better way to do this... var isFromWebApp = request.FromWebApp; if (!isFromWebApp) { ValidateAppVersion(request.ClientLanguageCode, createReportOrder); } // Find market var marketSettings = _taxiHailNetworkServiceClient.GetCompanyMarketSettings(request.PickupAddress.Latitude, request.PickupAddress.Longitude); var market = marketSettings.Market.HasValue() ? marketSettings.Market : null; createReportOrder.Market = market; var isFutureBooking = IsFutureBooking(request.PickupDate, marketSettings); if (!marketSettings.EnableFutureBooking && isFutureBooking) { // future booking not allowed ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_FutureBookingNotAllowed", request.ClientLanguageCode)); } BestAvailableCompany bestAvailableCompany; if (request.OrderCompanyKey.HasValue() || request.OrderFleetId.HasValue) { // For API user, it's possible to manually specify which company to dispatch to by using a fleet id bestAvailableCompany = _taxiHailNetworkHelper.FindSpecificCompany(market, createReportOrder, request.OrderCompanyKey, request.OrderFleetId, request.PickupAddress.Latitude, request.PickupAddress.Longitude); } else { bestAvailableCompany = _taxiHailNetworkHelper.FindBestAvailableCompany(marketSettings, request.PickupAddress.Latitude, request.PickupAddress.Longitude, isFutureBooking); } _logger.LogMessage("Best available company determined: {0}, in {1}", bestAvailableCompany.CompanyKey.HasValue() ? bestAvailableCompany.CompanyKey : "local company", market.HasValue() ? market : "local market"); createReportOrder.CompanyKey = bestAvailableCompany.CompanyKey; createReportOrder.CompanyName = bestAvailableCompany.CompanyName; if (market.HasValue()) { if (!bestAvailableCompany.CompanyKey.HasValue()) { // No companies available that are desserving this region for the company ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, _resources.Get("CannotCreateOrder_NoCompanies", request.ClientLanguageCode)); } _taxiHailNetworkHelper.UpdateVehicleTypeFromMarketData(request.Settings, bestAvailableCompany.CompanyKey); var isConfiguredForCmtPayment = _taxiHailNetworkHelper.FetchCompanyPaymentSettings(bestAvailableCompany.CompanyKey); if (!isConfiguredForCmtPayment) { // Only companies configured for CMT payment can support CoF orders outside of home market request.Settings.ChargeTypeId = ChargeTypes.PaymentInCar.Id; } if (marketSettings.DisableOutOfAppPayment && request.Settings.ChargeTypeId == ChargeTypes.PaymentInCar.Id) { // No payment method available since we can't pay in car ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_NoChargeType, _resources.Get("CannotCreateOrder_NoChargeType", request.ClientLanguageCode)); } } var isPaypal = request.Settings.ChargeTypeId == ChargeTypes.PayPal.Id; var isBraintree = (request.Settings.ChargeTypeId == ChargeTypes.CardOnFile.Id) && (_serverSettings.GetPaymentSettings().PaymentMode == PaymentMethod.Braintree); var isPrepaid = isFromWebApp && (isPaypal || isBraintree); createReportOrder.IsPrepaid = isPrepaid; account.IBSAccountId = CreateIbsAccountIfNeeded(account, bestAvailableCompany.CompanyKey); var pickupDate = request.PickupDate ?? GetCurrentOffsetedTime(bestAvailableCompany.CompanyKey); createReportOrder.PickupDate = pickupDate; // User can still create future order, but we allow only one active Book now order. if (!isFutureBooking) { var pendingOrderId = GetPendingOrder(); // We don't allow order creation if there's already an order scheduled if (!_serverSettings.ServerData.AllowSimultaneousAppOrders && pendingOrderId != null && !isFromWebApp) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_PendingOrder, pendingOrderId.ToString()); } } var rule = _ruleCalculator.GetActiveDisableFor( isFutureBooking, pickupDate, () => _ibsServiceProvider.StaticData(bestAvailableCompany.CompanyKey) .GetZoneByCoordinate( request.Settings.ProviderId, request.PickupAddress.Latitude, request.PickupAddress.Longitude), () => request.DropOffAddress != null ? _ibsServiceProvider.StaticData(bestAvailableCompany.CompanyKey) .GetZoneByCoordinate( request.Settings.ProviderId, request.DropOffAddress.Latitude, request.DropOffAddress.Longitude) : null, market, new Position(request.PickupAddress.Latitude, request.PickupAddress.Longitude)); if (rule != null) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, rule.Message); } // We need to validate the rules of the roaming market. if (market.HasValue()) { // External market, query company site directly to validate their rules var orderServiceClient = new RoamingValidationServiceClient(bestAvailableCompany.CompanyKey, _serverSettings.ServerData.Target); _logger.LogMessage(string.Format("Validating rules for company in external market... Target: {0}, Server: {1}", _serverSettings.ServerData.Target, orderServiceClient.Url)); var validationResult = orderServiceClient.ValidateOrder(request, true); if (validationResult.HasError) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_RuleDisable, validationResult.Message); } } if (Params.Get(request.Settings.Name, request.Settings.Phone).Any(p => p.IsNullOrEmpty())) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_SettingsRequired); } var referenceData = (ReferenceData)_referenceDataService.Get(new ReferenceDataRequest { CompanyKey = bestAvailableCompany.CompanyKey }); request.PickupDate = pickupDate; request.Settings.Passengers = request.Settings.Passengers <= 0 ? 1 : request.Settings.Passengers; if (_serverSettings.ServerData.Direction.NeedAValidTarif && (!request.Estimate.Price.HasValue || request.Estimate.Price == 0)) { ThrowAndLogException(createReportOrder, ErrorCode.CreateOrder_NoFareEstimateAvailable, GetCreateOrderServiceErrorMessage(ErrorCode.CreateOrder_NoFareEstimateAvailable, request.ClientLanguageCode)); } // IBS provider validation ValidateProvider(request, referenceData, market.HasValue(), createReportOrder); // Map the command to obtain a OrderId (web doesn't prepopulate it in the request) var orderCommand = Mapper.Map <Commands.CreateOrder>(request); _logger.LogMessage("MarketSettings for order {0}: {1}", orderCommand.OrderId, marketSettings.ToJson()); var marketFees = _feesDao.GetMarketFees(market); orderCommand.BookingFees = marketFees != null ? marketFees.Booking : 0; createReportOrder.BookingFees = orderCommand.BookingFees; createReportOrder.AssignVehicleId = orderCommand.AssignVehicleId; // Promo code validation var promotionId = ValidatePromotion(bestAvailableCompany.CompanyKey, request.PromoCode, request.Settings.ChargeTypeId, account.Id, pickupDate, isFutureBooking, request.ClientLanguageCode, createReportOrder); // Charge account validation var accountValidationResult = ValidateChargeAccountIfNecessary(bestAvailableCompany.CompanyKey, request, orderCommand.OrderId, account, isFutureBooking, isFromWebApp, orderCommand.BookingFees, createReportOrder); createReportOrder.IsChargeAccountPaymentWithCardOnFile = accountValidationResult.IsChargeAccountPaymentWithCardOnFile; // if ChargeAccount uses payment with card on file, payment validation was already done if (!accountValidationResult.IsChargeAccountPaymentWithCardOnFile) { // Payment method validation ValidatePayment(bestAvailableCompany.CompanyKey, request, orderCommand.OrderId, account, isFutureBooking, request.Estimate.Price, orderCommand.BookingFees, isPrepaid, createReportOrder); } var chargeTypeIbs = string.Empty; var chargeTypeEmail = string.Empty; var chargeTypeKey = ChargeTypes.GetList() .Where(x => x.Id == request.Settings.ChargeTypeId) .Select(x => x.Display) .FirstOrDefault(); chargeTypeKey = accountValidationResult.ChargeTypeKeyOverride ?? chargeTypeKey; if (chargeTypeKey != null) { // this must be localized with the priceformat to be localized in the language of the company // because it is sent to the driver chargeTypeIbs = _resources.Get(chargeTypeKey, _serverSettings.ServerData.PriceFormat); chargeTypeEmail = _resources.Get(chargeTypeKey, request.ClientLanguageCode); } // Get Vehicle Type from reference data var vehicleType = referenceData.VehiclesList .Where(x => x.Id == request.Settings.VehicleTypeId) .Select(x => x.Display) .FirstOrDefault(); // Use address alias if present. var addressAlias = request.PickupAddress.FriendlyName.HasValueTrimmed() ? request.PickupAddress.FriendlyName : request.PickupAddress.BuildingName; var ibsInformationNote = IbsHelper.BuildNote( _serverSettings.ServerData.IBS.NoteTemplate, chargeTypeIbs, request.Note, addressAlias, request.Settings.LargeBags, _serverSettings.ServerData.IBS.HideChargeTypeInUserNote); var fare = FareHelper.GetFareFromEstimate(request.Estimate); orderCommand.AccountId = account.Id; orderCommand.UserAgent = Request.UserAgent; orderCommand.ClientVersion = Request.Headers.Get("ClientVersion"); orderCommand.IsChargeAccountPaymentWithCardOnFile = accountValidationResult.IsChargeAccountPaymentWithCardOnFile; orderCommand.CompanyKey = bestAvailableCompany.CompanyKey; orderCommand.CompanyName = bestAvailableCompany.CompanyName; orderCommand.CompanyFleetId = bestAvailableCompany.FleetId; orderCommand.Market = market; orderCommand.IsPrepaid = isPrepaid; orderCommand.Settings.ChargeType = chargeTypeIbs; orderCommand.Settings.VehicleType = vehicleType; orderCommand.IbsAccountId = account.IBSAccountId.Value; orderCommand.ReferenceDataCompanyList = referenceData.CompaniesList.ToArray(); orderCommand.IbsInformationNote = ibsInformationNote; orderCommand.Fare = fare; orderCommand.Prompts = accountValidationResult.Prompts; orderCommand.PromptsLength = accountValidationResult.PromptsLength; orderCommand.PromotionId = promotionId; orderCommand.ChargeTypeEmail = chargeTypeEmail; orderCommand.OriginatingIpAddress = createReportOrder.OriginatingIpAddress = request.CustomerIpAddress; orderCommand.KountSessionId = createReportOrder.OriginatingIpAddress = request.KountSessionId; orderCommand.IsFutureBooking = createReportOrder.IsFutureBooking = isFutureBooking; orderCommand.AssignVehicleId = createReportOrder.AssignVehicleId; Debug.Assert(request.PickupDate != null, "request.PickupDate != null"); return(orderCommand); }
public object Post(CancelOrder request) { var order = _orderDao.FindById(request.OrderId); var account = _accountDao.FindById(new Guid(this.GetSession().UserAuthId)); if (order == null) { return(new HttpResult(HttpStatusCode.NotFound)); } if (account.Id != order.AccountId) { throw new HttpError(HttpStatusCode.Unauthorized, "Can't cancel another account's order"); } if (order.IBSOrderId.HasValue) { var currentIbsAccountId = _accountDao.GetIbsAccountId(account.Id, order.CompanyKey); var orderStatus = _orderDao.FindOrderStatusById(order.Id); var marketSettings = _networkServiceClient.GetCompanyMarketSettings(order.PickupAddress.Latitude, order.PickupAddress.Longitude); var canCancelWhenPaired = orderStatus.IBSStatusId.SoftEqual(VehicleStatuses.Common.Loaded) && marketSettings.DisableOutOfAppPayment; if (currentIbsAccountId.HasValue && (!orderStatus.IBSStatusId.HasValue() || orderStatus.IBSStatusId.SoftEqual(VehicleStatuses.Common.Waiting) || orderStatus.IBSStatusId.SoftEqual(VehicleStatuses.Common.Assigned) || orderStatus.IBSStatusId.SoftEqual(VehicleStatuses.Common.Arrived) || orderStatus.IBSStatusId.SoftEqual(VehicleStatuses.Common.Scheduled) || canCancelWhenPaired)) { _ibsCreateOrderService.CancelIbsOrder(order.IBSOrderId.Value, order.CompanyKey, order.Settings.Phone, account.Id); } else { var errorReason = !currentIbsAccountId.HasValue ? string.Format("no IbsAccountId found for accountid {0} and companykey {1}", account.Id, order.CompanyKey) : string.Format("orderDetail.IBSStatusId is not in the correct state: {0}, state: {1}", orderStatus.IBSStatusId, orderStatus.IBSStatusId); var errorMessage = string.Format("Could not cancel order because {0}", errorReason); _logger.LogMessage(errorMessage); throw new HttpError(HttpStatusCode.BadRequest, _resources.Get("CancelOrderError"), errorMessage); } } else { _logger.LogMessage("We don't have an ibs order id yet, send a CancelOrder command so that when we receive the ibs order info, we can cancel it"); } var command = new Commands.CancelOrder { OrderId = request.OrderId }; _commandBus.Send(command); UpdateStatusAsync(command.OrderId); return(new HttpResult(HttpStatusCode.OK)); }
public object Post(RegisterAccount request) { // Ensure user is not signed in RequestContext.Get <IHttpRequest>().RemoveSession(); if (_accountDao.FindByEmail(request.Email) != null) { throw new HttpError(ErrorCode.CreateAccount_AccountAlreadyExist.ToString()); } 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())); } if (_blackListEntryService.GetAll().Any(e => e.PhoneNumber.Equals(request.Phone))) { throw new HttpError(_resources.Get("PhoneBlackListed")); } if (request.FacebookId.HasValue()) { // Facebook registration if (_accountDao.FindByFacebookId(request.FacebookId) != null) { throw new HttpError(ErrorCode.CreateAccount_AccountAlreadyExist.ToString()); } var command = new RegisterFacebookAccount(); Mapper.Map(request, command); command.Id = Guid.NewGuid(); _commandBus.Send(command); return(new Account { Id = command.AccountId }); } if (request.TwitterId.HasValue()) { // Twitter registration if (_accountDao.FindByTwitterId(request.TwitterId) != null) { throw new HttpError(ErrorCode.CreateAccount_AccountAlreadyExist.ToString()); } var command = new RegisterTwitterAccount(); Mapper.Map(request, command); command.Id = Guid.NewGuid(); _commandBus.Send(command); return(new Account { Id = command.AccountId }); } else { // Normal registration var accountActivationDisabled = _serverSettings.ServerData.AccountActivationDisabled; var smsConfirmationEnabled = _serverSettings.ServerData.SMSConfirmationEnabled; var confirmationToken = smsConfirmationEnabled ? GenerateActivationCode() : Guid.NewGuid().ToString(); var command = new Commands.RegisterAccount(); Mapper.Map(request, command); command.Id = Guid.NewGuid(); command.ConfimationToken = confirmationToken; command.AccountActivationDisabled = accountActivationDisabled; _commandBus.Send(command); if (!accountActivationDisabled) { if (smsConfirmationEnabled && (request.ActivationMethod == null || request.ActivationMethod == ActivationMethod.Sms)) { _commandBus.Send(new SendAccountConfirmationSMS { ClientLanguageCode = command.Language, Code = confirmationToken, CountryCode = command.Country, PhoneNumber = command.Phone }); } else { _commandBus.Send(new SendAccountConfirmationEmail { ClientLanguageCode = command.Language, EmailAddress = command.Email, ConfirmationUrl = new Uri(string.Format("/api/account/confirm/{0}/{1}", command.Email, confirmationToken), UriKind.Relative), }); } } return(new Account { Id = command.AccountId }); } }
public InitializePayPalCheckoutResponse InitializeWebPayment(Guid accountId, Guid orderId, string baseUri, double?estimatedFare, decimal bookingFees, string clientLanguageCode) { if (!estimatedFare.HasValue) { return(new InitializePayPalCheckoutResponse { IsSuccessful = false, Message = _resources.Get("CannotCreateOrder_PrepaidNoEstimate", clientLanguageCode) }); } var regionName = _serverSettings.ServerData.PayPalRegionInfoOverride; var conversionRate = _serverSettings.ServerData.PayPalConversionRate; _logger.LogMessage("PayPal Conversion Rate: {0}", conversionRate); // Fare amount var fareAmount = Math.Round(Convert.ToDecimal(estimatedFare.Value) * conversionRate, 2); var currency = conversionRate != 1 ? CurrencyCodes.Main.UnitedStatesDollar : _resources.GetCurrencyCode(); // Need the fare object because tip amount should be calculated on the fare excluding taxes var fareObject = FareHelper.GetFareFromAmountInclTax(Convert.ToDouble(fareAmount), _serverSettings.ServerData.VATIsEnabled ? _serverSettings.ServerData.VATPercentage : 0); // Tip amount (on fare amount excl. taxes) var defaultTipPercentage = _accountDao.FindById(accountId).DefaultTipPercent; var tipPercentage = defaultTipPercentage ?? _serverSettings.ServerData.DefaultTipPercentage; var tipAmount = FareHelper.CalculateTipAmount(fareObject.AmountInclTax, tipPercentage); // Booking Fees with conversion rate if necessary var bookingFeesAmount = Math.Round(bookingFees * conversionRate, 2); // Fare amount with tip and booking fee var totalAmount = fareAmount + tipAmount + bookingFeesAmount; var redirectUrl = baseUri + string.Format("/{0}/proceed", orderId); _logger.LogMessage("PayPal Web redirect URL: {0}", redirectUrl); var redirUrls = new RedirectUrls { cancel_url = redirectUrl + "?cancel=true", return_url = redirectUrl }; // Create transaction var transactionList = new List <Transaction> { new Transaction { amount = new Amount { currency = currency, total = totalAmount.ToString("N", CultureInfo.InvariantCulture) }, description = string.Format( _resources.Get("PayPalWebPaymentDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), totalAmount), item_list = new ItemList { items = new List <Item> { new Item { name = _resources.Get("PayPalWebFareItemDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), currency = currency, price = fareAmount.ToString("N", CultureInfo.InvariantCulture), quantity = "1" }, new Item { name = string.Format(_resources.Get("PayPalWebTipItemDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), tipPercentage), currency = currency, price = tipAmount.ToString("N", CultureInfo.InvariantCulture), quantity = "1" } } } } }; if (bookingFeesAmount > 0) { transactionList.First().item_list.items.Add(new Item { name = _resources.Get("PayPalWebBookingFeeItemDescription", regionName.HasValue() ? SupportedLanguages.en.ToString() : clientLanguageCode), currency = currency, price = bookingFeesAmount.ToString("N", CultureInfo.InvariantCulture), quantity = "1" }); } // Create web experience profile var profile = new WebProfile { name = Guid.NewGuid().ToString(), flow_config = new FlowConfig { landing_page_type = _serverPaymentSettings.PayPalServerSettings.LandingPageType.ToString() } }; try { var webExperienceProfile = profile.Create(GetAPIContext(GetAccessToken())); // Create payment var payment = new Payment { intent = Intents.Sale, payer = new Payer { payment_method = "paypal" }, transactions = transactionList, redirect_urls = redirUrls, experience_profile_id = webExperienceProfile.id }; var createdPayment = payment.Create(GetAPIContext(GetAccessToken())); var links = createdPayment.links.GetEnumerator(); while (links.MoveNext()) { var link = links.Current; if (link.rel.ToLower().Trim().Equals("approval_url")) { return(new InitializePayPalCheckoutResponse { IsSuccessful = true, PaymentId = createdPayment.id, PayPalCheckoutUrl = link.href // Links that give the user the option to redirect to PayPal to approve the payment }); } } _logger.LogMessage("Error when creating PayPal Web payment: no approval_urls found"); // No approval_url found return(new InitializePayPalCheckoutResponse { IsSuccessful = false, Message = "No approval_url found" }); } catch (Exception ex) { var exceptionMessage = ex.Message; var paymentException = ex as PaymentsException; if (paymentException != null && paymentException.Details != null) { exceptionMessage = paymentException.Details.message; } _logger.LogMessage("Initialization of PayPal Web Store failed: {0}", exceptionMessage); return(new InitializePayPalCheckoutResponse { IsSuccessful = false, Message = exceptionMessage }); } }
public object Post(ManualRideLinqPairingRequest request) { try { var accountId = new Guid(this.GetSession().UserAuthId); var account = _accountDao.FindById(accountId); ValidateAppVersion(account); var currentRideLinq = _orderDao.GetCurrentManualRideLinq(request.PairingCode, account.Id); if (currentRideLinq != null) { return(new ManualRideLinqResponse { Data = currentRideLinq, IsSuccessful = true, Message = "Ok" }); } var creditCard = account.DefaultCreditCard.HasValue ? _creditCardDao.FindById(account.DefaultCreditCard.Value) : null; if (creditCard == null) { throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.ManualRideLinq_NoCardOnFile.ToString(), _resources.Get("ManualRideLinq_NoCardOnFile", account.Language)); } if (creditCard.IsDeactivated) { throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.ManualRideLinq_CardOnFileDeactivated.ToString(), _resources.Get("ManualRideLinq_CreditCardDisabled", account.Language)); } // Send pairing request to CMT API var pairingRequest = new ManualRideLinqCoFPairingRequest { AutoTipPercentage = account.DefaultTipPercent ?? _serverSettings.ServerData.DefaultTipPercentage, CustomerId = accountId.ToString(), CustomerName = account.Name, Latitude = request.PickupAddress.Latitude, Longitude = request.PickupAddress.Longitude, PairingCode = request.PairingCode, AutoCompletePayment = true, CardOnFileId = creditCard.Token, LastFour = creditCard.Last4Digits, ZipCode = creditCard.ZipCode, Email = account.Email, CustomerIpAddress = RequestContext.IpAddress, BillingFullName = creditCard.NameOnCard, SessionId = request.KountSessionId }; _logger.LogMessage("Pairing for manual RideLinq with Pairing Code {0}", request.PairingCode); var response = _cmtMobileServiceClient.Post(pairingRequest); _logger.LogMessage("Pairing result: {0}", response.ToJson()); var trip = _cmtTripInfoServiceHelper.WaitForTripInfo(response.PairingToken, response.TimeoutSeconds); if (trip.HttpStatusCode == (int)HttpStatusCode.OK) { var command = new CreateOrderForManualRideLinqPair { OrderId = Guid.NewGuid(), AccountId = accountId, UserAgent = Request.UserAgent, ClientVersion = Request.Headers.Get("ClientVersion"), PairingCode = request.PairingCode, PickupAddress = request.PickupAddress, PairingToken = response.PairingToken, PairingDate = DateTime.Now, ClientLanguageCode = request.ClientLanguageCode, Distance = trip.Distance, StartTime = trip.StartTime, EndTime = trip.EndTime, Extra = Math.Round(((double)trip.Extra / 100), 2), Fare = Math.Round(((double)trip.Fare / 100), 2), Tax = Math.Round(((double)trip.Tax / 100), 2), Tip = Math.Round(((double)trip.Tip / 100), 2), Toll = trip.TollHistory.Sum(toll => Math.Round(((double)toll.TollAmount / 100), 2)), Surcharge = Math.Round(((double)trip.Surcharge / 100), 2), Total = Math.Round(((double)trip.Total / 100), 2), FareAtAlternateRate = Math.Round(((double)trip.FareAtAlternateRate / 100), 2), Medallion = response.Medallion, DeviceName = response.DeviceName, RateAtTripStart = trip.RateAtTripStart, RateAtTripEnd = trip.RateAtTripEnd, RateChangeTime = trip.RateChangeTime, TripId = trip.TripId, DriverId = trip.DriverId, LastFour = trip.LastFour, AccessFee = Math.Round(((double)trip.AccessFee / 100), 2), OriginatingIpAddress = request.CustomerIpAddress, KountSessionId = request.KountSessionId, CreditCardId = creditCard.CreditCardId, }; _commandBus.Send(command); var data = new OrderManualRideLinqDetail { OrderId = command.OrderId, Distance = trip.Distance, StartTime = trip.StartTime, EndTime = trip.EndTime, Extra = command.Extra, Fare = command.Fare, Tax = command.Tax, Tip = command.Tip, Toll = command.Toll, Surcharge = command.Surcharge, Total = command.Total, FareAtAlternateRate = command.FareAtAlternateRate, Medallion = response.Medallion, DeviceName = response.DeviceName, RateAtTripStart = command.RateAtTripStart, RateAtTripEnd = command.RateAtTripEnd, RateChangeTime = trip.RateChangeTime, AccountId = accountId, PairingDate = command.PairingDate, PairingCode = pairingRequest.PairingCode, PairingToken = trip.PairingToken, DriverId = trip.DriverId, LastFour = command.LastFour, AccessFee = command.AccessFee }; return(new ManualRideLinqResponse { Data = data, IsSuccessful = true, Message = "Ok", TripInfoHttpStatusCode = trip.HttpStatusCode, ErrorCode = trip.ErrorCode.ToString() }); } else { if (trip.HttpStatusCode == (int)HttpStatusCode.BadRequest) { switch (trip.ErrorCode) { case CmtErrorCodes.CreditCardDeclinedOnPreauthorization: _notificationService.SendCmtPaymentFailedPush(accountId, _resources.Get("CreditCardDeclinedOnPreauthorizationErrorText", request.ClientLanguageCode)); break; case CmtErrorCodes.UnablePreauthorizeCreditCard: _notificationService.SendCmtPaymentFailedPush(accountId, _resources.Get("CreditCardUnableToPreathorizeErrorText", request.ClientLanguageCode)); break; default: _notificationService.SendCmtPaymentFailedPush(accountId, _resources.Get("TripUnableToPairErrorText", request.ClientLanguageCode)); break; } } return(new ManualRideLinqResponse { IsSuccessful = false, TripInfoHttpStatusCode = trip.HttpStatusCode, ErrorCode = trip.ErrorCode != null?trip.ErrorCode.ToString() : null }); } } catch (WebServiceException ex) { _logger.LogMessage( string.Format("A WebServiceException occured while trying to manually pair with CMT with pairing code: {0}", request.PairingCode)); _logger.LogError(ex); ErrorResponse errorResponse = null; if (ex.ResponseBody != null) { _logger.LogMessage("Error Response: {0}", ex.ResponseBody); errorResponse = ex.ResponseBody.FromJson <ErrorResponse>(); } return(new ManualRideLinqResponse { IsSuccessful = false, Message = errorResponse != null ? errorResponse.Message : ex.ErrorMessage, ErrorCode = errorResponse != null?errorResponse.ResponseCode.ToString() : ex.ErrorCode }); } catch (Exception ex) { _logger.LogMessage(string.Format("An error occured while trying to manually pair with CMT with pairing code: {0}", request.PairingCode)); _logger.LogError(ex); return(new ManualRideLinqResponse { IsSuccessful = false, Message = ex.Message }); } }
public object Post(CreateOrderRequest request) { var account = _accountDao.FindById(new Guid(this.GetSession().UserAuthId)); // Needed when we get a webapp request. if (request.FromWebApp && request.Id == Guid.Empty) { request.Id = Guid.NewGuid(); } _logger.LogMessage("CreateOrderService:: Post - Order: " + request.ToJson()); var createReportOrder = CreateReportOrder(request, account); var createOrderCommand = BuildCreateOrderCommand(request, account, createReportOrder); // Initialize PayPal if user is using PayPal web var paypalWebPaymentResponse = PaymentHelper.InitializePayPalCheckoutIfNecessary( createOrderCommand.AccountId, createOrderCommand.IsPrepaid, createOrderCommand.OrderId, request, createOrderCommand.BookingFees, createOrderCommand.CompanyKey, createReportOrder, Request.AbsoluteUri); _commandBus.Send(createOrderCommand); if (paypalWebPaymentResponse != null) { // Order prepaid by PayPal _commandBus.Send(new SaveTemporaryOrderCreationInfo { OrderId = createOrderCommand.OrderId, SerializedOrderCreationInfo = new TemporaryOrderCreationInfo { OrderId = createOrderCommand.OrderId, AccountId = createOrderCommand.AccountId, Request = createOrderCommand, ReferenceDataCompaniesList = createOrderCommand.ReferenceDataCompanyList, ChargeTypeIbs = createOrderCommand.Settings.ChargeType, ChargeTypeEmail = createOrderCommand.ChargeTypeEmail, VehicleType = createOrderCommand.Settings.VehicleType, Prompts = createOrderCommand.Prompts, PromptsLength = createOrderCommand.PromptsLength, BestAvailableCompany = new BestAvailableCompany { CompanyKey = createOrderCommand.CompanyKey, CompanyName = createOrderCommand.CompanyName }, PromotionId = createOrderCommand.PromotionId }.ToJson() }); return(paypalWebPaymentResponse); } if (request.QuestionsAndAnswers.HasValue()) { // Save question answers so we can display them the next time the user books var accountLastAnswers = request.QuestionsAndAnswers .Where(q => q.SaveAnswer) .Select(q => new AccountChargeQuestionAnswer { AccountId = createOrderCommand.AccountId, AccountChargeQuestionId = q.Id, AccountChargeId = q.AccountId, LastAnswer = q.Answer }); _commandBus.Send(new AddUpdateAccountQuestionAnswer { AccountId = createOrderCommand.AccountId, Answers = accountLastAnswers.ToArray() }); } return(new OrderStatusDetail { OrderId = createOrderCommand.OrderId, Status = OrderStatus.Created, IBSStatusId = string.Empty, IBSStatusDescription = _resources.Get("CreateOrder_WaitingForIbs", createOrderCommand.ClientLanguageCode), }); }
public void Get(ConfirmationCodeRequest request) { var account = _accountDao.FindByEmail(request.Email); if (account == null) { throw new HttpError(HttpStatusCode.NotFound, "No account matching this email address"); } if (!_serverSettings.ServerData.AccountActivationDisabled) { if (_serverSettings.ServerData.SMSConfirmationEnabled) { var countryCodeForSMS = account.Settings.Country; var phoneNumberForSMS = account.Settings.Phone; CountryCode countryCodeFromRequest = CountryCode.GetCountryCodeByIndex(CountryCode.GetCountryCodeIndexByCountryISOCode(request.CountryCode)); if (countryCodeFromRequest.IsValid() && request.PhoneNumber.HasValue() && PhoneHelper.IsPossibleNumber(countryCodeFromRequest, request.PhoneNumber) && (account.Settings.Country.Code != countryCodeFromRequest.CountryISOCode.Code || account.Settings.Phone != request.PhoneNumber)) { if (_blackListEntryService.GetAll().Any(e => e.PhoneNumber.Equals(request.PhoneNumber.ToSafeString()))) { throw new HttpError(_resources.Get("PhoneBlackListed")); } countryCodeForSMS = countryCodeFromRequest.CountryISOCode; phoneNumberForSMS = request.PhoneNumber; var updateBookingSettings = new UpdateBookingSettings() { AccountId = account.Id, Email = account.Email, Name = account.Name, Country = countryCodeFromRequest.CountryISOCode, Phone = request.PhoneNumber, Passengers = account.Settings.Passengers, VehicleTypeId = account.Settings.VehicleTypeId, ChargeTypeId = account.Settings.ChargeTypeId, ProviderId = account.Settings.ProviderId, NumberOfTaxi = account.Settings.NumberOfTaxi, AccountNumber = account.Settings.AccountNumber, CustomerNumber = account.Settings.CustomerNumber, DefaultTipPercent = account.DefaultTipPercent, PayBack = account.Settings.PayBack }; _commandBus.Send(updateBookingSettings); } _commandBus.Send(new SendAccountConfirmationSMS { ClientLanguageCode = account.Language, Code = account.ConfirmationToken, CountryCode = countryCodeForSMS, PhoneNumber = phoneNumberForSMS }); } else { _commandBus.Send(new SendAccountConfirmationEmail { ClientLanguageCode = account.Language, EmailAddress = account.Email, ConfirmationUrl = new Uri(string.Format("/api/account/confirm/{0}/{1}", account.Email, account.ConfirmationToken), UriKind.Relative) }); } } }
public void Handle(CreditCardPaymentCaptured_V2 @event) { @event.MigrateFees(); using (var context = _contextFactory.Invoke()) { var payment = context.Set <OrderPaymentDetail>().Find(@event.SourceId); if (payment == null) { throw new InvalidOperationException("Payment not found"); } payment.TransactionId = @event.TransactionId; payment.AuthorizationCode = @event.AuthorizationCode; payment.IsCompleted = true; payment.Amount = @event.Amount; payment.Meter = @event.Meter; payment.Tax = @event.Tax; payment.Tip = @event.Tip; payment.Toll = @event.Toll; payment.Surcharge = @event.Surcharge; payment.BookingFees = @event.BookingFees; payment.IsCancelled = false; payment.FeeType = @event.FeeType; payment.Error = null; // Update payment details after settling an overdue payment if (@event.NewCardToken.HasValue()) { payment.CardToken = @event.NewCardToken; } var order = context.Find <OrderDetail>(payment.OrderId); // Prevents NullReferenceException caused with web prepayed while running database initializer. if (order == null && @event.IsForPrepaidOrder) { order = new OrderDetail { Id = payment.OrderId, //Following values will be set to the correct date and time when that event is played. PickupDate = @event.EventDate, CreatedDate = @event.EventDate }; context.Set <OrderDetail>().Add(order); } if (!order.Fare.HasValue || order.Fare == 0) { order.Fare = Convert.ToDouble(@event.Meter); } if (!order.Tip.HasValue || order.Tip == 0) { order.Tip = Convert.ToDouble(@event.Tip); } if (!order.Tax.HasValue || order.Tax == 0) { order.Tax = Convert.ToDouble(@event.Tax); } if (!order.Toll.HasValue || order.Toll == 0) { order.Toll = Convert.ToDouble(@event.Toll); } if (!order.Surcharge.HasValue || order.Surcharge == 0) { order.Surcharge = Convert.ToDouble(@event.Surcharge); } if ([email protected]) { var orderStatus = context.Find <OrderStatusDetail>(payment.OrderId); orderStatus.IBSStatusId = VehicleStatuses.Common.Done; orderStatus.IBSStatusDescription = _resources.Get("OrderStatus_wosDONE", order.ClientLanguageCode); } context.SaveChanges(); } }
public object Get(ExecuteWebPaymentAndProceedWithOrder request) { _logger.LogMessage("ExecuteWebPaymentAndProceedWithOrder request : " + request.ToJson()); var temporaryInfo = _orderDao.GetTemporaryInfo(request.OrderId); var orderInfo = JsonSerializer.DeserializeFromString <TemporaryOrderCreationInfo>(temporaryInfo.SerializedOrderCreationInfo); if (request.Cancel || orderInfo == null) { var clientLanguageCode = orderInfo == null ? SupportedLanguages.en.ToString() : orderInfo.Request.ClientLanguageCode; _commandBus.Send(new CancelOrderBecauseOfError { OrderId = request.OrderId, ErrorDescription = _resources.Get("CannotCreateOrder_PrepaidPayPalPaymentCancelled", clientLanguageCode) }); } else { // Execute PayPal payment var response = _payPalServiceFactory.GetInstance(orderInfo.BestAvailableCompany.CompanyKey).ExecuteWebPayment(request.PayerId, request.PaymentId); if (response.IsSuccessful) { var account = _accountDao.FindById(orderInfo.AccountId); var tipPercentage = account.DefaultTipPercent ?? _serverSettings.ServerData.DefaultTipPercentage; var tipAmount = FareHelper.CalculateTipAmount(orderInfo.Request.Fare.AmountInclTax, tipPercentage); _commandBus.Send(new MarkPrepaidOrderAsSuccessful { OrderId = request.OrderId, TotalAmount = orderInfo.Request.Fare.AmountInclTax + tipAmount, MeterAmount = orderInfo.Request.Fare.AmountExclTax, TaxAmount = orderInfo.Request.Fare.TaxAmount, TipAmount = tipAmount, TransactionId = response.TransactionId, Provider = PaymentProvider.PayPal, Type = PaymentType.PayPal }); } else { _commandBus.Send(new CancelOrderBecauseOfError { OrderId = request.OrderId, ErrorDescription = response.Message }); } } // Build url used to redirect the web client to the booking status view string baseUrl; if (_serverSettings.ServerData.BaseUrl.HasValue()) { baseUrl = _serverSettings.ServerData.BaseUrl; } else { baseUrl = Request.AbsoluteUri .Replace(Request.PathInfo, string.Empty) .Replace(GetAppHost().Config.ServiceStackHandlerFactoryPath, string.Empty) .Replace(Request.QueryString.ToString(), string.Empty) .Replace("?", string.Empty); } var redirectUrl = string.Format("{0}#status/{1}", baseUrl, request.OrderId); return(new HttpResult { StatusCode = HttpStatusCode.Redirect, Headers = { { HttpHeaders.Location, redirectUrl } } }); }