-
Notifications
You must be signed in to change notification settings - Fork 0
/
CartExtractorBase.cs
3225 lines (2887 loc) · 106 KB
/
CartExtractorBase.cs
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 System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using _4_Tell.CommonTools;
#if !CART_EXTRACTOR_TEST_SITE
using _4_Tell.DashService;
#endif
using _4_Tell.IO;
using _4_Tell.Logs;
namespace _4_Tell.CartExtractors
{
/// <summary>
/// Abstract base class for shopping cart data extractor classes
/// </summary>
public abstract class CartExtractor
{
#region Support Classes
//FeedType Options:
// 1. single feed uri with query parameters to allow specific requests (SingleApi --preferred)
// 2. single feed uri with all data in separate xml sections (CombinedFeed)
// 3. separate feed uri for each data type (IndividualFeeds)
protected enum FeedType
{
SingleApi,
CombinedFeed,
IndividualFeeds,
None
}
public enum ExtractType
{
None,
Full,
Update,
Catalog,
Inventory,
Sales,
Customers,
#if DEBUG
Test,
#endif
GenerateOnly
}
/// <summary>
/// ParentItem is used to map child price ranges to the parent
/// </summary>
public class ParentItem
{
public string Id;
public int Inventory;
public float Price;
public float SalePrice;
public float ListPrice;
public float Cost;
public float TopPrice;
public float TopSalePrice;
public float TopListPrice;
public float TopCost;
public float TopRating;
public float RatingSum;
public int RatingCount;
public ParentItem()
{
Id = null;
Inventory = RatingCount = 0;
Price = TopPrice = SalePrice = TopSalePrice = ListPrice = TopListPrice = Cost = TopCost = TopRating = RatingSum = 0F;
}
}
/// <summary>
/// ChildItem is a simple struct to hold child details to accumulate into parent
/// </summary>
protected struct ChildItem
{
public string Id;
public int Inventory;
public float Price;
public float SalePrice;
public float ListPrice;
public float Cost;
public float Rating;
}
/// <summary>
/// A StreamReader that excludes XML-illegal characters while reading.
/// </summary>
public class XmlSanitizingStream : StreamReader
{
/// <summary>
/// The charactet that denotes the end of a file has been reached.
/// </summary>
private const int EOF = -1;
/// <summary>Create an instance of XmlSanitizingStream.</summary>
/// <param name="streamToSanitize">
/// The stream to sanitize of illegal XML characters.
/// </param>
public XmlSanitizingStream(Stream streamToSanitize)
: base(streamToSanitize, true)
{ }
/// <summary>
/// Get whether an integer represents a legal XML 1.0 or 1.1 character. See
/// the specification at w3.org for these characters.
/// </summary>
/// <param name="character"> the character to be checked for validity</param>
/// <param name="v1_0">
/// A switch to specify whether to use XML 1.0 character
/// validation, or XML 1.1 character validation.
/// </param>
public static bool IsLegalXmlChar(int character, bool v1_0 = true)
{
if (!v1_0) // http://www.w3.org/TR/xml11/#charsets
{
return
!(
character <= 0x8 ||
character == 0xB ||
character == 0xC ||
(character >= 0xE && character <= 0x1F) ||
(character >= 0x7F && character <= 0x84) ||
(character >= 0x86 && character <= 0x9F) ||
character > 0x10FFFF
);
}
return
(
character == 0x9 /* == '\t' == 9 */ ||
character == 0xA /* == '\n' == 10 */ ||
character == 0xD /* == '\r' == 13 */ ||
(character >= 0x20 && character <= 0xD7FF) ||
(character >= 0xE000 && character <= 0xFFFD) ||
(character >= 0x10000 && character <= 0x10FFFF)
);
}
public override int Read()
{
// Read each character, skipping over characters that XML has prohibited
int nextCharacter;
do
{
// Read a character
if ((nextCharacter = base.Read()) == EOF)
{
// If the character denotes the end of the file, stop reading
break;
}
}
// Skip the character if it's prohibited, and try the next
while (!IsLegalXmlChar(nextCharacter));
return nextCharacter;
}
public override int Peek()
{
// Return the next legl XML character without reading it
int nextCharacter;
do
{
// See what the next character is
nextCharacter = base.Peek();
}
while
(
// If it's prohibited XML, skip over the character in the stream
// and try the next.
!IsLegalXmlChar(nextCharacter) &&
(nextCharacter = base.Read()) != EOF
);
return nextCharacter;
} // method
#region Read*() method overrides
// The following methods are exact copies of the methods in TextReader,
// extracting by disassembling it in Refelctor
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if ((buffer.Length - index) < count)
{
throw new ArgumentException();
}
int num = 0;
do
{
var num2 = Read();
if (num2 == -1)
{
return num;
}
buffer[index + num++] = (char)num2;
}
while (num < count);
return num;
}
public override int ReadBlock(char[] buffer, int index, int count)
{
int num;
int num2 = 0;
do
{
num2 += num = Read(buffer, index + num2, count - num2);
}
while ((num > 0) && (num2 < count));
return num2;
}
public override string ReadLine()
{
var builder = new StringBuilder();
while (true)
{
var num = Read();
switch (num)
{
case -1:
return builder.Length > 0 ? builder.ToString() : null;
case 13:
case 10:
if ((num == 13) && (Peek() == 10))
{
Read();
}
return builder.ToString();
}
builder.Append((char)num);
}
}
public override string ReadToEnd()
{
int num;
var buffer = new char[0x1000];
var builder = new StringBuilder(0x1000);
while ((num = Read(buffer, 0, buffer.Length)) != 0)
{
builder.Append(buffer, 0, num);
}
return builder.ToString();
}
#endregion
} // class
#endregion
#region Internal Params
protected const string DataVersion = "3"; //data file format version
protected const int MinLockTime = 60; //Minumum time allowed between successful extractor starts
protected const int FastDurationLimit = 30; //longer than 30 min duration uses slow generator queue
public const string ExcludedCategoryCause = "Excluded Category";
public const string MissingImageCause = "Missing Image";
#if !CART_EXTRACTOR_TEST_SITE
protected RestAccess BoostService;
#endif
protected static readonly MD5 Hash = MD5.Create();
protected BoostLog Log = BoostLog.Instance;
public SiteRules Rules;
public readonly string Alias;
protected string DataReadPath; //can't be readonly since adjusted by SetMigrationSlave
protected readonly string DataWritePath;
protected bool HasCredentials;
public CatalogHandler Catalog { get; set; }
protected InventoryHandler Inventory { get; set; }
protected SalesHandler Sales { get; set; }
protected CustomerHandler Customers { get; set; }
protected AttributeHandler CategoryNames { get; set; }
protected AttributeHandler BrandNames { get; set; }
protected AttributeHandler DepartmentNames { get; set; }
protected IEnumerable<XElement> _categoryXml { get; set; }
protected List<ProductRecord> Products { get; set; }
public List<ExclusionRecord> Exclusions { get; private set; }
public FeaturedRecommendations FeaturedCrossSells { get; private set; }
public FeaturedRecommendations FeaturedUpSells { get; private set; }
public Dictionary<string, ParentItem> ParentProducts { get; private set; } //key is product id
public Dictionary<string, List<string>> AltPrices { get; private set; } //key is product id and value is a list of alternate prices
public Dictionary<string, List<string>> AltPageLinks { get; private set; } //key is product id and value is a list of alternate page links
public Dictionary<string, List<string>> AltImageLinks { get; private set; } //key is product id and value is a list of alternate image links
public Dictionary<string, List<string>> AltTitles { get; private set; } //key is product id and value is a list of alternate titles
public Dictionary<string, string> Departments { get; private set; } //key is product id and value is a list of alternate prices
public Dictionary<string, string> ExclusionCauses { get; private set; }
public Dictionary<string, int> ExclusionStats { get; private set; }
public List<ReplacementRecord> Replacements { get; set; }
protected CartWebClient _feedClient = null;
private Dictionary<DataGroup, FeedType> _feedTypes;
private Dictionary<DataGroup, string> _feedUrls;
private long _catalogFileSeekPosition;
protected XDocument _combinedFeed = null;
protected DateTime _lastFeedTime = DateTime.MinValue;
protected int _feedRefreshTime = 120; //default to two hours
//protected CartExtractor _migrationCart = null;
protected bool _migrationSlave = false;
#if DEBUG
protected DataGroup _lastJsonGroup = DataGroup.All;
#endif
#endregion
#region External Params
public static string CommonHeader //first header line in export file (set date dynamically each time it is used)
{
get { return String.Format("Version\t{0}\t{1}\r\n", DataVersion, DateTime.Now.ToShortDateString()); }
}
//filenames
//Optional Input Files
public const string ManualReplacementFilename = "ManualReplacements.txt"; //OldId<tab>NewId<cr-lf>
//Output Files for Generator
public const string CatalogFilename = "Catalog.txt";
public const string SalesFilenameFormat = "Sales-{0}.txt";
public const string ActionsFilenameFormat = "AutoActionsLog-{0}.txt";
public const string ClickStreamFilenameFormat = "AutoClickStreamLog-{0}.txt";
public const string CustomerFilenameFormat = "Customers_x-{0}.txt";
public const string Att1Filename = "Attribute1Names.txt";
public const string Att2Filename = "Attribute2Names.txt";
public const string ExclusionFilename = "Exclusions.txt";
public const string ReplacementFilename = "Replacements.txt";
public const string PromotionsFilename = "Promotions.txt";
public const string FeaturedCrossSellFilename = "FeaturedCrossSell_x.txt";
public const string FeaturedUpSellFilename = "FeaturedUpSell_x.txt";
public const string FeaturedTopSellFilename = "FeaturedTopSell_x.txt";
//Output Files for Boost Service and/or Dash Service
public const string AltPriceFilename = "AltPrices.txt";
public const string AltPageFilename = "AltPageLinks.txt";
public const string AltImageFilename = "AltImageLinks.txt";
public const string AltTitleFilename = "AltTitles.txt";
public const string InventoryFilename = "Inventory.txt";
public const string ExclusionCauseFilename = "ExclusionCauses.txt";
//Internal Temporary Files
public const string DepartmentFilename = "DepartmentNames.txt";
public bool IsExtractorQueued { get; private set; }
public bool IsExtracting { get; private set; }
public int TotalSales { get; private set; }
public int TotalCustomers { get; private set; }
//public Dictionary<string, string> MigrationSubMap = null;
//public Dictionary<string, string> MigrationFullMap = null;
public ExtractorProgress Progress;
#endregion
#region Base Methods
private CartExtractor()
{
throw new Exception("CartExtractor cannot use a default constructor");
}
protected CartExtractor(SiteRules rules)
{
if (rules == null) throw new NoNullAllowedException("CartExtractor Rules cannot be null");
Rules = rules;
Alias = Rules.Alias;
DataReadPath = IO.DataPath.Instance.ClientDataPath(ref Alias, true);
DataWritePath = IO.DataPath.Instance.ClientDataPath(Alias, true);
Progress = new ExtractorProgress();
IsExtractorQueued = false;
IsExtracting = false;
#if !CART_EXTRACTOR_TEST_SITE
BoostService = RestAccess.Instance;
FeaturedCrossSells = new FeaturedRecommendations();
FeaturedUpSells = new FeaturedRecommendations();
#endif
ExclusionStats = new Dictionary<string, int>();
Catalog = new CatalogHandler(Rules, this, Progress);
Inventory = new InventoryHandler(Rules, this, Progress);
Sales = new SalesHandler(Rules, this, Progress);
Customers = new CustomerHandler(Rules, this, Progress);
CategoryNames = new AttributeHandler(Rules, this, Progress, DataGroup.CategoryNames);
BrandNames = new AttributeHandler(Rules, this, Progress, DataGroup.ManufacturerNames);
DepartmentNames = new AttributeHandler(Rules, this, Progress, DataGroup.DepartmentNames);
//TODO: Move all below to the CatalogHandler class or depricate
Exclusions = new List<ExclusionRecord>();
Replacements = new List<ReplacementRecord>();
ParentProducts = new Dictionary<string, ParentItem>();
AltPrices = new Dictionary<string, List<string>>();
AltPageLinks = new Dictionary<string, List<string>>();
AltImageLinks = new Dictionary<string, List<string>>();
AltTitles = new Dictionary<string, List<string>>();
Departments = new Dictionary<string, string>();
ExclusionCauses = new Dictionary<string, string>();
}
#if !CART_EXTRACTOR_TEST_SITE
/// <summary>
/// Return the rules related to the cart, telling what type of extraction and upload options are valid
/// These are general rules related to the cart type, not specific to the client.
/// </summary>
/// <returns>DashCartDefinition</returns>
public static DashCartDefinition GetCartRules(CartType cartType)
{
//note, this is defined here instead of using an abstract method
//so that cart rules can exist for cart types that don't have extractors
var rules = new DashCartDefinition{ CartId = (int)cartType, CartValue = cartType.ToString() };
switch (cartType)
{
case CartType.BigCommerce:
rules.CartDisplayName = "BigCommerce";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = false;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.CommerceV3:
rules.CartDisplayName = "Commerce V3";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = false;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.MivaMerchant:
rules.CartDisplayName = "MivaMerchant";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = true;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.ThreeDCart:
rules.CartDisplayName = "3dcart";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = false;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.Volusion:
rules.CartDisplayName = "Volusion";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = false;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.Shopify:
rules.CartDisplayName = "Shopify";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = true;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.NetSuite:
rules.CartDisplayName = "NetSuite";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = true;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.JsonFeed:
rules.CartDisplayName = "JsonFeed";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = true;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.XmlFeed:
rules.CartDisplayName = "XmlFeed";
rules.HasCartExtractor = true;
rules.CanExtractCatalog = true;
rules.CanExtractAllSales = true;
rules.CanExtractSalesUpdate = true;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
case CartType.TabbedFeed:
case CartType.osCommerce:
case CartType.Magento:
case CartType.PrestaShop:
case CartType.WebsitePipeline:
case CartType.Other:
default:
rules.CartDisplayName = cartType.ToString();
rules.HasCartExtractor = false;
rules.CanExtractCatalog = false;
rules.CanExtractAllSales = false;
rules.CanExtractSalesUpdate = false;
rules.HasManualUpload = true;
rules.HasManualUploadLink = false;
break;
}
return rules;
}
#endif
public bool SetRules(SiteRules rules)
{
if (!rules.Alias.Equals(Rules.Alias)) return false; //can't change the alias
Rules = rules;
//FillDefaultFieldNames();
//Rules.InitFieldNames();
return true;
}
public void GetData(SiteRules.ExtractorSchedule ut)
{
GetData(ut.ExtractType);
}
/// <summary>
/// Extract data from the cart
/// </summary>
/// <param name="extractType"></param>
/// <returns>true if successful</returns>
public bool GetData(ExtractType extractType)
{
//choices are update only or full export
//all normal exports include catalog and related files (exclusions, attNames, etc)
//full export also includes all sales files (could be pulling from xml depending on the cart)
//update will include the current sales month only if Rules.ExtractSalesUpdate is true for this cart
if (Rules == null)
{
if (Log != null)
Log.WriteEntry(EventLogEntryType.Information, "Attempt to GetData with Rules null", "", Alias);
return false;
}
IsExtracting = true;
var dynamicUpdate = false;
var totalTime = new StopWatch(true);
var pullType = "new";
//check migration status
_migrationSlave = Rules.MigrationRules != null && Rules.MigrationRules.Enabled
&& !Rules.MigrationRules.IsMigrationMaster;
if (_migrationSlave)
{
pullType = "Migration";
Progress.IsSlave = true;
}
var result = String.Format("Pulling {0} data for {1} from {2}", pullType, Alias, Rules.CartName);
var details = "";
if (Log != null)
Log.WriteEntry(EventLogEntryType.Information, result, "", Alias);
Progress.Start(result);
var catalogCount = 0;
try
{
var generateTables = true;
switch (extractType)
{
case ExtractType.Full:
if (Rules.ExtractSalesFull) GetAllSales();
if (Rules.ExtractCustomerData) GetAllCustomers();
catalogCount = GetCatalog(true);
break;
case ExtractType.Update:
if (Rules.ExtractSalesUpdate) GetSalesUpdate();
if (Rules.ExtractCustomerData) GetCustomerUpdate();
catalogCount = GetCatalog();
break;
case ExtractType.Sales:
if (Rules.ExtractSalesFull || Rules.ExtractSalesFromXmlFile) GetAllSales();
else if (Rules.ExtractSalesUpdate) GetSalesUpdate();
else throw new Exception("Sales extraction is not supported for this site.");
break;
case ExtractType.Customers:
if (Rules.ExtractCustomerData) GetAllCustomers();
else throw new Exception("Customer extraction is not supported for this site.");
break;
case ExtractType.Inventory:
GetInventory();
dynamicUpdate = true;
generateTables = false; //inventory does not require generator
break;
case ExtractType.Catalog:
catalogCount = GetCatalog();
break;
#if DEBUG
case ExtractType.Test:
RunTest();
break;
#endif
case ExtractType.GenerateOnly:
break;
}
//check exclusion causes
var exCauses = "";
if (ExclusionStats != null && ExclusionStats.Any())
{
//only save to rules when extraction is completed
Rules.ExclusionStats = new Dictionary<string,int>(ExclusionStats);
//exclusionStats.AddRange(dashSite.Rules.ExclusionStats.Select(c => new List<string> { c.Key, c.Value.ToString("N0") }));
exCauses = "\n\n" + ExclusionStats
.Aggregate("Exclusion Causes:", (a, b) => String.Format("{0}\n {1} = {2}", a, b.Key, b.Value.ToString("N0")));
//check for excessive missing images
int causeCount;
if (Log != null && ExclusionStats.TryGetValue(MissingImageCause, out causeCount)
&& catalogCount > 0 && ((float)causeCount / catalogCount) * 100F > Rules.MissingImageThreshold) //defaults to 10%
throw new Exception(string.Format("Error: {0} of {1} items are excluded due to missing images.",
causeCount.ToString("N0"), catalogCount.ToString("N0")),
new Exception(exCauses));
}
totalTime.Stop();
if (dynamicUpdate)
{
Rules.LastDynamicUpdateType = extractType;
Rules.LastDynamicUpdateTime = DateTime.Now;
}
else
{
Rules.LastExtractionType = extractType;
Rules.LastExtractionTime = DateTime.Now;
Rules.LastExtractorDuration = (int)Math.Ceiling(totalTime.ElapsedMinutes);
}
if (!_migrationSlave)
{
#if !CART_EXTRACTOR_TEST_SITE
if (generateTables)
{
QueueGenerator();
result = string.Format("Successful update --pending Generator task{0}", exCauses);
}
else
#endif
result = string.Format("Successful {0} update{1}", extractType, exCauses);
}
Progress.End(true, result);
return true;
}
catch (ThreadAbortException)
{
result = "Update canceled by user";
return false;
}
catch (Exception ex)
{
result = ex.Message;
details = ex.InnerException == null ? "" : "Inner Exception: " + ex.InnerException.Message;
if (Log != null)
Log.WriteEntry(EventLogEntryType.Information, result, details, Alias, true); //send support alert
return false;
}
finally
{
if (!_migrationSlave)
{
Rules.QueueSettings(false); //save the extraction time and duration
ReleaseGlobalData();
ReleaseCartData();
}
IsExtracting = false;
if (Progress.Started) Progress.End(false, result);
if (Log != null)
{
Log.WriteEntry(EventLogEntryType.Information, Progress.Text, details, Alias);
}
}
}
#if DEBUG
private void RunTest()
{
var extraFields = "p.ProductID,pv.Price,AltPrice1,AltPageLink1";
string altFeedUrl = "http://webadapters.channeladvisor.com/CSEAdapter/Default.aspx?pid=YZP%5e%5eI%5cRA%3bHJ%40fW%2bQ%5bdwd%27QjEN%40_%25-P5%5bH%5e%25YjANr7X%60VKaC2%25%27gCM%3dj*%2f%24%5bbG%5dWQ8FMu_V-%24%5e2JbSU%3dwG";
int _storeId = 1;
int maxRows = 10000;
int startingRow = 1;
string[] rows;
////initialize extra field list
//List<string> extraFieldList = string.IsNullOrEmpty(extraFields) ? new List<string>() :
// extraFields.Split(new[] { ',' }).Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
//initialize extra field list
List<string> extraFieldList = new List<string>();
if (!string.IsNullOrEmpty(extraFields))
{
var tempList = extraFields.Split(new[] { ',' });
foreach (var e in tempList)
{
if (string.IsNullOrEmpty(e.Trim())) continue;
extraFieldList.Add(e);
}
}
//remove standard fields
var standardFields = new List<string>
{
"p.ProductID",
"p.SKU",
"p.Name",
"p.Deleted",
"p.Published",
"pv.Price",
"pv.SalePrice",
"pv.MSRP",
"pv.Cost",
"pv.Inventory",
"pm.ManufacturerID",
"pc.CategoryID",
"ps.SectionID",
"ProductId",
"Name",
"Att1Id",
"Att2Id",
"Price",
"SalePrice",
"ListPrice",
"Cost",
"Inventory",
"Visible",
"Link",
"ImageLink",
"Rating",
"StandardCode",
"Departments",
"CategoryList",
"ManufacturerID",
"SectionList"
};
extraFieldList.RemoveAll(x => standardFields.Contains(x));
//-------begin: CA Alt Feed Handling-------
//Read alternate eBay prices and links from separate CA feed
string[] altHeader = null;
var altFeedLookup = new Dictionary<string, List<string>>();
//string altFeedUrl = AppLogic.AppConfig("4Tell.CaFeedUrl");
var caFeedExists = !string.IsNullOrEmpty(altFeedUrl);
if (caFeedExists)
{
//Note: could make these config parameters
var colEnd = new[] { '\t' };
var rowEnd = new[] { '\n' };
var trimRow = new[] { '\r' };
string feedData = null;
using (var feed = new WebClient())
{
feed.Encoding = Encoding.UTF8;
feed.BaseAddress = "";
feed.Proxy = null;
feed.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0");
feed.Headers.Add("accept", "*/*");
feed.Headers.Add("content-type", "application/json");
using (var data = feed.OpenRead(altFeedUrl))
{
if (data != null)
{
using (var reader = new StreamReader(data))
{
feedData = reader.ReadToEnd();
}
}
}
}
//parse into dictionary for lookup below
if (!string.IsNullOrEmpty(feedData))
{
var feedRows = feedData.Split(rowEnd);
var rowCount = feedRows.Length;
if (rowCount > 1)
{
altHeader = feedRows[0].Trim(trimRow).Split(colEnd);
var columnCount = altHeader.Length;
for (var i = 1; i < rowCount; i++)
{
var columns = feedRows[i].Trim(trimRow).Split(colEnd);
if (columns.Length != columnCount) continue;
List<string> data;
if (!altFeedLookup.TryGetValue(columns[0], out data))
{
data = new List<string>();
for (var j = 1; j < columnCount; j++)
data.Add(columns[j]);
altFeedLookup.Add(columns[0], data);
}
}
}
}
if (altFeedLookup.Any())
{
//remove alt fields from the extrafieldList
extraFieldList.RemoveAll(x => altHeader.Contains(x));
//and add then to the catalog header list
//for (var i = 1; i < altHeader.Length; i++) ProductRecord.AddField(altHeader[i]);
}
else //no data
caFeedExists = false;
}
//-------end: CA Alt Feed Handling-------
//throw new Exception("made it here");
//add extra fields to the output catalog header
//foreach (var f in extraFieldList) ProductRecord.AddField(f);
//setup database query (and adjust extraFields)
var totalRows = 50000;// GetRowCount(DataGroup.Catalog);
var query = "SELECT";
if (maxRows > 0)
query += string.Format(" TOP {0} * FROM (SELECT TOP {1}", maxRows, totalRows - startingRow);
query += " p.ProductID, p.SKU, p.Name, p.Deleted, p.Published, pv.Price, pv.SalePrice, pv.MSRP, pv.Cost, pv.Inventory,"
+ " isnull(pm.ManufacturerID, 0) as ManufacturerID, "
+ " stuff((select ',' + cast(pc.CategoryID as varchar)"
+ " FROM ProductCategory pc WHERE p.ProductID = pc.ProductID"
+ " FOR xml path('')),1,1,'') as CategoryList,"
+ " stuff((select ',' + cast(ps.SectionID as varchar)"
+ " FROM ProductSection ps WHERE p.ProductID = ps.ProductID"
+ " FOR xml path('')),1,1,'') as SectionList";
if (extraFieldList.Any())
{
foreach (var f in extraFieldList) query += ", " + f;
}
query += " from Product p inner join ProductVariant pv on p.ProductID = pv.ProductID and pv.IsDefault = 1";
if (_storeId > 0)
query += string.Format(" inner join ProductStore ps on p.ProductID = ps.ProductID and ps.StoreID = {0}", _storeId);
query += " left join ProductManufacturer pm on p.ProductID = pm.ProductID";
if (maxRows > 0)
query += " ORDER BY p.ProductID DESC) as sub ORDER BY sub.ProductID ASC";
else
query += " ORDER BY p.ProductID ASC";
}
#endif
#if !CART_EXTRACTOR_TEST_SITE
private void QueueGenerator()
{
Progress.StartTable("Generator Task", "", "");
//base slow/fast and lockout minutes decision on combined last extractor/generator time (when they exist)
var slow = false;
if (Rules.LastExtractorDuration > 0 && Rules.LastGeneratorDuration > 0)
{
//both durations are valid so recalc settings
var lastTime = Rules.LastExtractorDuration + Rules.LastGeneratorDuration;
slow = lastTime > FastDurationLimit;
if (slow)
Rules.ExtractorLockoutMinutes = (int)(Math.Ceiling((double)lastTime / (double)FastDurationLimit) * MinLockTime);
else if (Rules.ExtractorLockoutMinutes > MinLockTime)
Rules.ExtractorLockoutMinutes = MinLockTime;
}
else
slow = Rules.ExtractorLockoutMinutes > 60;
var status = (GeneratorQueue.Instance != null && GeneratorQueue.Instance.AddToQueue(Alias, true, slow)) ?
"Queued" : "Unable to queue";
Progress.EndTable(-1, status);
}
#endif
private void GetSalesUpdate()
{
var exportDate = DateTime.Now;
var filename = String.Format(SalesFilenameFormat, exportDate.ToString("yyyy-MM"));
Progress.StartTable(filename, "items");
int itemCount;
TotalSales = 0;
var status = GetSalesMonth(exportDate, filename, out itemCount);
Progress.EndTable(itemCount, status);
TotalSales += itemCount;
}
private void GetAllSales()
{
var exportDate = DateTime.Now;
var itemCount = -1;
TotalSales = 0;
if (_migrationSlave)
{
//Get old customer data from "SalesMonths" to migration date
var firstDate = DateTime.Now.AddMonths(-1 * Rules.SalesMonthsToExport);
var lastDate = Rules.MigrationRules.StartDate;
exportDate = new DateTime(firstDate.Year, firstDate.Month, 1);
while (exportDate < lastDate)
{
//don't replace final month if new data is more relevant
if (lastDate.Day < CatalogMigration.MigrationCutoffDay
&& exportDate.Year == lastDate.Year && exportDate.Month == lastDate.Month) break;
//create filename and add to the upload list for ConfigBoost
var filename = String.Format(SalesFilenameFormat, exportDate.ToString("yyyy-MM"));
itemCount = -1;
Progress.StartTable("Migration Sales " + filename, "items");
var status = "";
if (Rules.MigrationRules.Use4TellSales)
{
List<SalesRecord> sales;
if (TableAccess.Instance.ReadTable(filename, Alias, out sales, true))
{
MigrateSlaveOrders(ref sales);
itemCount = sales.Count;
Progress.UpdateTable(itemCount, -1, "Writing table");
status = TableAccess.Instance.WriteTable(Alias, filename, sales);
}
else itemCount = 0;
}
else
status = GetSalesMonth(exportDate, filename, out itemCount);
Progress.EndTable(itemCount, status);
TotalSales += itemCount;
//move forward one month for next loop
exportDate = exportDate.AddMonths(1);
}
return;
}
for (var month = 0; month < Rules.SalesMonthsToExport; month++)
{
//create filename and add to the upload list for ConfigBoost
var filename = String.Format(SalesFilenameFormat, exportDate.ToString("yyyy-MM"));
Progress.StartTable(filename, "items");
var status = GetSalesMonth(exportDate, filename, out itemCount);
Progress.EndTable(itemCount, status);
TotalSales += itemCount;
//move back one month for next loop
exportDate = exportDate.AddMonths(-1);
//check migration rules
if (Rules.MigrationRules == null || !Rules.MigrationRules.Enabled || _migrationSlave) continue;
var lastDate = Rules.MigrationRules.StartDate;
if (exportDate < lastDate
|| (exportDate.Year == lastDate.Year && exportDate.Month == lastDate.Month && lastDate.Day < CatalogMigration.MigrationCutoffDay))
break; //earlier sales will be pulled from migration platform
}
}
private void GetCustomerUpdate()
{
var exportDate = DateTime.Now;