Codeunit 6102 E-Doc. Export

E-Document Core, Microsoft.eServices.EDocument

src/Apps/W1/EDocument/App/src/Processing/EDocExport.Codeunit.al760 lines, Copyright (c) Microsoft Corporation. MIT

// ------------------------------------------------------------------------------------------------// 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.eServices.EDocument.Processing.Interfaces;using Microsoft.Finance.GeneralLedger.Journal;using Microsoft.Foundation.Reporting;using Microsoft.Inventory.Transfer;using Microsoft.Peppol;using Microsoft.Purchases.Document;using Microsoft.Purchases.History;using Microsoft.Purchases.Payables;using Microsoft.Purchases.Vendor;using Microsoft.Sales.Document;using Microsoft.Sales.FinanceCharge;using Microsoft.Sales.History;using Microsoft.Sales.Reminder;using Microsoft.Service.Document;using Microsoft.Service.History;using System.Automation;using System.Telemetry;using System.Utilities;codeunit 6102 "E-Doc. Export"{    Permissions =        tabledata "E-Document" = im,        tabledata "E-Doc. Mapping" = im,        tabledata "E-Doc. Mapping Log" = im;    internal procedure CheckEDocument(var EDocSourceRecRef: RecordRef; EDocumentProcessingPhase: Enum "E-Document Processing Phase")    var        EDocumentService: Record "E-Document Service";        DocumentSendingProfile: Record "Document Sending Profile";        WorkFlow: Record Workflow;        EDocWorkFlowProcessing: Codeunit "E-Document WorkFlow Processing";        IsHandled: Boolean;        Type: Enum "E-Document Type";    begin        OnBeforeEDocumentCheck(EDocSourceRecRef, EDocumentProcessingPhase, IsHandled);        if IsHandled then            exit;        DocumentSendingProfile := EDocumentProcessing.GetDocSendingProfileForDocRef(EDocSourceRecRef);        if (DocumentSendingProfile."Electronic Document" = DocumentSendingProfile."Electronic Document"::"Extended E-Document Service Flow") and (not WorkFlow.Get(DocumentSendingProfile."Electronic Service Flow")) then            Error(DocumentSendingProfileWithWorkflowErr, DocumentSendingProfile."Electronic Service Flow", Format(DocumentSendingProfile."Electronic Document"::"Extended E-Document Service Flow"), DocumentSendingProfile.Code);        WorkFlow.TestField(Enabled);        if EDocWorkFlowProcessing.DoesFlowHasEDocService(EDocumentService, DocumentSendingProfile."Electronic Service Flow") then            if EDocumentService.FindSet() then                repeat                    Type := EDocumentProcessing.GetTypeFromSourceDocument(EDocSourceRecRef);                    if IsDocumentSupported(EDocumentService, EDocSourceRecRef, Type) then begin                        EDocumentInterface := EDocumentService."Document Format";                        EDocumentInterface.Check(EDocSourceRecRef, EDocumentService, EDocumentProcessingPhase);                    end;                until EDocumentService.Next() = 0;        OnAfterEDocumentCheck(EDocSourceRecRef, EDocumentProcessingPhase);    end;    /// <summary>    /// Creates a new E-Document for the provided document header and attempts to export it.    /// </summary>    /// <returns>    /// true if the E-Document has been created;    /// otherwise false.    /// </returns>    internal procedure CreateEDocument(DocumentHeader: RecordRef; DocumentSendingProfile: Record "Document Sending Profile"; EDocumentType: Enum "E-Document Type"): Boolean    begin        exit(CreateEDocument(DocumentHeader, DocumentSendingProfile, EDocumentType, false));    end;    /// <summary>    /// Creates a new E-Document of specified type for the provided document header and attempts to export it.    /// </summary>    /// <returns>    /// true if the E-Document has been created;    /// otherwise false.    /// </returns>    internal procedure CreateEDocument(DocumentHeader: RecordRef; DocumentSendingProfile: Record "Document Sending Profile"; EDocumentType: Enum "E-Document Type"; AllowReExport: Boolean): Boolean    var        WorkFlow: Record Workflow;        EDocumentService: Record "E-Document Service";        EDocWorkFlowProcessing: Codeunit "E-Document WorkFlow Processing";    begin        if not WorkFlow.Get(DocumentSendingProfile."Electronic Service Flow") then            Error(DocumentSendingProfileWithWorkflowErr, DocumentSendingProfile."Electronic Service Flow", Format(DocumentSendingProfile."Electronic Document"::"Extended E-Document Service Flow"), DocumentSendingProfile.Code);        WorkFlow.TestField(Enabled);        if DocumentSendingProfile."Electronic Document" <> DocumentSendingProfile."Electronic Document"::"Extended E-Document Service Flow" then            exit(false);        if not EDocWorkFlowProcessing.GetServicesFromEntryPointResponseInWorkflow(WorkFlow, EDocumentService) then            exit(false);        exit(CreateAndExportEDocument(DocumentHeader, EDocumentService, WorkFlow.Code, DocumentSendingProfile.Code, EDocumentType, AllowReExport));    end;    /// <summary>    /// Orchestrates creating and exporting an E-Document for the given document header and a given set of services.    /// On first call, creates the E-Document record and exports it for every supported service.    /// If an E-Document already exists for the document header, re-exports for every supported service when AllowReExport is true.    /// </summary>    procedure CreateAndExportEDocument(var DocumentHeader: RecordRef; var EDocumentService: Record "E-Document Service"; WorkflowCode: Code[20]; DocumentSendingProfileCode: Code[20]; EDocumentType: Enum "E-Document Type"; AllowReExport: Boolean): Boolean    var        EDocument: Record "E-Document";        EDocumentBackgroundJobs: Codeunit "E-Document Background Jobs";        SupportedServices: List of [Code[20]];        ServiceCode: Code[20];    begin        if EDocumentService.FindSet() then            repeat                if IsDocumentSupported(EDocumentService, DocumentHeader, EDocumentType) then                    SupportedServices.Add(EDocumentService.Code);            until EDocumentService.Next() = 0;        if SupportedServices.Count() = 0 then            exit(false);        EDocument.SetRange("Document Record ID", DocumentHeader.RecordId);        if not EDocument.FindFirst() then            CreateEDocumentRecord(EDocument, DocumentHeader, EDocumentType, WorkflowCode, DocumentSendingProfileCode, SupportedServices)        else begin            if not AllowReExport then                exit(false);            PopulateEDocument(EDocument, DocumentHeader);            EDocument.Modify();        end;        foreach ServiceCode in SupportedServices do begin            EDocumentService.Get(ServiceCode);            if EDocumentService."Use Batch Processing" then                continue;            EnsureServiceStatusRow(EDocument, EDocumentService);            ExportEDocument(EDocument, EDocumentService);        end;        EDocumentBackgroundJobs.StartEDocumentCreatedFlow(EDocument);        exit(true);    end;    /// <summary>    /// CreateEDocument - Creates an E-Document record for the given document header and a set of services.    /// If services do not support the document type they are filtered out.    /// If an E-Document already exists for the document header, no record is created    /// </summary>    procedure CreateEDocument(var EDocument: Record "E-Document"; var DocumentHeader: RecordRef; var EDocumentService: Record "E-Document Service"; EDocumentType: Enum "E-Document Type"): Boolean    var        SupportedServices: List of [Code[20]];    begin        EDocument.SetRange("Document Record ID", DocumentHeader.RecordId);        if not EDocument.IsEmpty() then            exit(false);        if EDocumentService.FindSet() then            repeat                if IsDocumentSupported(EDocumentService, DocumentHeader, EDocumentType) then                    SupportedServices.Add(EDocumentService.Code);            until EDocumentService.Next() = 0;        if SupportedServices.Count() = 0 then            exit(false);        CreateEDocumentRecord(EDocument, DocumentHeader, EDocumentType, EDocument."Workflow Code", EDocument."Document Sending Profile", SupportedServices);        Clear(EDocumentService);        exit(true);    end;    local procedure CreateEDocumentRecord(var EDocument: Record "E-Document"; var DocumentHeader: RecordRef; EDocumentType: Enum "E-Document Type"; WorkflowCode: Code[20]; DocumentSendingProfileCode: Code[20]; SupportedServices: List of [Code[20]])    var        EDocumentService: Record "E-Document Service";        EDocumentLog: Codeunit "E-Document Log";        ServiceCode: Code[20];    begin        OnBeforeCreateEDocument(EDocument, DocumentHeader);        EDocument.Validate("Document Record ID", DocumentHeader.RecordId);        EDocument.Validate("Document Type", EDocumentType);        EDocument.Validate(Status, EDocument.Status::"In Progress");        EDocument.Validate(Direction, EDocument.Direction::Outgoing);        EDocument."Workflow Code" := WorkflowCode;        EDocument."Document Sending Profile" := DocumentSendingProfileCode;        EDocument.Insert();        PopulateEDocument(EDocument, DocumentHeader);        EDocument.Modify();        OnAfterCreateEDocument(EDocument, DocumentHeader);        EDocumentLog.InsertLog(EDocument, Enum::"E-Document Service Status"::Created);        foreach ServiceCode in SupportedServices do begin            EDocumentService.Get(ServiceCode);            EDocumentProcessing.InsertServiceStatus(EDocument, EDocumentService, Enum::"E-Document Service Status"::Created);            EDocumentProcessing.ModifyEDocumentStatus(EDocument);        end;    end;    local procedure EnsureServiceStatusRow(var EDocument: Record "E-Document"; var EDocumentService: Record "E-Document Service")    var        EDocumentServiceStatus: Record "E-Document Service Status";    begin        EDocumentServiceStatus.ReadIsolation(IsolationLevel::ReadUncommitted);        EDocumentServiceStatus.SetRange("E-Document Entry No", EDocument."Entry No");        EDocumentServiceStatus.SetRange("E-Document Service Code", EDocumentService.Code);        if EDocumentServiceStatus.IsEmpty() then            EDocumentProcessing.InsertServiceStatus(EDocument, EDocumentService, Enum::"E-Document Service Status"::Created)        else            EDocumentProcessing.ModifyServiceStatus(EDocument, EDocumentService, Enum::"E-Document Service Status"::Created);        EDocumentProcessing.ModifyEDocumentStatus(EDocument);    end;    internal procedure ExportEDocument(var EDocument: Record "E-Document"; var EDocumentService: Record "E-Document Service") Success: Boolean    var        TempEDocMapping: Record "E-Doc. Mapping" temporary;        EDocLog: Record "E-Document Log";        EDocumentServiceStatus: Record "E-Document Service Status";        EDocumentLog: Codeunit "E-Document Log";        TempBlob: Codeunit "Temp Blob";        SourceDocumentHeaderMapped, SourceDocumentLineMapped : RecordRef;        SourceDocumentHeader, SourceDocumentLines : RecordRef;        EDocServiceStatus: Enum "E-Document Service Status";        ErrorCount: Integer;    begin        if not IsDocumentTypeSupported(EDocumentService, EDocument."Document Type") then begin            LogDocumentTypeNotSupportedForExport(EDocument, EDocumentService);            exit(false);        end;        SourceDocumentHeader.Get(EDocument."Document Record ID");        EDocumentProcessing.GetLines(EDocument, SourceDocumentLines);        MapEDocument(SourceDocumentHeader, SourceDocumentLines, EDocumentService, SourceDocumentHeaderMapped, SourceDocumentLineMapped, TempEDocMapping, false);        ErrorCount := EDocumentErrorHelper.ErrorMessageCount(EDocument);        CreateEDocument(EDocumentService, EDocument, SourceDocumentHeaderMapped, SourceDocumentLineMapped, TempBlob);        Success := EDocumentErrorHelper.ErrorMessageCount(EDocument) = ErrorCount;        if Success then            EDocServiceStatus := Enum::"E-Document Service Status"::Exported        else            EDocServiceStatus := Enum::"E-Document Service Status"::"Export Error";        EDocLog := EDocumentLog.InsertLog(EDocument, EDocumentService, TempBlob, EDocServiceStatus);        EDocumentLog.InsertMappingLog(EDocLog, TempEDocMapping);        EDocumentServiceStatus.ReadIsolation(IsolationLevel::ReadUncommitted);        EDocumentServiceStatus.SetRange("E-Document Entry No", EDocument."Entry No");        EDocumentServiceStatus.SetRange("E-Document Service Code", EDocumentService.Code);        if EDocumentServiceStatus.IsEmpty() then            EDocumentProcessing.InsertServiceStatus(EDocument, EDocumentService, EDocServiceStatus)        else            EDocumentProcessing.ModifyServiceStatus(EDocument, EDocumentService, EDocServiceStatus);        EDocumentProcessing.ModifyEDocumentStatus(EDocument);        OnExportEDocumentAfterCreateEDocument(EDocumentService, EDocument, SourceDocumentHeaderMapped, SourceDocumentLineMapped, TempBlob, Success);    end;    internal procedure ExportEDocumentBatch(var EDocuments: Record "E-Document"; var EDocService: Record "E-Document Service"; var TempEDocMappingLogs: Record "E-Doc. Mapping Log" temporary; var TempBlob: Codeunit "Temp Blob"; var EDocumentsErrorCount: Dictionary of [Integer, Integer])    var        TempEDocMapping: Record "E-Doc. Mapping" temporary;        SourceDocumentHeaderMapped, SourceDocumentLineMapped : RecordRef;        SourceDocumentHeader, SourceDocumentLines : RecordRef;        HasSupportedDocument: Boolean;        I: Integer;    begin        if EDocuments.FindSet() then            repeat                EDocumentsErrorCount.Add(EDocuments."Entry No", EDocumentErrorHelper.ErrorMessageCount(EDocuments));                if IsDocumentTypeSupported(EDocService, EDocuments."Document Type") then begin                    EDocuments.Mark(true);                    HasSupportedDocument := true;                end else                    LogDocumentTypeNotSupportedForExport(EDocuments, EDocService);            until EDocuments.Next() = 0;        EDocuments.MarkedOnly(true);        if not HasSupportedDocument then            exit;        I := 0;        if EDocuments.FindSet() then            repeat                TempEDocMapping.DeleteAll();                SourceDocumentHeader.Get(EDocuments."Document Record ID");                EDocumentProcessing.GetLines(EDocuments, SourceDocumentLines);                MapEDocument(SourceDocumentHeader, SourceDocumentLines, EDocService, SourceDocumentHeaderMapped, SourceDocumentLineMapped, TempEDocMapping, false);                if TempEDocMapping.FindSet() then                    repeat                        TempEDocMappingLogs.InitFromMapping(TempEDocMapping);                        TempEDocMappingLogs."Entry No." := I; // We need to set key for temp record when inserting                        TempEDocMappingLogs.Validate("E-Doc Entry No.", EDocuments."Entry No");                        TempEDocMappingLogs.Insert();                        I += 1;                    until TempEDocMapping.Next() = 0;                SourceDocumentLines.Close();                EDocumentProcessing.ModifyServiceStatus(EDocuments, EDocService, Enum::"E-Document Service Status"::Created);                EDocumentProcessing.ModifyEDocumentStatus(EDocuments);            until EDocuments.Next() = 0;        // Clear filters and find mapped records        SourceDocumentHeaderMapped.Reset();        SourceDocumentLineMapped.Reset();        SourceDocumentHeaderMapped.FindSet();        SourceDocumentLineMapped.FindSet();        CreateEDocumentBatch(EDocService, EDocuments, SourceDocumentHeaderMapped, SourceDocumentLineMapped, TempBlob);    end;    local procedure LogDocumentTypeNotSupportedForExport(var EDocument: Record "E-Document"; EDocumentService: Record "E-Document Service")    var        EDocumentServiceStatus: Record "E-Document Service Status";        EDocumentLog: Codeunit "E-Document Log";        EDocServiceStatus: Enum "E-Document Service Status";    begin        EDocumentErrorHelper.LogSimpleErrorMessage(EDocument, StrSubstNo(DocumentTypeNotSupportedForExportErr, EDocument."Document Type", EDocumentService.Code));        EDocServiceStatus := Enum::"E-Document Service Status"::"Export Error";        EDocumentLog.InsertLog(EDocument, EDocumentService, EDocServiceStatus);        EDocumentServiceStatus.ReadIsolation(IsolationLevel::ReadUncommitted);        EDocumentServiceStatus.SetRange("E-Document Entry No", EDocument."Entry No");        EDocumentServiceStatus.SetRange("E-Document Service Code", EDocumentService.Code);        if EDocumentServiceStatus.IsEmpty() then            EDocumentProcessing.InsertServiceStatus(EDocument, EDocumentService, EDocServiceStatus)        else            EDocumentProcessing.ModifyServiceStatus(EDocument, EDocumentService, EDocServiceStatus);        EDocumentProcessing.ModifyEDocumentStatus(EDocument);    end;    internal procedure Recreate(EDocument: Record "E-Document"; EDocService: Record "E-Document Service")    begin        ExportEDocument(EDocument, EDocService);    end;    internal procedure MapEDocument(var EDocumentSource: RecordRef; var EDocumentSourceLine: RecordRef; EDocumentFormat: Record "E-Document Service"; var EDocumentSourceMapped: RecordRef; var EDocumentSourceLineMapped: RecordRef; var TempEDocMapping: Record "E-Doc. Mapping" temporary; ForImport: Boolean)    var        EDocMapping: Record "E-Doc. Mapping";        EDocMappingNgt: Codeunit "E-Doc. Mapping";    begin        if EDocumentSourceMapped.Number() = 0 then            EDocumentSourceMapped.Open(EDocumentSource.Number(), true);        if EDocumentSourceLineMapped.Number() = 0 then            EDocumentSourceLineMapped.Open(EDocumentSourceLine.Number(), true);        EDocMapping.SetRange(Code, EDocumentFormat.Code);        EDocMapping.SetRange("For Import", ForImport);        EDocMapping.ModifyAll(Used, false);        EDocMappingNgt.MapRecord(EDocMapping, EDocumentSource, EDocumentSourceMapped, TempEDocMapping);        if EDocumentSourceLine.FindSet() then            repeat                EDocMappingNgt.MapRecord(EDocMapping, EDocumentSourceLine, EDocumentSourceLineMapped, TempEDocMapping);            until EDocumentSourceLine.Next() = 0;    end;    local procedure PopulateEDocument(var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef)    var        DocumentSendingProfile: Record "Document Sending Profile";        SalesHeader: Record "Sales Header";        PurchHeader: Record "Purchase Header";        FinanceChargeMemoHeader: Record "Finance Charge Memo Header";        PurchInvHeader: Record "Purch. Inv. Header";        PurchCrMemoHdr: Record "Purch. Cr. Memo Hdr.";        SalesDocumentType: Enum "Sales Document Type";        PurchDocumentType: Enum "Purchase Document Type";        RemainingAmount, InterestAmount, AdditionalFee, VATAmount : Decimal;    begin        EDocument.Validate("Document Record ID", SourceDocumentHeader.RecordId);        EDocument.Validate(Status, EDocument.Status::"In Progress");        EDocument.Direction := EDocument.Direction::Outgoing;        if EDocument."Document Sending Profile" = '' then begin            DocumentSendingProfile.Get(EDocumentProcessing.GetDocSendingProfileForDocRef(SourceDocumentHeader).Code);            EDocument."Document Sending Profile" := DocumentSendingProfile.Code;            EDocument."Workflow Code" := DocumentSendingProfile."Electronic Service Flow";        end;        case SourceDocumentHeader.Number of            Database::"Sales Header", Database::"Sales Invoice Header", Database::"Sales Cr.Memo Header",            Database::"Service Header", Database::"Service Invoice Header", Database::"Service Cr.Memo Header":                begin                    case SourceDocumentHeader.Number of                        Database::"Sales Header":                            begin                                SalesDocumentType := SourceDocumentHeader.Field(SalesHeader.FieldNo("Document Type")).Value;                                case SalesDocumentType of                                    SalesHeader."Document Type"::Quote:                                        EDocument."Document Type" := EDocument."Document Type"::"Sales Quote";                                    SalesHeader."Document Type"::Order:                                        EDocument."Document Type" := EDocument."Document Type"::"Sales Order";                                    SalesHeader."Document Type"::"Return Order":                                        EDocument."Document Type" := EDocument."Document Type"::"Sales Return Order";                                end;                            end;                        Database::"Sales Invoice Header":                            EDocument."Document Type" := EDocument."Document Type"::"Sales Invoice";                        Database::"Sales Cr.Memo Header":                            EDocument."Document Type" := EDocument."Document Type"::"Sales Credit Memo";                        Database::"Service Header":                            EDocument."Document Type" := EDocument."Document Type"::"Service Order";                        Database::"Service Invoice Header":                            EDocument."Document Type" := EDocument."Document Type"::"Service Invoice";                        Database::"Service Cr.Memo Header":                            EDocument."Document Type" := EDocument."Document Type"::"Service Credit Memo";                    end;                    EDocument."Document No." := SourceDocumentHeader.Field(SalesHeader.FieldNo("No.")).Value;                    EDocument."Bill-to/Pay-to No." := SourceDocumentHeader.Field(SalesHeader.FieldNo("Bill-to Customer No.")).Value;                    EDocument."Bill-to/Pay-to Name" := SourceDocumentHeader.Field(SalesHeader.FieldNo("Bill-to Name")).Value;                    EDocument."Posting Date" := SourceDocumentHeader.Field(SalesHeader.FieldNo("Posting Date")).Value;                    EDocument."Document Date" := SourceDocumentHeader.Field(SalesHeader.FieldNo("Document Date")).Value;                    EDocument."Due Date" := SourceDocumentHeader.Field(SalesHeader.FieldNo("Due Date")).Value;                    EDocument."Source Type" := EDocument."Source Type"::Customer;                    EDocument."Currency Code" := SourceDocumentHeader.Field(SalesHeader.FieldNo("Currency Code")).Value;                    SourceDocumentHeader.Field(SalesHeader.FieldNo(Amount)).CalcField();                    SourceDocumentHeader.Field(SalesHeader.FieldNo("Amount Including VAT")).CalcField();                    EDocument."Amount Excl. VAT" := SourceDocumentHeader.Field(SalesHeader.FieldNo(Amount)).Value;                    EDocument."Amount Incl. VAT" := SourceDocumentHeader.Field(SalesHeader.FieldNo("Amount Including VAT")).Value;                end;            Database::"Finance Charge Memo Header", Database::"Issued Fin. Charge Memo Header",            Database::"Reminder Header", Database::"Issued Reminder Header":                begin                    case SourceDocumentHeader.Number of                        Database::"Finance Charge Memo Header":                            EDocument."Document Type" := EDocument."Document Type"::"Finance Charge Memo";                        Database::"Issued Fin. Charge Memo Header":                            EDocument."Document Type" := EDocument."Document Type"::"Issued Finance Charge Memo";                        Database::"Reminder Header":                            EDocument."Document Type" := EDocument."Document Type"::Reminder;                        Database::"Issued Reminder Header":                            EDocument."Document Type" := EDocument."Document Type"::"Issued Reminder";                    end;                    EDocument."Document No." := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("No.")).Value;                    EDocument."Bill-to/Pay-to No." := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Customer No.")).Value;                    EDocument."Bill-to/Pay-to Name" := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo(Name)).Value;                    EDocument."Posting Date" := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Posting Date")).Value;                    EDocument."Document Date" := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Document Date")).Value;                    EDocument."Due Date" := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Due Date")).Value;                    EDocument."Source Type" := EDocument."Source Type"::Customer;                    EDocument."Currency Code" := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Currency Code")).Value;                    SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Remaining Amount")).CalcField();                    RemainingAmount := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Remaining Amount")).Value;                    SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Interest Amount")).CalcField();                    InterestAmount := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Interest Amount")).Value;                    SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Additional Fee")).CalcField();                    AdditionalFee := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("Additional Fee")).Value;                    SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("VAT Amount")).CalcField();                    VATAmount := SourceDocumentHeader.Field(FinanceChargeMemoHeader.FieldNo("VAT Amount")).Value;                    EDocument."Amount Excl. VAT" := RemainingAmount + InterestAmount + AdditionalFee;                    EDocument."Amount Incl. VAT" := RemainingAmount + InterestAmount + AdditionalFee + VATAmount;                end;            Database::"Purchase Header", Database::"Purch. Inv. Header", Database::"Purch. Cr. Memo Hdr.":                begin                    case SourceDocumentHeader.Number of                        Database::"Purchase Header":                            begin                                PurchDocumentType := SourceDocumentHeader.Field(PurchHeader.FieldNo("Document Type")).Value;                                case PurchDocumentType of                                    PurchHeader."Document Type"::Quote:                                        EDocument."Document Type" := EDocument."Document Type"::"Purchase Quote";                                    PurchHeader."Document Type"::Order:                                        EDocument."Document Type" := EDocument."Document Type"::"Purchase Order";                                    PurchHeader."Document Type"::"Return Order":                                        EDocument."Document Type" := EDocument."Document Type"::"Purchase Return Order";                                end;                            end;                        Database::"Purch. Inv. Header":                            EDocument."Document Type" := EDocument."Document Type"::"Purchase Invoice";                        Database::"Purch. Cr. Memo Hdr.":                            EDocument."Document Type" := EDocument."Document Type"::"Purchase Credit Memo";                    end;                    EDocument."Document No." := SourceDocumentHeader.Field(PurchHeader.FieldNo("No.")).Value;                    EDocument."Bill-to/Pay-to No." := SourceDocumentHeader.Field(PurchHeader.FieldNo("Pay-to Vendor No.")).Value;                    EDocument."Bill-to/Pay-to Name" := SourceDocumentHeader.Field(PurchHeader.FieldNo("Pay-to Name")).Value;                    case SourceDocumentHeader.Number of                        Database::"Purch. Inv. Header":                            if SourceDocumentHeader.Field(PurchInvHeader.FieldNo("Self-Billing Invoice")).Value then                                EDocument."Document Type" := EDocument."Document Type"::"Self-Billed Purchase Invoice";                        Database::"Purch. Cr. Memo Hdr.":                            begin                                SourceDocumentHeader.SetTable(PurchCrMemoHdr);                                if EDocumentProcessing.IsSelfBilledCreditMemo(PurchCrMemoHdr) then                                    EDocument."Document Type" := EDocument."Document Type"::"Self-Billed Purch. Cr. Memo";                            end;                    end;                    EDocument."Posting Date" := SourceDocumentHeader.Field(PurchHeader.FieldNo("Posting Date")).Value;                    EDocument."Document Date" := SourceDocumentHeader.Field(PurchHeader.FieldNo("Document Date")).Value;                    EDocument."Due Date" := SourceDocumentHeader.Field(PurchHeader.FieldNo("Due Date")).Value;                    EDocument."Source Type" := EDocument."Source Type"::Vendor;                    EDocument."Currency Code" := SourceDocumentHeader.Field(PurchHeader.FieldNo("Currency Code")).Value;                    SourceDocumentHeader.Field(PurchHeader.FieldNo(Amount)).CalcField();                    SourceDocumentHeader.Field(PurchHeader.FieldNo("Amount Including VAT")).CalcField();                    EDocument."Amount Excl. VAT" := SourceDocumentHeader.Field(PurchHeader.FieldNo(Amount)).Value;                    EDocument."Amount Incl. VAT" := SourceDocumentHeader.Field(PurchHeader.FieldNo("Amount Including VAT")).Value;                end;            Database::"Sales Shipment Header":                PopulateShipmentEDocument(EDocument, SourceDocumentHeader);            Database::"Transfer Shipment Header":                this.PopulateTransferShipmentEDocument(EDocument, SourceDocumentHeader);            Database::"Gen. Journal Line", Database::"Vendor Ledger Entry":                if EDocument."Document Type" = EDocument."Document Type"::"Remittance Advice" then                    PopulateRemittanceAdviceEDocument(EDocument, SourceDocumentHeader);        end;    end;    local procedure CreateEDocument(EDocumentService: Record "E-Document Service"; var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef; var SourceDocumentLines: RecordRef; var TempBlob: Codeunit "Temp Blob")    var        EDocumentCreate: Codeunit "E-Document Create";        TelemetryDimensions: Dictionary of [Text, Text];    begin        // Commit before create document with error handling        Commit();        EDocumentProcessing.GetTelemetryDimensions(EDocumentService, EDocument, TelemetryDimensions);        Telemetry.LogMessage('0000LBF', EDocTelemetryCreateScopeStartLbl, Verbosity::Normal, DataClassification::OrganizationIdentifiableInformation, TelemetryScope::All, TelemetryDimensions);        EDocumentCreate.SetSource(EDocumentService, EDocument, SourceDocumentHeader, SourceDocumentLines, TempBlob);        if not EDocumentCreate.Run() then            EDocumentErrorHelper.LogSimpleErrorMessage(EDocument, GetLastErrorText());        EDocumentCreate.GetBlob(TempBlob);        // After interface call, reread the EDocument for the latest values.        EDocument.Get(EDocument."Entry No");        Telemetry.LogMessage('0000LBG', EDocTelemetryCreateScopeEndLbl, Verbosity::Normal, DataClassification::OrganizationIdentifiableInformation, TelemetryScope::All);    end;    local procedure PopulateShipmentEDocument(var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef)    var        SalesShipmentHeader: Record "Sales Shipment Header";    begin        EDocument."Document Type" := EDocument."Document Type"::"Sales Shipment";        EDocument."Document No." := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("No.")).Value;        EDocument."Order No." := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Order No.")).Value;        EDocument."Bill-to/Pay-to No." := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Bill-to Customer No.")).Value;        EDocument."Bill-to/Pay-to Name" := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Bill-to Name")).Value;        EDocument."Posting Date" := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Posting Date")).Value;        EDocument."Document Date" := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Document Date")).Value;        EDocument."Due Date" := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Due Date")).Value;        EDocument."Source Type" := EDocument."Source Type"::Customer;        EDocument."Currency Code" := SourceDocumentHeader.Field(SalesShipmentHeader.FieldNo("Currency Code")).Value;    end;    local procedure PopulateTransferShipmentEDocument(var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef)    var        TransferShipmentHeader: Record "Transfer Shipment Header";    begin        EDocument."Document Type" := EDocument."Document Type"::"Transfer Shipment";        EDocument."Document No." := SourceDocumentHeader.Field(TransferShipmentHeader.FieldNo("No.")).Value;        EDocument."Posting Date" := SourceDocumentHeader.Field(TransferShipmentHeader.FieldNo("Posting Date")).Value;        EDocument."Bill-to/Pay-to No." := SourceDocumentHeader.Field(TransferShipmentHeader.FieldNo("Transfer-to Code")).Value;        EDocument."Bill-to/Pay-to Name" := SourceDocumentHeader.Field(TransferShipmentHeader.FieldNo("Transfer-to Name")).Value;        EDocument."Source Type" := EDocument."Source Type"::Location;    end;    local procedure PopulateRemittanceAdviceEDocument(var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef)    var        Vendor: Record Vendor;        GenJournalLine: Record "Gen. Journal Line";        VendorLedgerEntry: Record "Vendor Ledger Entry";        TempRemitAdviceBuffer: Record "Remit. Advice Buffer" temporary;        RemitAdviceBufferMgt: Codeunit "Remit. Advice Buffer Mgt.";    begin        case SourceDocumentHeader.Number of            Database::"Gen. Journal Line":                begin                    SourceDocumentHeader.SetTable(GenJournalLine);                    RemitAdviceBufferMgt.BuildFromJournalPayment(GenJournalLine, TempRemitAdviceBuffer);                    EDocument."Journal Line System ID" := SourceDocumentHeader.Field(SourceDocumentHeader.SystemIdNo).Value;                end;            Database::"Vendor Ledger Entry":                begin                    SourceDocumentHeader.SetTable(VendorLedgerEntry);                    RemitAdviceBufferMgt.BuildFromPostedPayment(VendorLedgerEntry, TempRemitAdviceBuffer);                end;        end;        TempRemitAdviceBuffer.SetRange("Line No.", 0);        TempRemitAdviceBuffer.FindFirst();        EDocument."Document No." := TempRemitAdviceBuffer."Payment Document No.";        if Vendor.Get(TempRemitAdviceBuffer."Vendor No.") then;        EDocument."Bill-to/Pay-to No." := TempRemitAdviceBuffer."Vendor No.";        EDocument."Bill-to/Pay-to Name" := Vendor.Name;        EDocument."Posting Date" := TempRemitAdviceBuffer."Payment Date";        EDocument."Document Date" := TempRemitAdviceBuffer."Payment Date";        EDocument."Currency Code" := TempRemitAdviceBuffer."Currency Code";        EDocument."Source Type" := EDocument."Source Type"::Vendor;        EDocument."Amount Excl. VAT" := Abs(TempRemitAdviceBuffer."Total Paid Amount");        EDocument."Amount Incl. VAT" := Abs(TempRemitAdviceBuffer."Total Paid Amount");    end;    local procedure CreateEDocumentBatch(EDocService: Record "E-Document Service"; var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef; var SourceDocumentLines: RecordRef; var TempBlob: Codeunit "Temp Blob")    var        EDocumentCreate: Codeunit "E-Document Create";        ErrorText: Text;        TelemetryDimensions: Dictionary of [Text, Text];    begin        // Commit before create document with error handling        Commit();        EDocumentProcessing.GetTelemetryDimensions(EDocService, EDocument, TelemetryDimensions);        Telemetry.LogMessage('0000LBH', EDocTelemetryCreateBatchScopeStartLbl, Verbosity::Normal, DataClassification::OrganizationIdentifiableInformation, TelemetryScope::All, TelemetryDimensions);        Clear(EDocumentCreate);        EDocumentCreate.SetSource(EDocService, EDocument, SourceDocumentHeader, SourceDocumentLines, TempBlob);        if not EDocumentCreate.Run() then begin            ErrorText := GetLastErrorText();            EDocument.FindSet();            repeat                EDocumentErrorHelper.LogSimpleErrorMessage(EDocument, ErrorText);            until EDocument.Next() = 0;        end;        // Read E-Document from database as multiple docs could be modified inside EDocumentCreate;        EDocument.FindSet();        Telemetry.LogMessage('0000LBI', EDocTelemetryCreateBatchScopeEndLbl, Verbosity::Normal, DataClassification::OrganizationIdentifiableInformation, TelemetryScope::All);    end;    procedure IsDocumentTypeSupported(EDocService: Record "E-Document Service"; EDocumentType: Enum "E-Document Type"): Boolean    begin        exit(IsDocumentTypeSupportedForDirection(EDocService, EDocumentType, Enum::"E-Doc. Supp. Type Direction"::Outgoing));    end;    /// <summary>    /// Determines whether a document type is configured for inbound processing on the E-Document Service.    /// The exact document-type row takes precedence over its fallback row. The matched row must allow    /// Incoming or Both; if neither row is configured, the document type is not supported.    /// </summary>    procedure IsDocumentTypeSupportedForImport(EDocService: Record "E-Document Service"; EDocumentType: Enum "E-Document Type"): Boolean    begin        exit(IsDocumentTypeSupportedForDirection(EDocService, EDocumentType, Enum::"E-Doc. Supp. Type Direction"::Incoming));    end;    /// <summary>    /// Shared inbound check used by both import paths. Returns false and sets ErrorText when the document type is not permitted for the Incoming direction.    /// </summary>    internal procedure CheckDocumentTypeSupportedForImport(EDocService: Record "E-Document Service"; EDocumentType: Enum "E-Document Type"; var ErrorText: Text): Boolean    begin        if IsDocumentTypeSupportedForImport(EDocService, EDocumentType) then            exit(true);        ErrorText := StrSubstNo(DocumentTypeNotSupportedForImportErr, EDocumentType, EDocService.Code);        exit(false);    end;    local procedure IsDocumentTypeSupportedForDirection(EDocService: Record "E-Document Service"; EDocumentType: Enum "E-Document Type"; QueriedDirection: Enum "E-Doc. Supp. Type Direction"): Boolean    var        EDocSourceType: Enum "E-Document Type";    begin        case EDocumentType of            EDocumentType::"Sales Order":                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::"Sales Order", EDocSourceType::"Sales Invoice", QueriedDirection));            EDocumentType::"Sales Return Order":                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::"Sales Return Order", EDocSourceType::"Sales Credit Memo", QueriedDirection));            EDocumentType::"Service Order":                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::"Service Order", EDocSourceType::"Service Invoice", QueriedDirection));            EDocumentType::"Finance Charge Memo":                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::"Finance Charge Memo", EDocSourceType::"Issued Finance Charge Memo", QueriedDirection));            EDocumentType::Reminder:                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::Reminder, EDocSourceType::"Issued Reminder", QueriedDirection));            EDocumentType::"Purchase Order":                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::"Purchase Order", EDocSourceType::"Purchase Invoice", QueriedDirection));            EDocumentType::"Purchase Return Order":                exit(IsFallbackPairSupported(EDocService.Code, EDocSourceType::"Purchase Return Order", EDocSourceType::"Purchase Credit Memo", QueriedDirection));        end;        exit(IsSingleTypeSupported(EDocService.Code, EDocumentType, QueriedDirection));    end;    local procedure IsSingleTypeSupported(EDocServiceCode: Code[20]; DocumentType: Enum "E-Document Type"; QueriedDirection: Enum "E-Doc. Supp. Type Direction"): Boolean    var        IsConfigured: Boolean;    begin        exit(IsSupportedTypeRow(EDocServiceCode, DocumentType, QueriedDirection, IsConfigured));    end;    local procedure IsFallbackPairSupported(EDocServiceCode: Code[20]; DocumentType1: Enum "E-Document Type"; DocumentType2: Enum "E-Document Type"; QueriedDirection: Enum "E-Doc. Supp. Type Direction"): Boolean    var        IsConfigured: Boolean;        IsSupported: Boolean;    begin        IsSupported := IsSupportedTypeRow(EDocServiceCode, DocumentType1, QueriedDirection, IsConfigured);        if IsConfigured then            exit(IsSupported);        IsSupported := IsSupportedTypeRow(EDocServiceCode, DocumentType2, QueriedDirection, IsConfigured);        if IsConfigured then            exit(IsSupported);        exit(false);    end;    local procedure IsSupportedTypeRow(EDocServiceCode: Code[20]; DocumentType: Enum "E-Document Type"; QueriedDirection: Enum "E-Doc. Supp. Type Direction"; var IsConfigured: Boolean): Boolean    var        EDocServiceSupportedType: Record "E-Doc. Service Supported Type";    begin        IsConfigured := EDocServiceSupportedType.Get(EDocServiceCode, DocumentType);        if not IsConfigured then            exit(false);        exit((EDocServiceSupportedType.Direction = EDocServiceSupportedType.Direction::Both) or (EDocServiceSupportedType.Direction = QueriedDirection));    end;    local procedure IsDocumentSupported(EDocumentService: Record "E-Document Service"; SourceDocumentHeader: RecordRef; DocumentType: Enum "E-Document Type"): Boolean    var        IExportEligibilityEvaluator: Interface IExportEligibilityEvaluator;    begin        if not IsDocumentTypeSupported(EDocumentService, DocumentType) then            exit(false);        IExportEligibilityEvaluator := EDocumentService."Export Eligibility Evaluator";        exit(IExportEligibilityEvaluator.ShouldExport(EDocumentService, SourceDocumentHeader, DocumentType));    end;    var        EDocumentProcessing: Codeunit "E-Document Processing";        EDocumentErrorHelper: Codeunit "E-Document Error Helper";        Telemetry: Codeunit Telemetry;        EDocumentInterface: Interface "E-Document";        DocumentTypeNotSupportedForExportErr: Label 'Document type %1 is explicitly restricted from the Outgoing direction on E-Document Service %2.', Comment = '%1 - E-Document Type, %2 - E-Document Service Code';        DocumentTypeNotSupportedForImportErr: Label 'Document type %1 is not permitted for the Incoming direction on E-Document Service %2.', Comment = '%1 - E-Document Type, %2 - E-Document Service Code';        DocumentSendingProfileWithWorkflowErr: Label 'Workflow %1 defined for %2 in Document Sending Profile %3 is not found.', Comment = '%1 - The workflow code, %2 - Enum value set in Electronic Document, %3 - Document Sending Profile Code';        EDocTelemetryCreateScopeStartLbl: Label 'E-Document Create: Start Scope', Locked = true;        EDocTelemetryCreateScopeEndLbl: Label 'E-Document Create: End Scope', Locked = true;        EDocTelemetryCreateBatchScopeStartLbl: Label 'E-Document Create Batch: Start Scope', Locked = true;        EDocTelemetryCreateBatchScopeEndLbl: Label 'E-Document Create Batch: End Scope', Locked = true;    [IntegrationEvent(false, false)]    local procedure OnBeforeEDocumentCheck(RecRef: RecordRef; EDocumentProcessingPhase: Enum "E-Document Processing Phase"; var IsHandled: Boolean)    begin    end;    [IntegrationEvent(false, false)]    local procedure OnAfterEDocumentCheck(RecRef: RecordRef; EDocumentProcessingPhase: Enum "E-Document Processing Phase")    begin    end;    [IntegrationEvent(false, false)]    local procedure OnBeforeCreateEDocument(var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef)    begin    end;    [IntegrationEvent(false, false)]    local procedure OnAfterCreateEDocument(var EDocument: Record "E-Document"; var SourceDocumentHeader: RecordRef)    begin    end;    [IntegrationEvent(false, false)]    local procedure OnExportEDocumentAfterCreateEDocument(EDocumentService: Record "E-Document Service"; EDocument: Record "E-Document"; SourceDocumentHeaderMapped: RecordRef; SourceDocumentLineMapped: RecordRef; var TempBlob: Codeunit "Temp Blob"; Success: Boolean)    begin    end;}