Commits

Michael Sumerano committed 3dcb91f

Fixing defects with shipment tracker. Requires public members be virtual.

Comments (0)

Files changed (4)

Nop.Plugin.Shipping.SeeSharpShipUsps/Description.txt

 Group: Shipping rate computation
 FriendlyName: SeeSharpShip USPS (US Postal Service)
 SystemName: Shipping.SeeSharpShipUsps
-Version: 2.00
+Version: 2.01
 SupportedVersions: 3.30
 Author: Michael J. Sumerano
 DisplayOrder: 1

Nop.Plugin.Shipping.SeeSharpShipUsps/Properties/AssemblyInfo.cs

 // You can specify all the values or you can default the Build and Revision Numbers 
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("2.0.0.*")]
-[assembly: AssemblyFileVersion("2.0.0.0")]
-[assembly: AssemblyInformationalVersion("2.0.0 nop-3.30")]
+[assembly: AssemblyVersion("2.0.1.*")]
+[assembly: AssemblyFileVersion("2.0.1.0")]
+[assembly: AssemblyInformationalVersion("2.0.1 nop-3.30")]

Nop.Plugin.Shipping.SeeSharpShipUsps/USPSComputationMethod.cs

 using Nop.Services.Configuration;
 using Nop.Services.Directory;
 using Nop.Services.Localization;
+using Nop.Services.Logging;
 using Nop.Services.Shipping;
 using Nop.Services.Shipping.Tracking;
 using SeeSharpShip.Extensions;
 
 namespace Nop.Plugin.Shipping.SeeSharpShipUsps {
     public class USPSComputationMethod : BasePlugin, IShippingRateComputationMethod {
+        private readonly ILogger _loggerService;
         private readonly IPriceCalculationService _priceCalculationService;
         private readonly IRateService _rateService;
         private readonly ISettingService _settingService;
-        private readonly ITrackService _trackService;
         private readonly USPSPackageSplitterService _uspsPackageSplitter;
         private readonly SeeSharpShipUspsSettings _uspsSettings;
         private readonly USPSVolumetricsService _uspsVolumetricsService;
 
-        public USPSComputationMethod(IMeasureService measureService, ISettingService settingService, IShippingService shippingService, SeeSharpShipUspsSettings uspsSettings,
-            IPriceCalculationService priceCalculationService, MeasureSettings measureSettings) {
+        public USPSComputationMethod(IMeasureService measureService, ISettingService settingService, IShippingService shippingService,
+            SeeSharpShipUspsSettings uspsSettings,
+            IPriceCalculationService priceCalculationService, MeasureSettings measureSettings, ILogger logger) {
             _uspsVolumetricsService = new USPSVolumetricsService(measureService, shippingService, measureSettings);
             _settingService = settingService;
             _uspsSettings = uspsSettings;
             _priceCalculationService = priceCalculationService;
+            _loggerService = logger;
             _uspsPackageSplitter = new USPSPackageSplitterService(measureService, shippingService, measureSettings);
 
-            // ReSharper disable CSharpWarnings::CS0618
+            // ReSharper disable once CSharpWarnings::CS0618
             _rateService = string.IsNullOrWhiteSpace(_uspsSettings.Url) ? new RateService() : new RateService(_uspsSettings.Url, new PostRequest());
-            _trackService = string.IsNullOrWhiteSpace(_uspsSettings.Url) ? new TrackService() : new TrackService(_uspsSettings.Url, new PostRequest());
-            // ReSharper restore CSharpWarnings::CS0618
         }
 
         #region IShippingRateComputationMethod Members
         ///     Gets a shipment tracker
         /// </summary>
         public IShipmentTracker ShipmentTracker {
-            get { return new USPSShipmentTracker(_trackService, _uspsSettings.Url); }
+            get { return new USPSShipmentTracker(_loggerService, _uspsSettings); }
         }
 
         #endregion

Nop.Plugin.Shipping.SeeSharpShipUsps/USPSShipmentTracker.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Text.RegularExpressions;
 using System.Web.Caching;
+using Nop.Services.Logging;
 using Nop.Services.Shipping.Tracking;
 using SeeSharpShip.Models.Usps;
 using SeeSharpShip.Services.Usps;
 
 namespace Nop.Plugin.Shipping.SeeSharpShipUsps {
     public class USPSShipmentTracker : IShipmentTracker {
+        private readonly Cache _cache = new Cache();
+        private readonly ILogger _logger;
         private readonly ITrackService _trackService;
-        private readonly string _userId;
-        private readonly Cache _cache = new Cache();
+        private readonly SeeSharpShipUspsSettings _uspsSettings;
 
-        public USPSShipmentTracker(ITrackService trackService, string userId) {
-            _trackService = trackService;
-            _userId = userId;
+        public USPSShipmentTracker(ILogger logger, SeeSharpShipUspsSettings uspsSettings) {
+            _logger = logger;
+            _uspsSettings = uspsSettings;
+
+            // ReSharper disable once CSharpWarnings::CS0618
+            _trackService = string.IsNullOrWhiteSpace(uspsSettings.Url) ? new TrackService() : new TrackService(uspsSettings.Url, new PostRequest());
         }
 
-        public bool IsMatch(string trackingNumber) {
-            return GetShipmentEvents(trackingNumber) != null;
+        #region IShipmentTracker Members
+
+        /// <summary>
+        ///     Matches the following formats:
+        ///     ^(7\d{19})$
+        ///     ^((92|93|94)\d{20})$
+        ///     ^(82\d{8})$
+        ///     ^((M|EC|EA|CP|RA)\d{9}US)$
+        ///     ^((14|23|03)\d{18})$
+        /// </summary>
+        /// <param name="trackingNumber"></param>
+        /// <returns></returns>
+        public virtual bool IsMatch(string trackingNumber) {
+            if (string.IsNullOrWhiteSpace(trackingNumber)) {
+                return false;
+            }
+
+            var patterns = new[] {
+                @"^(7\d{19})$",
+                @"^((92|93|94)\d{20})$",
+                @"^(82\d{8})$",
+                @"^((M|EC|EA|CP|RA)\d{9}US)$",
+                @"^((14|23|03)\d{18})$"
+            };
+
+            return patterns.Any(pattern => Regex.IsMatch(trackingNumber, pattern, RegexOptions.IgnoreCase));
         }
 
-        public string GetUrl(string trackingNumber) {
+        public virtual string GetUrl(string trackingNumber) {
             return string.Format("https://tools.usps.com/go/TrackConfirmAction.action?tLabels={0}", trackingNumber);
         }
 
-        public IList<ShipmentStatusEvent> GetShipmentEvents(string trackingNumber) {
+        public virtual IList<ShipmentStatusEvent> GetShipmentEvents(string trackingNumber) {
+            var events = new List<ShipmentStatusEvent>();
+
             if (string.IsNullOrWhiteSpace(trackingNumber)) {
-                throw new ArgumentNullException("trackingNumber", "Tracking number cannot be null or empty");
-            }
-
-            var events = _cache.Get(trackingNumber) as List<ShipmentStatusEvent>;
-            if (events != null) {
+                _logger.Information("Tracking number cannot be null or empty");
                 return events;
             }
 
-            events = new List<ShipmentStatusEvent>();
+            try {
+                var request = new TrackRequest {
+                    TrackId = new TrackId {Id = trackingNumber},
+                    UserId = _uspsSettings.Username
+                };
+                TrackResponse response = _trackService.Get(request);
+                TrackInfo info = response.TrackInfo.FirstOrDefault();
 
-            var request = new TrackRequest {
-                TrackId = new TrackId {Id = trackingNumber},
-                UserId = _userId
-            };
-            TrackResponse response = _trackService.Get(request);
-
-            if (!response.TrackInfo.Any()) {
-                return new[] {new ShipmentStatusEvent {EventName = "NOT FOUND"}};
+                if (info != null) {
+                    events.AddRange(info.TrackDetail.Select(e => new ShipmentStatusEvent { EventName = e.Value }));
+                }
+            } catch (Exception e) {
+                _logger.Error(string.Format("Error while getting USPS shipment tracking info - {0}", trackingNumber), e);
             }
-            TrackInfo info = response.TrackInfo.First();
-
-            events.AddRange(info.TrackDetail.Select(e => new ShipmentStatusEvent {EventName = e.Value}));
-
-            _cache.Add(trackingNumber, events, null, DateTime.Now.AddHours(1), TimeSpan.Zero, CacheItemPriority.Default, null);
 
             return events;
         }
+
+        #endregion
     }
-}
+}