-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCanadaPostComputationMethod.cs
More file actions
453 lines (404 loc) · 19.7 KB
/
CanadaPostComputationMethod.cs
File metadata and controls
453 lines (404 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Web.Routing;
using System.Xml;
using System.Xml.Linq;
using Grand.Core;
using Grand.Core.Domain.Shipping;
using Grand.Core.Plugins;
using Grand.Plugin.Shipping.CanadaPost.Domain;
using Grand.Services.Configuration;
using Grand.Services.Directory;
using Grand.Services.Localization;
using Grand.Services.Shipping;
using Grand.Services.Shipping.Tracking;
using Grand.Core.Infrastructure;
namespace Grand.Plugin.Shipping.CanadaPost
{
/// <summary>
/// Canada post computation method
/// </summary>
public class CanadaPostComputationMethod : BasePlugin, IShippingRateComputationMethod
{
#region Fields
private readonly IMeasureService _measureService;
private readonly IShippingService _shippingService;
private readonly ISettingService _settingService;
private readonly CanadaPostSettings _canadaPostSettings;
private readonly IWorkContext _workContext;
#endregion
#region Ctor
public CanadaPostComputationMethod(IMeasureService measureService,
IShippingService shippingService, ISettingService settingService,
CanadaPostSettings canadaPostSettings, IWorkContext workContext)
{
this._measureService = measureService;
this._shippingService = shippingService;
this._settingService = settingService;
this._canadaPostSettings = canadaPostSettings;
this._workContext = workContext;
}
#endregion
#region Utilities
/// <summary>
/// Sends the message to CanadaPost.
/// </summary>
/// <param name="eParcelMessage">The e parcel message.</param>
/// <returns></returns>
private string SendMessage(string eParcelMessage)
{
using (var socCanadaPost = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socCanadaPost.ReceiveTimeout = 12000;
var remoteEndPoint = new IPEndPoint(Dns.GetHostAddresses(_canadaPostSettings.Url)[0], _canadaPostSettings.Port);
socCanadaPost.Connect(remoteEndPoint);
byte[] data = System.Text.Encoding.ASCII.GetBytes(eParcelMessage);
socCanadaPost.Send(data);
string resp = String.Empty;
var buffer = new byte[8192];
while (!resp.Contains("<!--END_OF_EPARCEL-->"))
{
int iRx;
try
{
iRx = socCanadaPost.Receive(buffer, 0, 8192, SocketFlags.None);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.TimedOut)
break;
throw e;
}
if (iRx > 0)
{
resp += new string((System.Text.Encoding.UTF8.GetChars(buffer, 0, iRx)));
}
}
return resp;
}
}
/// <summary>
/// Handles the result.
/// </summary>
/// <param name="canadaPostResponse">The response from Canada Post.</param>
/// /// <param name="language">The language.</param>
/// <returns></returns>
private RequestResult HandleResult(string canadaPostResponse, CanadaPostLanguageEnum language)
{
var result = new RequestResult();
if (String.IsNullOrEmpty(canadaPostResponse))
{
result.IsError = true;
result.StatusCode = 0;
result.StatusMessage = "Unable to connect to Canada Post.";
return result;
}
var doc = new XmlDocument();
doc.LoadXml(canadaPostResponse);
XElement resultRates = XElement.Load(new StringReader(canadaPostResponse));
IEnumerable<XElement> query;
// if we have any errors
if (doc.GetElementsByTagName("error").Count > 0)
{
// query using LINQ the "error" node in the XML
query = from errors in resultRates.Elements("error")
select errors;
XElement error = query.FirstOrDefault();
if (error != null)
{
// set the status code information of the request
result.StatusCode = Convert.ToInt32(error.Element("statusCode").Value);
result.StatusMessage = error.Element("statusMessage").Value;
result.IsError = true;
}
}
else
{
// query using LINQ the "ratesAndServicesResponse" node in the XML because it contains
// the actual status code information
query = from response in resultRates.Elements("ratesAndServicesResponse")
select response;
XElement info = query.FirstOrDefault();
// if we have informations
if (info != null)
{
// set the status code information of the request
result.StatusCode = Convert.ToInt32(info.Element("statusCode").Value);
result.StatusMessage = info.Element("statusMessage").Value;
// query using LINQ all the returned "product" nodes in the XML
query = from prod in resultRates.Elements("ratesAndServicesResponse").Elements("product")
select prod;
foreach (XElement product in query)
{
// set the information related to this available rate
var rate = new DeliveryRate();
rate.Sequence = Convert.ToInt32(product.Attribute("sequence").Value);
rate.Name = product.Element("name").Value;
rate.Amount = Convert.ToDecimal(product.Element("rate").Value, new CultureInfo("en-US", false).NumberFormat);
DateTime shipDate;
if (DateTime.TryParse(product.Element("shippingDate").Value, out shipDate))
{
rate.ShippingDate = shipDate;
}
DateTime delivDate;
if (DateTime.TryParse(product.Element("deliveryDate").Value, out delivDate))
{
CultureInfo culture;
if (language == CanadaPostLanguageEnum.French)
{
culture = new CultureInfo("fr-ca");
rate.DeliveryDate = delivDate.ToString("d MMMM yyyy", culture);
}
else
{
culture = new CultureInfo("en-us");
rate.DeliveryDate = delivDate.ToString("MMMM d, yyyy", culture);
}
}
else
{
//rate.DeliveryDate = product.Element("deliveryDate").Value;
rate.DeliveryDate = string.Empty;
}
result.AvailableRates.Add(rate);
}
query = from packing in resultRates.Elements("ratesAndServicesResponse").Elements("packing").Elements("box")
select packing;
foreach (XElement packing in query)
{
var box = new BoxDetail();
box.Name = packing.Element("name").Value;
box.Weight = Convert.ToDouble(packing.Element("weight").Value, new CultureInfo("en-US", false).NumberFormat);
box.ExpediterWeight = Convert.ToDouble(packing.Element("expediterWeight").Value, new CultureInfo("en-US", false).NumberFormat);
box.Length = Convert.ToDouble(packing.Element("length").Value, new CultureInfo("en-US", false).NumberFormat);
box.Width = Convert.ToDouble(packing.Element("width").Value, new CultureInfo("en-US", false).NumberFormat);
box.Height = Convert.ToDouble(packing.Element("height").Value, new CultureInfo("en-US", false).NumberFormat);
box.Quantity = Convert.ToInt32(packing.Element("packedItem").Element("quantity").Value);
// add the box to the result
result.Boxes.Add(box);
}
}
}
return result;
}
/// <summary>
/// Gets the shipping options.
/// </summary>
/// <param name="profile">The profile.</param>
/// <param name="destination">The destination.</param>
/// <param name="items">The items.</param>
/// <param name="language">The language.</param>
/// <returns></returns>
private RequestResult GetShippingOptionsInternal(Profile profile, Destination destination, List<Item> items, CanadaPostLanguageEnum language)
{
var parcel = new eParcelBuilder(profile, destination, items, language);
string result = SendMessage(parcel.GetMessage(true));
return HandleResult(result, language);
}
private List<Item> CreateItems(GetShippingOptionRequest getShippingOptionRequest)
{
var result = new List<Item>();
var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword("kg");
if (usedMeasureWeight == null)
throw new NopException("CanadaPost shipping service. Could not load \"kg\" measure weight");
var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword("meters");
if (usedMeasureDimension == null)
throw new NopException("CanadaPost shipping service. Could not load \"meter(s)\" measure dimension");
foreach (var packageItem in getShippingOptionRequest.Items)
{
var sci = packageItem.ShoppingCartItem;
var qty = packageItem.GetQuantity();
var item = new Item();
item.Quantity = qty;
//Canada Post uses kg(s)
decimal unitWeight = _shippingService.GetShoppingCartItemWeight(sci);
item.Weight = _measureService.ConvertFromPrimaryMeasureWeight(unitWeight, usedMeasureWeight);
item.Weight = Math.Round(item.Weight, 2);
if (item.Weight == decimal.Zero)
item.Weight = 0.01M;
//get dimensions for qty 1
decimal lengthTmp, widthTmp, heightTmp;
_shippingService.GetDimensions(new List<GetShippingOptionRequest.PackageItem>
{
new GetShippingOptionRequest.PackageItem(sci, 1)
}, out widthTmp, out lengthTmp, out heightTmp);
//Canada Post uses centimeters
item.Length = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(lengthTmp, usedMeasureDimension) * 100));
if (item.Length == decimal.Zero)
item.Length = 1;
item.Width = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(widthTmp, usedMeasureDimension) * 100));
if (item.Width == decimal.Zero)
item.Width = 1;
item.Height = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(heightTmp, usedMeasureDimension) * 100));
if (item.Height == decimal.Zero)
item.Height = 1;
result.Add(item);
}
return result;
}
#endregion
#region Methods
/// <summary>
/// Gets available shipping options
/// </summary>
/// <param name="getShippingOptionRequest">A request for getting shipping options</param>
/// <returns>Represents a response of getting shipping rate options</returns>
public GetShippingOptionResponse GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest)
{
if (getShippingOptionRequest == null)
throw new ArgumentNullException("getShippingOptionRequest");
var response = new GetShippingOptionResponse();
if (getShippingOptionRequest.Items == null)
{
response.AddError("No shipment items");
return response;
}
if (getShippingOptionRequest.ShippingAddress == null)
{
response.AddError("Shipping address is not set");
return response;
}
if (String.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId))
{
response.AddError("Shipping country is not set");
return response;
}
if (String.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.StateProvinceId))
{
response.AddError("Shipping state is not set");
return response;
}
try
{
var profile = new Profile();
profile.MerchantId = _canadaPostSettings.CustomerId;
var destination = new Destination();
destination.City = getShippingOptionRequest.ShippingAddress.City;
var state = EngineContext.Current.Resolve<IStateProvinceService>().GetStateProvinceById(getShippingOptionRequest.ShippingAddress.StateProvinceId);
destination.StateOrProvince = state.Abbreviation;
var country = EngineContext.Current.Resolve<ICountryService>().GetCountryById(getShippingOptionRequest.ShippingAddress.CountryId);
destination.Country = country.TwoLetterIsoCode;
destination.PostalCode = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
var items = CreateItems(getShippingOptionRequest);
var lang = CanadaPostLanguageEnum.English;
if (_workContext.WorkingLanguage.LanguageCulture.StartsWith("fr", StringComparison.InvariantCultureIgnoreCase))
lang = CanadaPostLanguageEnum.French;
var requestResult = GetShippingOptionsInternal(profile, destination, items, lang);
if (requestResult.IsError)
{
response.AddError(requestResult.StatusMessage);
}
else
{
foreach (var dr in requestResult.AvailableRates)
{
var so = new ShippingOption();
so.Name = dr.Name;
if (!string.IsNullOrEmpty(dr.DeliveryDate))
so.Name += string.Format(" - {0}", dr.DeliveryDate);
so.Rate = dr.Amount;
response.ShippingOptions.Add(so);
}
}
foreach (var shippingOption in response.ShippingOptions)
{
if (!shippingOption.Name.StartsWith("canada post", StringComparison.InvariantCultureIgnoreCase))
shippingOption.Name = string.Format("Canada Post {0}", shippingOption.Name);
}
}
catch (Exception e)
{
response.AddError(e.Message);
}
return response;
}
/// <summary>
/// Gets fixed shipping rate (if shipping rate computation method allows it and the rate can be calculated before checkout).
/// </summary>
/// <param name="getShippingOptionRequest">A request for getting shipping options</param>
/// <returns>Fixed shipping rate; or null in case there's no fixed shipping rate</returns>
public decimal? GetFixedRate(GetShippingOptionRequest getShippingOptionRequest)
{
return null;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "ShippingCanadaPost";
routeValues = new RouteValueDictionary { { "Namespaces", "Grand.Plugin.Shipping.CanadaPost.Controllers" }, { "area", null } };
}
/// <summary>
/// Install plugin
/// </summary>
public override void Install()
{
//settings
var settings = new CanadaPostSettings
{
Url = "sellonline.canadapost.ca",
Port = 30000,
//use "CPC_DEMO_XML" merchant ID for testing
CustomerId = "CPC_DEMO_XML"
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Url", "Canada Post URL");
this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Url.Hint", "Specify Canada Post URL.");
this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Port", "Canada Post Port");
this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Port.Hint", "Specify Canada Post port.");
this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.CustomerId", "Canada Post Customer ID");
this.AddOrUpdatePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.CustomerId.Hint", "Specify Canada Post customer identifier.");
base.Install();
}
/// <summary>
/// Uninstall plugin
/// </summary>
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<CanadaPostSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Url");
this.DeletePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Url.Hint");
this.DeletePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Port");
this.DeletePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.Port.Hint");
this.DeletePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.CustomerId");
this.DeletePluginLocaleResource("Plugins.Shipping.CanadaPost.Fields.CustomerId.Hint");
base.Uninstall();
}
#endregion
#region Properties
/// <summary>
/// Gets a shipping rate computation method type
/// </summary>
public ShippingRateComputationMethodType ShippingRateComputationMethodType
{
get
{
return ShippingRateComputationMethodType.Realtime;
}
}
/// <summary>
/// Gets a shipment tracker
/// </summary>
public IShipmentTracker ShipmentTracker
{
get
{
return new CanadaPostShipmentTracker();
}
}
#endregion
}
}