-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderHandler.cs
More file actions
1378 lines (1225 loc) · 63.6 KB
/
OrderHandler.cs
File metadata and controls
1378 lines (1225 loc) · 63.6 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Dynamicweb.Core;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.Cache;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.Configuration;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.Connectors;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.Discounts;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.Extensions;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.Logging;
using Dynamicweb.Ecommerce.DynamicwebLiveIntegration.XmlGenerators;
using Dynamicweb.Ecommerce.Orders;
using Dynamicweb.Ecommerce.Prices;
using Dynamicweb.Extensibility.Notifications;
using Dynamicweb.Security.UserManagement;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
namespace Dynamicweb.Ecommerce.DynamicwebLiveIntegration
{
/// <summary>
/// Handler class to handle all interaction with the ERP.
/// </summary>
public static class OrderHandler
{
private static readonly string OrderErpCallFailed = "OrderHandler.ErpCallFailed";
private static readonly string OrderErpCallCancelled = "OrderHandler.ErpCallCancelled";
private static readonly string OrderErpCallSucceed = "OrderHandler.ErpCallSucceed";
/// <summary>
/// The order XML log folder
/// </summary>
private static readonly string OrderXmlLogFolder = "/Files/System/Log/LiveIntegration/OrderXml";
/// <summary>
/// Gets the cache level for order information.
/// </summary>
/// <value>The order cache level.</value>
private static ResponseCacheLevel GetOrderCacheLevel(Settings settings)
{
string cacheLevelString = settings.OrderCacheLevel;
return Helpers.GetEnumValueFromString(cacheLevelString, ResponseCacheLevel.Page);
}
/// <summary>
/// Updates an order in the ERP.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="order">The order that must be synced with the ERP.</param>
/// <param name="liveIntegrationSubmitType">Determines the origin of this submit such.</param>
/// <param name="successOrderStateId">The order state that is applied to the order when it integrates successfully.</param>
/// <param name="failedOrderStateId">The order state that is applied to the order when an error occurred during the integration.</param>
/// <returns>Returns null if no communication has made, or bool if order has been updated successfully or not.</returns>
public static bool? UpdateOrder(Settings settings, Order order, SubmitType liveIntegrationSubmitType, string successOrderStateId = null, string failedOrderStateId = null)
{
Diagnostics.ExecutionTable.Current.Add("DynamicwebLiveIntegration.OrderHandler.UpdateOrder START");
if (!IsOrderUpdateAllowed(settings, order, liveIntegrationSubmitType))
{
Diagnostics.ExecutionTable.Current.Add("DynamicwebLiveIntegration.OrderHandler.UpdateOrder END");
return null;
}
var orderId = order.Id ?? "ID is null";
bool executingContextIsBackEnd = LiveContext.IsBackEnd(liveIntegrationSubmitType);
var logger = new Logger(settings);
logger.Log(ErrorLevel.DebugInfo, $"Updating order with ID: {orderId}. Complete: {order.Complete}. Order submitted from the backend: {executingContextIsBackEnd}");
// use current user if is not backend running or if the cart is Anonymous
var user = UserManagementServices.Users.GetUserById(order.CustomerAccessUserId);
/* create order: if it is false, you will get a calculate order from the ERP with the total prices */
/* if it is true, then a new order will be created in the ERP */
bool createOrder = order.Complete;
/* Create order if the request is from Backend */
if (executingContextIsBackEnd && !createOrder)
{
createOrder = true;
}
if (!settings.EnableCartCommunicationForAnonymousUsers && user == null)
{
logger.Log(ErrorLevel.DebugInfo, $"No user is currently logged in. Anonymous user cart is not allowed. Order = {orderId}");
Diagnostics.ExecutionTable.Current.Add("DynamicwebLiveIntegration.OrderHandler.UpdateOrder END");
return null;
}
// default states
successOrderStateId ??= settings.OrderStateAfterExportSucceeded;
failedOrderStateId ??= settings.OrderStateAfterExportFailed;
var xmlGeneratorSettings = new OrderXmlGeneratorSettings
{
AddOrderLineFieldsToRequest = settings.AddOrderLineFieldsToRequest,
AddOrderFieldsToRequest = settings.AddOrderFieldsToRequest,
CreateOrder = createOrder,
LiveIntegrationSubmitType = liveIntegrationSubmitType,
ReferenceName = "OrdersPut",
ErpControlsDiscount = settings.ErpControlsDiscount,
ErpControlsShipping = settings.ErpControlsShipping,
ErpShippingItemKey = settings.ErpShippingItemKey,
ErpShippingItemType = settings.ErpShippingItemType,
CalculateOrderUsingProductNumber = settings.CalculateOrderUsingProductNumber
};
var requestXml = new OrderXmlGenerator().GenerateOrderXml(settings, order, xmlGeneratorSettings, logger);
xmlGeneratorSettings.GenerateXmlForHash = true;
var requestXmlForHash = new OrderXmlGenerator().GenerateOrderXml(settings, order, xmlGeneratorSettings, logger);
if (createOrder && settings.SaveCopyOfOrderXml && (liveIntegrationSubmitType == SubmitType.LiveOrderOrCart || liveIntegrationSubmitType == SubmitType.WebApi))
{
SaveCopyOfXml(order.Id, requestXml, logger);
}
// calculate current hash
string currentHash = Helpers.CalculateHash(requestXmlForHash);
// get last hash
string lastHash = GetLastOrderHash(settings);
if (liveIntegrationSubmitType != SubmitType.ScheduledTask && liveIntegrationSubmitType != SubmitType.CaptureTask &&
liveIntegrationSubmitType != SubmitType.ManualSubmit &&
!string.IsNullOrEmpty(lastHash) && lastHash == currentHash)
{
// no changes to order
Diagnostics.ExecutionTable.Current.Add("DynamicwebLiveIntegration.OrderHandler.UpdateOrder END");
return true;
}
// save this hash for next calls
SaveOrderHash(settings, currentHash);
XmlDocument response = GetResponse(settings, requestXml, order, createOrder, logger, out bool? requestCancelled, liveIntegrationSubmitType);
if (response != null && !string.IsNullOrWhiteSpace(response.InnerXml))
{
bool processResponseResult = ProcessResponse(settings, response, order, createOrder, successOrderStateId, failedOrderStateId, logger);
Diagnostics.ExecutionTable.Current.Add("DynamicwebLiveIntegration.OrderHandler.UpdateOrder END");
return processResponseResult;
}
else
{
// error occurred
if (createOrder && (!requestCancelled.HasValue || !requestCancelled.Value))
{
HandleIntegrationFailure(settings, order, failedOrderStateId, orderId, null, logger);
}
Diagnostics.ExecutionTable.Current.Add("DynamicwebLiveIntegration.OrderHandler.UpdateOrder END");
return false;
}
}
/// <summary>
/// Builds the XML copy path.
/// </summary>
/// <param name="orderId">The order identifier.</param>
/// <param name="folder">The folder.</param>
/// <returns>System.String.</returns>
public static string BuildXmlCopyPath(string orderId, string folder)
{
return Path.Combine(folder, $"{orderId}.xml");
}
public static string GetLogFolderForXmlCopies(DateTime? date = null)
{
return GetLogFolderForXmlCopies(null, date);
}
/// <summary>
/// Gets the log folder for XML copies.
/// </summary>
/// <param name="date">The date.</param>
/// <returns>System.String.</returns>
public static string GetLogFolderForXmlCopies(Logger logger, DateTime? date = null)
{
if (!date.HasValue)
{
date = DateTime.Now;
}
try
{
var logFolder = $"{OrderXmlLogFolder}/{date.Value.Year}/{date.Value:MM}";
var logFolderPhysical = SystemInformation.MapPath(logFolder);
if (!Directory.Exists(logFolderPhysical))
{
Directory.CreateDirectory(logFolderPhysical);
}
return logFolderPhysical;
}
catch (Exception e)
{
logger?.Log(ErrorLevel.Error, "Error creating log folder for order XML files: " + e.Message);
return string.Empty;
}
}
/// <summary>
/// Assigns the integration order identifier.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="orderNode">The order node.</param>
private static void AssignIntegrationOrderId(Order order, XmlNode orderNode)
{
// search for IntegrationOrderID field in response otherwise use the OrderIntegrationOrderID
XmlNode integrationIdNode = orderNode.SelectSingleNode("column [@columnName='OrderIntegrationOrderId']");
// otherwise use the traditional OrderID
if (string.IsNullOrEmpty(integrationIdNode?.InnerText))
{
integrationIdNode = orderNode.SelectSingleNode("column [@columnName='OrderId']");
}
if (!string.IsNullOrWhiteSpace(integrationIdNode?.InnerText))
{
order.IntegrationOrderId = integrationIdNode.InnerText;
order.IsExported = true;
}
}
/// <summary>
/// Creates the order line.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="productNumber">The product identifier.</param>
/// <returns>OrderLine.</returns>
private static OrderLine CreateOrderLine(Order order, string productNumber, Logger logger)
{
ArgumentNullException.ThrowIfNull(order);
if (string.IsNullOrEmpty(productNumber))
{
throw new ArgumentNullException(nameof(productNumber));
}
var product = Services.Products.GetProductByNumber(productNumber, order.LanguageId);
if (product is null && !string.Equals(order.LanguageId, Services.Languages.GetDefaultLanguageId(), StringComparison.OrdinalIgnoreCase))
{
product = Services.Products.GetProductByNumber(productNumber, Services.Languages.GetDefaultLanguageId());
}
if (product == null)
{
logger.Log(ErrorLevel.Error, $"Cannot CreateOrderLine: No product found with ProductNumber = '{productNumber}' Order = {order.Id}");
return null;
}
OrderLine orderLine = new OrderLine(order);
Services.OrderLines.SetProductInformation(orderLine, product);
orderLine.OrderLineType = OrderLineType.Product;
order.OrderLines.Add(orderLine);
return orderLine;
}
/// <summary>
/// Gets the response.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="requestXml">The request XML.</param>
/// <param name="order">The order.</param>
/// <param name="createOrder">if set to <c>true</c> [create order].</param>
/// <returns>XmlDocument.</returns>
private static XmlDocument GetResponse(Settings settings, string requestXml, Order order, bool createOrder, Logger logger, out bool? requestCancelled, SubmitType submitType)
{
XmlDocument response = null;
requestCancelled = null;
string orderIdentifier = Helpers.OrderIdentifier(order);
Dictionary<string, XmlDocument> responsesCache = ResponseCache.GetWebOrdersConnectorResponses(GetOrderCacheLevel(settings));
if (!createOrder && responsesCache is not null && responsesCache.TryGetValue(orderIdentifier, out response))
{
return response;
}
Notifications.Order.OnBeforeSendingOrderToErpArgs onBeforeSendingOrderToErpArgs = new Notifications.Order.OnBeforeSendingOrderToErpArgs(order, createOrder, settings, logger);
NotificationManager.Notify(Notifications.Order.OnBeforeSendingOrderToErp, onBeforeSendingOrderToErpArgs);
requestCancelled = onBeforeSendingOrderToErpArgs.Cancel;
if (!onBeforeSendingOrderToErpArgs.Cancel)
{
response = Connector.CalculateOrder(settings, requestXml, order, createOrder, out Exception error, logger, submitType);
if (createOrder && error != null)
{
string msg = !string.IsNullOrEmpty(error.Message) ? error.Message : error.ToString();
Services.OrderDebuggingInfos.Save(order, $"ERP communication failed with error: {msg}", OrderErpCallFailed, DebuggingInfoType.Undefined);
}
NotificationManager.Notify(Notifications.Order.OnAfterSendingOrderToErp, new Notifications.Order.OnAfterSendingOrderToErpArgs(order, createOrder, response, error, settings, logger));
if (responsesCache is not null)
{
responsesCache.Remove(orderIdentifier);
if (response != null && !string.IsNullOrWhiteSpace(response.InnerXml))
{
responsesCache.Add(orderIdentifier, response);
}
}
}
else
{
Services.OrderDebuggingInfos.Save(order, "Order not sent to ERP because a subscriber cancelled sending it", OrderErpCallCancelled, DebuggingInfoType.Undefined);
}
return response;
}
/// <summary>
/// Handles the integration failure.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="order">The order.</param>
/// <param name="failedState">State of the failed.</param>
/// <param name="orderId">The order identifier.</param>
/// <param name="discountOrderLines">The discount order lines.</param>
private static void HandleIntegrationFailure(Settings settings, Order order, string failedState, string orderId, OrderLineCollection discountOrderLines, Logger logger)
{
if (discountOrderLines != null && Global.EnableCartCommunication(settings, order.Complete))
{
RemoveDiscounts(order);
order.OrderLines.Add(discountOrderLines);
}
logger.Log(ErrorLevel.Error, $"Order with ID '{orderId}' was not created in the ERP system.");
if (Context.Current != null && Context.Current.Session != null)
{
Context.Current.Session["DynamicwebLiveIntegration.OrderExportFailed"] = true;
Context.Current.Session["DynamicwebLiveIntegration.FailedOrderId"] = order.Id;
}
if (!settings.QueueOrdersToExport)
{
Services.Orders.DowngradeToCart(order);
Common.Context.SetCart(order);
//order.CartV2StepIndex = --order.CartV2StepIndex; // DW10 Api breaking change
order.Complete = false;
}
if (!string.IsNullOrWhiteSpace(failedState))
{
order.StateId = failedState;
}
Services.Orders.Save(order);
}
/// <summary>
/// Handles the integration success.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="successState">State of the success.</param>
private static void HandleIntegrationSuccess(Order order, string successState)
{
if (!string.IsNullOrWhiteSpace(successState))
{
order.StateId = successState;
}
Services.Orders.Save(order);
if (Context.Current != null && Context.Current.Session != null)
{
Context.Current.Session["DynamicwebLiveIntegration.OrderExportFailed"] = null;
Context.Current.Session["DynamicwebLiveIntegration.FailedOrderId"] = null;
}
}
private static bool IsOrderUpdateAllowed(Settings settings, Order order, SubmitType liveIntegrationSubmitType)
{
if (order == null
|| !order.OrderLines.Any()
|| (order.IsLedgerEntry && settings.SkipLedgerOrder)
|| (!string.IsNullOrEmpty(order.IntegrationOrderId) && (liveIntegrationSubmitType == SubmitType.LiveOrderOrCart || liveIntegrationSubmitType == SubmitType.WebApi)))
{
return false;
}
return true;
}
private static void UpdateOrderLinesPricesCurrency(Order order)
{
foreach (var orderLine in order.OrderLines)
{
if (orderLine.UnitPrice.Currency != order.Currency)
orderLine.UnitPrice.Currency = order.Currency;
if (orderLine.Price.Currency != order.Currency)
orderLine.Price.Currency = order.Currency;
}
}
/// <summary>
/// Sets the price of the order with the values from the ERP.
/// </summary>
/// <param name="order">The order.</param>
/// <param name="orderNode">The order node.</param>
private static void OrderPriceCalculation(Settings settings, Order order, XmlNode orderNode, Logger logger, out bool updatePriceBeforeFeesFromOrderPrice)
{
updatePriceBeforeFeesFromOrderPrice = false;
//If currency was changed order Price and order lines Price have prices in previous currency
if (order.Price.Currency != order.Currency)
{
order.Price.Currency = order.Currency;
}
UpdateOrderLinesPricesCurrency(order);
var orderPriceNode = orderNode.SelectSingleNode("column [@columnName='OrderPrice']") ?? orderNode.SelectSingleNode("column [@columnName='OrderPriceWithVat']");
if (orderPriceNode != null)
{
order.Price.PriceWithVAT = Helpers.ToDouble(settings, logger, orderPriceNode.InnerText);
}
var orderPriceWithoutVatNode = orderNode.SelectSingleNode("column [@columnName='OrderPriceWithoutVat']");
if (orderPriceWithoutVatNode != null)
{
order.Price.PriceWithoutVAT = Helpers.ToDouble(settings, logger, orderPriceWithoutVatNode.InnerText);
}
if (order.Price.PriceWithVAT > 0 && order.Price.PriceWithoutVAT > 0)
{
order.Price.VAT = order.Price.PriceWithVAT - order.Price.PriceWithoutVAT;
}
var orderPriceBeforeFeesWithVat = orderNode.SelectSingleNode("column [@columnName='OrderPriceBeforeFeesWithVat']");
if (orderPriceBeforeFeesWithVat != null)
{
order.PriceBeforeFees.PriceWithVAT = Helpers.ToDouble(settings, logger, orderPriceBeforeFeesWithVat.InnerText);
}
else
{
order.PriceBeforeFees.PriceWithVAT = order.Price.PriceWithVAT;
updatePriceBeforeFeesFromOrderPrice = true;
}
var orderPriceBeforeFeesWithoutVat = orderNode.SelectSingleNode("column [@columnName='OrderPriceBeforeFeesWithoutVat']");
if (orderPriceBeforeFeesWithoutVat != null)
{
order.PriceBeforeFees.PriceWithoutVAT = Helpers.ToDouble(settings, logger, orderPriceBeforeFeesWithoutVat.InnerText);
}
else
{
order.PriceBeforeFees.PriceWithoutVAT = order.Price.PriceWithoutVAT;
updatePriceBeforeFeesFromOrderPrice = true;
}
if (order.PriceBeforeFees.PriceWithVAT > 0 && order.PriceBeforeFees.PriceWithoutVAT > 0)
{
order.PriceBeforeFees.VAT = order.PriceBeforeFees.PriceWithVAT - order.PriceBeforeFees.PriceWithoutVAT;
}
}
/// <summary>
/// Processes the discount order line.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="order">The order.</param>
/// <param name="discountOrderLines">The discount order lines.</param>
/// <param name="orderLineNode">The order line node.</param>
/// <param name="orderLineType">Type of the order line.</param>
private static void ProcessDiscountOrderLine(Settings settings, Order order, OrderLineCollection discountOrderLines, XmlNode orderLineNode, string orderLineType, Logger logger, List<string> orderLineIds, OrderLineFieldCollection allOrderLineFields)
{
string orderLineId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineId']")?.InnerText;
try
{
var orderLine = new OrderLine(order)
{
OrderLineType = Services.OrderLines.GetOrderLineType(orderLineType)
};
if (!settings.ErpControlsDiscount)
{
orderLine.DiscountId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineDiscountId']")?.InnerText;
}
OrderLine parentLine = null;
OrderLine parentLineWithVariant = null;
bool useUnitPrices = settings.UseUnitPrices;
if (orderLine.OrderLineType == OrderLineType.ProductDiscount)
{
string parentProductId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineProductNumber']")?.InnerText;
if (!string.IsNullOrEmpty(parentProductId))
{
string parentProductVariantId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineProductVariantId']")?.InnerText;
string unitId = null;
if (useUnitPrices)
{
unitId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineUnitId']")?.InnerText;
}
foreach (var productOrderLine in order.OrderLines)
{
string id = settings.CalculateOrderUsingProductNumber ? productOrderLine.ProductNumber : productOrderLine.ProductId;
if (string.Compare(id, parentProductId, StringComparison.OrdinalIgnoreCase) == 0)
{
bool found = false;
if (useUnitPrices)
{
if ((string.IsNullOrEmpty(unitId) && string.IsNullOrEmpty(productOrderLine.UnitId)) ||
string.Compare(productOrderLine.UnitId, unitId, StringComparison.OrdinalIgnoreCase) == 0)
{
parentLine = productOrderLine;
found = true;
}
}
else
{
parentLine = productOrderLine;
found = true;
}
if (found && !string.IsNullOrEmpty(parentProductVariantId) && string.Equals(productOrderLine.ProductVariantId, parentProductVariantId, StringComparison.OrdinalIgnoreCase))
{
parentLineWithVariant = productOrderLine;
}
}
}
}
}
parentLine = parentLineWithVariant ?? parentLine;
if (parentLine != null && string.IsNullOrEmpty(parentLine.Id))
{
Services.OrderLines.Save(parentLine);
orderLineIds.Add(parentLine.Id);
}
if (!string.IsNullOrEmpty(parentLine?.Id))
{
orderLine.ParentLineId = parentLine.Id;
}
orderLine.ProductName = DiscountTranslation.GetDiscountName(settings, orderLineNode, orderLine);
if (settings.ErpControlsDiscount)
{
orderLine.AllowOverridePrices = true;
}
double? value = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineQuantity']", logger);
if (value.HasValue)
{
orderLine.Quantity = value.Value;
}
else
{
orderLine.Quantity = 1;
}
double? unitPriceVat = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceVat']", logger);
SetPrice(
orderLine.UnitPrice,
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceWithVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceWithoutVat']", logger),
unitPriceVat);
double? priceVat = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceVat']", logger);
SetPrice(
orderLine.Price,
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceWithVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceWithoutVat']", logger),
priceVat);
orderLine.UnitPrice.PriceWithoutVAT = orderLine.UnitPrice.PriceWithoutVAT > 0 ? -orderLine.UnitPrice.PriceWithoutVAT : orderLine.UnitPrice.PriceWithoutVAT;
orderLine.UnitPrice.PriceWithVAT = orderLine.UnitPrice.PriceWithVAT > 0 ? -orderLine.UnitPrice.PriceWithVAT : orderLine.UnitPrice.PriceWithVAT;
if (unitPriceVat.HasValue)
{
orderLine.UnitPrice.VAT = orderLine.UnitPrice.VAT > 0 ? -orderLine.UnitPrice.VAT : orderLine.UnitPrice.VAT;
}
orderLine.Price.PriceWithVAT = orderLine.Price.PriceWithVAT > 0 ? -orderLine.Price.PriceWithVAT : orderLine.Price.PriceWithVAT;
orderLine.Price.PriceWithoutVAT = orderLine.Price.PriceWithoutVAT > 0 ? -orderLine.Price.PriceWithoutVAT : orderLine.Price.PriceWithoutVAT;
if (priceVat.HasValue)
{
orderLine.Price.VAT = orderLine.Price.VAT > 0 ? -orderLine.Price.VAT : orderLine.Price.VAT;
}
ProcessOrderLineCustomFields(settings, orderLine, allOrderLineFields, orderLineNode);
discountOrderLines.Add(orderLine);
}
catch (Exception ex)
{
logger.Log(ErrorLevel.Error, $"Error processing order line. Error: '{ex.Message}' OrderLineId = {orderLineId}.");
throw;
}
}
/// <summary>
/// Processes the order lines.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="response">The response.</param>
/// <param name="order">The order.</param>
/// <param name="discountOrderLines">The discount order lines.</param>
private static void ProcessOrderLines(Settings settings, XmlDocument response, Order order, OrderLineCollection discountOrderLines, Logger logger)
{
XmlNodeList orderLinesNodes = response.SelectNodes("//item [@table='EcomOrderLines']");
// Process OrderLines
if (orderLinesNodes != null)
{
List<string> orderLineIds = new List<string>();
List<OrderLine> orderLines = order.OrderLines.ToList();
OrderLineFieldCollection allOrderLineFields = null;
if (settings.AddOrderLineFieldsToRequest)
{
allOrderLineFields = Services.OrderLineFields.GetOrderLineFields();
}
bool processDiscounts = (settings.ErpControlsDiscount || !order.Complete);
Dictionary<string, OrderLine> responseIdOrderLineDictionary = new Dictionary<string, OrderLine>();
foreach (XmlNode orderLineNode in orderLinesNodes)
{
XmlNode orderLineTypeNode = orderLineNode.SelectSingleNode("column [@columnName='OrderLineType']") ?? orderLineNode.SelectSingleNode("column [@columnName='OrderLineTypeId']");
string orderLineType = orderLineTypeNode?.InnerText;
if (string.IsNullOrWhiteSpace(orderLineType) || orderLineType == "0" || orderLineType == "2") // 2=Fixed
{
ProcessProductOrderLine(settings, order, orderLineIds, orderLines, allOrderLineFields, orderLineNode, responseIdOrderLineDictionary, logger);
}
// 1=order discount, 3=Product Discount
if (processDiscounts && (orderLineType == "1" || orderLineType == "3"))
{
ProcessDiscountOrderLine(settings, order, discountOrderLines, orderLineNode, orderLineType, logger, orderLineIds, allOrderLineFields);
}
// 4=Product Tax
if (orderLineType == "4")
{
ProcessTaxOrderLine(settings, order, orderLineNode, logger, orderLineIds, allOrderLineFields);
}
}
bool keepDiscountOrderLines = !settings.ErpControlsDiscount && order.Complete;
// Remove deleted OrderLines
List<OrderLine> linesToRemove = new List<OrderLine>();
for (int i = order.OrderLines.Count - 1; i >= 0; i--)
{
var orderLine = order.OrderLines[i];
if ((string.IsNullOrWhiteSpace(orderLine.Id) && !orderLine.IsDiscount()) ||
orderLineIds.Contains(orderLine.Id))
{
continue;
}
if (keepDiscountOrderLines && orderLine.IsDiscount())
{
continue;
}
linesToRemove.Add(orderLine);
}
foreach (var orderLine in linesToRemove)
{
order.OrderLines.Remove(orderLine);
Services.OrderLines.Delete(orderLine.Id);
}
MergeOrderLines(settings, order);
}
}
private static void ProcessTaxOrderLine(Settings settings, Order order, XmlNode orderLineNode, Logger logger, List<string> orderLineIds, OrderLineFieldCollection allOrderLineFields)
{
string orderLineId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineId']")?.InnerText;
try
{
var orderLine = new OrderLine(order)
{
OrderLineType = OrderLineType.Tax
};
OrderLine parentLine = null;
OrderLine parentLineWithVariant = null;
bool useUnitPrices = settings.UseUnitPrices;
string parentProductId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineProductNumber']")?.InnerText;
if (!string.IsNullOrEmpty(parentProductId))
{
string parentProductVariantId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineProductVariantId']")?.InnerText;
string unitId = null;
if (useUnitPrices)
{
unitId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineUnitId']")?.InnerText;
}
foreach (var productOrderLine in order.OrderLines)
{
string id = settings.CalculateOrderUsingProductNumber ? productOrderLine.ProductNumber : productOrderLine.ProductId;
if (string.Compare(id, parentProductId, StringComparison.OrdinalIgnoreCase) == 0)
{
bool found = false;
if (useUnitPrices)
{
if ((string.IsNullOrEmpty(unitId) && string.IsNullOrEmpty(productOrderLine.UnitId)) ||
string.Compare(productOrderLine.UnitId, unitId, StringComparison.OrdinalIgnoreCase) == 0)
{
parentLine = productOrderLine;
found = true;
}
}
else
{
parentLine = productOrderLine;
found = true;
}
if (found && !string.IsNullOrEmpty(parentProductVariantId) && string.Equals(productOrderLine.ProductVariantId, parentProductVariantId, StringComparison.OrdinalIgnoreCase))
{
parentLineWithVariant = productOrderLine;
}
}
}
}
parentLine = parentLineWithVariant ?? parentLine;
if (parentLine != null && string.IsNullOrEmpty(parentLine.Id))
{
Services.OrderLines.Save(parentLine);
orderLineIds.Add(parentLine.Id);
}
if (!string.IsNullOrEmpty(parentLine?.Id))
{
orderLine.ParentLineId = parentLine.Id;
}
orderLine.AllowOverridePrices = true;
double? value = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineQuantity']", logger);
if (value.HasValue)
{
orderLine.Quantity = value.Value;
}
else
{
orderLine.Quantity = 1;
}
string productName = orderLineNode?.SelectSingleNode("column [@columnName='OrderLineProductName']")?.InnerText;
if (!string.IsNullOrWhiteSpace(productName))
{
orderLine.ProductName = productName;
}
double? unitPriceVat = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceVat']", logger);
SetPrice(
orderLine.UnitPrice,
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceWithVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceWithoutVat']", logger),
unitPriceVat);
double? priceVat = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceVat']", logger);
SetPrice(
orderLine.Price,
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceWithVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceWithoutVat']", logger),
priceVat);
ProcessOrderLineCustomFields(settings, orderLine, allOrderLineFields, orderLineNode);
order.OrderLines.Add(orderLine);
}
catch (Exception ex)
{
logger.Log(ErrorLevel.Error, $"Error processing order line. Error: '{ex.Message}' OrderLineId = {orderLineId}.");
throw;
}
}
/// <summary>
/// Processes the product order line.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="order">The order.</param>
/// <param name="orderLineIds">The order line IDs.</param>
/// <param name="orderLines">The order lines.</param>
/// <param name="allOrderLineFields">All order line fields.</param>
/// <param name="orderLineNode">The order line node.</param>
private static void ProcessProductOrderLine(Settings settings, Order order, List<string> orderLineIds, List<OrderLine> orderLines, OrderLineFieldCollection allOrderLineFields, XmlNode orderLineNode, Dictionary<string, OrderLine> responseIdOrderLineDictionary, Logger logger)
{
string productNumber = orderLineNode.SelectSingleNode("column [@columnName='OrderLineProductNumber']")?.InnerText;
try
{
if (!string.IsNullOrWhiteSpace(productNumber))
{
OrderLine orderLine = orderLines.FirstOrDefault(ol => ol.ProductNumber == productNumber);
if (orderLine == null && settings.AddOrderLinePartsToRequest)
{
orderLine = GetBomOrderLine(orderLineNode, responseIdOrderLineDictionary, productNumber);
}
if (orderLine != null)
{
// Remove found line for getting next line with same ProductNumber
orderLines.Remove(orderLine);
}
else
{
// Create an OrderLine if it doesn't exist
orderLine = CreateOrderLine(order, productNumber, logger);
if (orderLine == null)
{
return;
}
}
if (!orderLine.Bom && settings.AddOrderLinePartsToRequest)
{
string id = orderLineNode.SelectSingleNode("column [@columnName='OrderLineId']")?.InnerText;
if (!string.IsNullOrEmpty(id) && !responseIdOrderLineDictionary.ContainsKey(id))
responseIdOrderLineDictionary.Add(id, orderLine);
}
if (!string.IsNullOrWhiteSpace(orderLine.Id))
{
orderLineIds.Add(orderLine.Id);
}
// Set standard values on OrderLines
orderLine.AllowOverridePrices = true;
var doubleValue = ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineQuantity']", logger);
if (doubleValue.HasValue)
{
orderLine.Quantity = doubleValue.Value;
}
var unitId = orderLineNode.SelectSingleNode("column [@columnName='OrderLineUnitId']")?.InnerText;
if (!string.IsNullOrWhiteSpace(unitId))
{
orderLine.UnitId = unitId;
}
// order line unit price
PriceInfo unitPrice = new PriceInfo(order.Currency);
SetPrice(
unitPrice,
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceWithVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceWithoutVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLineUnitPriceVat']", logger));
Services.OrderLines.SetUnitPrice(orderLine, unitPrice, false);
if (settings.SetOrderlineFixed)
{
orderLine.OrderLineType = OrderLineType.Fixed;
}
// order line price
SetPrice(
orderLine.Price,
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceWithVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceWithoutVat']", logger),
ReadDouble(settings, orderLineNode, "column [@columnName='OrderLinePriceVat']", logger));
UpdateOrderLinesPricesCurrency(order);
// Set OrderLineCustomFields values
ProcessOrderLineCustomFields(settings, orderLine, allOrderLineFields, orderLineNode);
}
}
catch (Exception ex)
{
logger.Log(ErrorLevel.Error, $"Error processing order line. Error: '{ex.Message}' productNumber = {productNumber}.");
throw;
}
}
/// <summary>
/// Processes the response.
/// </summary>
/// <param name="settings">Settings.</param>
/// <param name="response">The response.</param>
/// <param name="order">The order.</param>
/// <param name="createOrder">if set to <c>true</c> [create order].</param>
/// <param name="successState">State of the success.</param>
/// <param name="failedState">State of the failed.</param>
/// <returns><c>true</c> if response was processed successfully, <c>false</c> otherwise.</returns>
private static bool ProcessResponse(Settings settings, XmlDocument response, Order order, bool createOrder, string successState, string failedState, Logger logger)
{
var orderId = order == null ? "is null" : order.Id ?? "ID is null";
if (response == null || order == null)
{
if (createOrder)
{
// if must create order and no response or invalid order fail to sync
logger.Log(ErrorLevel.Error, $"Response CreateOrder is null. Order = {orderId}");
return false;
}
// nothing to do so work done
return true;
}
try
{
XmlNode orderNode = response.SelectSingleNode("//item [@table='EcomOrders']");
PriceInfo shippingFeeSentInRequest = null;
if (!createOrder && !settings.ErpControlsShipping && !string.IsNullOrEmpty(order.ShippingMethodId))
{
shippingFeeSentInRequest = order.ShippingFee;
}
if (!createOrder && settings.ErpControlsDiscount)
order.IsPriceCalculatedByProvider = true;
SetCustomOrderFields(settings, order, orderNode);
var discountOrderLines = new OrderLineCollection(order);
bool enableCartCommunication = Global.EnableCartCommunication(settings, order.Complete);
bool updatePriceBeforeFeesFromOrderPrice = false;
if (enableCartCommunication)
{
ProcessOrderLines(settings, response, order, discountOrderLines, logger);
if (!order.Complete || settings.ErpControlsDiscount)
{
if (settings.ErpControlsDiscount)
{
foreach (var discountLine in discountOrderLines)
order.OrderLines.Add(discountLine, false);
SetOrderPrices(order, orderNode, settings, logger, orderId, out updatePriceBeforeFeesFromOrderPrice);
SetTotalOrderDiscount(order);
// When GetCart DwApi request is executed and ERP controls discounts:
// old discount lines are deleted and new discounts are not saved
// So at that time in backend the order lines will look incorrect, so order needs to be saved to keep discounts: https://vimeo.com/724424362/132443e631
if (!settings.UseUnitPrices && discountOrderLines.Count > 0 &&
Context.Current?.Request?.RawUrl is object &&
Context.Current.Request.RawUrl.Contains($"/dwapi/ecommerce/carts/{order.Secret}"))
{
Services.Orders.Save(order);
}
}
else if (!order.Complete)
{
SetOrderPrices(order, orderNode, settings, logger, orderId, out updatePriceBeforeFeesFromOrderPrice);
Services.Orders.CalculateDiscounts(order);
}
else
{
SetOrderPrices(order, orderNode, settings, logger, orderId, out updatePriceBeforeFeesFromOrderPrice);
}
}
else
{
SetOrderPrices(order, orderNode, settings, logger, orderId, out updatePriceBeforeFeesFromOrderPrice);
}
LiveShippingFeeProvider.ProcessShipping(settings, order, orderNode, logger);
}
else
{
SetOrderPrices(order, orderNode, settings, logger, orderId, out updatePriceBeforeFeesFromOrderPrice);
}
if (createOrder)
{
AssignIntegrationOrderId(order, orderNode);
bool.TryParse(orderNode?.SelectSingleNode("column [@columnName='OrderCreated']")?.InnerText, out bool orderCreatedSuccessfully);
if (!orderCreatedSuccessfully)
{
HandleIntegrationFailure(settings, order, failedState, orderId, discountOrderLines, logger);
}
else
{
SetShippingWarning(settings, order, orderNode);
HandleIntegrationSuccess(order, successState);
}
}
else
{
if (!settings.ErpControlsShipping && shippingFeeSentInRequest != null)
{
UpdateDynamicwebShipping(order, orderNode, shippingFeeSentInRequest, settings, logger, updatePriceBeforeFeesFromOrderPrice);
}
if (enableCartCommunication)
{
Services.Orders.Save(order);
}
}
}
catch (Exception ex)
{
logger.Log(ErrorLevel.Error, $"Error processing response. Error: '{ex.Message}' Order = {orderId}. Stack: {ex.StackTrace}.");
if (createOrder)
{
Services.OrderDebuggingInfos.Save(order, $"ERP communication failed with error: {ex}", OrderErpCallFailed, DebuggingInfoType.Undefined);
}
return false;
}
if (createOrder)
{
Services.OrderDebuggingInfos.Save(order, $"Order saved in ERP successfully.", OrderErpCallSucceed, DebuggingInfoType.Undefined);