OBJECT Table 1853 Sales Inventory Forecast Setup
{
  OBJECT-PROPERTIES
  {
    Date=;
    Time=;
    Version List=;
  }
  PROPERTIES
  {
    Permissions=TableData 1261=rimd;
  }
  FIELDS
  {
    { 1   ;   ;Primary Key         ;Code10         }
    { 2   ;   ;Period Type         ;Option        ;InitValue=Month;
                                                   OptionString=Day,Week,Month,Quarter,Year }
    { 3   ;   ;Show Setup Notification;Boolean    ;InitValue=Yes;
                                                   Editable=No }
    { 4   ;   ;Stockout Warning Horizon;Integer   ;InitValue=3 }
    { 5   ;   ;Horizon             ;Integer       ;InitValue=12 }
    { 6   ;   ;API URI             ;Text250        }
    { 7   ;   ;API Key ID          ;GUID          ;OnValidate=BEGIN
                                                                IF NOT ISNULLGUID("API Key ID") THEN
                                                                  EnableEncryption;
                                                              END;
                                                               }
    { 8   ;   ;Timeout (seconds)   ;Integer       ;InitValue=60 }
    { 9   ;   ;Variance %          ;Decimal       ;InitValue=35;
                                                   MinValue=1;
                                                   MaxValue=100 }
    { 10  ;   ;Expiration Period (Days);Integer   ;InitValue=7 }
    { 11  ;   ;Historical Periods  ;Integer       ;InitValue=24;
                                                   MinValue=5 }
    { 12  ;   ;Last Run Completed  ;DateTime      ;Editable=No }
    { 13  ;   ;Limit               ;Decimal       ;Editable=No }
    { 14  ;   ;Processing Time     ;Decimal       ;Editable=No }
    { 15  ;   ;API Cache Minutes   ;Integer       ;InitValue=5;
                                                   Description=Default period in minutes for caching the API URI and API Key. }
    { 16  ;   ;API Cache Expiry    ;DateTime      ;Description=Expiration datetime for the API URI and API Key. }
    { 17  ;   ;Service Pass API Uri ID;GUID       ;TableRelation="Service Password".Key;
                                                   Description=The Key for retrieving the API URI from the Service Password table. }
    { 18  ;   ;Service Pass API Key ID;GUID       ;TableRelation="Service Password".Key;
                                                   Description=The Key for retrieving the API Key from the Service Password table. }
  }
  KEYS
  {
    {    ;Primary Key                             ;Clustered=Yes }
  }
  FIELDGROUPS
  {
  }
  CODE
  {
    VAR
      ItemSalesForecastScheduler@1003 : Codeunit 1852;
      SpecifyApiKeyErr@1004 : TextConst 'ENU=You must specify an API key and an API URI in the Sales Inventory Forecast Setup.';

    PROCEDURE GetSingleInstance@1(AzureKeyVaultManagement@1000 : Codeunit 2200);
    BEGIN
      IF NOT GET THEN BEGIN
        INIT;
        INSERT;
      END;
      RefreshURIAndKey(AzureKeyVaultManagement);
    END;

    LOCAL PROCEDURE RefreshURIAndKey@3(AzureKeyVaultManagement@1000 : Codeunit 2200);
    VAR
      ServicePassword@1004 : Record 1261;
      PermissionManager@1003 : Codeunit 9002;
      APIKey@1001 : Text[200];
      APIURI@1002 : Text[250];
    BEGIN
      IF NOT PermissionManager.SoftwareAsAService THEN
        EXIT;

      IF ItemSalesForecastScheduler.JobQueueEntryCreationInProcess THEN
        EXIT;

      IF APICacheExpired OR URIOrKeyEmpty THEN BEGIN
        IF NOT AzureKeyVaultManagement.GetMachineLearningCredentials(APIURI,APIKey,Limit) THEN
          // The Azure ML KeyVault interrogation returned an error. Falling back to the previous credentials, if any.
          EXIT;
        IF (APIKey = '') OR (APIURI = '') OR (Limit <= 0) THEN
          // No credentials received (KeyVault unavailable), or credentials invalid. Falling back to the previous credentials, if any.
          EXIT;

        IF ServicePassword.WRITEPERMISSION THEN BEGIN
          SetKeyVaultAPIKey(APIKey);
          SetKeyVaultAPIUri(APIURI + '/execute?api-version=2.0&details=true');
        END;

        VALIDATE("API Cache Expiry",CREATEDATETIME(WORKDATE,TIME) + HMSDuration(0,"API Cache Minutes",0));
        VALIDATE(Limit);
        MODIFY(TRUE);
      END;
    END;

    PROCEDURE CheckURIAndKey@2();
    BEGIN
      IF URIOrKeyEmpty THEN
        ERROR(SpecifyApiKeyErr);
    END;

    LOCAL PROCEDURE EnableEncryption@6();
    VAR
      EncryptionManagement@1000 : Codeunit 1266;
    BEGIN
      IF NOT EncryptionManagement.IsEncryptionEnabled THEN
        EncryptionManagement.EnableEncryption;
    END;

    LOCAL PROCEDURE APICacheExpired@7() : Boolean;
    BEGIN
      IF "API Cache Expiry" = 0DT THEN
        EXIT(FALSE);
      EXIT(("API Cache Expiry" - CREATEDATETIME(WORKDATE,TIME)) < 0);
    END;

    PROCEDURE URIOrKeyEmpty@8() : Boolean;
    BEGIN
      EXIT((GetAPIUri = '') OR (GetAPIKey = ''));
    END;

    LOCAL PROCEDURE HMSDuration@4(H@1000 : Integer;M@1001 : Integer;S@1002 : Integer) : Duration;
    BEGIN
      EXIT((((H * 60) + M) * 60 + S) * 1000);
    END;

    PROCEDURE GetUserDefinedAPIKey@18() : Text[250];
    BEGIN
      // If the user has defined the API Key in the page UI, then retrieve it from
      // the encrypted Service Password table
      IF ISNULLGUID("API Key ID") THEN
        EXIT('');

      EXIT(TryReadAPICredential("API Key ID"));
    END;

    PROCEDURE SetUserDefinedAPIKey@15(UserDefinedAPIKey@1000 : Text[250]);
    BEGIN
      // Store the user-defined API Key in Service Password and remember its GUID in "API Key ID"
      IF UserDefinedAPIKey = '' THEN BEGIN
        DeleteAPICredential("API Key ID");
        EXIT;
      END;
      "API Key ID" := InsertAPICredential(UserDefinedAPIKey);
    END;

    PROCEDURE GetAPIKey@12() : Text[250];
    VAR
      UserDefinedAPIKey@1000 : Text[250];
    BEGIN
      // The API Key and URI entered by the user take precedence
      UserDefinedAPIKey := GetUserDefinedAPIKey;
      IF UserDefinedAPIKey <> '' THEN
        EXIT(UserDefinedAPIKey);

      // Try to retrieve the API URI cached and encrypted in the Service Password table
      EXIT(TryReadAPICredential("Service Pass API Key ID"));
    END;

    PROCEDURE GetAPIUri@9() : Text[250];
    BEGIN
      // The API Key and URI entered by the user take precedence
      IF "API URI" <> '' THEN
        EXIT("API URI");

      // Try to retrieve the API URI cached and encrypted in the Service Password table
      EXIT(TryReadAPICredential("Service Pass API Uri ID"));
    END;

    LOCAL PROCEDURE SetKeyVaultAPIUri@14(NewValue@1000 : Text[250]);
    VAR
      ServicePassword@1001 : Record 1261;
    BEGIN
      // First time storing it, create a new key
      IF ISNULLGUID("Service Pass API Uri ID") THEN BEGIN
        "Service Pass API Uri ID" := InsertAPICredential(NewValue);
        MODIFY;
        EXIT;
      END;

      // Invalid key, creating a new one
      IF NOT ServicePassword.GET("Service Pass API Uri ID") THEN BEGIN
        "Service Pass API Uri ID" := InsertAPICredential(NewValue);
        MODIFY;
        EXIT;
      END;

      // Update the value on the existing (valid) key
      ServicePassword.SavePassword(NewValue);
      ServicePassword.MODIFY;
    END;

    LOCAL PROCEDURE SetKeyVaultAPIKey@17(NewValue@1000 : Text[250]);
    VAR
      ServicePassword@1001 : Record 1261;
    BEGIN
      // First time storing it, create a new key
      IF ISNULLGUID("Service Pass API Key ID") THEN BEGIN
        "Service Pass API Key ID" := InsertAPICredential(NewValue);
        MODIFY;
        EXIT;
      END;

      // Invalid key, creating a new one
      IF NOT ServicePassword.GET("Service Pass API Key ID") THEN BEGIN
        "Service Pass API Key ID" := InsertAPICredential(NewValue);
        MODIFY;
        EXIT;
      END;

      // Update the value on the existing (valid) key
      ServicePassword.SavePassword(NewValue);
      ServicePassword.MODIFY;
    END;

    LOCAL PROCEDURE TryReadAPICredential@13(CredentialGUID@1000 : GUID) : Text[250];
    VAR
      ServicePassword@1001 : Record 1261;
    BEGIN
      IF ISNULLGUID(CredentialGUID) THEN
        EXIT('');

      IF NOT ServicePassword.GET(CredentialGUID) THEN
        EXIT('');

      EXIT(ServicePassword.GetPassword);
    END;

    LOCAL PROCEDURE InsertAPICredential@23(NewValue@1000 : Text[250]) : GUID;
    VAR
      ServicePassword@1001 : Record 1261;
    BEGIN
      ServicePassword.INIT;
      ServicePassword.SavePassword(NewValue);
      ServicePassword.INSERT(TRUE);
      EXIT(ServicePassword.Key)
    END;

    LOCAL PROCEDURE DeleteAPICredential@19(KeyId@1000 : GUID);
    VAR
      ServicePassword@1001 : Record 1261;
    BEGIN
      // Clear the local key id
      CLEAR("API Key ID");
      MODIFY;

      // Delete the stored API Key from Service Password table
      IF ServicePassword.GET(KeyId) THEN
        ServicePassword.DELETE;
    END;

    BEGIN
    END.
  }
}

