Codeunit 4400 SOA Setup

Sales Order Agent, Microsoft.Agent.SalesOrderAgent

src/Apps/W1/SalesOrderAgent/app/src/Setup/SOASetup.Codeunit.al1,252 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.// ------------------------------------------------------------------------------------------------#pragma warning disable AS0007namespace Microsoft.Agent.SalesOrderAgent;using Microsoft.CRM.Contact;using Microsoft.Finance.Currency;using Microsoft.Finance.GeneralLedger.Setup;using Microsoft.Sales.Customer;using Microsoft.Sales.Document;using System.Agents;using System.Azure.Identity;using System.Email;using System.Environment;using System.Environment.Configuration;using System.Globalization;using System.IO;using System.Reflection;using System.Security.AccessControl;using System.Telemetry;#pragma warning disable AS0049codeunit 4400 "SOA Setup"{    Access = Internal;    InherentEntitlements = X;    InherentPermissions = X;    Permissions = tabledata "Email Inbox" = rd;#pragma warning restore AS0049    /// <summary>    /// Used for testing OnPrem    /// </summary>    [Scope('OnPrem')]    procedure CreateDefaultAgentNoEmail()    var        TempAgentSetupBuffer: Record "Agent Setup Buffer";        TempSOASetup: Record "SOA Setup" temporary;        AgentSetup: Codeunit "Agent Setup";        SOASetup: Codeunit "SOA Setup";        AgentUserSecurityID: Guid;    begin        Clear(TempSOASetup);        AgentSetup.GetSetupRecord(TempAgentSetupBuffer,           TempSOASetup."User Security ID",           "Agent Metadata Provider"::"SO Agent",           SOASetup.GetSOAUsername(),           SOASetup.GetSOAUserDisplayName(),           SOASetup.GetAgentSummary()        );        TempAgentSetupBuffer.State := TempAgentSetupBuffer.State::Enabled;        AgentUserSecurityID := AgentSetup.SaveChanges(TempAgentSetupBuffer);        GetSOASetup(TempSOASetup, AgentUserSecurityID);        TempSOASetup."Email Monitoring" := false;        UpdateAgent(TempAgentSetupBuffer, TempSOASetup, true);    end;    local procedure CreateAgent(var AgentSetupBuffer: Record "Agent Setup Buffer"; var TempSOASetup: Record "SOA Setup" temporary)    var        AgentSetup: Codeunit "Agent Setup";    begin        EnsureAgentIdentityDefaults(TempSOASetup);        ValidateAgentIdentity(TempSOASetup);        CheckMailboxUnique(TempSOASetup);        AgentSetupBuffer."Display Name" := GetSOAUserDisplayName(TempSOASetup."Agent Name");        AgentSetupBuffer."User Name" := GetSOAUsername();        TempSOASetup."User Security ID" := AgentSetup.SaveChanges(AgentSetupBuffer);        UpdateInstructions(TempSOASetup);        if AgentSetupBuffer.State = AgentSetupBuffer.State::Enabled then begin            if TempSOASetup."Email Monitoring" then                UpdateSyncDateTime(TempSOASetup, true);            UpdateSOASetupActivationDT(TempSOASetup);        end;        UpdateSOASetup(TempSOASetup);        if AgentSetupBuffer.State = AgentSetupBuffer.State::Enabled then begin            EnableItemSearch();            if TempSOASetup."Email Monitoring" and not IsNullGuid(TempSOASetup."Email Account ID") then                SOAImpl.ScheduleSOAgent(TempSOASetup)        end;    end;    internal procedure GetInitials(): Text[4]    begin        exit(GetDefaultSOAInitials());    end;    internal procedure GetInitials(AgentUserSecurityID: Guid): Text[4]    var        SOASetup: Record "SOA Setup";    begin        if not IsNullGuid(AgentUserSecurityID) then            if SOASetup.GetBasedOnAgentUserSecurityID(AgentUserSecurityID, false) then                if SOASetup."Agent Initials" <> '' then                    exit(SOASetup."Agent Initials");        exit(GetDefaultSOAInitials());    end;    internal procedure GetAgentType(): Text    begin        exit(SalesOrderAgentTypeLbl);    end;    internal procedure GetAgentSummary(): Text    begin        exit(SOASummaryLbl);    end;    internal procedure AllowCreateNewSOAgent(): Boolean    var        AgentSystemPermissions: Codeunit "Agent System Permissions";    begin        if not AgentSystemPermissions.CurrentUserHasCanManageAllAgentsPermission() then            // Limit agent creation to agent admins.            exit(false);        exit(ActiveSOAgentCount(UserSecurityId()) < MaxSOAInstances());    end;    /// <summary>    /// Counts the Sales Order Agent instances owned by a user that still occupy a slot.    /// Archived agents are excluded because they can never be reactivated.    /// </summary>    internal procedure ActiveSOAgentCount(OwnerUserSecurityID: Guid): Integer    var        SOASetup: Record "SOA Setup";    begin        SOASetup.SetRange("Owner User Security ID", OwnerUserSecurityID);        exit(CountNonArchivedSetups(SOASetup));    end;    /// <summary>    /// Tells whether the company has at least one Sales Order Agent that is not archived. Kept to two    /// bounded queries because callers include paths that run for ordinary users.    /// </summary>    internal procedure ActiveSOAgentSetupExists(): Boolean    var        SOASetup: Record "SOA Setup";        AgentRec: Record Agent;    begin        if SOASetup.IsEmpty() then            exit(false);        // A setup record without a readable agent is treated as active, matching IsAgentArchived.        if not AgentRec.ReadPermission() then            exit(true);        // Filtered exists check only, for the reason given in IsAgentArchived. Any substate other than        // archived is a live agent, so a substate added later does not silently hide the agent.        AgentRec.SetRange("Agent Metadata Provider", Enum::"Agent Metadata Provider"::"SO Agent");        AgentRec.SetFilter(Substate, '<>%1', AgentRec.Substate::Archived);        exit(not AgentRec.IsEmpty());    end;    /// <summary>    /// Counts the records in an already filtered set of setup records whose agent is not archived.    /// </summary>    internal procedure CountNonArchivedSetups(var SOASetup: Record "SOA Setup") NonArchivedCount: Integer    begin        if not SOASetup.FindSet() then            exit(0);        repeat            if not IsAgentArchived(SOASetup."User Security ID") then                NonArchivedCount += 1;        until SOASetup.Next() = 0;    end;    /// <summary>    /// Finds the first record in an already filtered set of setup records whose agent is not archived.    /// </summary>    internal procedure FindFirstNonArchivedSetup(var SOASetup: Record "SOA Setup"): Boolean    begin        if not SOASetup.FindSet() then            exit(false);        repeat            if not IsAgentArchived(SOASetup."User Security ID") then                exit(true);        until SOASetup.Next() = 0;        exit(false);    end;    internal procedure IsAgentArchived(AgentUserSecurityID: Guid): Boolean    var        AgentRec: Record Agent;    begin        if IsNullGuid(AgentUserSecurityID) then            exit(false);        // A setup record can outlive its agent and not every session can read the Agent table.        // Counting and advisory callers treat both cases as not archived so they are never blocked.        if not AgentRec.ReadPermission() then            exit(false);        // Agent is a virtual table. Every read of it, including this filtered existence check, is served        // by building agent records, and building a record calls back into the agent metadata provider of        // this app. Nothing that the platform can invoke while it builds a record may call this, or the        // callback re-enters itself until the stack overflows. Filtering keeps the work small, it does        // not make the read safe from that context.        AgentRec.SetRange("User Security ID", AgentUserSecurityID);        AgentRec.SetRange("Agent Metadata Provider", Enum::"Agent Metadata Provider"::"SO Agent");        AgentRec.SetRange(Substate, AgentRec.Substate::Archived);        exit(not AgentRec.IsEmpty());    end;    /// <summary>    /// Tells whether the agent behind a setup record is currently live, meaning it exists, is enabled and    /// is not archived. Sessions that cannot read the Agent table get true, so callers never act on a    /// state they were unable to determine.    /// </summary>    internal procedure IsAgentActive(AgentUserSecurityID: Guid): Boolean    var        AgentRec: Record Agent;    begin        if IsNullGuid(AgentUserSecurityID) then            exit(false);        if not AgentRec.ReadPermission() then            exit(true);        // Filtered exists check only, for the reason given in IsAgentArchived. Any substate other than        // archived is a live agent, so a substate added later does not silently make agents look inactive.        AgentRec.SetRange("User Security ID", AgentUserSecurityID);        AgentRec.SetRange("Agent Metadata Provider", Enum::"Agent Metadata Provider"::"SO Agent");        AgentRec.SetRange(State, AgentRec.State::Enabled);        AgentRec.SetFilter(Substate, '<>%1', AgentRec.Substate::Archived);        exit(not AgentRec.IsEmpty());    end;    /// <summary>    /// Archived state for callers that block an operation. Unlike IsAgentArchived this fails closed:    /// an agent whose state cannot be read is treated as archived, so the guard cannot be bypassed    /// by running without access to the Agent table.    /// </summary>    internal procedure MustTreatAgentAsArchived(AgentUserSecurityID: Guid): Boolean    var        AgentRec: Record Agent;    begin        if IsNullGuid(AgentUserSecurityID) then            exit(false);        if not AgentRec.ReadPermission() then            exit(true);        exit(IsAgentArchived(AgentUserSecurityID));    end;    internal procedure CheckAgentNotArchived(AgentUserSecurityID: Guid)    begin        if MustTreatAgentAsArchived(AgentUserSecurityID) then            Error(AgentArchivedErr);    end;    internal procedure MaxSOAInstances(): Integer    begin        exit(20);    end;    internal procedure GetDispatcherBaseDelaySeconds(): Integer    begin        exit(30);    end;    internal procedure GetDispatcherDelayIncrementSeconds(): Integer    begin        exit(15);    end;    internal procedure UpdateAgent(var AgentSetupBuffer: Record "Agent Setup Buffer"; var TempSOASetup: Record "SOA Setup" temporary; Schedule: Boolean)    var        ExistingSOASetup: Record "SOA Setup";        AzureADGraphUser: Codeunit "Azure AD Graph User";        AgentSetup: Codeunit "Agent Setup";    begin        if AzureADGraphUser.IsUserDelegatedAdmin() or AzureADGraphUser.IsUserDelegatedHelpdesk() then            Error(DelegateAdminErr);        // Keep setup and agent buffer identities aligned to avoid drifting updates.        if IsNullGuid(TempSOASetup."User Security ID") then            TempSOASetup."User Security ID" := AgentSetupBuffer."User Security ID";        if IsNullGuid(AgentSetupBuffer."User Security ID") then            AgentSetupBuffer."User Security ID" := TempSOASetup."User Security ID";        CheckAgentNotArchived(TempSOASetup."User Security ID");        EnsureAgentIdentityDefaults(TempSOASetup);        if IsNullGuid(AgentSetupBuffer."User Security ID") then            CreateAgent(AgentSetupBuffer, TempSOASetup)        else begin            if ExistingSOASetup.GetBasedOnAgentUserSecurityID(TempSOASetup."User Security ID", false) then                // Preserve persisted ID for uniqueness validation while keeping user-edited values.                if TempSOASetup.ID = 0 then                    TempSOASetup.ID := ExistingSOASetup.ID;            ValidateAgentIdentity(TempSOASetup);            CheckMailboxUnique(TempSOASetup);            AgentSetupBuffer."Display Name" := GetSOAUserDisplayName(TempSOASetup."Agent Name");            AgentSetup.SaveChanges(AgentSetupBuffer);            if AgentSetupBuffer.State = AgentSetupBuffer.State::Enabled then begin                UpdateSOASetupActivationDT(TempSOASetup);                UpdateInstructions(TempSOASetup);                if TempSOASetup."Email Monitoring" and (TempSOASetup."Earliest Sync At" = 0DT) then                    UpdateSyncDateTime(TempSOASetup, false);            end;            if AgentSetupBuffer.State = AgentSetupBuffer.State::Enabled then begin                EnableItemSearch();                if TempSOASetup."Email Monitoring" and not IsNullGuid(TempSOASetup."Email Account ID") and Schedule then                    SOAImpl.ScheduleSOAgent(TempSOASetup);            end            else                SOAImpl.RemoveScheduledTask(TempSOASetup);            UpdateSOASetup(TempSOASetup);        end;        SyncAgentIdentity(AgentSetupBuffer, TempSOASetup);        // Log SOA setup telemetry        LogTelemetry(AgentSetupBuffer, TempSOASetup);    end;    local procedure SyncAgentIdentity(var AgentSetupBuffer: Record "Agent Setup Buffer"; var TempSOASetup: Record "SOA Setup" temporary)    var        AgentRec: Record Agent;        AgentUserSecurityID: Guid;        AgentDisplayName: Text[80];        AgentInitials: Text[4];    begin        AgentUserSecurityID := TempSOASetup."User Security ID";        if IsNullGuid(AgentUserSecurityID) then            AgentUserSecurityID := AgentSetupBuffer."User Security ID";        if IsNullGuid(AgentUserSecurityID) then            exit;        AgentDisplayName := GetSOAUserDisplayName(TempSOASetup."Agent Name");        AgentInitials := TempSOASetup."Agent Initials";        if AgentRec.Get(AgentUserSecurityID) then            if (AgentRec."Display Name" <> AgentDisplayName) or (AgentRec.Initials <> AgentInitials) then begin                AgentRec."Display Name" := AgentDisplayName;                AgentRec.Initials := AgentInitials;                AgentRec.Modify();            end;    end;    local procedure UpdateSOASetup(var TempSOASetup: Record "SOA Setup" temporary)    var        SOASetup: Record "SOA Setup";    begin        if SOASetup.GetBasedOnAgentUserSecurityID(TempSOASetup."User Security ID", false) then begin            SOASetup."Incoming Monitoring" := TempSOASetup."Incoming Monitoring";            SOASetup."Email Monitoring" := TempSOASetup."Email Monitoring";            if SOASetup."Email Monitoring" then begin                SOASetup."Email Account ID" := TempSOASetup."Email Account ID";                SOASetup."Email Connector" := TempSOASetup."Email Connector";                SOASetup."Email Address" := TempSOASetup."Email Address";                SOASetup."Email Folder" := TempSOASetup."Email Folder";                SOASetup."Email Folder Id" := TempSOASetup."Email Folder Id";            end;            SOASetup."Analyze Attachments" := TempSOASetup."Analyze Attachments";            SOASetup."Activated At" := TempSOASetup."Activated At";            SOASetup."Earliest Sync At" := TempSOASetup."Earliest Sync At";            SOASetup."Last Sync At" := TempSOASetup."Last Sync At";            SOASetup."Sales Doc. Configuration" := TempSOASetup."Sales Doc. Configuration";            SOASetup."Quote Review" := TempSOASetup."Quote Review";            SOASetup."Order Review" := TempSOASetup."Order Review";            SOASetup."Create Order from Quote" := TempSOASetup."Create Order from Quote";            SOASetup."Search Only Available Items" := TempSOASetup."Search Only Available Items";            SOASetup."Incl. Capable to Promise" := TempSOASetup."Incl. Capable to Promise";            SOASetup."Agent Scheduled Task ID" := TempSOASetup."Agent Scheduled Task ID";            SOASetup."Recovery Scheduled Task ID" := TempSOASetup."Recovery Scheduled Task ID";            SOASetup."Known Sender In. Msg. Review" := TempSOASetup."Known Sender In. Msg. Review";            SOASetup."Unknown Sender In. Msg. Review" := TempSOASetup."Unknown Sender In. Msg. Review";            SOASetup."Instructions Last Sync At" := TempSOASetup."Instructions Last Sync At";            SOASetup."Configure Email Template" := TempSOASetup."Configure Email Template";            SOASetup."Mark Email As Read" := TempSOASetup."Mark Email As Read";            CopyMailSignatureField(TempSOASetup, SOASetup);            SOASetup."Message Limit" := TempSOASetup."Message Limit";            SOASetup."Send Sales Quote" := TempSOASetup."Send Sales Quote";            SOASetup."Agent Name" := TempSOASetup."Agent Name";            SOASetup."Agent Initials" := TempSOASetup."Agent Initials";            SOASetup.Modify();        end        else begin            SOASetup.Copy(TempSOASetup);            if IsNullGuid(SOASetup."Owner User Security ID") then                SOASetup."Owner User Security ID" := UserSecurityId();            SOASetup.Insert();            TempSOASetup := SOASetup;            TempSOASetup.Insert();        end;    end;    local procedure LogTelemetry(var AgentSetupBuffer: Record "Agent Setup Buffer"; var TempSOASetup: Record "SOA Setup" temporary)    var        TempUserSettings: Record "User Settings";        FeatureTelemetry: Codeunit "Feature Telemetry";        Language: Codeunit Language;        TelemetryCustomDimension: Dictionary of [Text, Text];    begin        // SOA user settings        TelemetryCustomDimension.Add('AgentUserId', Format(TempSOASetup."User Security ID"));        Agent.GetUserSettings(AgentSetupBuffer."User Security ID", TempUserSettings);        if TempUserSettings."Language ID" <> 0 then            TelemetryCustomDimension.Add('Language', Language.GetCultureName(TempUserSettings."Language ID"))        else            TelemetryCustomDimension.Add('Language', '');        if TempUserSettings."Locale ID" <> 0 then            TelemetryCustomDimension.Add('Locale', Language.GetCultureName(TempUserSettings."Locale ID"))        else            TelemetryCustomDimension.Add('Locale', '');        TelemetryCustomDimension.Add('TimeZone', TempUserSettings."Time Zone");        // SOA setup config        TelemetryCustomDimension.Add('IncomingMonitoring', Format(TempSOASetup."Incoming Monitoring"));        TelemetryCustomDimension.Add('EmailMonitoring', Format(TempSOASetup."Email Monitoring"));        TelemetryCustomDimension.Add('AnalyzeAttachments', Format(TempSOASetup."Analyze Attachments"));        TelemetryCustomDimension.Add('SalesDocConfiguration', Format(TempSOASetup."Sales Doc. Configuration"));        TelemetryCustomDimension.Add('QuoteReview', Format(TempSOASetup."Quote Review"));        TelemetryCustomDimension.Add('OrderReview', Format(TempSOASetup."Order Review"));        TelemetryCustomDimension.Add('CreateOrderFromQuote', Format(TempSOASetup."Create Order from Quote"));        TelemetryCustomDimension.Add('SearchOnlyAvailableItems', Format(TempSOASetup."Search Only Available Items"));        TelemetryCustomDimension.Add('InclCapableToPromise', Format(TempSOASetup."Incl. Capable to Promise"));        TelemetryCustomDimension.Add('SendSalesQuote', Format(TempSOASetup."Send Sales Quote"));        TelemetryCustomDimension.Add('ConfigureEmailTemplate', Format(TempSOASetup."Configure Email Template"));        TelemetryCustomDimension.Add('KnownSenderInMsgReview', Format(TempSOASetup."Known Sender In. Msg. Review"));        TelemetryCustomDimension.Add('UnknownSenderInMsgReview', Format(TempSOASetup."Unknown Sender In. Msg. Review"));        TelemetryCustomDimension.Add('MarkEmailAsRead', Format(TempSOASetup."Mark Email As Read"));        TelemetryCustomDimension.Add('MessageLimit', Format(TempSOASetup."Message Limit"));        if not IsNullGuid(TempSOASetup."Email Account ID") then            TelemetryCustomDimension.Add('HasEmailAccountId', 'true')        else            TelemetryCustomDimension.Add('HasEmailAccountId', 'false');        TelemetryCustomDimension.Add('EmailConnector', Format(TempSOASetup."Email Connector"));        if (AgentSetupBuffer.State = AgentSetupBuffer.State::Enabled) then            FeatureTelemetry.LogUptake('0000QB5', GetFeatureName(), Enum::"Feature Uptake Status"::"Set up", TelemetryCustomDimension)        else            FeatureTelemetry.LogUptake('0000QB6', GetFeatureName(), Enum::"Feature Uptake Status"::Undiscovered, TelemetryCustomDimension);    end;    local procedure SetDefaultSalesDocConfig(var SOASetup: Record "SOA Setup"; SalesDocConfigValue: Boolean)    begin        SOASetup."Sales Doc. Configuration" := SalesDocConfigValue;        SOASetup."Quote Review" := false;        SOASetup."Order Review" := false;        SOASetup."Create Order from Quote" := true;        SOASetup."Search Only Available Items" := false;        SOASetup."Incl. Capable to Promise" := false;        SOASetup."Send Sales Quote" := true;    end;    local procedure CopyMailSignatureField(var FromSOASetup: Record "SOA Setup"; var ToSOASetup: Record "SOA Setup")    var        InStream: InStream;        OutStream: OutStream;    begin        Clear(ToSOASetup."Email Template");        FromSOASetup.CalcFields("Email Template");        if FromSOASetup."Email Template".HasValue() then begin            FromSOASetup."Email Template".CreateInStream(InStream, TextEncoding::UTF8);            ToSOASetup."Email Template".CreateOutStream(OutStream, TextEncoding::UTF8);            CopyStream(OutStream, InStream);        end;    end;    local procedure SetDefaultEmailSignature(var SOASetup: Record "SOA Setup")    begin        SOASetup.SetEmailSignature(GetDefaultEmailSignatureAsTxt());    end;    internal procedure GetDefaultEmailSignatureAsTxt(): Text    begin        exit(StrSubstNo(EmailSignatureLbl, SignatureClosingLbl, CompanyProperty.DisplayName(), SignatureNoteLbl));    end;    internal procedure UpdateInstructions(var TempSOASetup: Record "SOA Setup" temporary)    var        SOAPromptBuilder: Codeunit "SOA Prompt Builder";        InstructionsSecret: SecretText;    begin        CheckAgentNotArchived(TempSOASetup."User Security ID");        SOAPromptBuilder.PrepareInstructions(InstructionsSecret, TempSOASetup);        Agent.SetInstructions(TempSOASetup."User Security ID", InstructionsSecret);        TempSOASetup."Instructions Last Sync At" := CurrentDateTime();    end;    internal procedure InstructionsSyncRequired(var SOASetup: Record "SOA Setup"): Boolean    var        CurrentSOASetup: Record "SOA Setup";    begin        CurrentSOASetup.ReadIsolation := IsolationLevel::ReadCommitted;        if not CurrentSOASetup.Get(SOASetup.RecordId) then            exit(true);        if CurrentSOASetup."Instructions Last Sync At" = 0DT then            exit(true);        if CurrentDateTime > CurrentSOASetup."Instructions Last Sync At" + GetSOAInstructionsSyncPeriod() then //last sync was more than 30 minutes ago            exit(true);        exit(false);    end;    internal procedure UpdateSOASetupInstructionsLastSync(var SOASetup: Record "SOA Setup")    var        CurrentSOASetup: Record "SOA Setup";    begin        if not CurrentSOASetup.Get(SOASetup.RecordId) then            exit;        CurrentSOASetup."Instructions Last Sync At" := SOASetup."Instructions Last Sync At";        CurrentSOASetup.Modify();    end;    local procedure GetSOAInstructionsSyncPeriod(): Integer    begin        exit(1800000); // 30 minutes    end;    internal procedure UpdateSOASetupActivationDT(var TempSOASetup: Record "SOA Setup" temporary)    begin        TempSOASetup."Activated At" := CurrentDateTime();    end;    local procedure EnableItemSearch()    var        ItemSearch: Codeunit "Global Item Search";    begin        ItemSearch.EnableItemSearch();    end;    internal procedure GetDefaultAgentAccessControl(AgentUserSecurityID: Guid; var TempAgentAccessControl: Record "Agent Access Control" temporary)    begin        if IsNullGuid(AgentUserSecurityID) then            exit;        Agent.GetUserAccess(AgentUserSecurityID, TempAgentAccessControl);    end;    internal procedure GetDefaultProfile(var TempAllProfile: Record "All Profile" temporary)    var        ModuleInfo: ModuleInfo;    begin        NavApp.GetCurrentModuleInfo(ModuleInfo);        Agent.PopulateDefaultProfile(SalesOrderAgentTok, ModuleInfo.Id, TempAllProfile);    end;    internal procedure GetDefaultAccessControls(var TempAccessControlBuffer: Record "Access Control Buffer" temporary)    var        ModuleInfo: ModuleInfo;    begin        NavApp.GetCurrentModuleInfo(ModuleInfo);        TempAccessControlBuffer.Init();        TempAccessControlBuffer."Company Name" := CopyStr(CompanyName(), 1, MaxStrLen(TempAccessControlBuffer."Company Name"));        TempAccessControlBuffer.Scope := TempAccessControlBuffer.Scope::System;        TempAccessControlBuffer."App ID" := ModuleInfo.Id;        TempAccessControlBuffer."Role ID" := SOAEditTok;        TempAccessControlBuffer.Insert();    end;    internal procedure GetSOASetup(var TempSOASetup: Record "SOA Setup" temporary; AgentUserSecurityID: Guid)    var        SOASetup: Record "SOA Setup";    begin        if IsNullGuid(AgentUserSecurityID) then begin            SetSOASetupDefaults(TempSOASetup, AgentUserSecurityID);            exit;        end;        if IsNullGuid(TempSOASetup."User Security ID") then begin            SOASetup.SetRange("User Security ID", AgentUserSecurityID);            if SOASetup.FindFirst() then begin                SOASetup.CalcFields("Email Template");                TempSOASetup := SOASetup;                TempSOASetup.Insert();                exit;            end;            SetSOASetupDefaults(TempSOASetup, AgentUserSecurityID);            exit;        end;        if SOASetup.GetBasedOnAgentUserSecurityID(TempSOASetup."User Security ID", false) then begin            SOASetup.CalcFields("Email Template");            TempSOASetup := SOASetup;            TempSOASetup.Insert();        end        else            SetSOASetupDefaults(TempSOASetup, AgentUserSecurityID);    end;    internal procedure CheckSOASetupStillValid(var SOASetup: Record "SOA Setup"): Boolean    var        CurrentSOASetup: Record "SOA Setup";    begin        CurrentSOASetup.ReadIsolation := IsolationLevel::ReadCommitted;        CurrentSOASetup.SetAutoCalcFields(State);        if not CurrentSOASetup.Get(SOASetup.RecordId) then            exit(false);        if not (CurrentSOASetup.State = CurrentSOASetup.State::Enabled) then            exit(false);        if SOASetup."Email Account ID" <> CurrentSOASetup."Email Account ID" then            exit(false);        exit(true);    end;    internal procedure ValidateAgentIdentity(SOASetup: Record "SOA Setup")    var        OtherSOASetup: Record "SOA Setup";        AgentNameRequiredErr: Label 'A display name is required for the Sales Order Agent instance.';        AgentNameConflictErr: Label 'This display name is already used by another Sales Order Agent instance.';        AgentInitialsRequiredErr: Label 'Initials are required for the Sales Order Agent instance.';        AgentInitialsConflictErr: Label 'These initials are already used by another Sales Order Agent instance.';    begin        if SOASetup."Agent Name" = '' then            Error(AgentNameRequiredErr);        if SOASetup."Agent Initials" = '' then            Error(AgentInitialsRequiredErr);        OtherSOASetup.SetRange("Agent Name", SOASetup."Agent Name");        OtherSOASetup.SetFilter(ID, '<>%1', SOASetup.ID);        if FindFirstNonArchivedSetup(OtherSOASetup) then            Error(AgentNameConflictErr);        OtherSOASetup.Reset();        OtherSOASetup.SetRange("Agent Initials", SOASetup."Agent Initials");        OtherSOASetup.SetFilter(ID, '<>%1', SOASetup.ID);        if FindFirstNonArchivedSetup(OtherSOASetup) then            Error(AgentInitialsConflictErr);    end;    internal procedure CheckMailboxUnique(SOASetup: Record "SOA Setup")    var        OtherSOASetup: Record "SOA Setup";    begin        if IsNullGuid(SOASetup."Email Account ID") then            exit;        OtherSOASetup.SetRange("Email Account ID", SOASetup."Email Account ID");        OtherSOASetup.SetRange("Email Connector", SOASetup."Email Connector");        OtherSOASetup.SetFilter(ID, '<>%1', SOASetup.ID);        if SOASetup."Email Folder Id" = '' then begin            OtherSOASetup.SetRange("Email Folder Id", '');            if FindFirstNonArchivedSetup(OtherSOASetup) then                Error(MailboxAlreadyUsedWithoutFolderErr, OtherSOASetup."Agent Name", OtherSOASetup."Agent Initials");            exit;        end;        OtherSOASetup.SetRange("Email Folder Id", SOASetup."Email Folder Id");        if FindFirstNonArchivedSetup(OtherSOASetup) then            Error(MailboxAndFolderAlreadyUsedErr, OtherSOASetup."Agent Name", OtherSOASetup."Agent Initials");    end;    internal procedure GetEmailAccount(var SOASetup: Record "SOA Setup"; var TempEmailAccount: Record "Email Account" temporary)    var        TempAllEmailAccounts: Record "Email Account" temporary;        EmailAccount: Codeunit "Email Account";    begin        EmailAccount.GetAllAccounts(false, TempAllEmailAccounts);        TempAllEmailAccounts.SetRange("Account Id", SOASetup."Email Account ID");        TempAllEmailAccounts.SetRange(Connector, SOASetup."Email Connector");        if TempAllEmailAccounts.FindFirst() then            TempEmailAccount.Copy(TempAllEmailAccounts);    end;    internal procedure GetDefaultEmailAccount(var TempEmailAccount: Record "Email Account" temporary)    var        EmailAccount: Codeunit "Email Account";    begin        EmailAccount.GetAllAccounts(false, TempEmailAccount);        if TempEmailAccount.FindFirst() then;    end;    internal procedure GetAgentTaskUserInterventionSuggestions(AgentTaskUserInterventionRequestDetails: Record "Agent User Int Request Details"; var AgentTaskUserInterventionSuggestion: Record "Agent Task User Int Suggestion")    begin        Clear(AgentTaskUserInterventionSuggestion);        case AgentTaskUserInterventionRequestDetails.Type of            AgentTaskUserInterventionRequestDetails.Type::ReviewMessage:                begin                    if (AgentTaskUserInterventionRequestDetails."Page ID" = Page::"Sales Quote") then begin                        AgentTaskUserInterventionSuggestion.Init();                        AgentTaskUserInterventionSuggestion.Code := GetUpdatedQuoteInterventionSuggestionCode();                        AgentTaskUserInterventionSuggestion.Summary := StrSubstNo(SOAInterventionSuggestionSummaryLbl, SOAInterventionSuggestionQuoteLbl);                        AgentTaskUserInterventionSuggestion.Description := StrSubstNo(SOAInterventionSuggestionDescriptionLbl, SOAInterventionSuggestionQuoteLockedLbl);                        AgentTaskUserInterventionSuggestion.Instructions := StrSubstNo(SOAInterventionSuggestionInstructionsLbl, SOAInterventionSuggestionQuoteLockedLbl);                        AgentTaskUserInterventionSuggestion.Insert();                    end;                    if (AgentTaskUserInterventionRequestDetails."Page ID" = Page::"Sales Order") then begin                        AgentTaskUserInterventionSuggestion.Init();                        AgentTaskUserInterventionSuggestion.Code := GetUpdatedOrderInterventionSuggestionCode();                        AgentTaskUserInterventionSuggestion.Summary := StrSubstNo(SOAInterventionSuggestionSummaryLbl, SOAInterventionSuggestionOrderLbl);                        AgentTaskUserInterventionSuggestion.Description := StrSubstNo(SOAInterventionSuggestionDescriptionLbl, SOAInterventionSuggestionOrderLockedLbl);                        AgentTaskUserInterventionSuggestion.Instructions := StrSubstNo(SOAInterventionSuggestionInstructionsLbl, SOAInterventionSuggestionOrderLockedLbl);                        AgentTaskUserInterventionSuggestion.Insert();                    end;                end;            AgentTaskUserInterventionRequestDetails.Type::Assistance:                begin                    if AgentTaskUserInterventionRequestDetails."Page ID" = Page::"SOA Multi Items Availability" then begin                        AgentTaskUserInterventionSuggestion.Init();                        AgentTaskUserInterventionSuggestion.Code := SOAItemAvailabilityInterventionSuggestionCodeLbl;                        AgentTaskUserInterventionSuggestion.Summary := SOAItemAvailabilityInterventionSuggestionSummaryLbl;                        AgentTaskUserInterventionSuggestion.Description := SOAItemAvailabilityInterventionSuggestionDescriptionLbl;                        AgentTaskUserInterventionSuggestion.Instructions := SOAItemAvailabilityInterventionSuggestionInstructionsLbl;                        AgentTaskUserInterventionSuggestion.Insert();                    end;                    if AgentTaskUserInterventionRequestDetails."Page ID" = Page::"Customer List" then begin                        AgentTaskUserInterventionSuggestion.Init();                        AgentTaskUserInterventionSuggestion.Code := SOACustomerInterventionSuggestionCodeLbl;                        AgentTaskUserInterventionSuggestion.Summary := SOACustomerInterventionSuggestionSummaryLbl;                        AgentTaskUserInterventionSuggestion.Description := SOACustomerInterventionSuggestionDescriptionLbl;                        AgentTaskUserInterventionSuggestion.Instructions := SOACustomerInterventionSuggestionInstructionsLbl;                        AgentTaskUserInterventionSuggestion.Insert();                        AgentTaskUserInterventionSuggestion.Init();                        AgentTaskUserInterventionSuggestion.Code := SOAContactInterventionSuggestionCodeLbl;                        AgentTaskUserInterventionSuggestion.Summary := SOAContactInterventionSuggestionSummaryLbl;                        AgentTaskUserInterventionSuggestion.Description := SOAContactInterventionSuggestionDescriptionLbl;                        AgentTaskUserInterventionSuggestion.Instructions := SOAContactInterventionSuggestionInstructionsLbl;                        AgentTaskUserInterventionSuggestion.Insert();                    end;                    if AgentTaskUserInterventionRequestDetails."Page ID" = Page::"Contact List" then begin                        AgentTaskUserInterventionSuggestion.Init();                        AgentTaskUserInterventionSuggestion.Code := SOAContactInterventionSuggestionCodeLbl;                        AgentTaskUserInterventionSuggestion.Summary := SOAContactInterventionSuggestionSummaryLbl;                        AgentTaskUserInterventionSuggestion.Description := SOAContactInterventionSuggestionDescriptionLbl;                        AgentTaskUserInterventionSuggestion.Instructions := SOAContactInterventionSuggestionInstructionsLbl;                        AgentTaskUserInterventionSuggestion.Insert();                    end;                end;        end;    end;    internal procedure GetAgentTaskPageContext(AgentTaskPageContextRequest: Record "Agent Task Page Context Req."; var AgentTaskPageContext: Record "Agent Task Page Context")    var        Contact: Record Contact;        Currency: Record Currency;        Customer: Record Customer;        GeneralLedgerSetup: Record "General Ledger Setup";        SalesHeader: Record "Sales Header";        LanguageSelection: Record "Language Selection";        Language: Codeunit Language;        SOAFiltersImpl: Codeunit "SOA Filters Impl.";        CustomerFilter: Text;        CurrencyCode: Code[10];        LanguageID: Integer;        FormatID: Integer;        LanguageCode: Code[10];        FormatRegion: Text[80];    begin        Clear(AgentTaskPageContext);        case AgentTaskPageContextRequest."Page ID" of            Page::"Sales Quote",            Page::"Sales Order":                if SalesHeader.Get(AgentTaskPageContextRequest."Record ID") then                    CurrencyCode := SalesHeader."Currency Code";            Page::"Contact Card":                if Contact.Get(AgentTaskPageContextRequest."Record ID") then begin                    if Contact.Type = Contact.Type::Person then                        if Contact.Get(Contact."Company No.") then;                    CurrencyCode := Contact."Currency Code";                end;            Page::"Customer Card":                if Customer.Get(AgentTaskPageContextRequest."Record ID") then                    CurrencyCode := Customer."Currency Code";            Page::"SOA Multi Items Availability":                begin                    CustomerFilter := SOAFiltersImpl.GetSecurityFiltersForCustomers(SOAFiltersImpl.GetSecurityFiltersForContacts(AgentTaskPageContextRequest."Task ID"));                    if CustomerFilter <> '' then begin                        Customer.SetFilter("No.", CustomerFilter);                        if Customer.FindFirst() then                            CurrencyCode := Customer."Currency Code";                    end;                end;        end;        GetCommunicationLanguageCodeAndFormat(AgentTaskPageContextRequest."Task ID", LanguageCode, FormatRegion);        if LanguageCode <> '' then            LanguageID := Language.GetLanguageId(LanguageCode);        if FormatRegion <> '' then begin            LanguageSelection.SetRange("Language Tag", FormatRegion);            if LanguageSelection.FindFirst() then                FormatID := LanguageSelection."Language ID";        end;        if CurrencyCode <> '' then begin            if Currency.Get(CurrencyCode) then                SetAgentTaskPageContext(Currency.Code, Currency.GetCurrencySymbol(), LanguageID, FormatID, AgentTaskPageContext)        end else            if GeneralLedgerSetup.Get() then                SetAgentTaskPageContext(GeneralLedgerSetup."LCY Code", GeneralLedgerSetup.GetCurrencySymbol(), LanguageID, FormatID, AgentTaskPageContext);    end;    /// <summary>    /// By priority: from the contact card, from the customer card, or from the user settings.    /// </summary>    internal procedure GetCommunicationLanguageCodeAndFormat(AgentTaskId: BigInteger; var LanguageCode: Code[10]; var FormatRegion: Text[80])    var        TaskContact: Record "Contact";        TaskCustomer: Record Customer;        SOAFiltersImpl: Codeunit "SOA Filters Impl.";        CustomerFilter: Text;        ContactFilter: Text;    begin        ContactFilter := SOAFiltersImpl.GetSecurityFiltersForContacts(AgentTaskID);        if ContactFilter <> '' then begin            CustomerFilter := SOAFiltersImpl.GetSecurityFiltersForCustomers(ContactFilter);            TaskContact.SetFilter("No.", ContactFilter);            if TaskContact.FindFirst() then begin                LanguageCode := TaskContact."Language Code";                FormatRegion := TaskContact."Format Region";            end;        end;        if (CustomerFilter <> '') and (CustomerFilter <> SOAFiltersImpl.GetExcludeAllFilter()) then begin            TaskCustomer.SetFilter("No.", CustomerFilter);            if TaskCustomer.FindFirst() then begin                if (LanguageCode = '') then                    LanguageCode := TaskCustomer."Language Code";                if (FormatRegion = '') then                    FormatRegion := TaskCustomer."Format Region";            end;        end;    end;    local procedure SetAgentTaskPageContext(CurrencyCode: Code[10]; CurrencySymbol: Code[10]; LanguageID: Integer; FormatID: Integer; var AgentTaskPageContext: Record "Agent Task Page Context")    begin        Clear(AgentTaskPageContext);        AgentTaskPageContext."Currency Code" := CurrencyCode;        AgentTaskPageContext."Currency Symbol" := CurrencySymbol;        AgentTaskPageContext."Communication Language LCID" := LanguageID;        AgentTaskPageContext."Communication Format LCID" := FormatID;        AgentTaskPageContext.Insert();    end;    local procedure SetSOASetupDefaults(var TempSOASetup: Record "SOA Setup" temporary; AgentUserSecurityID: Guid)    begin        TempSOASetup.Init();        TempSOASetup."Earliest Sync At" := CreateDateTime(Today(), 0T);        TempSOASetup."Last Sync At" := TempSOASetup."Earliest Sync At";        TempSOASetup."Incoming Monitoring" := true;        TempSOASetup."Email Monitoring" := true;        SetDefaultSalesDocConfig(TempSOASetup, true);        TempSOASetup."Analyze Attachments" := true;        TempSOASetup."Mark Email As Read" := true;        TempSOASetup."User Security ID" := AgentUserSecurityID;        TempSOASetup."Owner User Security ID" := UserSecurityId();        TempSOASetup."Agent Name" := GetDefaultSOAAgentName();        TempSOASetup."Agent Initials" := GetDefaultSOAInitials();        SetDefaultEmailSignature(TempSOASetup);        TempSOASetup.Insert();    end;    internal procedure GetSOAUserDisplayName(): Text[80]    begin        exit(GetSOAUserDisplayName(GetDefaultSOAAgentName()));    end;    internal procedure GetSOAUserDisplayName(AgentName: Text[50]): Text[80]    begin        if AgentName = '' then            exit(SalesOrderAgentDisplayNameLbl);        exit(CopyStr(AgentName, 1, 80));    end;    internal procedure GetSOAUsername(): Text[50]    var        CandidateUserName: Text[50];        Token: Text;        Index: Integer;    begin        Index := 1;        repeat            CandidateUserName := BuildSOAUserName(Index);            if not UserNameExists(CandidateUserName) then                exit(CandidateUserName);            Index += 1;        until Index > MaxAgentIdentitySuffix();        // Best-effort fallback to avoid blocking setup on exhausted default candidates.        Token := DelChr(Format(CreateGuid()), '=', '{}-');        exit(CopyStr(StrSubstNo('%1 %2', CopyStr(SalesOrderAgentNameLbl, 1, 40), CopyStr(Token, 1, 8)), 1, 50));    end;    local procedure EnsureAgentIdentityDefaults(var TempSOASetup: Record "SOA Setup" temporary)    begin        if TempSOASetup."Agent Name" = '' then            TempSOASetup."Agent Name" := GetDefaultSOAAgentName();        if TempSOASetup."Agent Initials" = '' then            TempSOASetup."Agent Initials" := GetDefaultSOAInitials();    end;    local procedure AgentNameExists(AgentName: Text[50]): Boolean    var        SOASetup: Record "SOA Setup";    begin        // Archived agents keep their place in the series, so the next suggested identity continues after        // them instead of reusing a name that was already handed out. Validation still allows an admin to        // type an archived agent's name, so the identity can be reused deliberately.        SOASetup.SetRange("Agent Name", AgentName);        exit(not SOASetup.IsEmpty());    end;    local procedure UserNameExists(UserName: Text[50]): Boolean    var        AgentRec: Record Agent;    begin        AgentRec.SetRange("User Name", UserName);        exit(not AgentRec.IsEmpty());    end;    local procedure InitialsExists(AgentInitials: Text[4]): Boolean    var        SOASetup: Record "SOA Setup";    begin        // Archived agents keep their place in the series. See AgentNameExists.        SOASetup.SetRange("Agent Initials", AgentInitials);        exit(not SOASetup.IsEmpty());    end;    local procedure GetNextAvailableAgentIdentityIndex(): Integer    var        FirstAvailableNameIndex: Integer;        FirstAvailableInitialsIndex: Integer;        CandidateIndex: Integer;    begin        FirstAvailableNameIndex := GetFirstAvailableAgentNameIndex();        FirstAvailableInitialsIndex := GetFirstAvailableAgentInitialsIndex();        CandidateIndex := FirstAvailableNameIndex;        if FirstAvailableInitialsIndex > CandidateIndex then            CandidateIndex := FirstAvailableInitialsIndex;        while CandidateIndex <= MaxAgentIdentitySuffix() do begin            if not AgentNameExists(BuildSOAAgentName(CandidateIndex)) and               not InitialsExists(BuildSOAAgentInitials(CandidateIndex))            then                exit(CandidateIndex);            CandidateIndex += 1;        end;        // Fall back to the base identity and let explicit validation handle conflicts.        exit(1);    end;    local procedure GetFirstAvailableAgentNameIndex(): Integer    var        CandidateName: Text[50];        Index: Integer;    begin        Index := 1;        repeat            CandidateName := BuildSOAAgentName(Index);            if not AgentNameExists(CandidateName) then                exit(Index);            Index += 1;        until Index > MaxAgentIdentitySuffix();        exit(1);    end;    local procedure GetDefaultSOAAgentName(): Text[50]    begin        exit(BuildSOAAgentName(GetNextAvailableAgentIdentityIndex()));    end;    local procedure BuildSOAAgentName(Index: Integer): Text[50]    begin        if Index <= 1 then            exit(CopyStr(SalesOrderAgentDisplayNameLbl, 1, 50));        exit(CopyStr(StrSubstNo('%1 %2', SalesOrderAgentDisplayNameLbl, Format(Index)), 1, 50));    end;    local procedure BuildSOAUserName(Index: Integer): Text[50]    var        BaseUserName: Text[250];        Suffix: Text[30];        MaxBaseLength: Integer;    begin        BaseUserName := SalesOrderAgentNameLbl + ' - ' + CompanyName();        if Index <= 1 then            Suffix := ''        else            Suffix := ' ' + Format(Index);        MaxBaseLength := 50 - StrLen(Suffix);        if MaxBaseLength < 1 then            MaxBaseLength := 1;        exit(CopyStr(BaseUserName, 1, MaxBaseLength) + Suffix);    end;    local procedure GetFirstAvailableAgentInitialsIndex(): Integer    var        CandidateInitials: Text[4];        Index: Integer;    begin        Index := 1;        repeat            CandidateInitials := BuildSOAAgentInitials(Index);            if not InitialsExists(CandidateInitials) then                exit(Index);            Index += 1;        until Index > MaxAgentIdentitySuffix();        exit(1);    end;    local procedure GetDefaultSOAInitials(): Text[4]    begin        exit(BuildSOAAgentInitials(GetNextAvailableAgentIdentityIndex()));    end;    local procedure BuildSOAAgentInitials(Index: Integer): Text[4]    begin        if Index <= 1 then            exit(CopyStr(SalesOrderAgentInitialLbl, 1, 4));        exit(CopyStr(SalesOrderAgentInitialLbl + Format(Index), 1, 4));    end;    local procedure MaxAgentIdentitySuffix(): Integer    begin        exit(99);    end;    internal procedure ValidateEmailConnectionStatus(var TempSOASetup: Record "SOA Setup" temporary) ConnectionSuccess: Boolean    var        SOATestSetup: Codeunit "SOA Test Setup";    begin        SOATestSetup.SetTestEmailConnection(true);        ConnectionSuccess := SOATestSetup.Run(TempSOASetup);    end;    internal procedure ValidateEmailConnection(StateChanged: Boolean; var TempSOASetup: Record "SOA Setup" temporary; MailboxChanged: Boolean; IsFirstActivation: Boolean)    var        NAVAppSettings: Record "NAV App Setting";        EnvironmentInformation: Codeunit "Environment Information";        CurrentModuleInfo: ModuleInfo;        GeneralError: Boolean;    begin        if TempSOASetup."Email Monitoring" and not IsNullGuid(TempSOASetup."Email Account ID") then begin            if StateChanged or MailboxChanged then                UpdateSyncDateTime(TempSOASetup, IsFirstActivation);            if ValidateEmailConnectionStatus(TempSOASetup) then                exit;            if GuiAllowed() then begin                GeneralError := true;                if EnvironmentInformation.IsSandbox() then begin                    NavApp.GetCurrentModuleInfo(CurrentModuleInfo);                    NAVAppSettings.ReadIsolation(IsolationLevel::ReadUncommitted);                    NAVAppSettings.SetRange("App ID", CurrentModuleInfo.Id);                    if NAVAppSettings.FindFirst() then                        if NAVAppSettings."Allow HttpClient Requests" = false then begin                            GeneralError := false;                            Error(SOAAttemptedConnectionHttpRequestFailedErr);                        end;                end;                if GeneralError then                    Error(SOAAttemptedConnectionFailedErr);            end;        end;    end;    local procedure UpdateSyncDateTime(var TempSOASetup: Record "SOA Setup" temporary; IsFirstActivation: Boolean)    var        SOAEmailSetup: Codeunit "SOA Email Setup";        EmailsCount: Integer;        ConfirmMessage: Text;    begin        if IsFirstActivation or (TempSOASetup."Activated At" = 0DT) then            exit;        EmailsCount := GetEmailsCount(TempSOASetup);        if EmailsCount = 0 then begin            TempSOASetup."Earliest Sync At" := CurrentDateTime();            TempSOASetup."Last Sync At" := TempSOASetup."Earliest Sync At";            exit;        end;        if EmailsCount < SOAEmailSetup.GetMaxNoOfEmails() then            ConfirmMessage := StrSubstNo(NewEmailsSinceDeactivationLbl, Format(EmailsCount), Format(TempSOASetup."Last Sync At"))        else            ConfirmMessage := StrSubstNo(NewEmailsSinceDeactivationLbl, Format(EmailsCount) + '+', Format(TempSOASetup."Last Sync At"));        if Confirm(ConfirmMessage, true) then            TempSOASetup."Earliest Sync At" := TempSOASetup."Activated At"        else            TempSOASetup."Earliest Sync At" := CurrentDateTime();        TempSOASetup."Last Sync At" := TempSOASetup."Earliest Sync At";    end;    local procedure GetEmailsCount(var TempSOASetup: Record "SOA Setup" temporary) EmailsCount: Integer    var        SOATestSetup: Codeunit "SOA Test Setup";    begin        SOATestSetup.SetTestEmailCount(true);        if SOATestSetup.Run(TempSOASetup) then;        EmailsCount := SOATestSetup.GetEmailCount();    end;    internal procedure GetInboxEmailCount(var SOASetup: Record "SOA Setup") InboxCount: Integer    var        TempSOASetup: Record "SOA Setup" temporary;    begin        TempSOASetup := SOASetup;        InboxCount := GetEmailsCount(TempSOASetup);    end;    procedure SupportedAttachmentContentType(FileMIMEType: Text): Boolean    begin        if FileMIMEType in ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png'] then            exit(true)        else            exit(false);    end;    internal procedure IsPdfAttachmentContentType(FileMIMEType: Text): Boolean    begin        if FileMIMEType = 'application/pdf' then            exit(true);        exit(false);    end;    internal procedure IsImageAttachmentContentType(FileMIMEType: Text): Boolean    begin        // The platform derives the content type from the file extension and maps image extensions to        // non-standard 'application/<extension>' values, so both those and the standard image types are recognized.        if LowerCase(FileMIMEType) in            ['image/jpeg', 'image/jpg', 'image/png', 'image/gif',             'application/jpeg', 'application/jpg', 'application/png', 'application/gif'] then            exit(true);        exit(false);    end;    [TryFunction]    internal procedure DocumentExceedsPageCountThreshold(DocInStream: Instream; var Exceeds: Boolean)    var        PdfDocument: Codeunit "PDF Document";    begin        Exceeds := PdfDocument.GetPdfPageCount(DocInStream) > PageCountThreshold();    end;    internal procedure PageCountThreshold(): Integer    begin        exit(50)    end;    internal procedure GetMaxNoOfAttachmentsPerEmail(): Integer    begin        exit(10)    end;    internal procedure GetMaxAttachmentSizeInBytes(): Integer    var        MaxAttachmentSizeInMB: Integer;    begin        MaxAttachmentSizeInMB := 25;        exit(MaxAttachmentSizeInMB * 1024 * 1024);    end;    internal procedure GetFeatureName(): Text    begin        exit('Sales Order Agent');    end;    internal procedure GetUpdatedQuoteInterventionSuggestionCode(): Code[20]    begin        exit(StrSubstNo(SOAInterventionSuggestionCodeLbl, SOAInterventionSuggestionQuoteLockedLbl));    end;    internal procedure GetUpdatedOrderInterventionSuggestionCode(): Code[20]    begin        exit(StrSubstNo(SOAInterventionSuggestionCodeLbl, SOAInterventionSuggestionOrderLockedLbl));    end;    var        SOAImpl: Codeunit "SOA Impl";        Agent: Codeunit Agent;        SalesOrderAgentNameLbl: Label 'SALES ORDER AGENT', Locked = true, MaxLength = 17;        SalesOrderAgentDisplayNameLbl: Label 'Sales Order Agent', MaxLength = 80;        SalesOrderAgentTypeLbl: Label 'By Microsoft';        SOAEditTok: Label 'SOA - EDIT', Locked = true, MaxLength = 20;        SalesOrderAgentTok: Label 'Sales Order Agent', Locked = true;        SalesOrderAgentInitialLbl: Label 'SO', MaxLength = 4;        SOASummaryLbl: Label 'Monitors incoming emails for sales inquiries, matches senders to customers, checks inventory, and creates quotes. When processing replies, the agent converts accepted quotes into orders.';        DelegateAdminErr: Label 'Delegated admin and helpdesk users are not allowed to update the agent.';        AgentArchivedErr: Label 'This Sales Order Agent is archived and is read-only.';        SOAInterventionSuggestionCodeLbl: Label 'SOA-UPDATE-%1', Locked = true, Comment = '%1 = Sales Document Type';        SOAInterventionSuggestionSummaryLbl: Label 'I have updated the %1', Comment = '%1 = Sales Document Type', MaxLength = 100;        SOAInterventionSuggestionDescriptionLbl: Label 'Used to indicate that a user has done some manual updates to a sales %1 as part of reviewing it before sending it to a customer.', Comment = '%1 = Sales Document Type', Locked = true, MaxLength = 1024;        SOAInterventionSuggestionInstructionsLbl: Label 'I have updated the sales %1. Make sure to download the PDF again before including the %1 information in any outgoing communication.', Comment = '%1 = Sales Document Type', Locked = true, MaxLength = 1024;        SOAInterventionSuggestionQuoteLbl: Label 'quote';        SOAInterventionSuggestionOrderLbl: Label 'order';        SOAInterventionSuggestionQuoteLockedLbl: Label 'quote', Locked = true;        SOAInterventionSuggestionOrderLockedLbl: Label 'order', Locked = true;        SOAItemAvailabilityInterventionSuggestionCodeLbl: Label 'SOA-ITEM-AVAILABLE', Locked = true;        SOAItemAvailabilityInterventionSuggestionSummaryLbl: Label 'I have made the items available', MaxLength = 100;        SOAItemAvailabilityInterventionSuggestionDescriptionLbl: Label 'Used to indicate that a user has done some manual updates to the item availability. Rerun the item availability check', Locked = true, MaxLength = 1024;        SOAItemAvailabilityInterventionSuggestionInstructionsLbl: Label 'I have updated the item availability. Make sure to recheck the item availability and proceed further.', Locked = true, MaxLength = 1024;        SOACustomerInterventionSuggestionCodeLbl: Label 'SOA-CUSTOMER-ADDED', Locked = true;        SOACustomerInterventionSuggestionSummaryLbl: Label 'I have added the customer', MaxLength = 100;        SOACustomerInterventionSuggestionDescriptionLbl: Label 'Used to indicate that a user has done some manual updates to add the customer information. Rerun the customer information check', Locked = true, MaxLength = 1024;        SOACustomerInterventionSuggestionInstructionsLbl: Label 'I have updated the customer information. Navigate to the customer list page, search for the customer again, and then proceed.', Locked = true, MaxLength = 1024;        SOAContactInterventionSuggestionCodeLbl: Label 'SOA-CONTACT-ADDED', Locked = true;        SOAContactInterventionSuggestionSummaryLbl: Label 'I have added the contact', MaxLength = 100;        SOAContactInterventionSuggestionDescriptionLbl: Label 'Used to indicate that a user has done some manual updates to add the contact information. Rerun the contact information check', Locked = true, MaxLength = 1024;        SOAContactInterventionSuggestionInstructionsLbl: Label 'I have updated the contact information. Navigate to the contact list page and search for the contact again. If the contact is found, proceed with it, and only search the customer list if the contact is still not found.', Locked = true, MaxLength = 1024;        NewEmailsSinceDeactivationLbl: Label 'New e-mails (%1) have arrived since %2 but haven''t been processed yet. Should Sales Order Agent also process these?', Comment = '%1 - Number of emails, %2 - Date and time of deactivation.';        SOAAttemptedConnectionFailedErr: Label 'The agent can''t be activated because the connection to the selected Microsoft 365 mailbox failed. Ask your Microsoft 365 administrator to check if the user configuring the agent has permission to access the mailbox.';        SOAAttemptedConnectionHttpRequestFailedErr: Label 'The agent can''t be activated because its settings don''t allow Http Requests. Ask your administrator to update this setting and try again.';        EmailSignatureLbl: Label '%1<div>%2</div><div><br></div><div><em>%3</em></div>', Locked = true;        SignatureClosingLbl: Label 'Best regards';        SignatureNoteLbl: Label 'We write mails with AI. We review and send with care.';        MailboxAlreadyUsedWithoutFolderErr: Label 'This email account is already used by Sales Order Agent "%1" (%2).', Comment = '%1 = agent name, %2 = agent initials';        MailboxAndFolderAlreadyUsedErr: Label 'This email account and folder combination is already used by Sales Order Agent "%1" (%2).', Comment = '%1 = agent name, %2 = agent initials';}