OBJECT Codeunit 1852 Item Sales Forecast Scheduler
{
  OBJECT-PROPERTIES
  {
    Date=;
    Time=;
    Version List=;
  }
  PROPERTIES
  {
    OnRun=BEGIN
          END;

  }
  CODE
  {
    VAR
      SpecifyApiKeyErr@1003 : TextConst 'ENU=You must specify an API key and an API URI in the Sales Inventory Forecast Setup before automated sales forecasting can be activated.';
      SetupScheduledForecastingMsg@1000 : TextConst 'ENU=Would you like to get the sales forecast updated automatically every week?';
      ButtonYesPleaseTxt@1001 : TextConst 'ENU=Yes, please';
      ButtonNoThanksTxt@1004 : TextConst 'ENU=No, thanks';
      ScheduledForecastingEnabledMsg@1002 : TextConst '@@@="%1 = weekday (e.g. Monday)";ENU=The sales forecast will be updated every %1. You can change the schedule in the Setup Scheduled Forecasting window in the Sales Inventory Forecast Setup.';

    PROCEDURE CreateJobQueueEntryAndOpenCard@1();
    VAR
      JobQueueEntry@1000 : Record 472;
    BEGIN
      CreateJobQueueEntry(JobQueueEntry,TRUE);
      PAGE.RUN(PAGE::"Job Queue Entry Card",JobQueueEntry);
    END;

    PROCEDURE CreateJobQueueEntry@2(VAR JobQueueEntry@1000 : Record 472;Recurring@1002 : Boolean);
    VAR
      NoOfMinutesInAWeek@1001 : Integer;
    BEGIN
      WITH JobQueueEntry DO BEGIN
        SETRANGE("Object Type to Run","Object Type to Run"::Codeunit);
        SETRANGE("Object ID to Run",CODEUNIT::"Update Item Sales Forecast");
        SETRANGE("Recurring Job",Recurring);
        IF FINDFIRST THEN
          EXIT;

        NoOfMinutesInAWeek := 7 * 24 * 60;

        INIT;
        VALIDATE("Object Type to Run","Object Type to Run"::Codeunit);
        VALIDATE("Object ID to Run",CODEUNIT::"Update Item Sales Forecast");
        "Earliest Start Date/Time" := CURRENTDATETIME;
        IF Recurring THEN BEGIN
          VALIDATE("Run on Mondays",TRUE);
          VALIDATE("Run on Tuesdays",TRUE);
          VALIDATE("Run on Wednesdays",TRUE);
          VALIDATE("Run on Thursdays",TRUE);
          VALIDATE("Run on Fridays",TRUE);
          VALIDATE("Run on Saturdays",TRUE);
          VALIDATE("Run on Sundays",TRUE);
          "No. of Minutes between Runs" := NoOfMinutesInAWeek;
        END;
        "Maximum No. of Attempts to Run" := 3;
        Priority := 1000;
        "Notify On Success" := TRUE;
        Status := Status::"On Hold";
        INSERT(TRUE);
      END;
    END;

    PROCEDURE RemoveScheduledTaskIfUserInactive@8();
    VAR
      PeriodType@1000 : 'Day,Week,Month,Quarter,Year,Accounting Period';
    BEGIN
      IF NOT UserLogonExistsWithinPeriod(PeriodType::Week,2) THEN
        DeleteJobQueueEntries;
    END;

    LOCAL PROCEDURE DeleteJobQueueEntries@6();
    VAR
      JobQueueEntry@1000 : Record 472;
    BEGIN
      WITH JobQueueEntry DO BEGIN
        SETRANGE("Object Type to Run","Object Type to Run"::Codeunit);
        SETRANGE("Object ID to Run",CODEUNIT::"Update Item Sales Forecast");
        // Non-recurring jobs will be deleted after execution has completed.
        MODIFYALL("Recurring Job",FALSE);
      END;
    END;

    PROCEDURE SetupScheduledForecasting@5(SetupNotification@1000 : Notification);
    VAR
      JobQueueEntry@1002 : Record 472;
      SalesInventoryForecastSetup@1004 : Record 1853;
      Date@1005 : Record 2000000007;
      AzureKeyVaultManagement@1001 : Codeunit 2200;
    BEGIN
      SalesInventoryForecastSetup.GetSingleInstance(AzureKeyVaultManagement);
      IF SalesInventoryForecastSetup.URIOrKeyEmpty THEN
        ERROR(SpecifyApiKeyErr);

      CreateJobQueueEntry(JobQueueEntry,TRUE);
      CODEUNIT.RUN(CODEUNIT::"Job Queue - Enqueue",JobQueueEntry);
      Date.GET(Date."Period Type"::Date,DT2DATE(JobQueueEntry."Earliest Start Date/Time"));
      MESSAGE(ScheduledForecastingEnabledMsg,Date."Period Name");
    END;

    PROCEDURE DeactivateNotification@11(SetupNotification@1000 : Notification);
    VAR
      SalesInventoryForecastSetup@1004 : Record 1853;
    BEGIN
      IF NOT SalesInventoryForecastSetup.GET THEN
        EXIT;
      SalesInventoryForecastSetup."Show Setup Notification" := FALSE;
      SalesInventoryForecastSetup.MODIFY;
    END;

    LOCAL PROCEDURE JobQueueEntryExists@4() : Boolean;
    VAR
      JobQueueEntry@1000 : Record 472;
    BEGIN
      JobQueueEntry.SETRANGE("Object Type to Run",JobQueueEntry."Object Type to Run"::Codeunit);
      JobQueueEntry.SETRANGE("Object ID to Run",CODEUNIT::"Update Item Sales Forecast");
      EXIT(NOT JobQueueEntry.ISEMPTY);
    END;

    LOCAL PROCEDURE UserLogonExistsWithinPeriod@7(PeriodType@1002 : 'Day,Week,Month,Quarter,Year,Accounting Period';NoOfPeriods@1000 : Integer) : Boolean;
    VAR
      SessionEvent@1004 : Record 2000000111;
      PeriodFormManagement@1001 : Codeunit 359;
      FromEventDateTime@1003 : DateTime;
    BEGIN
      FromEventDateTime := CREATEDATETIME(PeriodFormManagement.MoveDateByPeriod(TODAY,PeriodType,-NoOfPeriods),TIME);
      SessionEvent.SETRANGE("Event Datetime",FromEventDateTime,CURRENTDATETIME);
      SessionEvent.SETRANGE("Event Type",SessionEvent."Event Type"::Logon);
      // Filter out sessions of type Web Service, Client Service, NAS, Background and Management Client
      SessionEvent.SETFILTER("Client Type",'<%1|>%2',
        SessionEvent."Client Type"::"Web Service",SessionEvent."Client Type"::"Management Client");
      SessionEvent.SETRANGE("Database Name",GetDatabase);
      EXIT(NOT SessionEvent.ISEMPTY);
    END;

    LOCAL PROCEDURE GetDatabase@9() : Text[250];
    VAR
      ActiveSession@1001 : Record 2000000110;
    BEGIN
      ActiveSession.GET(SERVICEINSTANCEID,SESSIONID);
      EXIT(ActiveSession."Database Name");
    END;

    LOCAL PROCEDURE CreateSetupNotification@10();
    VAR
      SetupNotification@1001 : Notification;
    BEGIN
      IF NOT ShowNotification THEN
        EXIT;

      SetupNotification.MESSAGE := SetupScheduledForecastingMsg;
      SetupNotification.SCOPE := NOTIFICATIONSCOPE::LocalScope;
      SetupNotification.ADDACTION(ButtonYesPleaseTxt,CODEUNIT::"Item Sales Forecast Scheduler",'SetupScheduledForecasting');
      SetupNotification.ADDACTION(ButtonNoThanksTxt,CODEUNIT::"Item Sales Forecast Scheduler",'DeactivateNotification');
      SetupNotification.SEND;
    END;

    LOCAL PROCEDURE ShowNotification@13() : Boolean;
    VAR
      SalesInventoryForecastSetup@1001 : Record 1853;
      O365GettingStarted@1000 : Record 1309;
      Item@1002 : Record 27;
      AzureKeyVaultManagement@1003 : Codeunit 2200;
    BEGIN
      IF JobQueueEntryExists THEN
        EXIT(FALSE);

      IF Item.ISEMPTY THEN
        EXIT(FALSE);

      IF O365GettingStarted.GET(USERID,CURRENTCLIENTTYPE) THEN
        IF O365GettingStarted."Tour in Progress" THEN
          EXIT(FALSE);

      SalesInventoryForecastSetup.GetSingleInstance(AzureKeyVaultManagement);
      IF SalesInventoryForecastSetup.URIOrKeyEmpty THEN
        EXIT(FALSE);

      IF NOT SalesInventoryForecastSetup."Show Setup Notification" THEN
        EXIT(FALSE);

      EXIT(TRUE);
    END;

    [EventSubscriber(Page,1853,OnOpenPageEvent)]
    LOCAL PROCEDURE OnOpenSalesInventoryForecastSetup@3(VAR Rec@1000 : Record 1853);
    BEGIN
      CreateSetupNotification;
    END;

    [EventSubscriber(Page,31,OnOpenPageEvent)]
    LOCAL PROCEDURE OnOpenItemList@12(VAR Rec@1000 : Record 27);
    BEGIN
      CreateSetupNotification;
    END;

    PROCEDURE JobQueueEntryCreationInProcess@50() : Boolean;
    VAR
      JobQueueEntry@1000 : Record 472;
    BEGIN
      WITH JobQueueEntry DO BEGIN
        SETRANGE("Object Type to Run","Object Type to Run"::Codeunit);
        SETRANGE("Object ID to Run",CODEUNIT::"Update Item Sales Forecast");
        SETRANGE(Status,Status::"In Process");
        IF FINDFIRST THEN
          EXIT(TRUE);
        EXIT(FALSE);
      END;
    END;

    BEGIN
    END.
  }
}

