-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathEDocumentImportHelper.Codeunit.al
More file actions
1038 lines (918 loc) · 48.4 KB
/
EDocumentImportHelper.Codeunit.al
File metadata and controls
1038 lines (918 loc) · 48.4 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
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// ------------------------------------------------------------------------------------------------
namespace Microsoft.eServices.EDocument;
using Microsoft.Bank.Reconciliation;
#if not CLEAN26
using Microsoft.eServices.EDocument.Processing.Import;
#endif
using Microsoft.eServices.EDocument.Service.Participant;
using Microsoft.Finance.Currency;
using Microsoft.Finance.GeneralLedger.Journal;
using Microsoft.Finance.GeneralLedger.Setup;
using Microsoft.Finance.VAT.Calculation;
using Microsoft.Foundation.Company;
using Microsoft.Foundation.UOM;
using Microsoft.Inventory.Item;
using Microsoft.Inventory.Item.Catalog;
using Microsoft.Purchases.Document;
using Microsoft.Purchases.Setup;
using Microsoft.Purchases.Vendor;
using Microsoft.Utilities;
using System.IO;
using System.Reflection;
codeunit 6109 "E-Document Import Helper"
{
/// <summary>
/// Use it to check, resolve and update unit of measure information for the imported document line.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentLine">Imported document line.</param>
/// <returns>True if successful.</returns>
procedure ResolveUnitOfMeasureFromDataImport(var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
PurchaseLine: Record "Purchase Line";
UnitOfMeasure: Record "Unit of Measure";
UOMCodeFieldRef: FieldRef;
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
UOMCodeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Unit of Measure Code"));
end;
if Format(UOMCodeFieldRef.Value()) = '' then begin
UOMCodeFieldRef.Value('');
exit(true);
end;
UnitOfMeasure.SetRange(Code, CopyStr(UOMCodeFieldRef.Value(), 1, MaxStrLen(UnitOfMeasure.Code)));
if UnitOfMeasure.FindFirst() then begin
UOMCodeFieldRef.Value(UnitOfMeasure.Code);
exit(true);
end;
UnitOfMeasure.SetRange(Code);
UnitOfMeasure.SetRange("International Standard Code", CopyStr(UOMCodeFieldRef.Value(), 1, MaxStrLen(UnitOfMeasure."International Standard Code")));
if UnitOfMeasure.FindFirst() then begin
UOMCodeFieldRef.Value(UnitOfMeasure.Code);
exit(true);
end;
UnitOfMeasure.SetRange("International Standard Code");
UnitOfMeasure.SetRange(Description, UOMCodeFieldRef.Value());
if UnitOfMeasure.FindFirst() then begin
UOMCodeFieldRef.Value(UnitOfMeasure.Code);
exit(true);
end;
EDocErrorHelper.LogErrorMessage(EDocument, UnitOfMeasure, UnitOfMeasure.FieldNo(Code), StrSubstNo(UOMNotFoundErr, UOMCodeFieldRef.Value()));
exit(false);
end;
/// <summary>
/// Use it to find an item by reference and update item information for the imported document line.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentLine">Imported document line.</param>
/// <returns>True if successful.</returns>
procedure FindItemReferenceForLine(var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
PurchaseLine: Record "Purchase Line";
ItemReference: Record "Item Reference";
Vendor: Record Vendor;
UOMCodeFieldRef, ItemRefFieldRef, TypeFieldRef, NoFieldRef : FieldRef;
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
if not Vendor.Get(EDocument."Bill-to/Pay-to No.") then
exit(false);
ItemRefFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Item Reference No."));
TypeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo(Type));
NoFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("No."));
UOMCodeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Unit of Measure Code"));
ItemReference.SetRange("Reference Type", "Item Reference Type"::Vendor);
ItemReference.SetRange("Reference Type No.", Vendor."No.");
end;
end;
ItemReference.SetRange("Reference No.", CopyStr(ItemRefFieldRef.Value(), 1, MaxStrLen(ItemReference."Reference No.")));
if not FindMatchingItemReference(ItemReference, UOMCodeFieldRef.Value()) then
exit(false);
TypeFieldRef.Value(Format(PurchaseLine.Type::Item, 0, 9));
NoFieldRef.Value(Format(ItemReference."Item No.", 0, 9));
ResolveUnitOfMeasureFromItemReference(ItemReference, EDocument, TempDocumentLine);
exit(true);
end;
/// <summary>
/// Use it to find an item by GTIN and update item information for the imported document line.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentLine">Imported document line.</param>
/// <returns>True if successful.</returns>
procedure FindItemForLine(var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
PurchaseLine: Record "Purchase Line";
Item: Record Item;
TypeFieldRef, NoFieldRef : FieldRef;
GTIN: Text;
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
TypeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo(Type));
NoFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("No."));
end;
end;
GTIN := NoFieldRef.Value;
if GTIN = '' then
exit(false);
Item.SetRange(GTIN, GTIN);
if not Item.FindFirst() then
exit(false);
TypeFieldRef.Value(Format(PurchaseLine.Type::Item, 0, 9));
NoFieldRef.Value(Format(Item."No.", 0, 9));
ResolveUnitOfMeasureFromItem(Item, EDocument, TempDocumentLine);
exit(true);
end;
/// <summary>
/// Use it to find a G/L account by imported text in Text-to-Account Mapping and update account information for the imported document line.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentLine">Imported document line.</param>
/// <returns>True if successful.</returns>
procedure FindGLAccountForLine(var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
PurchaseLine: Record "Purchase Line";
TypeFieldRef, NoFieldRef, ItemRefNoFieldRef : FieldRef;
GLAccountNo: Code[20];
LineDescription: Text[250];
LineDirectUnitCost: Decimal;
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
TypeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo(Type));
NoFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("No."));
ItemRefNoFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Item Reference No."));
LineDescription := TempDocumentLine.Field(PurchaseLine.FieldNo(Description)).Value();
LineDirectUnitCost := TempDocumentLine.Field(PurchaseLine.FieldNo("Direct Unit Cost")).Value();
end;
end;
GLAccountNo := FindAppropriateGLAccount(EDocument, TempDocumentLine, LineDescription, LineDirectUnitCost);
if GLAccountNo <> '' then begin
NoFieldRef.Value(GLAccountNo);
TypeFieldRef.Value(Format(PurchaseLine.Type::"G/L Account", 0, 9));
ItemRefNoFieldRef.Value('');
end;
exit(GLAccountNo <> '');
end;
/// <summary>
/// Use it to log an error if an item or a G/L account is not found for the imported document line.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentLine">Imported document line.</param>
/// <returns>True if successful.</returns>
procedure LogErrorIfItemNotFound(var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
PurchaseLine: Record "Purchase Line";
Item: Record Item;
GTIN, ItemName, VendorItemNo : Text[250];
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
GTIN := TempDocumentLine.Field(PurchaseLine.FieldNo("No.")).Value();
VendorItemNo := TempDocumentLine.Field(PurchaseLine.FieldNo("Item Reference No.")).Value();
ItemName := TempDocumentLine.Field(PurchaseLine.FieldNo(Description)).Value();
end;
end;
if (GTIN <> '') and (VendorItemNo <> '') then begin
EDocErrorHelper.LogErrorMessage(EDocument, Item, Item.FieldNo("No."), StrSubstNo(ItemNotFoundErr, ItemName, EDocument."Bill-to/Pay-to No.", VendorItemNo, GTIN));
exit(false);
end;
if GTIN <> '' then begin
EDocErrorHelper.LogErrorMessage(EDocument, Item, Item.FieldNo("No."), StrSubstNo(ItemNotFoundByGTINErr, ItemName, GTIN));
exit(false);
end;
if VendorItemNo <> '' then begin
EDocErrorHelper.LogErrorMessage(EDocument, Item, Item.FieldNo("No."), StrSubstNo(ItemNotFoundByVendorItemNoErr, ItemName, EDocument."Bill-to/Pay-to No.", VendorItemNo));
exit(false);
end;
exit(true);
end;
/// <summary>
/// Use it to validate discount for the imported document line.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentLine">Imported document line.</param>
procedure ValidateLineDiscount(var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef)
var
PurchaseLine: Record "Purchase Line";
LineDirectUnitCostFieldRef, LineQuantityFieldRef, LineAmountFieldRef, LineDiscountAmountFieldRef : FieldRef;
LineDirectUnitCost: Decimal;
LineAmount: Decimal;
LineQuantity: Decimal;
LineDiscountAmount: Decimal;
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
LineDirectUnitCostFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Direct Unit Cost"));
LineQuantityFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo(Quantity));
LineAmountFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo(Amount));
LineDiscountAmountFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Line Discount Amount"));
end;
end;
LineDirectUnitCost := LineDirectUnitCostFieldRef.Value();
LineQuantity := LineQuantityFieldRef.Value();
LineAmount := LineAmountFieldRef.Value();
LineDiscountAmount := (LineQuantity * LineDirectUnitCost) - LineAmount;
LineDiscountAmountFieldRef.Value(LineDiscountAmount);
end;
/// <summary>
/// Use it to check if receiving company information is in line with Company Information.
/// Also checks if the Receiving Company Id matches a Company Service Participant.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="EDocService">The E-Document Service record to match against.</param>
procedure ValidateReceivingCompanyInfo(EDocument: Record "E-Document"; EDocService: Record "E-Document Service")
begin
// First, check if the Receiving Company Id matches a Company Service Participant
if MatchCompanyByServiceParticipant(EDocument, EDocService) then
exit;
ValidateReceivingCompanyInfo(EDocument);
end;
/// <summary>
/// Use it to check if receiving company information is in line with Company Information.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
procedure ValidateReceivingCompanyInfo(EDocument: Record "E-Document")
var
CompanyInformation: Record "Company Information";
begin
CompanyInformation.Get();
if (EDocument."Receiving Company GLN" = '') and (EDocument."Receiving Company VAT Reg. No." = '') then begin
ValidateReceivingCompanyInfoByNameAndAddress(EDocument);
exit;
end;
if (CompanyInformation.GLN = '') and (CompanyInformation."VAT Registration No." = '') then
EDocErrorHelper.LogErrorMessage(EDocument, CompanyInformation, CompanyInformation.FieldNo(GLN), MissingCompanyInfoSetupErr);
if not (CompanyInformation.GLN in ['', EDocument."Receiving Company GLN"]) then
EDocErrorHelper.LogErrorMessage(EDocument, CompanyInformation, CompanyInformation.FieldNo(GLN), StrSubstNo(InvalidCompanyInfoGLNErr, EDocument."Receiving Company GLN"));
if not (ExtractVatRegNo(CompanyInformation."VAT Registration No.", '') in ['', ExtractVatRegNo(EDocument."Receiving Company VAT Reg. No.", '')]) then
EDocErrorHelper.LogErrorMessage(EDocument, CompanyInformation, CompanyInformation.FieldNo("VAT Registration No."), StrSubstNo(InvalidCompanyInfoVATRegNoErr, EDocument."Receiving Company VAT Reg. No."));
end;
/// <summary>
/// Use it to check if receiving company information matches a Company Service Participant for a specific service.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="EDocService">The E-Document Service record to match against.</param>
/// <returns>True if a matching Company Service Participant is found.</returns>
local procedure MatchCompanyByServiceParticipant(EDocument: Record "E-Document"; EDocService: Record "E-Document Service"): Boolean
var
ServiceParticipant: Record "Service Participant";
begin
if EDocument."Receiving Company Id" = '' then
exit(false);
ServiceParticipant.SetRange("Participant Type", ServiceParticipant."Participant Type"::Company);
ServiceParticipant.SetRange("Participant Identifier", EDocument."Receiving Company Id");
ServiceParticipant.SetRange(Service, EDocService.Code);
exit(not ServiceParticipant.IsEmpty());
end;
/// <summary>
/// Use it to check if receiving company name and address is in line with Company Information.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
procedure ValidateReceivingCompanyInfoByNameAndAddress(EDocument: Record "E-Document")
var
CompanyInfo: Record "Company Information";
RecordMatchMgt: Codeunit "Record Match Mgt.";
CompanyName: Text;
CompanyAddr: Text;
NameNearness: Integer;
AddressNearness: Integer;
begin
CompanyInfo.Get();
CompanyName := CompanyInfo.Name;
CompanyAddr := CompanyInfo.Address;
NameNearness := RecordMatchMgt.CalculateStringNearness(CompanyName, EDocument."Receiving Company Name", MatchThreshold(), NormalizingFactor());
AddressNearness := RecordMatchMgt.CalculateStringNearness(CompanyAddr, EDocument."Receiving Company Address", MatchThreshold(), NormalizingFactor());
if (EDocument."Receiving Company Name" <> '') and (NameNearness < RequiredNearness()) then
EDocErrorHelper.LogErrorMessage(EDocument, CompanyInfo, CompanyInfo.FieldNo(Name), StrSubstNo(InvalidCompanyInfoNameErr, EDocument."Receiving Company Name"));
if (EDocument."Receiving Company Address" <> '') and (AddressNearness < RequiredNearness()) then
EDocErrorHelper.LogErrorMessage(EDocument, CompanyInfo, CompanyInfo.FieldNo(Address), StrSubstNo(InvalidCompanyInfoAddressErr, EDocument."Receiving Company Address"));
end;
/// <summary>
/// Use it to apply invoice discount for the imported document.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentHeader">Imported document header.</param>
/// <param name="DocumentHeader">Created document header.</param>
procedure ApplyInvoiceDiscount(var EDocument: Record "E-Document"; var TempDocumentHeader: RecordRef; var DocumentHeader: RecordRef)
var
PurchaseHeader: Record "Purchase Header";
PurchLine: Record "Purchase Line";
#pragma warning disable AL0432
TempVATAmountLine: Record "VAT Amount Line" temporary;
#pragma warning restore AL0432
PurchCalcDiscByType: Codeunit "Purch - Calc Disc. By Type";
InvoiceDiscountAmount: Decimal;
InvDiscBaseAmount: Decimal;
begin
case TempDocumentHeader.Number of
Database::"Purchase Header":
begin
DocumentHeader.SetTable(PurchaseHeader);
InvoiceDiscountAmount := TempDocumentHeader.Field(PurchaseHeader.FieldNo("Invoice Discount Value")).Value();
if InvoiceDiscountAmount = 0 then
exit;
if InvoiceDiscountAmount > 0 then begin
PurchLine.SetRange("Document No.", PurchaseHeader."No.");
PurchLine.SetRange("Document Type", PurchaseHeader."Document Type");
PurchLine.CalcVATAmountLines(0, PurchaseHeader, PurchLine, TempVATAmountLine);
InvDiscBaseAmount := TempVATAmountLine.GetTotalInvDiscBaseAmount(false, PurchaseHeader."Currency Code");
if PurchCalcDiscByType.InvoiceDiscIsAllowed(PurchaseHeader."Invoice Disc. Code") and (InvDiscBaseAmount <> 0) then
PurchCalcDiscByType.ApplyInvDiscBasedOnAmt(InvoiceDiscountAmount, PurchaseHeader)
else
EDocErrorHelper.LogErrorMessage(EDocument, PurchaseHeader, PurchaseHeader.FieldNo("No."), StrSubstNo(UnableToApplyDiscountErr, InvoiceDiscountAmount));
end;
end;
end;
end;
/// <summary>
/// Use it to verify compare imported document totals with created docuemnt totals.
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="TempDocumentHeader">Imported document header.</param>
/// <param name="DocumentHeader">Created document header.</param>
procedure VerifyTotal(var EDocument: Record "E-Document"; var TempDocumentHeader: RecordRef; var DocumentHeader: RecordRef)
var
PurchaseHeader: Record "Purchase Header";
TempTotalPurchaseLine: Record "Purchase Line" temporary;
CurrentPurchaseLine: Record "Purchase Line";
DocumentTotals: Codeunit "Document Totals";
AmountIncludingVATFromFile: Decimal;
VATAmount: Decimal;
begin
case TempDocumentHeader.Number of
Database::"Purchase Header":
begin
DocumentHeader.SetTable(PurchaseHeader);
AmountIncludingVATFromFile := TempDocumentHeader.Field(PurchaseHeader.FieldNo("Amount Including VAT")).Value();
if AmountIncludingVATFromFile = 0 then
exit;
VATAmount := 0;
TempTotalPurchaseLine.Init();
CurrentPurchaseLine.SetRange("Document Type", PurchaseHeader."Document Type");
CurrentPurchaseLine.SetRange("Document No.", PurchaseHeader."No.");
// calculate totals and compare them with values from the incoming document
if CurrentPurchaseLine.FindFirst() then begin
DocumentTotals.PurchaseCalculateTotalsWithInvoiceRounding(CurrentPurchaseLine, VATAmount, TempTotalPurchaseLine);
if AmountIncludingVATFromFile <> TempTotalPurchaseLine."Amount Including VAT" then
EDocErrorHelper.LogSimpleErrorMessage(EDocument, StrSubstNo(TotalsMismatchErr, TempTotalPurchaseLine."Amount Including VAT", AmountIncludingVATFromFile));
end;
end;
end;
end;
/// <summary>
/// Use it to find a vendor by number, GLN or VAT registration number.
/// </summary>
/// <param name="VendorNoText">Vendor's number.</param>
/// <param name="GLN">Vendor's GLN.</param>
/// <param name="VATRegistrationNo">Vendor's VAT registration number.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendor(VendorNoText: Code[20]; GLN: Code[13]; VATRegistrationNo: Text[20]): Code[20]
var
VendorNo: Code[20];
begin
VendorNo := FindVendorByNo(VendorNoText);
if VendorNo <> '' then
exit(VendorNo);
VendorNo := FindVendorByGLN(GLN);
if VendorNo <> '' then
exit(VendorNo);
VendorNo := FindVendorByVATRegistrationNo(VATRegistrationNo);
if VendorNo <> '' then
exit(VendorNo);
end;
/// <summary>
/// Use it to find a vendor by Id.
/// </summary>
/// <param name="VendorIdText">Vendor's Id.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorById(VendorIdText: Text): Code[20]
var
Vendor: Record Vendor;
VendorId: Guid;
begin
if VendorIdText = '' then
exit('');
if not Evaluate(VendorId, VendorIdText, 9) then
exit('');
if Vendor.GetBySystemId(VendorId) then
exit(Vendor."No.");
end;
/// <summary>
/// Use it to find a vendor by number.
/// </summary>
/// <param name="VendorNoText">Vendor's number.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByNo(VendorNoText: Code[20]): Code[20]
var
Vendor: Record Vendor;
begin
if VendorNoText = '' then
exit('');
if Vendor.Get(VendorNoText) then
exit(Vendor."No.");
end;
/// <summary>
/// Use it to find a vendor by GLN.
/// </summary>
/// <param name="GLN">Vendor's GLN.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByGLN(GLN: Code[13]): Code[20]
var
Vendor: Record Vendor;
begin
if GLN = '' then
exit('');
Vendor.SetRange(GLN, GLN);
if Vendor.FindFirst() then
exit(Vendor."No.");
end;
/// <summary>
/// Use it to find a vendor by VAT registration number.
/// </summary>
/// <param name="VATRegistrationNo">Vendor's VAT registration number.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByVATRegistrationNo(VATRegistrationNo: Text[20]): Code[20]
var
Vendor: Record Vendor;
VendorNo: Code[20];
begin
if VATRegistrationNo = '' then
exit('');
VendorNo := Vendor.FindVendorByVATRegistrationNo(VATRegistrationNo);
exit(VendorNo);
end;
/// <summary>
/// Use it to find a vendor by phone number.
/// </summary>
/// <param name="PhoneNo">Vendor's Phone number.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByPhoneNo(PhoneNo: Text): Code[20]
var
Vendor: Record Vendor;
RecordMatchMgt: Codeunit "Record Match Mgt.";
PhoneNoNearness: Integer;
begin
if PhoneNo = '' then
exit('');
PhoneNo := DelChr(PhoneNo, '=', DelChr(PhoneNo, '=', '0123456789'));
Vendor.SetCurrentKey(Blocked);
Vendor.SetLoadFields("Phone No.");
if Vendor.FindSet() then
repeat
PhoneNoNearness := RecordMatchMgt.CalculateStringNearness(PhoneNo, Vendor."Phone No.", MatchThreshold(), NormalizingFactor());
if PhoneNoNearness >= RequiredNearness() then
exit(Vendor."No.");
until Vendor.Next() = 0;
end;
/// <summary>
/// Use it to find a vendor by name and address.
/// </summary>
/// <param name="VendorName">Vendor's name.</param>
/// <param name="VendorAddress">Vendor's address.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByNameAndAddress(VendorName: Text; VendorAddress: Text): Code[20]
begin
exit(FindVendorByNameAndAddressWithNotification(VendorName, VendorAddress, 0));
end;
/// <summary>
/// Use it to find a vendor by name and address and raise a notification if vendor is found by name but not by address.
/// </summary>
/// <param name="VendorName">Name of a vendor</param>
/// <param name="VendorAddress">Address of a vendor</param>
/// <param name="EDocumentEntryNo">Id of e-document</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByNameAndAddressWithNotification(VendorName: Text; VendorAddress: Text; EDocEntryNoForNotification: Integer): Code[20]
var
Vendor: Record Vendor;
RecordMatchMgt: Codeunit "Record Match Mgt.";
EDocumentNotification: Codeunit "E-Document Notification";
NameNearness: Integer;
AddressNearness: Integer;
MatchedByAddress: Boolean;
begin
Vendor.SetCurrentKey(Blocked);
Vendor.SetLoadFields(Name, Address);
if Vendor.FindSet() then
repeat
NameNearness := RecordMatchMgt.CalculateStringNearness(VendorName, Vendor.Name, MatchThreshold(), NormalizingFactor());
if VendorAddress = '' then
AddressNearness := RequiredNearness()
else
AddressNearness := RecordMatchMgt.CalculateStringNearness(VendorAddress, Vendor.Address, MatchThreshold(), NormalizingFactor());
if NameNearness >= RequiredNearness() then begin
MatchedByAddress := AddressNearness >= RequiredNearness();
if MatchedByAddress then
exit(Vendor."No.");
if EDocEntryNoForNotification <> 0 then
EDocumentNotification.AddVendorMatchedByNameNotAddressNotification(EDocEntryNoForNotification);
end;
until Vendor.Next() = 0;
end;
/// <summary>
/// Use it to find a vendor by IBAN, vendor bank branch number and vendor bank account number.
/// </summary>
/// <param name="VendorIBAN">Vendor's IBAN.</param>
/// <param name="VendorBankBranchNo">Vendor's bank account branch number.</param>
/// <param name="VendorBankAccountNo">Vendor's bank account number.</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByBankAccount(VendorIBAN: Code[50]; VendorBankBranchNo: Text[20]; VendorBankAccountNo: Text[30]): Code[20]
var
VendorBankAccount: Record "Vendor Bank Account";
VendorNo: Code[20];
begin
if VendorIBAN <> '' then begin
VendorBankAccount.SetRange(IBAN, VendorIBAN);
VendorNo := TryFindLeastBlockedVendorNoByVendorBankAcc(VendorBankAccount);
end;
if (VendorNo = '') and (VendorBankBranchNo <> '') and (VendorBankAccountNo <> '') then begin
VendorBankAccount.Reset();
VendorBankAccount.SetRange("Bank Branch No.", VendorBankBranchNo);
VendorBankAccount.SetRange("Bank Account No.", VendorBankAccountNo);
VendorNo := TryFindLeastBlockedVendorNoByVendorBankAcc(VendorBankAccount);
end;
if VendorNo <> '' then
exit(VendorNo);
end;
/// <summary>
/// Use it to get a vendor by number, or rise an error if vendor does not exist
/// </summary>
/// <param name="VendorNo">Vendor's number</param>
/// <returns>Vendor record if exists or error.</returns>
procedure GetVendor(var EDocument: Record "E-Document"; VendorNo: Code[20]) Vendor: Record Vendor
begin
if not Vendor.Get(VendorNo) then
EDocErrorHelper.LogSimpleErrorMessage(EDocument, StrSubstNo(VendorNotFoundErr, EDocument."Bill-to/Pay-to Name"));
end;
/// <summary>
/// Use it to find a vendor by service participant
/// </summary>
/// <param name="VendorID">Vendor's ID</param>
/// <param name="EDocumentServiceCode">E-Document Service code</param>
/// <returns>Vendor number if exists or empty string.</returns>
procedure FindVendorByServiceParticipant(VendorID: Text[200]; EDocumentServiceCode: Code[20]): Code[20]
var
ServiceParticipant: Record "Service Participant";
begin
ServiceParticipant.SetRange("Participant Type", ServiceParticipant."Participant Type"::Vendor);
ServiceParticipant.SetRange("Participant Identifier", VendorID);
ServiceParticipant.SetRange(Service, EDocumentServiceCode);
if ServiceParticipant.FindFirst() then
exit(ServiceParticipant.Participant);
ServiceParticipant.SetRange(Service);
if ServiceParticipant.FindFirst() then
exit(ServiceParticipant.Participant);
end;
#if not CLEAN26
/// <summary>
/// Use it to process imported E-Document
/// </summary>
/// <param name="EDocument">The E-Document record.</param>
/// <param name="CreateJnlLine">If processing should create journal line</param>
[Obsolete('Use codeunit 6140 "E-Doc. Import"''s method ProcessIncomingEDocument', '26.0')]
procedure ProcessDocument(var EDocument: Record "E-Document"; CreateJnlLine: Boolean)
var
EDocImportParameters: Record "E-Doc. Import Parameters";
begin
EDocImportParameters."Step to Run" := "Import E-Document Steps"::"Finish draft";
EDocumentImport.ProcessIncomingEDocument(EDocument, EDocImportParameters);
end;
#endif
/// <summary>
/// Use it to set hide dialogs when importing E-Document.
/// </summary>
/// <param name="Hide">Hide or show the dialog.</param>
procedure SetHideDialogs(Hide: Boolean)
begin
EDocumentImport.SetHideDialogs(Hide);
end;
/// <summary>
/// Use it to find attachment file extension when importing E-Document.
/// </summary>
procedure DetermineFileType(MimeType: Text): Text
begin
case MimeType of
'image/jpeg':
exit('jpeg');
'image/png':
exit('png');
'application/pdf':
exit('pdf');
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.oasis.opendocument.spreadsheet':
exit('xlsx');
else
exit('');
end;
end;
local procedure TryFindLeastBlockedVendorNoByVendorBankAcc(var VendorBankAccount: record "Vendor Bank Account"): Code[20]
var
Vendor: Record Vendor;
NonBlockedVendorNo: Code[20];
BlockedPaymentVendorNo: Code[20];
BlockedAllVendorNo: Code[20];
begin
BlockedAllVendorNo := '';
BlockedPaymentVendorNo := '';
if VendorBankAccount.FindSet() then
repeat
if Vendor.Get(VendorBankAccount."Vendor No.") then begin
if Vendor.Blocked = "Vendor Blocked"::" " then
NonBlockedVendorNo := Vendor."No.";
if (Vendor.Blocked = "Vendor Blocked"::Payment) and (BlockedPaymentVendorNo = '') then
BlockedPaymentVendorNo := Vendor."No.";
if (Vendor.Blocked = "Vendor Blocked"::All) and (BlockedAllVendorNo = '') then
BlockedAllVendorNo := Vendor."No.";
end;
until (VendorBankAccount.Next() = 0) or (NonBlockedVendorNo <> '');
if NonBlockedVendorNo <> '' then
exit(NonBlockedVendorNo);
if BlockedPaymentVendorNo <> '' then
exit(BlockedPaymentVendorNo);
if BlockedAllVendorNo <> '' then
exit(BlockedAllVendorNo);
exit('');
end;
internal procedure ProcessField(EDocument: Record "E-Document"; RecRef: RecordRef; Field: Record Field; DocumentFieldRef: FieldRef)
begin
if Field.Type = Field.Type::Decimal then
ProcessDecimalField(EDocument, RecRef, Field."No.", DocumentFieldRef.Value())
else
ProcessField(EDocument, RecRef, Field."No.", DocumentFieldRef.Value());
end;
internal procedure ProcessFieldNoValidate(RecRef: RecordRef; FieldNo: Integer; Value: Text[250])
var
FieldRef: FieldRef;
begin
FieldRef := RecRef.Field(FieldNo);
FieldRef.Value(Value);
end;
internal procedure ProcessField(EDocument: Record "E-Document"; RecRef: RecordRef; FieldNo: Integer; Value: Text[250])
var
FieldRef: FieldRef;
begin
FieldRef := RecRef.Field(FieldNo);
SetFieldValue(EDocument, FieldRef, Value);
end;
internal procedure ProcessDecimalField(EDocument: Record "E-Document"; RecRef: RecordRef; FieldNo: Integer; Value: Decimal)
var
FieldRef: FieldRef;
begin
FieldRef := RecRef.Field(FieldNo);
SetDecimalFieldValue(EDocument, FieldRef, Value);
end;
internal procedure GetCurrencyRoundingPrecision(CurrencyCode: Code[10]): Decimal
var
GeneralLedgerSetup: Record "General Ledger Setup";
Currency: Record Currency;
AmountRoundingPrecision: Decimal;
begin
GeneralLedgerSetup.Get();
AmountRoundingPrecision := GeneralLedgerSetup."Amount Rounding Precision";
if CurrencyCode <> '' then
if Currency.Get(CurrencyCode) then
AmountRoundingPrecision := Currency."Amount Rounding Precision";
exit(AmountRoundingPrecision);
end;
local procedure FindAppropriateGLAccount(var EDocument: Record "E-Document"; var SourceRecRef: RecordRef; LineDescription: Text[250]; LineDirectUnitCost: Decimal): Code[20]
var
PurchasesPayablesSetup: Record "Purchases & Payables Setup";
TextToAccountMapping: Record "Text-to-Account Mapping";
PurchaseHeader: Record "Purchase Header";
PurchaseLine: Record "Purchase Line";
DocumentTypeTxt: Text;
DocumentType: Enum "Gen. Journal Document Type";
DefaultGLAccount: Code[20];
CountOfResult: Integer;
begin
case SourceRecRef.Number of
Database::"Purchase Line":
DocumentTypeTxt := SourceRecRef.Field(PurchaseLine.FieldNo("Document Type")).Value();
Database::"Purchase Header":
DocumentTypeTxt := SourceRecRef.Field(PurchaseHeader.FieldNo("Document Type")).Value();
end;
if not Evaluate(DocumentType, DocumentTypeTxt) then
exit('');
CountOfResult := TextToAccountMapping.SearchEnteriesInText(TextToAccountMapping, LineDescription, EDocument."Bill-to/Pay-to No.");
if CountOfResult = 1 then
exit(FindCorrectAccountFromMapping(TextToAccountMapping, LineDirectUnitCost, DocumentType));
if CountOfResult > 1 then begin
EDocErrorHelper.LogErrorMessage(EDocument, TextToAccountMapping, TextToAccountMapping.FieldNo("Mapping Text"), StrSubstNo(UnableToFindAppropriateAccountErr, LineDescription));
exit('');
end;
if EDocument."Bill-to/Pay-to No." <> '' then begin
CountOfResult := TextToAccountMapping.SearchEnteriesInText(TextToAccountMapping, LineDescription, '');
if CountOfResult = 1 then
exit(FindCorrectAccountFromMapping(TextToAccountMapping, LineDirectUnitCost, DocumentType));
if CountOfResult > 1 then begin
EDocErrorHelper.LogErrorMessage(EDocument, TextToAccountMapping, TextToAccountMapping.FieldNo("Mapping Text"), StrSubstNo(UnableToFindAppropriateAccountErr, LineDescription));
exit('');
end;
end;
// if you don't find any suggestion in Text-to-Account Mapping, then look in the Purchases & Payables table
PurchasesPayablesSetup.Get();
case DocumentType of
"Gen. Journal Document Type"::Invoice:
if LineDirectUnitCost >= 0 then
DefaultGLAccount := PurchasesPayablesSetup."Debit Acc. for Non-Item Lines"
else
DefaultGLAccount := PurchasesPayablesSetup."Credit Acc. for Non-Item Lines";
"Gen. Journal Document Type"::"Credit Memo":
if LineDirectUnitCost >= 0 then
DefaultGLAccount := PurchasesPayablesSetup."Credit Acc. for Non-Item Lines"
else
DefaultGLAccount := PurchasesPayablesSetup."Debit Acc. for Non-Item Lines";
end;
if DefaultGLAccount = '' then
EDocErrorHelper.LogErrorMessage(EDocument, TextToAccountMapping, TextToAccountMapping.FieldNo("Mapping Text"), StrSubstNo(UnableToFindAppropriateAccountErr, LineDescription));
exit(DefaultGLAccount)
end;
local procedure FindMatchingItemReference(var ItemReference: Record "Item Reference"; ImportedUnitCode: Code[10]): Boolean
begin
if not ItemReference.FindFirst() then
exit(false);
ItemReference.SetRange("Unit of Measure", ImportedUnitCode);
if ItemReference.FindSet() then
repeat
if ItemReference.HasValidUnitOfMeasure() then
exit(true);
until ItemReference.Next() = 0;
ItemReference.SetRange("Unit of Measure", '');
if ItemReference.FindSet() then
repeat
if ItemReference.HasValidUnitOfMeasure() then
exit(true);
until ItemReference.Next() = 0;
ItemReference.SetRange("Unit of Measure");
exit(ItemReference.FindFirst());
end;
local procedure ResolveUnitOfMeasureFromItemReference(var ItemReference: Record "Item Reference"; var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
Item: Record Item;
PurchaseLine: Record "Purchase Line";
UOMCodeFieldRef, LineNoFieldRef : FieldRef;
ResolvedUnitCode: Code[10];
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
LineNoFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Line No."));
UOMCodeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Unit of Measure Code"));
end;
end;
ResolvedUnitCode := ItemReference."Unit of Measure";
if ResolvedUnitCode = '' then begin
Item.Get(ItemReference."Item No.");
exit(ResolveUnitOfMeasureFromItem(Item, EDocument, TempDocumentLine));
end;
if not (Format(UOMCodeFieldRef.Value()) in ['', ResolvedUnitCode]) then begin
EDocErrorHelper.LogErrorMessage(EDocument, ItemReference, ItemReference.FieldNo("Unit of Measure"), StrSubstNo(UOMConflictWithItemRefErr, UOMCodeFieldRef.Value(), LineNoFieldRef.Value(), UnitCodeToString(ResolvedUnitCode)));
exit(false);
end;
if not ItemReference.HasValidUnitOfMeasure() then begin
EDocErrorHelper.LogErrorMessage(EDocument, ItemReference, ItemReference.FieldNo("Unit of Measure"), StrSubstNo(UOMConflictItemRefWithItemErr, UnitCodeToString(ResolvedUnitCode)));
exit(false);
end;
InsertOrUpdateUnitOfMeasureCode(TempDocumentLine, ResolvedUnitCode);
exit(true);
end;
local procedure ResolveUnitOfMeasureFromItem(var Item: Record Item; var EDocument: Record "E-Document"; var TempDocumentLine: RecordRef): Boolean
var
PurchaseLine: Record "Purchase Line";
UOMCodeFieldRef, LineNoFieldRef : FieldRef;
ResolvedUnitCode: Code[10];
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
begin
LineNoFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Line No."));
UOMCodeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Unit of Measure Code"));
ResolvedUnitCode := Item."Purch. Unit of Measure";
end;
end;
if ResolvedUnitCode = '' then
ResolvedUnitCode := Item."Base Unit of Measure";
if not (Format(UOMCodeFieldRef.Value()) in ['', ResolvedUnitCode]) then begin
EDocErrorHelper.LogErrorMessage(EDocument, Item, Item.FieldNo("Base Unit of Measure"), StrSubstNo(UOMConflictWithItemErr, UOMCodeFieldRef.Value(), LineNoFieldRef.Value, UnitCodeToString(ResolvedUnitCode)));
exit(false);
end;
InsertOrUpdateUnitOfMeasureCode(TempDocumentLine, ResolvedUnitCode);
exit(true);
end;
local procedure InsertOrUpdateUnitOfMeasureCode(var TempDocumentLine: RecordRef; UnitCode: Code[10])
var
PurchaseLine: Record "Purchase Line";
UOMCodeFieldRef: FieldRef;
begin
case TempDocumentLine.Number of
Database::"Purchase Line":
UOMCodeFieldRef := TempDocumentLine.Field(PurchaseLine.FieldNo("Unit of Measure Code"));
end;
UOMCodeFieldRef.Value(UnitCode);
end;
local procedure UnitCodeToString(UnitCode: Code[10]): Text
begin
if UnitCode <> '' then
exit(UnitCode);
exit(NotSpecifiedUnitOfMeasureTxt);
end;
local procedure FindCorrectAccountFromMapping(TextToAccountMapping: Record "Text-to-Account Mapping"; LineDirectUnitCost: Decimal; DocumentType: Enum "Gen. Journal Document Type"): Code[20]
begin
case DocumentType of
"Gen. Journal Document Type"::Invoice:
begin
if (LineDirectUnitCost >= 0) and (TextToAccountMapping."Debit Acc. No." <> '') then
exit(TextToAccountMapping."Debit Acc. No.");
if (LineDirectUnitCost < 0) and (TextToAccountMapping."Credit Acc. No." <> '') then
exit(TextToAccountMapping."Credit Acc. No.");
end;
"Gen. Journal Document Type"::"Credit Memo":
begin
if (LineDirectUnitCost >= 0) and (TextToAccountMapping."Credit Acc. No." <> '') then
exit(TextToAccountMapping."Credit Acc. No.");
if (LineDirectUnitCost < 0) and (TextToAccountMapping."Debit Acc. No." <> '') then
exit(TextToAccountMapping."Debit Acc. No.");
end;
end
end;
local procedure ExtractVatRegNo(VatRegNo: Text; CountryRegionCode: Text): Text
var
CompanyInformation: Record "Company Information";
begin
if CountryRegionCode = '' then begin
CompanyInformation.Get();
CountryRegionCode := CompanyInformation."Country/Region Code";
end;
VatRegNo := UpperCase(VatRegNo);
VatRegNo := DelChr(VatRegNo, '=', DelChr(VatRegNo, '=', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'));
if StrPos(VatRegNo, UpperCase(CountryRegionCode)) = 1 then
VatRegNo := DelStr(VatRegNo, 1, StrLen(CountryRegionCode));
exit(VatRegNo);
end;
local procedure SetDecimalFieldValue(EDocument: Record "E-Document"; var FieldRef: FieldRef; Value: Decimal)
var
ConfigValidateManagement: Codeunit "Config. Validate Management";
ErrorText: Text;
begin
// ConfigValidateManagement works with XML formats, but we need to adapt it to the regional settings
ErrorText := ConfigValidateManagement.EvaluateValueWithValidate(FieldRef, Format(Value, 0, 9), false);
if ErrorText <> '' then
EDocErrorHelper.LogSimpleErrorMessage(EDocument, ErrorText);
end;
local procedure SetFieldValue(EDocument: Record "E-Document"; var FieldRef: FieldRef; Value: Text[250])
var
ConfigValidateManagement: Codeunit "Config. Validate Management";
ErrorText: Text;
begin
TruncateValueToFieldLength(FieldRef, Value);
ErrorText := ConfigValidateManagement.EvaluateValueWithValidate(FieldRef, Value, false);
if ErrorText <> '' then
EDocErrorHelper.LogSimpleErrorMessage(EDocument, ErrorText);
end;
local procedure TruncateValueToFieldLength(FieldRef: FieldRef; var Value: Text[250])
begin
if FieldRef.Type in [FieldType::Code, FieldType::Text] then
Value := CopyStr(Value, 1, FieldRef.Length);