Page 6181 E-Document Purchase Draft

E-Document Core, Microsoft.eServices.EDocument.Processing.Import.Purchase

src/Apps/W1/EDocument/App/src/Processing/Import/Purchase/EDocumentPurchaseDraft.Page.al874 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.Processing.Import.Purchase;using Microsoft.eServices.EDocument;using Microsoft.eServices.EDocument.Processing.Import;using Microsoft.Foundation.Attachment;using Microsoft.Purchases.Document;using Microsoft.Purchases.Setup;using Microsoft.Purchases.Vendor;using System.Environment.Configuration;using System.Feedback;using System.Telemetry;using System.Text;using System.Utilities;page 6181 "E-Document Purchase Draft"{    ApplicationArea = Basic, Suite;    DataCaptionExpression = DataCaption;    Caption = 'Purchase Document Draft';    PageType = Card;    SourceTable = "E-Document";    InsertAllowed = false;    DeleteAllowed = true;    ModifyAllowed = true;    RefreshOnActivate = true;    layout    {        area(content)        {            group(General)            {                Caption = 'General';                field(Record; RecordLinkTxt)                {                    Caption = 'Purchase Document';                    Editable = false;                    Importance = Promoted;                    ToolTip = 'Specifies the record, document, journal line, or ledger entry, that is linked to the electronic document.';                    trigger OnDrillDown()                    begin                        Rec.ShowRecord();                        CurrPage.Update();                    end;                }                field(DraftType; Rec."Read into Draft Impl.")                {                    Caption = 'Draft Type';                    ToolTip = 'Specifies the type of draft document.';                    Visible = false;                    Editable = false;                }                group("Buy-from")                {                    ShowCaption = false;                    field("Vendor No."; EDocumentPurchaseHeader."[BC] Vendor No.")                    {                        ApplicationArea = Suite;                        Caption = 'Vendor No.';                        Importance = Promoted;                        ShowMandatory = true;                        ToolTip = 'Specifies the internal vendor identifier code.';                        Editable = PageEditable;                        Lookup = true;                        trigger OnValidate()                        begin                            EDocumentPurchaseHeader.Validate("[BC] Vendor No.", EDocumentPurchaseHeader."[BC] Vendor No.");                            EDocumentPurchaseHeader.Modify();                            PrepareDraft();                        end;                        trigger OnLookup(var Text: Text): Boolean                        begin                            exit(LookupVendor(Text));                        end;                    }                    field("Vendor Name"; EDocumentPurchaseHeader."Vendor Company Name")                    {                        ApplicationArea = Suite;                        Caption = 'Vendor Name';                        Importance = Promoted;                        Editable = false;                        ToolTip = 'Specifies the extracted name of the vendor who delivers the products.';                    }                    field("Vendor Address"; EDocumentPurchaseHeader."Vendor Address")                    {                        ApplicationArea = Suite;                        Caption = 'Vendor Address';                        Importance = Additional;                        Editable = false;                        ToolTip = 'Specifies the extracted vendor''s address.';                    }                }                group(Document)                {                    ShowCaption = false;                    field("Document Type"; Rec."Document Type")                    {                        Caption = 'Document Type';                        ToolTip = 'Specifies the electronic document type.';                        Editable = false;                    }                    field("Document No."; EDocumentPurchaseHeader."Sales Invoice No.")                    {                        Importance = Promoted;                        Caption = 'Document No.';                        ToolTip = 'Specifies the extracted ID for this specific document.';                        Editable = true;                        trigger OnValidate()                        begin                            EDocumentPurchaseHeader.Modify();                            CurrPage.Update();                        end;                    }                    field("Posting Description"; EDocumentPurchaseHeader."Posting Description")                    {                        Importance = Promoted;                        Caption = 'Posting Description';                        ToolTip = 'Specifies the extracted posting description for the document.';                        Editable = true;                        trigger OnValidate()                        begin                            EDocumentPurchaseHeader.Modify();                            CurrPage.Update();                        end;                    }                    field("Document Date"; EDocumentPurchaseHeader."Document Date")                    {                        Caption = 'Document Date';                        ToolTip = 'Specifies the extracted document date.';                        Importance = Promoted;                        Editable = true;                        trigger OnValidate()                        begin                            EDocumentPurchaseHeader.Modify();                            CurrPage.Update();                        end;                    }                    field("Due Date"; EDocumentPurchaseHeader."Due Date")                    {                        Importance = Promoted;                        Caption = 'Due Date';                        ToolTip = 'Specifies the extracted due date.';                        Editable = true;                        trigger OnValidate()                        begin                            EDocumentPurchaseHeader.Modify();                            CurrPage.Update();                        end;                    }                    field("Applies-to Vendor Inv. No."; EDocumentPurchaseHeader."Vendor Invoice No.")                    {                        Caption = 'Applies-to Vendor Inv. No.';                        ToolTip = 'Specifies the vendor''s invoice number that this credit memo corrects, as stated on the credit note. It is used to find the invoice in Applies-to Doc. No.';                        Visible = IsCreditMemo;                        Editable = PageEditable;                        trigger OnValidate()                        var                            EDocPrepareCrMemoDraft: Codeunit "EDoc Prepare Cr. Memo Draft";                        begin                            // The user entered the one invoice to apply to, so the credit note's other references no longer apply.                            EDocumentPurchaseHeader."Several Invoices Referenced" := false;                            EDocumentPurchaseHeader.Modify();                            EDocPrepareCrMemoDraft.RefreshInvoiceToApplyTo(Rec);                            EDocumentPurchaseHeader.GetFromEDocument(Rec);                            UpdateInvoiceWarnings();                            CurrPage.Update();                        end;                    }                    field("Applies-to Doc. No."; EDocumentPurchaseHeader."Applies-to Doc. No.")                    {                        Caption = 'Applies-to Doc. No.';                        ToolTip = 'Specifies the posted purchase invoice that the credit memo is applied to. It is suggested from Applies-to Vendor Inv. No.; you can select another open invoice of the vendor or clear it.';                        Visible = IsCreditMemo;                        Editable = PageEditable;                        trigger OnLookup(var Text: Text): Boolean                        var                            EDocPrepareCrMemoDraft: Codeunit "EDoc Prepare Cr. Memo Draft";                        begin                            exit(EDocPrepareCrMemoDraft.LookupInvoiceToApplyTo(EDocumentPurchaseHeader, Text));                        end;                        trigger OnValidate()                        var                            EDocPrepareCrMemoDraft: Codeunit "EDoc Prepare Cr. Memo Draft";                        begin                            EDocPrepareCrMemoDraft.ValidateInvoiceToApplyTo(EDocumentPurchaseHeader);                            EDocumentPurchaseHeader.Modify();                            EDocPrepareCrMemoDraft.RefreshWarningsForSelectedInvoice(Rec);                            UpdateInvoiceWarnings();                            CurrPage.Update();                        end;                    }                    field(InvoiceWarnings; InvoiceWarningsTxt)                    {                        ShowCaption = false;                        ToolTip = 'Specifies any warnings about the invoice that the credit memo will be applied to.';                        Visible = IsCreditMemo and (InvoiceWarningsTxt <> '');                        Editable = false;                        MultiLine = true;                        Style = Ambiguous;                        StyleExpr = InvoiceWarningsTxt <> '';                    }                }                field("Status"; Rec.Status)                {                    Caption = 'Status';                    Importance = Additional;                    ToolTip = 'Specifies whether the EDocument is in progress and awaiting processing, has been processed into a Purchase Document, or encountered an error. The processing behavior depends on the EDocument Service setup.';                    StyleExpr = StyleStatusTxt;                    Editable = false;                }            }            part(Lines; "E-Doc. Purchase Draft Subform")            {                ApplicationArea = Suite;                Editable = PageEditable;                SubPageLink = "E-Document Entry No." = field("Entry No");                UpdatePropagation = Both;            }            group("E-Document Details")            {                ShowCaption = false;                field("Applied VAT Amount Diff."; AppliedVATAmountDiff)                {                    Caption = 'Applied VAT Amount Diff.';                    ToolTip = 'Specifies the VAT amount difference that was automatically applied to reconcile the document total VAT with the computed line VAT amounts.';                    Importance = Additional;                    Editable = false;                    Visible = ApplyVATDiffEnabled;                    AutoFormatType = 1;                    AutoFormatExpression = EDocumentPurchaseHeader."Currency Code";                }                field("Amount Excl. VAT"; EDocumentPurchaseHeader."Sub Total")                {                    Caption = 'Amount Excl. VAT';                    ToolTip = 'Specifies the total amount of the electronic document excluding VAT.';                    Importance = Promoted;                    trigger OnValidate()                    begin                        UpdateTotal();                        EDocumentPurchaseHeader.Modify();                        GlobalEDocumentNotification.RefreshAndShowSubTotalMismatchAfterHeaderEdit(EDocumentPurchaseHeader);                        CurrPage.Update();                    end;                }                field("Invoice Discount"; EDocumentPurchaseHeader."Total Discount")                {                    Caption = 'Invoice Discount';                    ToolTip = 'Specifies the discount in addition to the lines';                    Importance = Promoted;                    trigger OnValidate()                    begin                        UpdateTotal();                        EDocumentPurchaseHeader.Modify();                        CurrPage.Update();                    end;                }                field("Total VAT"; EDocumentPurchaseHeader."Total VAT")                {                    Caption = 'Total VAT';                    ToolTip = 'Specifies the total VAT';                    Importance = Promoted;                    trigger OnValidate()                    begin                        UpdateTotal();                        EDocumentPurchaseHeader.Modify();                        CurrPage.Update();                    end;                }                field("Amount Incl. VAT"; EDocumentPurchaseHeader.Total)                {                    Caption = 'Amount Incl. VAT';                    ToolTip = 'Specifies the total amount of the electronic document including VAT.';                    Importance = Promoted;                    trigger OnValidate()                    begin                        EDocumentPurchaseHeader.Modify();                        CurrPage.Update();                    end;                }                field("Currency Code"; EDocumentPurchaseHeader."Currency Code")                {                    Caption = 'Currency Code';                    Importance = Promoted;                    ToolTip = 'Specifies the electronic document currency code.';                    Editable = true;                    trigger OnValidate()                    begin                        EDocumentPurchaseHeader.Modify();                        GlobalEDocumentNotification.RefreshAndShowSubTotalMismatchAfterHeaderEdit(EDocumentPurchaseHeader);                        CurrPage.Update();                    end;                }            }        }        area(factboxes)        {            part("Attached Documents List"; "Doc. Attachment List Factbox")            {                ApplicationArea = All;                Caption = 'Documents';                UpdatePropagation = Both;                SubPageLink = "E-Document Entry No." = field("Entry No"),                              "E-Document Attachment" = const(true);            }            part(InboundEDocPicture; "Inbound E-Doc. Picture")            {                Caption = 'Preview';                SubPageLink = "Entry No." = field("Unstructured Data Entry No."),                            "File Format" = const("E-Doc. File Format"::PDF);                ShowFilter = false;            }            part(InboundEDocFactbox; "Inbound E-Doc. Factbox")            {                Caption = 'Details';                SubPageLink = "E-Document Entry No" = field("Entry No");                ShowFilter = false;            }            part(ErrorMessagesFactBox; "Error Messages Part")            {                Visible = HasErrorsOrWarnings;                ShowFilter = false;                UpdatePropagation = Both;            }        }    }    actions    {        area(Processing)        {            group(ProcessDocument)            {                Caption = 'Process';                Image = Process;                action(CreateDocument)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Finalize draft';                    ToolTip = 'Process the electronic document into a business central document';                    Image = CreateDocument;                    Visible = ShowFinalizeDraftAction;                    trigger OnAction()                    var                        TempEDocImportParameters: Record "E-Doc. Import Parameters";                    begin                        Session.LogMessage('0000PCO', FinalizeDraftInvokedTxt, Verbosity::Normal, DataClassification::SystemMetadata, TelemetryScope::All, 'Category', EDocumentPurchaseHeader.FeatureName());                        Rec.SetAutoCalcFields("Import Processing Status");                        if Rec.Get(Rec."Entry No") then                            if Rec."Import Processing Status" = "Import E-Doc. Proc. Status"::Processed then begin                                Rec.ShowRecord();                                exit;                            end;                        FinalizeEDocument(TempEDocImportParameters);                    end;                }                action(ResetDraftDocument)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Reset draft';                    ToolTip = 'Resets the draft document. Any changes made to the draft document will be lost.';                    Image = Restore;                    trigger OnAction()                    begin                        ResetDraft();                    end;                }                action(AnalyzeDocument)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Analyze document';                    ToolTip = 'Analyze the selected electronic document';                    Image = SendAsPDF;                    Visible = ShowAnalyzeDocumentAction;                    trigger OnAction()                    begin                        AnalyzeEDocument();                    end;                }                action(LinkToExistingDocument)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Link to existing document';                    ToolTip = 'Link this electronic document to an existing purchase document in Business Central. Use this when you have already created the document manually and want to attach the e-document to it.';                    Image = Links;                    Visible = false;                    trigger OnAction()                    begin                        DoLinkToExistingDocument();                    end;                }            }            group(ViewDocument)            {                Caption = 'View';                Image = View;                action(ViewFile)                {                    ApplicationArea = Basic, Suite;                    Caption = 'View pdf';                    ToolTip = 'View pdf.';                    Image = ViewDetails;                    Visible = HasPDFSource;                    trigger OnAction()                    begin                        Rec.ViewSourceFile();                    end;                }                action(ViewExtractedDocumentData)                {                    ApplicationArea = Basic, Suite;                    Caption = 'View extracted data';                    ToolTip = 'View the extracted data from the source file.';                    Image = ViewRegisteredOrder;                    trigger OnAction()                    var                        EDocImport: Codeunit "E-Doc. Import";                    begin                        EDocImport.ViewExtractedData(Rec);                    end;                }            }            group(Help)            {                Caption = 'Help';                Image = Help;                action(GetFeedback)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Provide feedback';                    ToolTip = 'Provide feedback on the Payables Agent experience.';                    Image = Comment;                    Visible = FeedbackActionVisible;                    trigger OnAction()                    begin                        ProvideFeedback();                    end;                }            }        }        area(Navigation)        {            group(Vendors)            {                action(HistoricalVendorMatches)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Historical Vendor Matches';                    ToolTip = 'Opens Vendor Assignment History to see names and addresses matched to vendors based on received e-documents.';                    Image = History;                    RunObject = page "E-Doc. Vendor Assignment Hist.";                    RunPageMode = View;                }                action(OpenVendorList)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Vendor List';                    ToolTip = 'Opens the Vendor List.';                    Image = Vendor;                    RunObject = page "Vendor List";                    RunPageMode = View;                }                action(CreateVendorAction)                {                    ApplicationArea = Basic, Suite;                    Caption = 'Create Vendor';                    ToolTip = 'Creates a vendor based on the invoice details.';                    Image = AddContacts;                    trigger OnAction()                    var                        Vendor: Record Vendor;                        VendorTemplMgt: Codeunit "Vendor Templ. Mgt.";                        VendorCard: Page "Vendor Card";                        IsHandled: Boolean;                    begin                        if VendorTemplMgt.CreateVendorFromTemplate(Vendor, IsHandled) then begin                            Vendor.Validate(Blocked, Enum::"Vendor Blocked"::All);                            Vendor.Modify();                            VendorCard.SetRecord(Vendor);                            VendorCard.Run();                        end;                    end;                }            }        }        area(Promoted)        {            group(Category_Process)            {                Caption = 'Process';                actionref(Promoted_CreateDocument; CreateDocument)                {                    Visible = false;                }                actionref(Promoted_AnalyseDocument; AnalyzeDocument)                {                }            }            group(Category_View)            {                Caption = 'View';                actionref(Promoted_ViewFile; ViewFile)                {                }                actionref(Promoted_ViewExtractedData; ViewExtractedDocumentData)                {                }            }            group(Category_Help)            {                Caption = 'Help';                actionref(Promoted_GetFeedback; GetFeedback)                {                }            }        }    }    trigger OnOpenPage()    var        EDocumentDataStorage: Record "E-Doc. Data Storage";        PurchasesPayablesSetup: Record "Purchases & Payables Setup";        EDocPOMatching: Codeunit "E-Doc. PO Matching";        MatchesRemovedMsg: Label 'This e-document was matched to purchase order lines, but the matches are no longer consistent with the current data. The matches have been removed';    begin        if EDocumentPurchaseHeader.Get(Rec."Entry No") then;        if not EDocPOMatching.IsPOMatchConsistent(EDocumentPurchaseHeader) then begin            EDocPOMatching.RemoveAllMatchesForEDocument(EDocumentPurchaseHeader);            Message(MatchesRemovedMsg);        end;        CurrPage.Lines.Page.SetEDocumentPurchaseHeader(EDocumentPurchaseHeader);        if Rec."Unstructured Data Entry No." <> 0 then begin            EDocumentDataStorage.Get(Rec."Unstructured Data Entry No.");            HasPDFSource := EDocumentDataStorage."File Format" = Enum::"E-Doc. File Format"::PDF;        end;        EDocumentServiceStatus := Rec.GetEDocumentServiceStatus();        HasErrorsOrWarnings := false;        HasErrors := false;        PageEditable := IsEditable();        IsCreditMemo := Rec."Document Type" = Enum::"E-Document Type"::"Purchase Credit Memo";        // Field visibility is evaluated when the page opens, so the warnings must be known here.        UpdateInvoiceWarnings();        GlobalEDocumentNotification.RefreshAndShowPendingDraftNotifications(Rec."Entry No");        FeedbackActionVisible := IsUserInitiatedFeedbackEnabled();        if PurchasesPayablesSetup.Get() then            ApplyVATDiffEnabled := PurchasesPayablesSetup."Apply VAT Diff. For Purch EDoc";        if Rec."Entry No" <> 0 then            Rec.SetRecFilter(); // Filter the record to only this instance to avoid navigation     end;    local procedure IsEditable(): Boolean    begin        exit(Rec.Status <> Rec.Status::Processed);    end;    trigger OnAfterGetRecord()    begin        RecordLinkTxt := EDocumentProcessing.GetRecordLinkText(Rec);        HasErrorsOrWarnings := (EDocumentErrorHelper.ErrorMessageCount(Rec) + EDocumentErrorHelper.WarningMessageCount(Rec)) > 0;        HasErrors := EDocumentErrorHelper.ErrorMessageCount(Rec) > 0;        if HasErrorsOrWarnings then            ShowErrorsAndWarnings()        else            ClearErrorsAndWarnings();        SetStyle();        SetPageCaption();        AppliedVATAmountDiff := EDocumentPurchaseHeader.GetAppliedVATAmountDiff();        Rec.CalcFields("Import Processing Status");        ShowFinalizeDraftAction := Rec."Import Processing Status" in [Enum::"Import E-Doc. Proc. Status"::"Ready for draft", Enum::"Import E-Doc. Proc. Status"::"Draft Ready"];        ShowAnalyzeDocumentAction :=            (Rec."Import Processing Status" = Enum::"Import E-Document Steps"::"Structure received data") and            (Rec.Status = Enum::"E-Document Status"::Error);        PageEditable := IsEditable();        IsCreditMemo := Rec."Document Type" = Enum::"E-Document Type"::"Purchase Credit Memo";        UpdateInvoiceWarnings();    end;    local procedure UpdateInvoiceWarnings()    var        EDocPrepareCrMemoDraft: Codeunit "EDoc Prepare Cr. Memo Draft";        Warning: Text;        Warnings: TextBuilder;    begin        Clear(InvoiceWarningsTxt);        if not IsCreditMemo then            exit;        foreach Warning in EDocPrepareCrMemoDraft.GetInvoiceWarnings(Rec) do            Warnings.AppendLine(Warning);        InvoiceWarningsTxt := Warnings.ToText().TrimEnd();    end;    local procedure SetPageCaption()    var        Vendor: Record Vendor;        CaptionBuilder: TextBuilder;    begin        if Rec."File Name" <> '' then            CaptionBuilder.Append(Rec."File Name" + ' - ');        if Rec."Document Type" <> Rec."Document Type"::None then            CaptionBuilder.Append(Format(Rec."Document Type") + ' - ');        EDocumentPurchaseHeader.GetFromEDocument(Rec);        if Vendor.Get(EDocumentPurchaseHeader."[BC] Vendor No.") then            CaptionBuilder.Append(Vendor.Name + ' - ')        else            if EDocumentPurchaseHeader."Vendor Company Name" <> '' then                CaptionBuilder.Append(EDocumentPurchaseHeader."Vendor Company Name" + ' - ');        CaptionBuilder.Append(Format(Rec."Entry No"));        DataCaption := CaptionBuilder.ToText();    end;    local procedure SetStyle()    begin        case Rec.Status of            Rec.Status::Error:                StyleStatusTxt := 'Unfavorable';            Rec.Status::Processed:                StyleStatusTxt := 'Favorable';            else                StyleStatusTxt := 'None';        end;    end;    local procedure UpdateTotal()    begin        EDocumentPurchaseHeader.Total := EDocumentPurchaseHeader."Sub Total" - EDocumentPurchaseHeader."Total Discount" + EDocumentPurchaseHeader."Total VAT";    end;    local procedure ShowErrorsAndWarnings()    var        ErrorMessage: Record "Error Message";        TempErrorMessage: Record "Error Message" temporary;    begin        ErrorMessage.SetRange("Context Record ID", Rec.RecordId);        ErrorMessage.CopyToTemp(TempErrorMessage);        CurrPage.ErrorMessagesFactBox.Page.SetRecords(TempErrorMessage);        CurrPage.ErrorMessagesFactBox.Page.Update(false);    end;    local procedure LookupVendor(var VendorNo: Text): Boolean    var        Vendor: Record Vendor;        VendorList: Page "Vendor List";    begin        VendorList.LookupMode := true;        if VendorList.RunModal() = Action::LookupOK then begin            VendorList.GetRecord(Vendor);            VendorNo := Vendor."No.";            exit(true);        end;    end;    local procedure ClearErrorsAndWarnings()    var        TempErrorMessage: Record "Error Message" temporary;    begin        CurrPage.ErrorMessagesFactBox.Page.SetRecords(TempErrorMessage);        CurrPage.ErrorMessagesFactBox.Page.Update(false);    end;    local procedure FinalizeEDocument(EDocImportParameters: Record "E-Doc. Import Parameters")    var        EDocImport: Codeunit "E-Doc. Import";        EDocImpSessionTelemetry: Codeunit "E-Doc. Imp. Session Telemetry";        Telemetry: Codeunit Telemetry;        CustomDimensions: Dictionary of [Text, Text];    begin        if not GlobalEDocumentHelper.EnsureInboundEDocumentHasService(Rec) then            exit;        EDocImportParameters."Step to Run" := "Import E-Document Steps"::"Finish draft";        EDocImport.ProcessIncomingEDocument(Rec, EDocImportParameters);        Rec.Get(Rec."Entry No");        EDocumentErrorHelper.ThrowIfHasErrors(Rec);        PageEditable := IsEditable();        CurrPage.Lines.Page.Update();        CurrPage.Update();        if Rec.Status = Rec.Status::Processed then begin            CustomDimensions.Set('Category', EDocumentPurchaseHeader.FeatureName());            CustomDimensions.Set('SystemId', EDocImpSessionTelemetry.CreateSystemIdText(Rec.SystemId));            Telemetry.LogMessage('0000PCP', FinalizeDraftPerformedTxt, Verbosity::Normal, DataClassification::SystemMetadata, TelemetryScope::All, CustomDimensions);            FeatureTelemetry.LogUsage('0000PCU', EDocumentPurchaseHeader.FeatureName(), 'Finalize draft');            Rec.ShowRecord();        end;    end;    local procedure ResetDraft()    var        TempEDocImportParameters: Record "E-Doc. Import Parameters";        EDocImport: Codeunit "E-Doc. Import";        ConfirmDialogMgt: Codeunit "Confirm Management";        Progress: Dialog;    begin        if not GlobalEDocumentHelper.EnsureInboundEDocumentHasService(Rec) then            exit;        if not ConfirmDialogMgt.GetResponseOrDefault(ResetDraftQst) then            exit;        if GuiAllowed() then            Progress.Open(ProcessingDocumentMsg);        // Regardless of document state, we re-run the read data into IR, then prepare draft step.        TempEDocImportParameters."Step to Run" := Enum::"Import E-Document Steps"::"Read into Draft";        EDocImport.ProcessIncomingEDocument(Rec, TempEDocImportParameters);        TempEDocImportParameters."Step to Run" := Enum::"Import E-Document Steps"::"Prepare draft";        EDocImport.ProcessIncomingEDocument(Rec, TempEDocImportParameters);        Rec.Get(Rec."Entry No");        if GuiAllowed() then            Progress.Close();        EDocumentErrorHelper.ThrowIfHasErrors(Rec);    end;    local procedure PrepareDraft()    var        TempEDocImportParameters: Record "E-Doc. Import Parameters";        EDocImport: Codeunit "E-Doc. Import";        EDocumentHelper: Codeunit "E-Document Helper";        Progress: Dialog;    begin        if not EDocumentHelper.EnsureInboundEDocumentHasService(Rec) then            exit;        if GuiAllowed() then            Progress.Open(ProcessingDocumentMsg);        TempEDocImportParameters."Step to Run" := Enum::"Import E-Document Steps"::"Prepare draft";        EDocImport.ProcessIncomingEDocument(Rec, TempEDocImportParameters);        Rec.Get(Rec."Entry No");        if GuiAllowed() then            Progress.Close();    end;    local procedure AnalyzeEDocument()    var        TempEDocImportParameters: Record "E-Doc. Import Parameters";        EDocImport: Codeunit "E-Doc. Import";        Progress: Dialog;    begin        if not GlobalEDocumentHelper.EnsureInboundEDocumentHasService(Rec) then            exit;        if GuiAllowed() then            Progress.Open(ProcessingDocumentMsg);        // Regardless of document state, we re-run the structure received data, then prepare draft step.        TempEDocImportParameters."Step to Run" := Enum::"Import E-Document Steps"::"Structure received data";        EDocImport.ProcessIncomingEDocument(Rec, TempEDocImportParameters);        TempEDocImportParameters."Step to Run" := Enum::"Import E-Document Steps"::"Prepare draft";        EDocImport.ProcessIncomingEDocument(Rec, TempEDocImportParameters);        Rec.Get(Rec."Entry No");        if GuiAllowed() then            Progress.Close();        EDocumentErrorHelper.ThrowIfHasErrors(Rec);    end;    local procedure IsUserInitiatedFeedbackEnabled(): Boolean    var        TenantFeedbackSettings: Codeunit "Tenant Feedback Settings";    begin        exit(TenantFeedbackSettings.GetUserInitiatedFeedbackEnabled());    end;    local procedure ProvideFeedback()    var        EDocumentDataStorage: Record "E-Doc. Data Storage";        MicrosoftUserFeedback: Codeunit "Microsoft User Feedback";        Base64Convert: Codeunit "Base64 Convert";        EDocDraftFeedback: Page "E-Doc. Draft Feedback";        Base64Data: Text;        InStream: InStream;        ContextFiles, ContextProperties : Dictionary of [Text, Text];    begin        if not IsUserInitiatedFeedbackEnabled() then            exit;        if EDocDraftFeedback.RunModal() = Action::Yes then begin            if EDocumentDataStorage.Get(Rec."Unstructured Data Entry No.") then begin                EDocumentDataStorage.GetTempBlob().CreateInStream(InStream);                Base64Data := Base64Convert.ToBase64(InStream);                ContextFiles.Add(EDocumentDataStorage.Name, Base64Data);            end;            MicrosoftUserFeedback.SetIsAIFeedback(true).RequestFeedback('Payables Agent Draft', 'PayablesAgent', 'Payables Agent', ContextFiles, ContextProperties);        end;    end;    local procedure DoLinkToExistingDocument()    var        PurchaseHeader: Record "Purchase Header";        TempEDocImportParameters: Record "E-Doc. Import Parameters";        ConfirmDialogMgt: Codeunit "Confirm Management";        LinkToExistingDocumentQst: Label 'Do you want to link this e-document to %1 %2?', Comment = '%1 = Document Type, %2 = Document No.';        RelinkToExistingDocumentQst: Label 'This e-document is already linked to a document. Linking to %1 %2 will unlink the currently linked document. You will need to manually clean up that document. Do you want to continue?', Comment = '%1 = Document Type, %2 = Document No.';        ConfirmQst: Text;    begin        EDocumentProcessing.ErrorIfNotAllowedToLinkToExistingDoc(Rec, EDocumentPurchaseHeader);        PurchaseHeader.SetRange("Buy-from Vendor No.", EDocumentPurchaseHeader."[BC] Vendor No.");        PurchaseHeader.SetRange("Doc. Amount Incl. VAT", EDocumentPurchaseHeader.Total);        if not EDocumentProcessing.OpenPurchaseDocumentList(Rec."Document Type", PurchaseHeader) then            exit;        ConfirmQst := StrSubstNo(Rec.Status = Rec.Status::Processed ? RelinkToExistingDocumentQst : LinkToExistingDocumentQst, PurchaseHeader."Document Type", PurchaseHeader."No.");        if not ConfirmDialogMgt.GetResponseOrDefault(ConfirmQst, Rec.Status <> Rec.Status::Processed) then            exit;        TempEDocImportParameters."Existing Doc. RecordId" := PurchaseHeader.RecordId();        FinalizeEDocument(TempEDocImportParameters);    end;    var        EDocumentPurchaseHeader: Record "E-Document Purchase Header";        EDocumentServiceStatus: Record "E-Document Service Status";        EDocumentErrorHelper: Codeunit "E-Document Error Helper";        GlobalEDocumentNotification: Codeunit "E-Document Notification";        EDocumentProcessing: Codeunit "E-Document Processing";        FeatureTelemetry: Codeunit "Feature Telemetry";        GlobalEDocumentHelper: Codeunit "E-Document Helper";        RecordLinkTxt, StyleStatusTxt, DataCaption : Text;        HasErrorsOrWarnings, HasErrors : Boolean;        ShowFinalizeDraftAction: Boolean;        ShowAnalyzeDocumentAction: Boolean;        FinalizeDraftInvokedTxt: Label 'User invoked Finalize Draft action.', Locked = true;        FinalizeDraftPerformedTxt: Label 'User completed Finalize Draft action.', Locked = true;        ProcessingDocumentMsg: Label 'Processing document...';        ResetDraftQst: Label 'All the changes that you may have made on the document draft will be lost. Do you want to continue?';        PageEditable, HasPDFSource, IsCreditMemo : Boolean;        ApplyVATDiffEnabled: Boolean;        FeedbackActionVisible: Boolean;        AppliedVATAmountDiff: Decimal;        InvoiceWarningsTxt: Text;}