public override Attempt<IShipmentRateQuote> QuoteShipment(IShipment shipment) { try { var visitor = new FoaShipmentLineItemVisitor() { UseOnSalePriceIfOnSale = false }; shipment.Items.Accept(visitor); if (visitor.TotalPrice >= _processorSettings.Amount) { return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, ShipMethod) { Rate = 0 }); } else { return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, ShipMethod) { Rate = 100 }); } } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } }
public Attempt<IShipmentRateQuote> CalculatePrice(IShipment shipment, IShipMethod shipMethod, decimal totalWeight, int quantity, IShipProvince province) { // First sum up the total weight for the shipment. // We're assumning that a custom order line property // was set on the order line prior when the product was added to the order line. var shippingPrice = 0M; try { var service = new RateService {Url = "https://wsbeta.fedex.com:443/web-services/rate"}; var reply = service.getRates(RateRequest(shipment, totalWeight, quantity)); if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING) { var collection = BuildDeliveryOptions(reply, shipment); var firstCarrierRate = collection.FirstOrDefault(option => option.Service.Contains(shipMethod.ServiceCode.Split('-').First())); if (firstCarrierRate != null) shippingPrice = firstCarrierRate.Rate; } } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, shipMethod) { Rate = shippingPrice }); }
public override Attempt<IShipmentRateQuote> QuoteShipment(IShipment shipment) { try { var visitor = new FoaShipmentLineItemVisitor() { UseOnSalePriceIfOnSale = false }; shipment.Items.Accept(visitor); if (visitor.TotalPrice >= _processorSettings.Amount) { return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, ShipMethod) { Rate = 0 }); } else { // TODO shouldn't this just fail so that a different method is selected or have a configurable default rate. return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, ShipMethod) { Rate = 100 }); } } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } }
/// <summary> /// The perform task. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// The <see cref="Attempt"/>. /// </returns> public override Attempt<IShipment> PerformTask(IShipment value) { Guid orderStatusKey; // not fulfilled if (Order.ShippableItems().All(x => ((OrderLineItem)x).ShipmentKey == null)) { orderStatusKey = Core.Constants.DefaultKeys.OrderStatus.NotFulfilled; return this.SaveOrderStatus(value, orderStatusKey); } if (Order.ShippableItems().Any(x => ((OrderLineItem)x).ShipmentKey == null)) { orderStatusKey = Core.Constants.DefaultKeys.OrderStatus.Open; return this.SaveOrderStatus(value, orderStatusKey); } // now we need to look at all of the shipments to make sure the shipment statuses are either // shipped or delivered. If either of those two, we will consider the shipment as 'Fulfilled', // otherwise the shipment will remain in the open status var shipmentKeys = Order.ShippableItems().Select(x => ((OrderLineItem)x).ShipmentKey.GetValueOrDefault()).Distinct(); var shipments = _shipmentService.GetByKeys(shipmentKeys); orderStatusKey = shipments.All(x => x.ShipmentStatusKey.Equals(Core.Constants.DefaultKeys.ShipmentStatus.Delivered) || x.ShipmentStatusKey.Equals(Core.Constants.DefaultKeys.ShipmentStatus.Shipped)) ? Core.Constants.DefaultKeys.OrderStatus.Fulfilled : Core.Constants.DefaultKeys.OrderStatus.Open; return this.SaveOrderStatus(value, orderStatusKey); }
public virtual ShippingRate GetRate(IShipment shipment, ShippingMethodInfoModel shippingMethodInfoModel, IMarket currentMarket) { var type = Type.GetType(shippingMethodInfoModel.ClassName); var shippingGateway = (IShippingGateway)Activator.CreateInstance(type, currentMarket); string message = null; return shippingGateway.GetRate(shippingMethodInfoModel.MethodId, (Shipment)shipment, ref message); }
public List<IShippingRate> RateShipment(IShipment shipment) { int totalItems = 0; foreach (IShippable item in shipment.Items) { totalItems += item.QuantityOfItemsInBox; } decimal amountPerItem = 0; if (Settings != null) { if (Settings.GetLevels() != null) { amountPerItem = RateTableLevel.FindRateFromLevels(totalItems, Settings.GetLevels()); } } ShippingRate r = new ShippingRate(); r.ServiceId = this.Id; r.EstimatedCost = amountPerItem * totalItems; List<IShippingRate> rates = new List<IShippingRate>(); rates.Add(r); return rates; }
public List<IShippingRate> RateShipment(IShipment shipment) { decimal totalValue = 0; foreach (IShippable item in shipment.Items) { totalValue += item.BoxValue; } decimal amount = 0; if (Settings != null) { if (Settings.GetLevels() != null) { amount = RateTableLevel.FindRateFromLevels(totalValue, Settings.GetLevels()); } } ShippingRate r = new ShippingRate(); r.ServiceId = this.Id; r.EstimatedCost = amount; List<IShippingRate> rates = new List<IShippingRate>(); rates.Add(r); return rates; }
public Attempt<IShipmentRateQuote> CalculatePrice(IShipment shipment, IShipMethod shipMethod, decimal totalWeight, IShipProvince province) { // First sum up the total weight for the shipment. // We're assumning that a custom order line property // was set on the order line prior when the product was added to the order line. var shippingPrice = 0M; try { var http = new UpsHttpRequestHandler(); var rateXml = http.Post(RateRequest(shipment, totalWeight)); var collection = UpsParseRates(rateXml); var firstCarrierRate = collection.FirstOrDefault(option => option.Service == shipMethod.Name); if (firstCarrierRate != null) shippingPrice = firstCarrierRate.Rate; } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, shipMethod) { Rate = shippingPrice }); }
public static Shipment CloneAddressesFromInterface(IShipment source) { Shipment result = new Shipment(); result.DestinationAddress = MerchantTribe.Web.Geography.SimpleAddress.CloneAddress(source.DestinationAddress); result.SourceAddress = MerchantTribe.Web.Geography.SimpleAddress.CloneAddress(source.SourceAddress); return result; }
// Gets all rates filtered by service settings private List<IShippingRate> GetUPSRatesForShipment(IShipment shipment) { List<IShippingRate> rates = new List<IShippingRate>(); List<IShippingRate> allrates = GetAllShippingRatesForShipment(shipment); // Filter all rates by just the ones we want List<IServiceCode> codefilters = this.Settings.ServiceCodeFilter; foreach (IShippingRate rate in allrates) { if (this.Settings.GetAllRates || codefilters.Count < 1) { rates.Add(rate); continue; } else { if (codefilters.Where(y => y.Code == (rate.ServiceCodes.TrimStart('0'))).Count() > 0) { rates.Add(rate); continue; } } } return rates; }
/// <summary> /// The build. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="contacts"> /// The collection of contact addresses /// </param> /// <returns> /// The <see cref="IShipmentResultNotifyModel"/>. /// </returns> public IShipmentResultNotifyModel Build(IShipment shipment, IEnumerable<string> contacts) { var notifyModel = new ShipmentResultNotifyModel() { Shipment = shipment, Contacts = contacts == null ? new string[] { } : contacts.ToArray() }; var item = shipment.Items.FirstOrDefault(x => !x.ContainerKey.Equals(Guid.Empty)); if (item != null) { var orderKey = item.ContainerKey; var order = _orderService.GetByKey(orderKey); if (order != null) { var invoice = _invoiceService.GetByKey(order.InvoiceKey); if (invoice != null) { notifyModel.Invoice = invoice; if (invoice.Items.Any()) { var currencyCode = invoice.Items.First() .ExtendedData.GetValue(Core.Constants.ExtendedDataKeys.CurrencyCode); var currency = _storeSettingService.GetCurrencyByCode(currencyCode); notifyModel.CurrencySymbol = currency.Symbol; } } } } return notifyModel; }
/// <summary> /// Initializes a new instance of the <see cref="DefaultShipmentRateQuoteStrategy"/> class. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="shippingGatewayMethods"> /// The shipping gateway methods. /// </param> /// <param name="runtimeCache"> /// The runtime cache. /// </param> public DefaultShipmentRateQuoteStrategy( IShipment shipment, IShippingGatewayMethod[] shippingGatewayMethods, IRuntimeCacheProvider runtimeCache) : base(shipment, shippingGatewayMethods, runtimeCache) { }
/// <summary> /// The perform task. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// The <see cref="Attempt"/>. /// </returns> public override Attempt<IShipment> PerformTask(IShipment value) { var trackableItems = Order.InventoryTrackedItems().Where(x => KeysToShip.Contains(x.Key)).ToArray(); var variants = _productVariantService.GetByKeys(trackableItems.Select(x => x.ExtendedData.GetProductVariantKey())).ToArray(); if (variants.Any()) { foreach (var item in trackableItems) { var variant = variants.FirstOrDefault(x => x.Key == item.ExtendedData.GetProductVariantKey()); if (variant == null) return Attempt<IShipment>.Fail(new NullReferenceException("A ProductVariant reference in the order could not be found")); var inventory = variant.CatalogInventories.FirstOrDefault(x => x.CatalogKey == item.ExtendedData.GetWarehouseCatalogKey()); if (inventory == null) return Attempt<IShipment>.Fail(new NullReferenceException("An inventory record could not be found for an order line item")); inventory.Count -= item.Quantity; } if (trackableItems.Any()) _productVariantService.Save(variants); } // persist the shipment and update the line items if (value.ShipMethodKey == Guid.Empty) value.ShipMethodKey = null; _shipmentService.Save(value); return Attempt<IShipment>.Succeed(value); }
public static ShippingRate RatePackage(FedExGlobalServiceSettings globals, MerchantTribe.Web.Logging.ILogger logger, FedExServiceSettings settings, IShipment package) { ShippingRate result = new ShippingRate(); // Get ServiceType ServiceType currentServiceType = ServiceType.FEDEXGROUND; currentServiceType = (ServiceType)settings.ServiceCode; // Get PackageType PackageType currentPackagingType = PackageType.YOURPACKAGING; currentPackagingType = (PackageType)settings.Packaging; // Set max weight by service CarrierCodeType carCode = GetCarrierCode(currentServiceType); result.EstimatedCost = RateSinglePackage(globals, logger, package, currentServiceType, currentPackagingType, carCode); return result; }
public override Attempt<IShipment> PerformTask(IShipment value) { return Order.ShippableItems().All(x => ((OrderLineItem)x).ShipmentKey == null) ? SaveOrderStatus(value, Constants.DefaultKeys.OrderStatus.NotFulfilled) : SaveOrderStatus(value, Order.ShippableItems().All(x => ((OrderLineItem) x).ShipmentKey != null) ? Constants.DefaultKeys.OrderStatus.Fulfilled : Constants.DefaultKeys.OrderStatus.BackOrder); }
/// <summary> /// Initializes a new instance of the <see cref="ShipmentRateQuoteStrategyBase"/> class. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="shippingGatewayMethods"> /// The shipping gateway methods. /// </param> /// <param name="runtimeCache"> /// The runtime cache. /// </param> protected ShipmentRateQuoteStrategyBase(IShipment shipment, IShippingGatewayMethod[] shippingGatewayMethods, IRuntimeCacheProvider runtimeCache) { Mandate.ParameterNotNull(shipment, "shipment"); Mandate.ParameterNotNull(shippingGatewayMethods, "gatewayShipMethods"); Mandate.ParameterNotNull(runtimeCache, "runtimeCache"); _shipment = shipment; _shippingGatewayMethods = shippingGatewayMethods; _runtimeCache = runtimeCache; }
public List<IShippingRate> RateShipment(IShipment shipment) { ShippingRate r = new ShippingRate(); r.ServiceId = this.Id; r.EstimatedCost = Settings.Amount; List<IShippingRate> rates = new List<IShippingRate>(); rates.Add(r); return rates; }
private Attempt<IShipment> SaveOrderStatus(IShipment shipment, Guid orderStatusKey) { var orderStatus = _orderService.GetOrderStatusByKey(orderStatusKey); if (orderStatus == null) return Attempt<IShipment>.Fail(new NullReferenceException("Order status was not found")); Order.OrderStatus = orderStatus; _orderService.Save(Order); return Attempt<IShipment>.Succeed(shipment); }
/// <summary> /// Initializes a new instance of the <see cref="ShipmentRateQuote"/> class. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="shipMethod"> /// The ship method. /// </param> /// <param name="extendedData"> /// The extended data. /// </param> public ShipmentRateQuote(IShipment shipment, IShipMethod shipMethod, ExtendedDataCollection extendedData) { Mandate.ParameterNotNull(shipment, "shipment"); Mandate.ParameterNotNull(shipMethod, "shipMethod"); Mandate.ParameterNotNull(extendedData, "extendedData"); shipment.ShipMethodKey = shipMethod.Key; Shipment = shipment; ShipMethod = shipMethod; ExtendedData = extendedData; }
public override Attempt<IShipmentRateQuote> QuoteShipment(IShipment shipment) { try { // TODO this should be made configurable var visitor = new FedExShipmentLineItemVisitor() { UseOnSalePriceIfOnSale = false }; shipment.Items.Accept(visitor); var province = ShipMethod.Provinces.FirstOrDefault(x => x.Code == shipment.ToRegion); var shippingPrice = 0M; try { var service = new RateService { Url = "https://wsbeta.fedex.com:443/web-services/rate" }; var collection = GetCollectionFromCache(shipment); if (collection == null) { var reply = service.getRates(RateRequest(shipment, visitor.TotalWeight, visitor.Quantity)); if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING) { collection = BuildDeliveryOptions(reply, shipment); _runtimeCache.InsertCacheItem(MakeCacheKey(shipment), () => collection); } } var firstCarrierRate = collection.FirstOrDefault(option => option.Service.Contains(_shipMethod.ServiceCode)); if (firstCarrierRate != null) shippingPrice = firstCarrierRate.Rate; } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, _shipMethod) { Rate = shippingPrice }); } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } }
public bool ShipmentHasAddresses(IShipment shipment) { if (shipment.SourceAddress == null) { return false; } if (shipment.DestinationAddress == null) { return false; } return true; }
public override Attempt<IShipmentRateQuote> QuoteShipment(IShipment shipment) { // TODO this should be made configurable var visitor = new FixedRateShipmentLineItemVisitor { UseOnSalePriceIfOnSale = false }; shipment.Items.Accept(visitor); var province = ShipMethod.Provinces.FirstOrDefault(x => x.Code == shipment.ToRegion); return _quoteType == QuoteType.VaryByWeight ? CalculateVaryByWeight(shipment, visitor.TotalWeight, province) : CalculateVaryByPrice(shipment, visitor.TotalPrice, province); }
/// <summary> /// The perform task. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// The <see cref="Attempt"/>. /// </returns> public override Attempt<IShipment> PerformTask(IShipment value) { var unfulfilled = Order.UnfulfilledItems(MerchelloContext).Where(x => x.BackOrder == false && KeysToShip.Contains(x.Key)).ToArray(); if (unfulfilled.Count() != Order.Items.Count(x => KeysToShip.Contains(x.Key))) return Attempt<IShipment>.Fail(new InvalidOperationException("The order contains items that are either on back order or cannot be shipped.")); foreach (var item in unfulfilled) { value.Items.Add(item); } return Attempt<IShipment>.Succeed(value); }
public override Attempt<IShipmentRateQuote> QuoteShipment(IShipment shipment) { try { // TODO this should be made configurable var visitor = new UPSShipmentLineItemVisitor() { UseOnSalePriceIfOnSale = false }; shipment.Items.Accept(visitor); var province = ShipMethod.Provinces.FirstOrDefault(x => x.Code == shipment.ToRegion); var collection = GetCollectionFromCache(shipment); if (collection == null) { try { var http = new UpsHttpRequestHandler(); var rateXml = http.Post(RateRequest(shipment, visitor)); collection = UpsParseRates(rateXml); _runtimeCache.InsertCacheItem(MakeCacheKey(shipment), () => collection); } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } } var shippingPrice = 0M; var firstCarrierRate = collection.FirstOrDefault(option => option.Service == _shipMethod.ServiceCode); if (firstCarrierRate != null) shippingPrice = firstCarrierRate.Rate; return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, _shipMethod) { Rate = shippingPrice }); } catch (Exception ex) { return Attempt<IShipmentRateQuote>.Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again.")); } }
/// <summary> /// The to order confirmation notification. /// </summary> /// <param name="paymentResult"> /// The payment result. /// </param> /// <param name="contacts"> /// The contacts. /// </param> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="shipMethod"> /// The ship Method. /// </param> /// <param name="currencySymbol"> /// The currency Symbol. /// </param> /// <returns> /// The <see cref="IPaymentResultMonitorModel"/>. /// </returns> public static IPaymentResultMonitorModel ToOrderConfirmationNotification(this IPaymentResult paymentResult, IEnumerable<string> contacts, IShipment shipment = null, IShipMethod shipMethod = null, string currencySymbol = "") { return new PaymentResultNotifyModel() { PaymentSuccess = paymentResult.Payment.Success, Payment = paymentResult.Payment.Success ? paymentResult.Payment.Result : null, Invoice = paymentResult.Invoice, Contacts = contacts.ToArray(), Shipment = shipment, ShipMethod = shipMethod, CurrencySymbol = currencySymbol, ApproveOrderCreation = paymentResult.ApproveOrderCreation }; }
private RateRequest RateRequest(IShipment shipment, decimal totalWeight, int quantity) { // Build the RateRequest var request = new RateRequest { WebAuthenticationDetail = new WebAuthenticationDetail { UserCredential = new WebAuthenticationCredential { Key = "fhbqZrPFKWRe2Ndf", Password = "******" } } }; if (usePropertyFile()) //Set values from a file for testing purposes { request.WebAuthenticationDetail.UserCredential.Key = getProperty("key"); request.WebAuthenticationDetail.UserCredential.Password = getProperty("password"); } request.ClientDetail = new ClientDetail {AccountNumber = "510087569", MeterNumber = "118628262"}; if (usePropertyFile()) //Set values from a file for testing purposes { request.ClientDetail.AccountNumber = getProperty("accountnumber"); request.ClientDetail.MeterNumber = getProperty("meternumber"); } request.TransactionDetail = new TransactionDetail { CustomerTransactionId = "***Rate Available Services v14 Request using VC#***" }; request.Version = new VersionId(); request.ReturnTransitAndCommit = true; request.ReturnTransitAndCommitSpecified = true; SetShipmentDetails(request, shipment, totalWeight, quantity); return request; }
public List<IShippingRate> RateShipment(IShipment shipment) { _Messages.Clear(); List<IShippingRate> result = new List<IShippingRate>(); bool hasErrors = false; int serviceCode = Settings.ServiceCode; int packaging = Settings.Packaging; try { List<Shipment> optimizedPackages = this.OptimizeSingleGroup(shipment); if (optimizedPackages.Count > 0) { result = RatePackages(optimizedPackages); } else { if (this.GlobalSettings.DiagnosticsMode) { _Logger.LogMessage("No packages found to rate for FedEx"); } } } catch (Exception ex) { _Logger.LogException(ex); ShippingServiceMessage m = new ShippingServiceMessage(); m.SetError("Exception", ex.Message + " | " + ex.StackTrace); _Messages.Add(m); } if (hasErrors) { result = new List<IShippingRate>(); } return result; }
/// <summary> /// Performs the actual work of performing the shipment rate quote for the shipment based on what items are in the shipment. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <returns> /// An Umbraco <see cref="Attempt"/>. /// </returns> public override Attempt<IShipmentRateQuote> QuoteShipment(IShipment shipment) { var itemHeavyCount = 0; foreach (ILineItem item in shipment.Items) { var isHeavyItem = false; bool.TryParse(item.ExtendedData.GetValue("IsOverweight"), out isHeavyItem); if (isHeavyItem) { itemHeavyCount++; } } // each item gets an added charge, instead of one charge regardless of how many items there are var shippingRate = itemHeavyCount * _isHeavyShippingRate; return Attempt<IShipmentRateQuote>.Succeed(new ShipmentRateQuote(shipment, this.ShipMethod){Rate = shippingRate}); }
public List<IShippingRate> RateShipment(IShipment shipment) { int totalItems = 0; foreach (IShippable item in shipment.Items) { totalItems += item.QuantityOfItemsInBox; } decimal perItemAmount = Settings.Amount; ShippingRate r = new ShippingRate(); r.ServiceId = this.Id; r.EstimatedCost = perItemAmount * totalItems; List<IShippingRate> rates = new List<IShippingRate>(); rates.Add(r); return rates; }
/// <summary> /// Saves a single <see cref="IShipment"/> object /// </summary> /// <param name="shipment">The <see cref="IShipment"/> to save</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param> public void Save(IShipment shipment, bool raiseEvents = true) { if (raiseEvents) if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IShipment>(shipment), this)) { ((Shipment)shipment).WasCancelled = true; return; } using (new WriteLock(Locker)) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateShipmentRepository(uow)) { repository.AddOrUpdate(shipment); uow.Commit(); } } if (raiseEvents) Saved.RaiseEvent(new SaveEventArgs<IShipment>(shipment), this); }
/// <summary> /// Adds shipment replaceable patters. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="currencySymbol"> /// The currency Symbol. /// </param> /// <returns> /// The <see cref="IEnumerable{IReplaceablePattern}"/>. /// </returns> internal static IEnumerable <IReplaceablePattern> ReplaceablePatterns(this IShipment shipment, string currencySymbol) { var patterns = new List <IReplaceablePattern> { ReplaceablePattern.GetConfigurationReplaceablePattern("ShippedDate", shipment.ShippedDate.FormatAsStoreDate()), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToOrganization", shipment.ToOrganization), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToName", shipment.ToName), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToAddress1", shipment.ToAddress1), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToAddress2", shipment.ToAddress2), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToLocality", shipment.ToLocality), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToRegion", shipment.ToRegion), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToPostalCode", shipment.ToPostalCode), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToCountryCode", shipment.ToCountryCode), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToEmail", shipment.Email), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToPhone", shipment.Phone), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToOrganization", shipment.ToOrganization), ReplaceablePattern.GetConfigurationReplaceablePattern("TrackingCode", shipment.TrackingCode) }; patterns.AddRange(shipment.LineItemReplaceablePatterns(currencySymbol)); return(patterns.Where(x => x != null)); }
public Attempt <IShipmentRateQuote> CalculatePrice(IShipment shipment, IShipMethod shipMethod, decimal totalWeight, int quantity, IShipProvince province) { // First sum up the total weight for the shipment. // We're assumning that a custom order line property // was set on the order line prior when the product was added to the order line. var shippingPrice = 0M; try { var service = new RateService { Url = "https://wsbeta.fedex.com:443/web-services/rate" }; var reply = service.getRates(RateRequest(shipment, totalWeight, quantity)); if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING) { var collection = BuildDeliveryOptions(reply, shipment); var firstCarrierRate = collection.FirstOrDefault(option => option.Service.Contains(shipMethod.ServiceCode.Split('-').First())); if (firstCarrierRate != null) { shippingPrice = firstCarrierRate.Rate; } } } catch (Exception ex) { return(Attempt <IShipmentRateQuote> .Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again."))); } return(Attempt <IShipmentRateQuote> .Succeed(new ShipmentRateQuote(shipment, shipMethod) { Rate = shippingPrice })); }
private List <IShippingRate> GetAllShippingRatesForShipment(IShipment shipment) { var rates = new List <IShippingRate>(); var hasErrors = false; try { var packagesToRate = OptimizePackages(shipment); if (packagesToRate.Count > 0) { rates = RatePackages(packagesToRate); } else { if (GlobalSettings.DiagnosticsMode) { _Logger.LogMessage("No Packaged to Rate for US Postal Service: Code 795"); } } } catch (Exception ex) { _Logger.LogException(ex); var m = new ShippingServiceMessage(); m.SetError("Exception", ex.Message + " | " + ex.StackTrace); _Messages.Add(m); } if (hasErrors) { rates = new List <IShippingRate>(); } return(rates); }
public void RecreateLineItemsBasedOnShipments(ICart cart, IEnumerable <CartItemViewModel> cartItems, IEnumerable <AddressModel> addresses) { var form = cart.GetFirstForm(); var items = cartItems .GroupBy(x => new { x.AddressId, x.Code, x.IsGift }) .Select(x => new { Code = x.Key.Code, AddressId = x.Key.AddressId, Quantity = x.Count(), IsGift = x.Key.IsGift }); foreach (var shipment in form.Shipments) { shipment.LineItems.Clear(); } form.Shipments.Clear(); foreach (var address in addresses) { IShipment shipment = _orderGroupFactory.CreateShipment(cart); form.Shipments.Add(shipment); shipment.ShippingAddress = _addressBookService.ConvertToAddress(cart, address); foreach (var item in items.Where(x => x.AddressId == address.AddressId)) { var lineItem = _orderGroupFactory.CreateLineItem(item.Code, cart); lineItem.IsGift = item.IsGift; lineItem.Quantity = item.Quantity; shipment.LineItems.Add(lineItem); } } ValidateCart(cart); }
public List <IShippingRate> RateShipment(IShipment shipment) { decimal totalValue = 0; foreach (var item in shipment.Items) { totalValue += item.BoxValue; } decimal amount = 0; if (Settings != null) { if (Settings.GetLevels() != null) { var level = RateTableLevel.FindRateForLevel(totalValue, Settings.GetLevels()); if (level != null && level.Rate >= 0) { amount = level.Rate; var percent = totalValue * (level.Percent / 100); amount += percent; } } } var r = new ShippingRate { ServiceId = Id, EstimatedCost = amount }; var rates = new List <IShippingRate> { r }; return(rates); }
/// <summary> /// The perform task. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// The <see cref="Attempt"/>. /// </returns> public override Attempt <IShipment> PerformTask(IShipment value) { var trackableItems = Order.InventoryTrackedItems().Where(x => KeysToShip.Contains(x.Key)).ToArray(); var variants = _productVariantService.GetByKeys(trackableItems.Select(x => x.ExtendedData.GetProductVariantKey())).ToArray(); if (variants.Any()) { foreach (var item in trackableItems) { var variant = variants.FirstOrDefault(x => x.Key == item.ExtendedData.GetProductVariantKey()); if (variant == null) { return(Attempt <IShipment> .Fail(new NullReferenceException("A ProductVariant reference in the order could not be found"))); } var inventory = variant.CatalogInventories.FirstOrDefault(x => x.CatalogKey == item.ExtendedData.GetWarehouseCatalogKey()); if (inventory == null) { return(Attempt <IShipment> .Fail(new NullReferenceException("An inventory record could not be found for an order line item"))); } inventory.Count -= item.Quantity; } _productVariantService.Save(variants); } // persist the shipment and update the line items if (value.ShipMethodKey == Guid.Empty) { value.ShipMethodKey = null; } _shipmentService.Save(value); return(Attempt <IShipment> .Succeed(value)); }
/// <summary> /// Gets a collection of <see cref="IReplaceablePattern"/> for the invoice /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <returns> /// The collection of replaceable patterns /// </returns> internal static IEnumerable <IReplaceablePattern> ReplaceablePatterns(this IShipment shipment) { // TODO localization needed on pricing and datetime var patterns = new List <IReplaceablePattern> { ReplaceablePattern.GetConfigurationReplaceablePattern("ShippedDate", shipment.ShippedDate.ToShortDateString()), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToOrganization", shipment.ToOrganization), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToName", shipment.ToName), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToAddress1", shipment.ToAddress1), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToAddress2", shipment.ToAddress2), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToLocality", shipment.ToLocality), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToRegion", shipment.ToRegion), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToPostalCode", shipment.ToPostalCode), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToCountryCode", shipment.ToCountryCode), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToEmail", shipment.Email), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToPhone", shipment.Phone), ReplaceablePattern.GetConfigurationReplaceablePattern("ShipToOrganization", shipment.ToOrganization), ReplaceablePattern.GetConfigurationReplaceablePattern("TrackingCode", shipment.TrackingCode) }; patterns.AddRange(shipment.LineItemReplaceablePatterns()); return(patterns); }
// Create rating request XML string private string RateRequest(IShipment shipment, UspsShipmentLineItemVisitor visitor) { // Changed weight logic per JeffreyABecker suggestions //int tOz = (int)Math.Ceiling(weight * 16.0m); //int packageWeightPounds = tOz / 16; //int packageWeightOunces = tOz % 16; var sb = new StringBuilder(); using (var writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true })) { writer.WriteStartDocument(); writer.WriteStartElement(shipment.ToCountryCode == "US" ? "RateV4Request" : "IntlRateV2Response"); writer.WriteAttributeString("USERID", _processorSettings.UspsUsername); writer.WriteAttributeString("PASSWORD", _processorSettings.UspsPassword); writer.WriteElementString("Revision", null); BuildRatePackage(writer, shipment, visitor); writer.WriteEndDocument(); } return("API=RateV4&XML=" + ApplicationXWwwFormUrlencodedEncode(sb.ToString())); }
/// <summary> /// The build. /// </summary> /// <param name="shipment"> /// The shipment. /// </param> /// <param name="contacts"> /// The collection of contact addresses /// </param> /// <returns> /// The <see cref="IShipmentResultNotifyModel"/>. /// </returns> public IShipmentResultNotifyModel Build(IShipment shipment, IEnumerable <string> contacts) { var notifyModel = new ShipmentResultNotifyModel() { Shipment = shipment, Contacts = contacts == null ? new string[] { } : contacts.ToArray() }; var item = shipment.Items.FirstOrDefault(x => !x.ContainerKey.Equals(Guid.Empty)); if (item != null) { var orderKey = item.ContainerKey; var order = _orderService.GetByKey(orderKey); if (order != null) { var invoice = _invoiceService.GetByKey(order.InvoiceKey); if (invoice != null) { notifyModel.Invoice = invoice; if (invoice.Items.Any()) { var currencyCode = invoice.Items.First() .ExtendedData.GetValue(Core.Constants.ExtendedDataKeys.CurrencyCode); var currency = _storeSettingService.GetCurrencyByCode(currencyCode); notifyModel.CurrencySymbol = currency != null ? currency.Symbol : "£"; } } } } return(notifyModel); }
public virtual ShippingRate GetRate(IShipment shipment, ShippingMethodInfoModel shippingMethodInfoModel, IMarket currentMarket) { var type = Type.GetType(shippingMethodInfoModel.ClassName); if (type == null) { throw new TypeInitializationException(shippingMethodInfoModel.ClassName, null); } string message = string.Empty; var shippingPlugin = _shippingPluginsAccessor().FirstOrDefault(s => s.GetType() == type); if (shippingPlugin != null) { return(shippingPlugin.GetRate(currentMarket, shippingMethodInfoModel.MethodId, shipment, ref message)); } var shippingGateway = _shippingGatewaysAccessor().FirstOrDefault(s => s.GetType() == type); if (shippingGateway != null) { return(shippingGateway.GetRate(currentMarket, shippingMethodInfoModel.MethodId, (Shipment)shipment, ref message)); } throw new InvalidOperationException($"There is no registered {nameof(IShippingPlugin)} or {nameof(IShippingGateway)} instance."); }
/// <summary> /// Returns a collection of all available <see cref="IShipmentRateQuote"/> for a given shipment /// </summary> /// <param name="shipment"><see cref="IShipmentRateQuote"/></param> /// <returns>A collection of <see cref="IShipmentRateQuote"/></returns> public virtual IEnumerable <IShipmentRateQuote> QuoteShippingGatewayMethodsForShipment(IShipment shipment) { var gatewayShipMethods = GetShippingGatewayMethodsForShipment(shipment); var ctrValues = new object[] { shipment, gatewayShipMethods.ToArray(), RuntimeCache }; var typeName = MerchelloConfiguration.Current.GetStrategyElement(Constants.StrategyTypeAlias.DefaultShipmentRateQuote).Type; var attempt = ActivatorHelper.CreateInstance <ShipmentRateQuoteStrategyBase>(typeName, ctrValues); if (!attempt.Success) { LogHelper.Error <ShippingGatewayProviderBase>("Failed to instantiate strategy " + typeName, attempt.Exception); throw attempt.Exception; } return(QuoteShippingGatewayMethodsForShipment(attempt.Result)); }
/// <summary> /// Returns a collection of available <see cref="IShippingGatewayMethod"/> associated by this provider for a given shipment /// </summary> /// <param name="shipment">the <see cref="IShipment"/></param> /// <returns>A collection of <see cref="IShippingGatewayMethod"/></returns> public virtual IEnumerable <IShippingGatewayMethod> GetShippingGatewayMethodsForShipment(IShipment shipment) { var attempt = shipment.GetValidatedShipCountry(GatewayProviderService); // quick validation of shipment if (!attempt.Success) { LogHelper.Error <ShippingGatewayProviderBase>("ShipMethods could not be determined for Shipment passed to GetAvailableShipMethodsForDestination method. Attempt message: " + attempt.Exception.Message, new ArgumentException("merchWarehouseCatalogKey")); return(new List <IShippingGatewayMethod>()); } var shipCountry = attempt.Result; var shipmethods = GetAllShippingGatewayMethods(shipCountry); var gatewayShipMethods = shipmethods as IShippingGatewayMethod[] ?? shipmethods.ToArray(); if (!gatewayShipMethods.Any()) { return(new List <IShippingGatewayMethod>()); } if (!shipCountry.HasProvinces) { return(gatewayShipMethods); } var available = new List <IShippingGatewayMethod>(); foreach (var gwshipmethod in gatewayShipMethods) { var province = gwshipmethod.ShipMethod.Provinces.FirstOrDefault(x => x.Code == shipment.ToRegion); if (province == null) { LogHelper.Debug <ShippingGatewayProviderBase>("Province code '" + shipment.ToRegion + "' was not found in ShipCountry with code : " + shipCountry.CountryCode); available.Add(gwshipmethod); } else { if (province.AllowShipping) { available.Add(gwshipmethod); } } } return(available); }
public AddToCartResult AddToCart(ICart cart, string code, string warehouseCode, decimal quantity) { var result = new AddToCartResult(); var contentLink = _referenceConverter.GetContentLink(code); var entryContent = _contentLoader.Get <EntryContentBase>(contentLink); if (entryContent is BundleContent) { foreach (var relation in _relationRepository.GetChildren <BundleEntry>(contentLink)) { var entry = _contentLoader.Get <EntryContentBase>(relation.Child); var recursiveResult = AddToCart(cart, entry.Code, warehouseCode, relation.Quantity ?? 1); if (recursiveResult.EntriesAddedToCart) { result.EntriesAddedToCart = true; } foreach (var message in recursiveResult.ValidationMessages) { result.ValidationMessages.Add(message); } } return(result); } ILineItem lineItem = null; if (!string.IsNullOrEmpty(warehouseCode)) { IShipment shipment = null; if (cart.GetFirstForm().Shipments.Count == 1 && string.IsNullOrEmpty(cart.GetFirstForm().Shipments.First().WarehouseCode)) { shipment = cart.GetFirstForm().Shipments.First(); shipment.WarehouseCode = warehouseCode; } else { shipment = cart.GetFirstForm().Shipments.FirstOrDefault(s => s.WarehouseCode.Equals(warehouseCode, StringComparison.CurrentCultureIgnoreCase)); } if (shipment == null) { shipment = cart.CreateShipment(_orderGroupFactory); shipment.WarehouseCode = warehouseCode; cart.AddShipment(shipment); } lineItem = shipment.LineItems.FirstOrDefault(x => x.Code == code && !x.IsGift); if (lineItem == null) { //this is just like AddNewLineItem but doesn't add there - adds to shipment instead lineItem = cart.CreateLineItem(code, _orderGroupFactory); lineItem.Quantity = quantity; lineItem.DisplayName = entryContent.DisplayName; //cart.AddLineItem(newLineItem, _orderGroupFactory); var price = _pricingService.GetPrice(code); if (price != null) { lineItem.PlacedPrice = price.UnitPrice.Amount; } cart.AddLineItem(shipment, lineItem); } else { cart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + quantity); } } else { lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code && !x.IsGift); if (lineItem == null) { lineItem = AddNewLineItem(cart, code, quantity, entryContent.DisplayName); } else { var shipment = cart.GetFirstShipment(); cart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + quantity); } } var validationIssues = ValidateCart(cart); AddValidationMessagesToResult(result, lineItem, validationIssues); return(result); }
public List <IShippingRate> RateShipment(IShipment shipment) { _Messages.Clear(); var result = new List <IShippingRate>(); var hasErrors = false; try { var optimizedPackages = OptimizeSingleGroup(shipment); if (optimizedPackages.Count > 0) { result = RatePackages(optimizedPackages); if (GlobalSettings.DiagnosticsMode) { foreach (var package in optimizedPackages) { _Logger.LogMessage("FEDEX SHIPMENT", string.Format("Source Address: {0}, {1}, {2}, {3}, {4} {5}", package.SourceAddress.Street, package.SourceAddress.Street2, package.SourceAddress.City, package.SourceAddress.RegionData.DisplayName, package.SourceAddress.CountryData.DisplayName, package.SourceAddress.PostalCode), EventLogSeverity.Information); _Logger.LogMessage("FEDEX SHIPMENT", string.Format("Destination Address: {0}, {1}, {2}, {3}, {4} {5}", package.DestinationAddress.Street, package.DestinationAddress.Street2, package.DestinationAddress.City, package.DestinationAddress.RegionData.DisplayName, package.DestinationAddress.CountryData.DisplayName, package.DestinationAddress.PostalCode), EventLogSeverity.Information); } } } else { if (GlobalSettings.DiagnosticsMode) { _Logger.LogMessage("No packages found to rate for FedEx"); } } } catch (Exception ex) { _Logger.LogException(ex); var m = new ShippingServiceMessage(); m.SetError("Exception", ex.Message + " | " + ex.StackTrace); _Messages.Add(m); } if (GlobalSettings.DiagnosticsMode) { foreach (var rate in result) { _Logger.LogMessage("OPTIMIZED FEDEX RATE", string.Format( "Service Id: {0}<br />Display Name: {1}<br />Service Codes:{2}<br />Estimated Cost:{3}", rate.ServiceId, rate.DisplayName, rate.ServiceCodes, rate.EstimatedCost), EventLogSeverity.Information); } } if (hasErrors) { result = new List <IShippingRate>(); } return(result); }
public override Attempt <IShipmentRateQuote> QuoteShipment(IShipment shipment) { decimal shippingPrice = 0M; try { var visitor = new UspsShipmentLineItemVisitor() { UseOnSalePriceIfOnSale = false }; shipment.Items.Accept(visitor); var http = new HttpRequestHandler(); var collection = GetCollectionFromCache(shipment); if (collection == null) { var rateXml = http.Post(RateRequest(shipment, visitor)); collection = UspsParseRates(rateXml, shipment); _runtimeCache.InsertCacheItem(MakeCacheKey(shipment), () => collection); } //if (collection.Any(option => option.Service.Contains(shipment.ShipmentName) && // option.Service.ToLower().Contains("medium") || option.Service.ToLower().Contains("large"))) //{ // var packageSize = GetPackageSize(length, height, width); // shippingPrice = packageSize == "REGULAR" ? collection.First(option => option.Service.Contains(shipment.ShipmentName) && // option.Service.ToLower().Contains("medium")).Rate : collection.First(option => option.Service.Contains(shipment.ShipmentName) && // option.Service.ToLower().Contains("large")).Rate; //} //else //{ // shippingPrice = collection.First(option => option.Service.Contains(shipment.ShipmentName)).Rate; //} var namedCollection = collection.Where(option => HttpUtility.HtmlDecode(option.Service).Contains(HttpUtility.HtmlDecode(_shipMethod.ServiceCode))); var deliveryOptions = namedCollection as IList <DeliveryOption> ?? namedCollection.ToList(); if (deliveryOptions.Any(o => o.Service.Contains("medium") || o.Service.Contains("large"))) { var packageSize = GetPackageSize(1, 1, 1); var firstOrDefault = deliveryOptions.FirstOrDefault(x => x.Service.Contains("medium")); if (firstOrDefault != null) { var deliveryOption = deliveryOptions.FirstOrDefault(x => x.Service.Contains("large")); if (deliveryOption != null) { shippingPrice = packageSize == "REGULAR" ? firstOrDefault.Rate : deliveryOption.Rate; } } } else { var firstOrDefault = deliveryOptions.FirstOrDefault(); if (firstOrDefault != null) { shippingPrice = firstOrDefault.Rate; } } } catch (Exception ex) { return(Attempt <IShipmentRateQuote> .Fail( new Exception("An error occured during your request : " + ex.Message + " Please contact your administrator or try again."))); } return(Attempt <IShipmentRateQuote> .Succeed(new ShipmentRateQuote(shipment, _shipMethod) { Rate = shippingPrice })); }
/// <summary>Process payment associated with shipment.</summary> /// <param name="orderGroup">The order group.</param> /// <param name="payment">The payment.</param> /// <param name="shipment">The shipment.</param> /// <returns><c>True</c> if process successful, otherwise <c>False</c>.</returns> public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment, IShipment shipment) { OrderGroup = orderGroup; _orderForm = orderGroup.GetFirstForm(); var result = ProcessPayment(payment, shipment); var message = result.Message; return(result.Status ? PaymentProcessingResult.CreateSuccessfulResult(message) : PaymentProcessingResult.CreateUnsuccessfulResult(message)); }
private List <IShippable> OptimizeSingleGroup(IShipment shipment) { const decimal MAXWEIGHT = 70; var result = new List <IShippable>(); var itemsToSplit = new List <IShippable>(); foreach (var item in shipment.Items) { if (IsOversized(item)) { result.Add(item.CloneShippable()); } else { itemsToSplit.Add(item); } } IShippable tempPackage = new Shippable(); foreach (var pak in itemsToSplit) { if (MAXWEIGHT - tempPackage.BoxWeight >= pak.BoxWeight) { // add to current box tempPackage.BoxWeight += pak.BoxWeight; tempPackage.QuantityOfItemsInBox += pak.QuantityOfItemsInBox; tempPackage.BoxValue += pak.BoxValue; } else { // Save the temp package if it has items if (tempPackage.BoxWeight > 0 || tempPackage.QuantityOfItemsInBox > 0) { result.Add(tempPackage.CloneShippable()); tempPackage = new Shippable(); } // create new box if (pak.BoxWeight > MAXWEIGHT) { //Loop to break up > maxWeight Packages var currentItemsInBox = pak.QuantityOfItemsInBox; var currentWeight = pak.BoxWeight; while (currentWeight > 0) { if (currentWeight > MAXWEIGHT) { var newP = pak.CloneShippable(); newP.BoxWeight = MAXWEIGHT; if (currentItemsInBox > 0) { currentItemsInBox -= 1; newP.QuantityOfItemsInBox = 1; } result.Add(newP); currentWeight = currentWeight - MAXWEIGHT; if (currentWeight < 0) { currentWeight = 0; } } else { // Create a new shippable box var newP = pak.CloneShippable(); newP.BoxWeight = currentWeight; if (currentItemsInBox > 0) { newP.QuantityOfItemsInBox = currentItemsInBox; } result.Add(newP); currentWeight = 0; } } } else { tempPackage = pak.CloneShippable(); } } } // Save the temp package if it has items if (tempPackage.BoxWeight > 0 || tempPackage.QuantityOfItemsInBox > 0) { result.Add(tempPackage.CloneShippable()); tempPackage = new Shippable(); } return(result); }
private static decimal RateSinglePackage(FedExGlobalServiceSettings globalSettings, ILogger logger, IShipment pak, ServiceType service, PackageType packaging, CarrierCodeType carCode, bool useNegotiatedRates) { var result = 0m; try { // Auth Header Data var req = new RateRequest { WebAuthenticationDetail = new WebAuthenticationDetail { UserCredential = new WebAuthenticationCredential { Key = globalSettings.UserKey, Password = globalSettings.UserPassword } } }; req.ClientDetail = new ClientDetail { AccountNumber = globalSettings.AccountNumber, MeterNumber = globalSettings.MeterNumber, IntegratorId = "Hotcakes" }; req.Version = new VersionId(); // Basic Transaction Data req.TransactionDetail = new TransactionDetail { CustomerTransactionId = Guid.NewGuid().ToString() }; req.ReturnTransitAndCommit = false; req.CarrierCodes = new CarrierCodeType[1] { carCode }; // Shipment Details req.RequestedShipment = new RequestedShipment { LabelSpecification = new LabelSpecification { ImageType = ShippingDocumentImageType.PDF, LabelFormatType = LabelFormatType.COMMON2D, CustomerSpecifiedDetail = new CustomerSpecifiedLabelDetail() }, RateRequestTypes = new[] { RateRequestType.LIST }, DropoffType = GetDropOffType(globalSettings.DefaultDropOffType), PackagingType = GetPackageType(packaging), TotalWeight = new Weight { Value = Math.Round(pak.Items.Sum(y => y.BoxWeight), 1), Units = pak.Items[0].BoxWeightType == Shipping.WeightType.Kilograms ? WeightUnits.KG : WeightUnits.LB }, PackageCount = pak.Items.Count.ToString(), RequestedPackageLineItems = new RequestedPackageLineItem[pak.Items.Count] }; /* * Possible values for RateRequestType include: LIST and ACCOUNT. * ACCOUNT will return negotiated rates, but LIST will return both regular and negotiated rates. * http://www.fedex.com/us/developer/product/WebServices/MyWebHelp_March2010/Content/WS_Developer_Guide/Rate_Services.htm */ //req.RequestedShipment.RateRequestTypes = new[] { RateRequestType.ACCOUNT }; // Uncomment these lines to get insured values passed in // //var totalValue = pak.Items.Sum(y => y.BoxValue); //req.RequestedShipment.TotalInsuredValue = new Money(); //req.RequestedShipment.TotalInsuredValue.Amount = totalValue; //req.RequestedShipment.TotalInsuredValue.Currency = "USD"; for (var i = 0; i < pak.Items.Count; i++) { req.RequestedShipment.RequestedPackageLineItems[i] = new RequestedPackageLineItem { GroupNumber = "1", GroupPackageCount = (i + 1).ToString(), Weight = new Weight { Value = pak.Items[i].BoxWeight, Units = pak.Items[i].BoxWeightType == Shipping.WeightType.Kilograms ? WeightUnits.KG : WeightUnits.LB } }; req.RequestedShipment.RequestedPackageLineItems[i].Dimensions = new Dimensions { Height = pak.Items[i].BoxHeight.ToString(), Length = pak.Items[i].BoxLength.ToString(), Width = pak.Items[i].BoxWidth.ToString(), Units = pak.Items[i].BoxLengthType == LengthType.Centimeters ? LinearUnits.CM : LinearUnits.IN }; } req.RequestedShipment.Recipient = new Party { Address = new FedExRateServices.Address { City = pak.DestinationAddress.City, CountryCode = GetCountryCode(pak.DestinationAddress.CountryData), PostalCode = pak.DestinationAddress.PostalCode } }; if (pak.DestinationAddress.CountryData.IsoCode == "US" || pak.DestinationAddress.CountryData.IsoCode == "CA") { req.RequestedShipment.Recipient.Address.StateOrProvinceCode = pak.DestinationAddress.RegionBvin; } else { req.RequestedShipment.Recipient.Address.StateOrProvinceCode = string.Empty; } req.RequestedShipment.Recipient.Address.StreetLines = new string[2] { pak.DestinationAddress.Street, pak.DestinationAddress.Street2 }; switch (service) { case ServiceType.GROUNDHOMEDELIVERY: req.RequestedShipment.Recipient.Address.Residential = true; req.RequestedShipment.Recipient.Address.ResidentialSpecified = true; break; case ServiceType.FEDEXGROUND: req.RequestedShipment.Recipient.Address.Residential = false; req.RequestedShipment.Recipient.Address.ResidentialSpecified = true; break; default: req.RequestedShipment.Recipient.Address.ResidentialSpecified = false; break; } req.RequestedShipment.Shipper = new Party { AccountNumber = globalSettings.AccountNumber, Address = new FedExRateServices.Address { City = pak.SourceAddress.City, CountryCode = GetCountryCode(pak.SourceAddress.CountryData), PostalCode = pak.SourceAddress.PostalCode, Residential = false } }; if (pak.SourceAddress.CountryData.IsoCode == "US" || // US or Canada pak.SourceAddress.CountryData.IsoCode == "CA") { req.RequestedShipment.Shipper.Address.StateOrProvinceCode = pak.SourceAddress.RegionBvin; } else { req.RequestedShipment.Shipper.Address.StateOrProvinceCode = string.Empty; } req.RequestedShipment.Shipper.Address.StreetLines = new string[2] { pak.SourceAddress.Street, pak.SourceAddress.Street2 }; var svc = new FedExRateServices.RateService { Url = globalSettings.UseDevelopmentServiceUrl ? FedExConstants.DevRateServiceUrl : FedExConstants.LiveRateServiceUrl }; var res = svc.getRates(req); if (res.HighestSeverity == NotificationSeverityType.ERROR || res.HighestSeverity == NotificationSeverityType.FAILURE) { if (globalSettings.DiagnosticsMode) { foreach (var err in res.Notifications) { logger.LogMessage("FEDEX", err.Message, EventLogSeverity.Debug); } } result = 0m; } else { result = 0m; var lookingForService = GetServiceType(service); var matchingResponse = res.RateReplyDetails.FirstOrDefault(y => y.ServiceType == lookingForService); if (matchingResponse != null) { if (useNegotiatedRates) { var matchedRate = matchingResponse.RatedShipmentDetails.FirstOrDefault( y => y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_ACCOUNT_PACKAGE || y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_ACCOUNT_SHIPMENT); if (matchedRate != null) { result = matchedRate.ShipmentRateDetail.TotalNetCharge.Amount; if (globalSettings.DiagnosticsMode) { logger.LogMessage("FEDEX SHIPMENT", "Negotiated rates were found and are currently being used.", EventLogSeverity.Information); } } else { matchedRate = matchingResponse.RatedShipmentDetails.FirstOrDefault( y => y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_LIST_PACKAGE || y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_LIST_SHIPMENT); result = matchedRate.ShipmentRateDetail.TotalNetCharge.Amount; if (globalSettings.DiagnosticsMode) { logger.LogMessage("FEDEX SHIPMENT", "No negotiated rates were found. Public rates are being shown. You should update your account information, or uncheck the ‘Use Negotiated Rates’ checkbox.", EventLogSeverity.Information); } else { logger.LogMessage("FEDEX SHIPMENT", "No negotiated rates were found.", EventLogSeverity.Information); } } } else { var matchedRate = matchingResponse.RatedShipmentDetails.FirstOrDefault( y => y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_LIST_PACKAGE || y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_LIST_SHIPMENT); if (matchedRate != null) { result = matchedRate.ShipmentRateDetail.TotalNetCharge.Amount; if ( matchingResponse.RatedShipmentDetails.Any( y => y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_ACCOUNT_PACKAGE || y.ShipmentRateDetail.RateType == ReturnedRateType.PAYOR_ACCOUNT_SHIPMENT)) { if (globalSettings.DiagnosticsMode) { logger.LogMessage("FEDEX SHIPMENT", "We also found negotiated rates for your account. You should consider checking the ‘Use Negotiated Rates’ checkbox.", EventLogSeverity.Information); } } } } } } } catch (Exception ex) { result = 0m; logger.LogException(ex); } return(result); }
public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment, IShipment shipment) { switch (payment.TransactionType) { case nameof(TransactionType.Authorization): return(VippsPaymentsService.Initiate(orderGroup, payment)); case nameof(TransactionType.Capture): return(VippsPaymentsService.Capture(orderGroup, payment)); case nameof(TransactionType.Sale): return(VippsPaymentsService.Initiate(orderGroup, payment)); case nameof(TransactionType.Void): return(VippsPaymentsService.Cancel(orderGroup, payment)); case nameof(TransactionType.Credit): return(VippsPaymentsService.Refund(orderGroup, payment)); default: throw new NotImplementedException(); } }
/// <summary> /// Generates a unique cache key for runtime caching of the <see cref="FedExShippingGatewayMethod"/> /// </summary> /// <param name="shipment"> The Shipment</param> /// <returns>The unique CacheKey string</returns> /// <remarks> /// /// CacheKey is assumed to be unique per customer and globally for CheckoutBase. Therefore this will NOT be unique if /// to different checkouts are happening for the same customer at the same time - we consider that an extreme edge case. /// /// </remarks> private string MakeCacheKey(IShipment shipment) { return(string.Format("merchello.shippingquotecollection.{0}.{1}.{2}", _shipMethod.ProviderKey, _gatewayProviderSettings.Key, shipment.VersionKey)); }
private IEnumerable <DeliveryOption> UspsParseRates(string response, IShipment package) { var optionCollection = new List <DeliveryOption>(); using (var reader = new XmlTextReader(new StringReader(response))) { while (reader.Read()) { if ((reader.Name == "Error") && (reader.NodeType == XmlNodeType.Element)) { string errorText = ""; while (reader.Read()) { if ((reader.Name == "HelpContext") && (reader.NodeType == XmlNodeType.Element)) { errorText += "USPS Help Context: " + reader.ReadString() + ", "; } if ((reader.Name == "Description") && (reader.NodeType == XmlNodeType.Element)) { errorText += "Error Desc: " + reader.ReadString(); } } throw new ProviderException("USPS Error returned: " + errorText); } if ((reader.Name == "Postage") && (reader.NodeType == XmlNodeType.Element)) { int serviceCode; Int32.TryParse(reader.GetAttribute("CLASSID"), out serviceCode); string postalRate = ""; String mailService = ""; reader.Read(); if (reader.Name == "MailService" && reader.NodeType == XmlNodeType.Element) { mailService = reader.ReadString(); reader.ReadEndElement(); } if (reader.Name == "Rate" && reader.NodeType == XmlNodeType.Element) { postalRate = reader.ReadString(); reader.ReadEndElement(); } IEnumerable <UspsDeliveryOption> options = GetDeliveryOptions(serviceCode, package); if (options == null) { continue; } decimal rate; if (!Decimal.TryParse(postalRate, out rate)) { continue; } if (!String.IsNullOrEmpty(_processorSettings.UspsAdditionalHandlingCharge)) { decimal additionalHandling; if (Decimal.TryParse(_processorSettings.UspsAdditionalHandlingCharge, out additionalHandling)) { rate += additionalHandling; } } // Weed out unavailable service rates //if (options.Any(option => option.Fits(weight, width, length, height))) //{ var deliveryOption = new DeliveryOption { Rate = rate, Service = mailService, ServiceCode = serviceCode.ToString() }; optionCollection.Add(deliveryOption); //} } } return(optionCollection); } }
public CaptureData CaptureOrder(string orderId, int?amount, string description, IOrderGroup orderGroup, IOrderForm orderForm, IPayment payment, IShipment shipment) { var order = _client.NewOrder(orderId); var capture = _client.NewCapture(order.Location); if (shipment == null) { throw new InvalidOperationException("Can't find correct shipment"); } var lines = shipment.LineItems.Select(l => FromLineItem(l, orderGroup.Currency)).ToList(); var shippingInfo = new ShippingInfo { // TODO shipping info ShippingMethod = "Own", TrackingNumber = shipment.ShipmentTrackingNumber }; var captureData = new CaptureData { CapturedAmount = amount, Description = description, OrderLines = lines, ShippingInfo = new List <ShippingInfo>() { shippingInfo } }; if (ServiceLocator.Current.TryGetExistingInstance(out ICaptureBuilder captureBuilder)) { captureData = captureBuilder.Build(captureData, orderGroup, orderForm, payment); } capture.Create(captureData); return(capture.Fetch()); }
// Gets all available rates regardless of settings private List <IShippingRate> GetAllShippingRatesForShipment(IShipment shipment) { var rates = new List <IShippingRate>(); var hasErrors = false; try { var sErrorMessage = string.Empty; var sErrorCode = string.Empty; var sURL = string.Concat(UPSLIVESERVER, "Rate"); // Build XML var settings = new UpsSettings { UserID = GlobalSettings.Username, Password = GlobalSettings.Password, ServerUrl = UPSLIVESERVER, License = GlobalSettings.LicenseNumber }; var sXML = string.Empty; sXML = XmlTools.BuildAccessKey(settings); sXML += "\n"; sXML += BuildUPSRateRequestForShipment(shipment, settings); var sResponse = string.Empty; sResponse = XmlTools.ReadHtmlPage_POST(sURL, sXML); XmlDocument xDoc; XmlNodeList NodeList; var sStatusCode = "-1"; try { xDoc = new XmlDocument(); xDoc.LoadXml(sResponse); if (xDoc.DocumentElement.Name == "RatingServiceSelectionResponse") { XmlNode n; var i = 0; XmlNode nTag; NodeList = xDoc.GetElementsByTagName("RatingServiceSelectionResponse"); n = NodeList.Item(0); for (i = 0; i <= n.ChildNodes.Count - 1; i++) { nTag = n.ChildNodes.Item(i); switch (nTag.Name) { case "Response": var iRes = 0; XmlNode nRes; for (iRes = 0; iRes <= nTag.ChildNodes.Count - 1; iRes++) { nRes = nTag.ChildNodes[iRes]; switch (nRes.Name) { case "ResponseStatusCode": sStatusCode = nRes.FirstChild.Value; break; case "ResponseStatusDescription": // Not Used break; case "Error": var iErr = 0; XmlNode nErr; for (iErr = 0; iErr <= nRes.ChildNodes.Count - 1; iErr++) { nErr = nRes.ChildNodes[iErr]; switch (nErr.Name) { case "ErrorCode": sErrorCode = nErr.FirstChild.Value; break; case "ErrorDescription": sErrorMessage = nErr.FirstChild.Value; break; case "ErrorSeverity": // Not Used break; } } break; } } break; case "RatedShipment": var iRated = 0; XmlNode nRated; var sPostage = string.Empty; var sCurrencyCode = string.Empty; var sCode = string.Empty; var sDescription = string.Empty; for (iRated = 0; iRated <= nTag.ChildNodes.Count - 1; iRated++) { nRated = nTag.ChildNodes[iRated]; switch (nRated.Name) { case "Service": var iServices = 0; XmlNode nServices; for (iServices = 0; iServices <= nRated.ChildNodes.Count - 1; iServices++) { nServices = nRated.ChildNodes[iServices]; switch (nServices.Name) { case "Code": sCode = nServices.FirstChild.Value; sDescription = DecodeUpsServiceCode(sCode); break; case "Description": sDescription = nServices.FirstChild.Value; break; } } break; case "TotalCharges": var iCharges = 0; XmlNode nCharges; for (iCharges = 0; iCharges <= nRated.ChildNodes.Count - 1; iCharges++) { nCharges = nRated.ChildNodes[iCharges]; switch (nCharges.Name) { case "MonetaryValue": sPostage = nCharges.FirstChild.Value; break; case "CurrencyCode": sCurrencyCode = nCharges.FirstChild.Value; break; } } break; } } var dRate = -1m; if (sPostage.Length > 0) { dRate = decimal.Parse(sPostage, NumberStyles.Currency, CultureInfo.InvariantCulture); } else { var nop = new ShippingServiceMessage(); nop.SetInfo(string.Empty, "No UPS Postage Found"); _Messages.Add(nop); hasErrors = true; } if (dRate >= 0) { var r = new ShippingRate { DisplayName = sDescription, EstimatedCost = dRate, ServiceCodes = sCode, ServiceId = Id }; rates.Add(r); } if (GlobalSettings.DiagnosticsMode) { var msg = new ShippingServiceMessage(); msg.SetDiagnostics("UPS Rates Found", string.Concat("StatusCode = ", sStatusCode, ", Postage = ", sPostage, ", Errors = ", sErrorMessage, ", Rate = ", dRate)); _Messages.Add(msg); } break; } } } else { hasErrors = true; sErrorMessage = "Couldn't find valid XML response from server."; } } catch (Exception Exx) { _Logger.LogException(Exx); var mex = new ShippingServiceMessage(); mex.SetError("Exception", string.Concat(Exx.Message, " | ", Exx.Source)); _Messages.Add(mex); return(rates); } if (sStatusCode != "1") { hasErrors = true; } } catch (Exception ex) { _Logger.LogException(ex); var m = new ShippingServiceMessage(); m.SetError("Exception", string.Concat(ex.Message, " | ", ex.StackTrace)); _Messages.Add(m); } if (hasErrors) { rates = new List <IShippingRate>(); } return(rates); }
private IEnumerable <ShippingMethodViewModel> CreateShippingMethodViewModels(IMarket market, Currency currency, IShipment shipment) { var shippingRates = GetShippingRates(market, currency, shipment); return(shippingRates.Select(r => new ShippingMethodViewModel { Id = r.Id, DisplayName = r.Name, Price = r.Money })); }
private string BuildUPSRateRequestForShipment(IShipment shipment, UpsSettings settings) { var sXML = string.Empty; var strWriter = new StringWriter(); var xw = new XmlTextWriter(strWriter); try { xw.Formatting = Formatting.Indented; xw.Indentation = 3; //-------------------------------------------- // Agreement Request xw.WriteStartElement("RatingServiceSelectionRequest"); //-------------------------------------------- // Request xw.WriteStartElement("Request"); //-------------------------------------------- // TransactionReference xw.WriteStartElement("TransactionReference"); xw.WriteElementString("CustomerContext", "Rate Request"); xw.WriteElementString("XpciVersion", "1.0001"); xw.WriteEndElement(); // End TransactionReference //-------------------------------------------- xw.WriteElementString("RequestOption", "Shop"); xw.WriteEndElement(); // End Request //-------------------------------------------- //-------------------------------------------- // Pickup Type if (GlobalSettings.PickUpType != PickupType.Unknown) { var pickupCode = ((int)GlobalSettings.PickUpType).ToString(); if (pickupCode.Trim().Length < 2) { pickupCode = "0" + pickupCode; } xw.WriteStartElement("PickupType"); xw.WriteElementString("Code", pickupCode); xw.WriteEndElement(); } // End Pickup Type //-------------------------------------------- //-------------------------------------------- // Shipment xw.WriteStartElement("Shipment"); // Shipper xw.WriteStartElement("Shipper"); xw.WriteStartElement("Address"); //Use City name for countries that don't have postal codes if (shipment.SourceAddress.PostalCode.Trim().Length > 0) { xw.WriteElementString("PostalCode", XmlTools.TrimToLength(shipment.SourceAddress.PostalCode.Trim(), 9)); } else { xw.WriteElementString("City", XmlTools.TrimToLength(shipment.SourceAddress.City.Trim(), 30)); } if (shipment.SourceAddress.RegionData != null) { xw.WriteElementString("StateProvinceCode", shipment.SourceAddress.RegionData.Abbreviation); } xw.WriteElementString("CountryCode", shipment.SourceAddress.CountryData.IsoCode); xw.WriteElementString("ShipperNumber", settings.License); xw.WriteEndElement(); xw.WriteEndElement(); // Ship To xw.WriteStartElement("ShipTo"); xw.WriteStartElement("Address"); if (shipment.DestinationAddress.PostalCode.Length > 0) { xw.WriteElementString("PostalCode", shipment.DestinationAddress.PostalCode); } else { if (shipment.DestinationAddress.City.Length > 0) { xw.WriteElementString("City", shipment.DestinationAddress.City); } } if (shipment.DestinationAddress.RegionData != null) { xw.WriteElementString("StateProvinceCode", shipment.DestinationAddress.RegionData.Abbreviation); } if (shipment.DestinationAddress.CountryData.Bvin.Length > 0) { xw.WriteElementString("CountryCode", shipment.DestinationAddress.CountryData.IsoCode); } if (GlobalSettings.ForceResidential) { xw.WriteElementString("ResidentialAddress", string.Empty); } xw.WriteEndElement(); xw.WriteEndElement(); var ignoreDimensions = GlobalSettings.IgnoreDimensions; // Optimize Packages for Weight var optimizedPackages = OptimizeSingleGroup(shipment); foreach (var p in optimizedPackages) { WriteSingleUPSPackage(ref xw, p, ignoreDimensions); } if (Settings.NegotiatedRates) { xw.WriteStartElement("RateInformation"); xw.WriteElementString("NegotiatedRatesIndicator", string.Empty); xw.WriteEndElement(); } xw.WriteEndElement(); // End Shipment //-------------------------------------------- xw.WriteEndElement(); // End Agreement Request //-------------------------------------------- xw.Flush(); xw.Close(); } catch (Exception ex) { _Logger.LogException(ex); } sXML = strWriter.GetStringBuilder().ToString(); return(sXML); }
private IEnumerable <ShippingRate> GetShippingRates(IMarket market, Currency currency, IShipment shipment) { var methods = _shippingManagerFacade.GetShippingMethodsByMarket(market.MarketId.Value, false); var currentLanguage = _languageService.GetCurrentLanguage().TwoLetterISOLanguageName; return(methods.Where(shippingMethodRow => currentLanguage.Equals(shippingMethodRow.LanguageId, StringComparison.OrdinalIgnoreCase) && string.Equals(currency, shippingMethodRow.Currency, StringComparison.OrdinalIgnoreCase)) .OrderBy(shippingMethodRow => shippingMethodRow.Ordering) .Select(shippingMethodRow => _shippingManagerFacade.GetRate(shipment, shippingMethodRow, market))); }
public List <IShippingRate> RateShipment(IShipment shipment) { _Messages.Clear(); return(GetUPSRatesForShipment(shipment)); }
protected IEnumerable <DeliveryOption> GetCollectionFromCache(IShipment shipment) { return(_runtimeCache.GetCacheItem(MakeCacheKey(shipment)) as IEnumerable <DeliveryOption>); }
public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message) { if (payment.TransactionType == TransactionType.Void.ToString()) { try { var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString(); if (!string.IsNullOrEmpty(orderId)) { KlarnaOrderService.CancelOrder(orderId); payment.Status = PaymentStatus.Processed.ToString(); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Order cancelled at Klarna"); return(true); } } catch (Exception ex) when(ex is ApiException || ex is WebException) { var exceptionMessage = GetExceptionMessage(ex); payment.Status = PaymentStatus.Failed.ToString(); message = exceptionMessage; AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}"); Logger.Error(exceptionMessage, ex); return(false); } } else if (Successor != null) { return(Successor.Process(payment, orderForm, orderGroup, shipment, ref message)); } return(false); }
/// <summary> /// Validate a shipment with a rule set. /// </summary> /// <param name="shipment"></param> /// <param name="rules"></param> /// <returns></returns> public bool Validate(IShipment shipment, CarrierRule rules) { Shipment = shipment; Visit(rules); return(IsValid); }