-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGTD_Parser.cs
1129 lines (903 loc) · 46.4 KB
/
GTD_Parser.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.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace Hello
{
class GTD_Parser
{
public int DocumentPagesCount { get; set; }
public string nameNodeAdditionalDocumentDefinition { get; set; }
public string nameNodeMainDocumentDefinition { get; set; }
public int ItemsCount { get; set; } // распознанное количество страниц
int _countItemsCalculate = 1;
public string DocumentNumber { get; set; }
private string DeclarationType { get; set; }
public string AverageDeclarationNumber { get; set; }
public string MainXMLFilePath { get; set; }
public string[] xmlFiles;
public string finalXMLFileExportPath;
public string finalXMLFileName;
public string tmpFolderPath;
public string pathItemsListFolder { get; set; }
public bool HasAdditionalPages { get; private set; } = false;
bool pagesCountMatch = false;
bool itemsCountMatch = false;
// содержит информацию о количестве товаров на лист
// в дополнительных листах
List<int> _numberItemsInList = new List<int>();
public decimal TotalCost { get; set; }
private XmlDocument mainDoc = new XmlDocument();
private List<XmlDocument> addDocuments = new List<XmlDocument>();
private string[] tifFilesCollection;
public HashSet<string> errorGTDParser = new HashSet<string>();
public HashSet<string> warningGTDParser = new HashSet<string>();
HashSet<int> _listCountItemsOnList = new HashSet<int>();
ItemsList classItemsList = null;
List <AdditionalDocument> listClassAdditionalDocument = null;
public GTD_Parser(string folderPath, string declarationType)
{
DeclarationType = declarationType;
xmlFiles = Directory.GetFiles(folderPath, "*.xml");
tifFilesCollection = Directory.GetFiles(folderPath, "*.tif");
tifFilesCollection.Reverse();
xmlFiles.Reverse();
MainXMLFilePath = xmlFiles[0];
finalXMLFileName = Path.GetFileName(MainXMLFilePath);
finalXMLFileExportPath = Path.GetDirectoryName(folderPath);
mainDoc.Load(MainXMLFilePath);
tmpFolderPath = folderPath;
nameNodeMainDocumentDefinition = mainDoc.LastChild.FirstChild.FirstChild.Name;
DocumentNumber = CastDocumentNumber(mainDoc.GetElementsByTagName("_DeclarationNumber").Item(0).InnerText.ToLower());
warningGTDParser.Add("Предупреждения для документа " + this.DeclarationType + " № " + DocumentNumber);
try
{
DocumentPagesCount = int.Parse(mainDoc.GetElementsByTagName("_PagesCount").Item(0).InnerText.Trim(' '));
}
catch
{
DocumentPagesCount = -1;
}
try
{
ItemsCount = int.Parse(mainDoc.GetElementsByTagName("_ItemsCount").Item(0).InnerText.Trim(' '));
}
catch
{
ItemsCount = -1;
}
try
{
string test = "";
if (declarationType == "ГДТ")
{
var result = mainDoc.GetElementsByTagName("_TotalCost");
if (result.Count > 0)
test = result.Item(0).InnerText.Trim(' ');
else
test = "-1";
}
else
{
var result = mainDoc.GetElementsByTagName("_TotalCostNew");
if (result.Count > 0)
test = result.Item(0).InnerText.Trim(' ');
else
test = "-1";
}
test = test.Replace('.', ',');
TotalCost = decimal.Parse(test, NumberStyles.Currency);
}
catch
{
TotalCost = -1;
}
// очистка таблицы от пустых строк
XmlNode nodeMainDocument = mainDoc.GetElementsByTagName(nameNodeMainDocumentDefinition).Item(0);
XmlNode nodeTableForClean = nodeMainDocument.SelectSingleNode("_PaymentTable1");
if (nodeTableForClean != null)
DeleteEmptyRows(nodeTableForClean);
else // либо создаем новую таблицу PaymentTable1
{
nodeTableForClean = mainDoc.CreateNode(XmlNodeType.Element, "_PaymentTable1", null);
nodeMainDocument.InsertAfter(nodeTableForClean, nodeMainDocument.LastChild);
}
}
public void LoadAdditionalDocs()
{
AssertMe.assert(xmlFiles.Length > 1);
HasAdditionalPages = true;
if (DocumentPagesCount == xmlFiles.Length)
pagesCountMatch = true;
else
warningGTDParser.Add("Указанное количество страниц в документе: (" + DocumentPagesCount + ") и распознаваемое количество страниц: (" + xmlFiles.Length + ") не совпадают");
listClassAdditionalDocument = new List<AdditionalDocument>();
for (int i = 1; i < xmlFiles.Length; i++)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlFiles[i]);
addDocuments.Add(doc);
}
nameNodeAdditionalDocumentDefinition = addDocuments[0].LastChild.FirstChild.FirstChild.Name;
foreach (XmlDocument doc in addDocuments)
{
XmlNodeList itemNodes = doc.GetElementsByTagName("_Items");
_countItemsCalculate += itemNodes.Count;
// проверяем, сколько товаров размещено на лист
// должно быть 3, но бывает, что два
_numberItemsInList.Add(itemNodes.Count);
}
if (pagesCountMatch)
EnumeratePages();
GetAddDocumensInfo();
}
private void EnumerateItems()
{
int itemCount = 2;
foreach (XmlDocument doc in addDocuments)
{
XmlNodeList itemNodes = doc.GetElementsByTagName("_Items");
foreach (XmlNode node in itemNodes)
{
node.SelectSingleNode("_ItemNumber").InnerText = itemCount.ToString();
itemCount++;
}
}
}
private void EnumerateItems2()
{
foreach (XmlDocument doc in addDocuments)
{
XmlNodeList itemNodes = doc.GetElementsByTagName("_Items");
int[] itemsNumbers = new int[itemNodes.Count];
for (int i = 0; i < itemNodes.Count; i++)
{
try
{
int itemCount = Int32.Parse(itemNodes[i].SelectSingleNode("_ItemNumber").InnerText);
itemsNumbers[i] = itemCount;
}
catch
{
itemsNumbers[i] = -1;
}
}
for (int i = 0; i < itemsNumbers.Length - 1; i++)
{
if (itemsNumbers[i] == -1)
{
int counter = i + 1;
while (counter < itemsNumbers.Length)
{
if (itemsNumbers[counter] != -1)
{
itemsNumbers[i] = itemsNumbers[counter] - (counter - i);
itemNodes[i].SelectSingleNode("_ItemNumber").InnerText = itemsNumbers[i].ToString();
break;
}
else
counter++;
}
}
}
for (int i = itemsNumbers.Length - 1; i > 0; i--)
{
if (itemsNumbers[i] == -1)
{
int counter = i - 1;
while (counter > -1)
{
if (itemsNumbers[counter] != -1)
{
itemsNumbers[i] = itemsNumbers[counter] + (i - counter);
itemNodes[i].SelectSingleNode("_ItemNumber").InnerText = itemsNumbers[i].ToString();
break;
}
else
counter--;
}
}
}
}
}
private void EnumeratePages()
{
int itemCount = 2;
foreach (XmlDocument doc in addDocuments)
{
XmlNodeList itemNodes = doc.GetElementsByTagName(nameNodeAdditionalDocumentDefinition);
itemNodes[0].SelectSingleNode("_PageNumber").InnerText = itemCount.ToString();
itemCount++;
}
}
// объеденяет данные xml файлов в единый файл
void CombineFiles()
{
foreach (XmlDocument doc in addDocuments.Reverse<XmlDocument>())
{
XmlNodeList nodes = doc.GetElementsByTagName(nameNodeAdditionalDocumentDefinition);
XmlNodeList mainNodes = mainDoc.GetElementsByTagName(nameNodeMainDocumentDefinition);
XmlNode importNode = mainDoc.ImportNode(nodes[0], true);
// копируем аттрибуты
ImportNodeAttributes(nodes[0], importNode, nameNodeAdditionalDocumentDefinition);
mainNodes[0].ParentNode.InsertAfter(importNode, mainNodes[0]);
}
}
public void RenameAddItemsTagName()
{
foreach (XmlDocument doc in addDocuments)
{
XmlNodeList nodes = doc.GetElementsByTagName(nameNodeAdditionalDocumentDefinition);
string replaceText = nodes[0].InnerXml;
int countItemsOnList = _numberItemsInList[addDocuments.IndexOf(doc)];
// пронумеровываем ячейки Items
int tagNumber = 1;
string oldNodeName = "_Items";
int count = new Regex(Regex.Escape(oldNodeName + ">")).Matches(replaceText).Count / 2;
while (tagNumber < count + 1)
{
XmlNode newNode = doc.CreateNode(XmlNodeType.Element, oldNodeName + tagNumber.ToString(), nodes[0].SelectSingleNode(oldNodeName).NamespaceURI);
newNode.InnerXml = nodes[0].SelectSingleNode(oldNodeName).InnerXml;
nodes[0].ReplaceChild(newNode, nodes[0].SelectSingleNode(oldNodeName));
tagNumber++;
}
// создаем новые ячейки Items для КДТ,
// если их нет в документе, для последующего заполнения данными из соответсвующего ГДТ
if (count == 0)
{
while (tagNumber != countItemsOnList + 1)
{
XmlNode nodeItemNew = doc.CreateNode(XmlNodeType.Element, oldNodeName + tagNumber.ToString(), null);
nodes[0].InsertBefore(nodeItemNew, nodes[0].LastChild);
tagNumber++;
}
}
// пронумеровываем таблицы _PaymentTable13
tagNumber = 1;
oldNodeName = "_PaymentTable13";
count = new Regex(Regex.Escape(oldNodeName)).Matches(replaceText).Count / 2;
int pos = 1;
// в зависимости от количестватоваров на страницу
// переименовываем табличные ячейки
XmlNode nodeTableForClean = null;
try
{
nodeTableForClean = nodes[0].SelectSingleNode("_PaymentTable2");
}
catch
{
warningGTDParser.Add("не найдена таблица для второго товара");
}
switch (_numberItemsInList[addDocuments.IndexOf(doc)])
{
case 1:
if (count == 1)
RenameTableNode(doc, nodes[0], 1, oldNodeName);
else
{
XmlNode newNodeTable13 = doc.CreateNode(XmlNodeType.Element, oldNodeName.Substring(0, oldNodeName.Length - 2) + pos.ToString(), null);
nodes[0].InsertBefore(newNodeTable13, nodes[0].LastChild);
}
break;
case 2:
if (count == 2)
{
if (nodeTableForClean != null)
{
if (!nodeTableForClean.HasChildNodes)
{
nodes[0].RemoveChild(nodeTableForClean);
RenameTableNode(doc, nodes[0], 1, oldNodeName);
RenameTableNode(doc, nodes[0], 2, oldNodeName);
}
else
{
DeleteEmptyRows(nodeTableForClean);
RenameTableNode(doc, nodes[0], 1, oldNodeName);
nodes[0].RemoveChild(nodes[0].SelectSingleNode(oldNodeName));
}
}
else
{
RenameTableNode(doc, nodes[0], 1, oldNodeName);
RenameTableNode(doc, nodes[0], 2, oldNodeName);
}
}
else if (count == 1)
{
RenameTableNode(doc, nodes[0], 1, oldNodeName);
if (nodeTableForClean != null)
{
if (nodeTableForClean.HasChildNodes)
DeleteEmptyRows(nodeTableForClean);
}
}
else
{
CreateNewNodeTable(doc, nodes[0], oldNodeName, 1);
if (nodeTableForClean != null)
{
if (nodeTableForClean.HasChildNodes)
DeleteEmptyRows(nodeTableForClean);
}
else
CreateNewNodeTable(doc, nodes[0], oldNodeName, 2);
}
break;
case 3:
{
if (count == 2)
{
RenameTableNode(doc, nodes[0], 1, oldNodeName);
RenameTableNode(doc, nodes[0], 3, oldNodeName);
}
else if (count == 1)
{
RenameTableNode(doc, nodes[0], 1, oldNodeName);
CreateNewNodeTable(doc, nodes[0], oldNodeName, 3);
}
else
{
CreateNewNodeTable(doc, nodes[0], oldNodeName, 1);
CreateNewNodeTable(doc, nodes[0], oldNodeName, 3);
}
if (nodeTableForClean != null)
{
if (nodeTableForClean.HasChildNodes)
DeleteEmptyRows(nodeTableForClean);
}
else
CreateNewNodeTable(doc, nodes[0], oldNodeName, 2);
break;
}
}
}
}
void AssembleImages(string paramNameDirectoryExport)
{
try
{
// If only 1 page was passed, copy directly to output
if (tifFilesCollection.Length == 1)
{
File.Copy(tifFilesCollection[0], paramNameDirectoryExport + "\\" + Path.GetFileName(tifFilesCollection[0]), true); //finalXMLFileExportPath + "\\" + Path.GetFileName(tifFilesCollection[0])
return;
}
int pageCount = tifFilesCollection.Length;
// First page
Image finalImage = Image.FromFile(tifFilesCollection[0]);
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.SaveFlag;
System.Drawing.Imaging.Encoder encoderComp = System.Drawing.Imaging.Encoder.Compression;
ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
EncoderParameters encoderParameters = new EncoderParameters(2);
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
encoderParameters.Param[1] = new EncoderParameter(encoderComp, (long)EncoderValue.CompressionCCITT4);
finalImage.Save(paramNameDirectoryExport + "\\" + Path.GetFileName(tifFilesCollection[0]), encoderInfo, encoderParameters);
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
// All other pages
for (int i = 1; i < pageCount; i++)
{
Image img = Image.FromFile(tifFilesCollection[i]);
finalImage.SaveAdd(img, encoderParameters);
img.Dispose();
}
// Close out the file
encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
// Last page
finalImage.SaveAdd(encoderParameters);
encoderParameters.Dispose();
finalImage.Dispose();
}
catch (Exception ex)
{
warningGTDParser.Add("Ошибка при создании Tif файла для ГДТ: " + ex);
}
}
void GetAddDocumensInfo()
{
List<string> listNamesDeclarationNumber = new List<string>();
foreach (XmlDocument doc in addDocuments.Reverse<XmlDocument>())
{
XmlNodeList nodes = doc.GetElementsByTagName(nameNodeAdditionalDocumentDefinition);
XmlNode docNumberNode = nodes[0].SelectSingleNode("_DeclarationNumber");
string stringNumber = docNumberNode.InnerText.Trim();
//stringNumber = Regex.Replace(stringNumber, @"\s+", "");
XmlNode pageNumberNode = nodes[0].SelectSingleNode("_PageNumber");
int pageNumber = -1;
int.TryParse(docNumberNode.InnerText.Trim(), out pageNumber);
listNamesDeclarationNumber.Add(stringNumber);
listClassAdditionalDocument.Add(new AdditionalDocument(stringNumber, pageNumber));
}
// calc average declaration number
AverageDeclarationNumber = GetAverageStringValue(listNamesDeclarationNumber);
}
string GetAverageStringValue(List<string> paramListValues)
{
IEnumerable<string> top1 = paramListValues
.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Take(1)
.Select(g => g.Key);
if (top1.Count() == 0)
return "";
return top1.First();
}
public bool SaveDocumentToFile(string paramPathExport)
{
try
{
if (HasAdditionalPages)
CombineFiles();
mainDoc.Save(paramPathExport);
AssembleImages(Path.GetDirectoryName(paramPathExport));
}
catch (Exception ex)
{
errorGTDParser.Add("Error to write a final xml: " + ex);
throw new Exception(string.Join("; ", errorGTDParser));
}
if (pagesCountMatch || itemsCountMatch)
return true;
else
{
warningGTDParser.Add("Указанное количество товаров в документе: (" + ItemsCount + ") и распознанное количество товаров: (" + _countItemsCalculate + ") не совпадают");
return false;
}
}
public bool InitItemsList(string paramFolderName)
{
// load items list
AssertMe.assert(!String.IsNullOrEmpty(paramFolderName));
pathItemsListFolder = tmpFolderPath + "\\" + paramFolderName;
string[] arrayFilesTiffItemsList = Directory.GetFiles(pathItemsListFolder, "*.tif");
tifFilesCollection = tifFilesCollection.Union(arrayFilesTiffItemsList).ToArray();
try
{
classItemsList = new ItemsList(pathItemsListFolder);
}
catch (Exception e)
{
errorGTDParser.Add("Не удалось инициализировать класс ItemsList." + e);
return false;
}
return true;
}
public bool AddItemsListData()
{
bool condInjectedAll = true;
List<ItemsList.ItemAttributes> copyListItemsAttributes = classItemsList.listAttributesItem.ToList();
//Debug.Assert(mainDoc.GetElementsByTagName(nameNodeAdditionalDocumentDefinition).Count == 0);
// inject data in main page
if (!AddItemsListDataInDocument(mainDoc, 1, DocumentNumber, copyListItemsAttributes))
condInjectedAll = false;
if (addDocuments.Count == 0)
return condInjectedAll;
// for additional documents
foreach (XmlDocument additionalDocument in addDocuments)
{
int index = addDocuments.IndexOf(additionalDocument);
if (!AddItemsListDataInDocument(additionalDocument, listClassAdditionalDocument[index].numberDocumentPage,
listClassAdditionalDocument[index].nameDocumentNumber, copyListItemsAttributes))
condInjectedAll = false;
}
if (copyListItemsAttributes.Count > 0)
{
condInjectedAll = false;
warningGTDParser.Add("Не все листы списка товаров удалось сопоставить для Декларациии №: " + DocumentNumber);
foreach (ItemsList.ItemAttributes attribute in copyListItemsAttributes)
{
warningGTDParser.Add("Не обработан лист №: " + (attribute.numberItemInList).ToString() + " ,код товара: " + attribute.nameCodeItemInList);
}
}
// сравниваем распознанное количество товаров и подсчитанное
if (_countItemsCalculate == ItemsCount)
itemsCountMatch = true;
else
{
DeleteEmptyItemsInLastPage();
if (_countItemsCalculate == ItemsCount)
itemsCountMatch = true;
else
itemsCountMatch = false;
}
// пронумеровываем товары
if (pagesCountMatch || itemsCountMatch)
{
EnumerateItems();
}
else
EnumerateItems2();
return condInjectedAll;
}
bool AddItemsListDataInDocument(XmlDocument documentInject, int numberPage, string paramNameNumberDocument, List<ItemsList.ItemAttributes> paramCopyListItemsAttributes)
{
AssertMe.assert(classItemsList != null);
XmlNodeList nodes = documentInject.GetElementsByTagName("_Items");
if (nodes.Count == 1)
numberPage++;
else
numberPage = numberPage + 2;
string[] nameKeyWords = { "товары", "согласно", "прилагаемому", "списку" };
foreach (XmlNode node in nodes)
{
string nameItem = node.SelectSingleNode("_ItemName").InnerText.ToLower();
// ДОРАБОТКА расширить условие, добавив код товара к условию
if (nameKeyWords.Any(w => nameItem.Contains(w)))
{
int numberItem = -1;
string nameCodeItem = "";
// пытаемся получить номер товара на странице Декларации
if (!int.TryParse(node.SelectSingleNode("_ItemNumber").InnerText, out numberItem))
{
warningGTDParser.Add("Не удалось извлечь номер для списка товаров из документа " + DeclarationType + ":" +
paramNameNumberDocument + " , страница: " + numberPage.ToString());
}
// берем код товара
nameCodeItem = node.SelectSingleNode("_ItemCode").InnerText.Trim();
if (!Regex.IsMatch(nameCodeItem, @"^\d+$"))
{
nameCodeItem = "";
warningGTDParser.Add("Не удалось извлечь код для списка товаров из документа " + DeclarationType + ":" +
paramNameNumberDocument + " , страница: " + numberPage.ToString());
}
if (numberItem == -1 & String.IsNullOrEmpty(nameCodeItem))
return false;
// ищем во всех листах списка товаров нужные данные
foreach (ItemsList.ItemAttributes singleItemList in classItemsList.listAttributesItem)
{
// сначала сравниваем номера
if (String.Compare(CastDocumentNumber(singleItemList.nameNumberItemDeclaration), CastDocumentNumber(paramNameNumberDocument), true) != 0)
warningGTDParser.Add("Номера документа из " + this.DeclarationType + " №: " + paramNameNumberDocument + " и списка товаров №:" + singleItemList.nameNumberItemDeclaration + " не совпадают");
// если номера товара или код совпадают, делаем вставку данных в Декларацию
if (singleItemList.numberItemInList == numberItem || string.Compare(singleItemList.nameCodeItemInList, nameCodeItem, true) == 0)
{
InjectItemListData(node, singleItemList, documentInject);
paramCopyListItemsAttributes.Remove(singleItemList);
classItemsList.condMatchedItemListCollection = true;
_countItemsCalculate = _countItemsCalculate + singleItemList.nodesTableItemsList.Count - 1;
}
}
if (!classItemsList.condMatchedItemListCollection)
{
warningGTDParser.Add("Не удалось соспоставить данные из списка товаров №: " + numberItem + " для " + DeclarationType +
" ,страница №: " + numberPage.ToString() + " и по коду товара: " + nameCodeItem);
classItemsList.condMatchedItemListCollection = false;
}
}
}
return classItemsList.condMatchedItemListCollection;
}
void InjectItemListData(XmlNode paramInjectingNode, ItemsList.ItemAttributes paramItemList, XmlDocument paramDocument)
{
XmlNode nodeNumberItem = paramInjectingNode.SelectSingleNode("_ItemNumber");
paramInjectingNode.RemoveAll();
paramInjectingNode.InsertAfter(nodeNumberItem, paramInjectingNode.FirstChild);
foreach (XmlNode newItemNode in paramItemList.nodesTableItemsList)
{
XmlNode importNode = paramDocument.ImportNode(newItemNode, true);
paramInjectingNode.InsertAfter(importNode, paramInjectingNode.LastChild);
}
EnumerateItemListNodes(paramInjectingNode, paramDocument);
}
void EnumerateItemListNodes(XmlNode paramNodeRename, XmlDocument paramDocumentInject)
{
int tagNumber = 1;
string nameNode = "_ItemDescription";
foreach (XmlNode node in paramNodeRename.SelectNodes(nameNode))
{
XmlNode newNode = paramDocumentInject.CreateNode(XmlNodeType.Element, nameNode + tagNumber.ToString(), node.ParentNode.SelectSingleNode(nameNode).NamespaceURI);
newNode.InnerXml = node.ParentNode.SelectSingleNode(nameNode).InnerXml;
node.ParentNode.ReplaceChild(newNode, node.ParentNode.SelectSingleNode(nameNode));
tagNumber++;
}
}
void DeleteExtraData()
{
XmlDocument lastDocument = addDocuments.First();
}
string CastDocumentNumber(string paramDocumentNumber) // возвращает первые две секции номера документа
{
string stringDocNumber = "";
int numberEnd = paramDocumentNumber.IndexOf('/', paramDocumentNumber.IndexOf('/') + 1);
if (numberEnd != -1)
stringDocNumber = paramDocumentNumber.Substring(0, numberEnd);
else
return paramDocumentNumber;
return Regex.Replace(stringDocNumber, @"\s+", "");
}
public void FillKDTEmptyFields(GTD_Parser GDT, bool paramCondContainAddDocuments)
{
Debug.Assert(DeclarationType == "КДТ");
var pathGDTDocument = GDT.finalXMLFileExportPath + "\\" + GDT.finalXMLFileName;
var pathKDTDocument = GDT.finalXMLFileExportPath + "\\" + this.finalXMLFileName;
XmlDocument xmlGDT = new XmlDocument();
XmlDocument xmlKDT = new XmlDocument();
try
{
xmlGDT.Load(pathGDTDocument);
xmlKDT.Load(pathKDTDocument);
}
catch (Exception ex)
{
this.errorGTDParser.Add("Ошибка заполнения пустых данных КДТ: Не удалось загрузить один из документов. " + ex.Message);
return;
}
// сначала заполняем основной лист КДТ
XmlNodeList listNodesMainDocument = xmlKDT.DocumentElement.GetElementsByTagName(nameNodeMainDocumentDefinition);
XmlNodeList listNodesDonor = xmlGDT.DocumentElement.GetElementsByTagName(GDT.nameNodeMainDocumentDefinition);
// Делаем обход по всем ячейкам и заменяем пустые значениями ячеек из ГДТ
int i = 0;
if (listNodesMainDocument.Count > 0) // сначала основная страница
{
foreach (XmlNode xmlnode in listNodesMainDocument)
{
RemoveNullChildAndAttibute(xmlnode, listNodesDonor[i], nameNodeMainDocumentDefinition);
i++;
}
}
// теперь заполняем пустые ячейки в дополнительных листах, если они есть
if (paramCondContainAddDocuments)
{
// проверяем наличие дополнительных листов ГДТ
if (!GDT.HasAdditionalPages)
{
warningGTDParser.Add("Невозможно заполнить пустые данные добавочного листа КДТ, отсутсвтует соответствующий лист ГДТ");
return;
}
Debug.Assert(!String.IsNullOrEmpty(nameNodeAdditionalDocumentDefinition));
Debug.Assert(!String.IsNullOrEmpty(GDT.nameNodeAdditionalDocumentDefinition));
XmlNodeList listNodesAdditionalKDT = xmlKDT.DocumentElement.GetElementsByTagName(nameNodeAdditionalDocumentDefinition);
XmlNodeList listNodesAdditionalGDT = xmlGDT.DocumentElement.GetElementsByTagName(GDT.nameNodeAdditionalDocumentDefinition);
if (listNodesAdditionalGDT.Count != listNodesAdditionalKDT.Count)
warningGTDParser.Add("Количество товаров в дополнительных листах ГДТ и КДТ не совпадают");
else
{
i = 0;
foreach (XmlNode additionalKDT in listNodesAdditionalKDT)
{
RemoveNullChildAndAttibute(additionalKDT, listNodesAdditionalGDT.Item(i), nameNodeAdditionalDocumentDefinition);
i++;
}
}
}
xmlKDT.Save(pathKDTDocument);
}
void RemoveNullChildAndAttibute(XmlNode xmlNode, XmlNode documentDonor, string rootKDT)
{
if (xmlNode.HasChildNodes)
{
for (int xmlNodeCount = xmlNode.ChildNodes.Count - 1; xmlNodeCount >= 0; xmlNodeCount--)
{
RemoveNullChildAndAttibute(xmlNode.ChildNodes[xmlNodeCount], documentDonor, rootKDT);
}
}
else if ((String.IsNullOrEmpty(xmlNode.InnerText) & xmlNode.Name != "_ItemCostNew" & xmlNode.Name != "_ItemCostOld" & xmlNode.Name != "_ItemCost") ||
(xmlNode.Name == "_ItemCostOld" & xmlNode.ParentNode.Name == "_ItemsTable"))
{
if (xmlNode.ParentNode != null)
{
var fullNodePath = GetNodePath(xmlNode, rootKDT);
XmlNode nodeDonor = null;
try
{
nodeDonor = documentDonor.SelectSingleNode(fullNodePath);
if (nodeDonor != null)
{
if (!String.IsNullOrEmpty(nodeDonor.InnerText))
{
XmlNode importNode = xmlNode.OwnerDocument.ImportNode(nodeDonor, true);
// копируем аттрибуты ячейки
XmlElement elementXmlDonor = documentDonor.SelectSingleNode(fullNodePath) as XmlElement;
XmlAttributeCollection collectionAttributesXml;
if (elementXmlDonor.HasAttributes)
{
XmlElement elementXml = xmlNode as XmlElement;
collectionAttributesXml = elementXmlDonor.Attributes;
foreach (XmlAttribute AttributeXml in collectionAttributesXml)
{
if (String.Compare(AttributeXml.Name, "addData:ErrorRef") == 0)
{
XmlAttribute attribute = xmlNode.OwnerDocument.CreateAttribute(AttributeXml.Name);
attribute.Value = AttributeXml.Value;
xmlNode.Attributes.Append(attribute);
}
}
}
xmlNode.ParentNode.InsertAfter(importNode, xmlNode);
xmlNode.ParentNode.RemoveChild(xmlNode);
// ДОРАБОТКА: Убрать все лишние атрибуты
//string strXMLPattern = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
//xml = Regex.Replace(xml, strXMLPattern, "");
}
}
else
{
// ДОРАБОТКА: указать точный адрес ячейки
this.warningGTDParser.Add("Не удалось заполнить пустое значение ячейки КДТ значением из ГДТ");
}
}
catch (Exception ex)
{
throw new Exception("Ошибка обработки КДТ: Не удалось сделать замену ячейки из ГДТ: " + ex);
}
}
}
else if (!String.IsNullOrEmpty(xmlNode.InnerText) & xmlNode.Name == "#text" & xmlNode.ParentNode.Name != "_ItemCostNew" &
xmlNode.ParentNode.Name != "_PageNumber" & xmlNode.ParentNode.Name != "_ItemCostOld") // добавляем атрибут для подсветки ГДТ значений
{
XmlAttribute attribute = xmlNode.OwnerDocument.CreateAttribute("DoHighlight");
attribute.Prefix = "addData";
attribute.Value = "Yes";
xmlNode.ParentNode.Attributes.Append(attribute);
}
}
// Get the node full path
string GetNodePath(XmlNode node, string stopPath)
{
string path = node.Name;
XmlNode search = null;
if (node.ParentNode == null)
return path;
// Get up until ROOT
while ((search = node.ParentNode).Name != stopPath)
{
path = search.Name + "/" + path; // Add to path
node = search;
if (node.ParentNode == null) break;
}
return path;
}
void ImportNodeAttributes(XmlNode nodeDonor, XmlNode nodeImport, string root)
{
if (nodeDonor.HasChildNodes)
{
for (int xmlNodeCount = nodeDonor.ChildNodes.Count - 1; xmlNodeCount >= 0; xmlNodeCount--)
{
ImportNodeAttributes(nodeDonor.ChildNodes[xmlNodeCount], nodeImport, root);
}
}
else if (nodeDonor.Name != "#text")
{
// копируем аттрибуты ячейки
XmlElement elementXmlDonor = nodeDonor as XmlElement;
XmlAttributeCollection collectionAttributesXml;
if (elementXmlDonor.HasAttributes)
{
XmlElement elementXml = nodeImport.SelectSingleNode(GetNodePath(nodeImport, root)) as XmlElement;
collectionAttributesXml = elementXmlDonor.Attributes;
foreach (XmlAttribute AttributeXml in collectionAttributesXml)
{
if (String.Compare(AttributeXml.Name, "addData:ErrorRef") == 0)
{
XmlAttribute attribute = nodeImport.OwnerDocument.CreateAttribute(AttributeXml.Name);
attribute.Value = AttributeXml.Value;
nodeImport.Attributes.Append(attribute);
}
}
}
}
}
XmlNode RemoveAllNamespaces(XmlNode documentElement)
{
var xmlnsPattern = "\\s+xmlns\\s*(:\\w)?\\s*=\\s*\\\"(?<url>[^\\\"]*)\\\"";
var outerXml = documentElement.OuterXml;
var matchCol = Regex.Matches(outerXml, xmlnsPattern);
foreach (var match in matchCol)
outerXml = outerXml.Replace(match.ToString(), "");
var result = new XmlDocument();
result.LoadXml(outerXml);
return result;
}