OBJECT Codeunit 1854 Item Sales Forecast Notifier
{
  OBJECT-PROPERTIES
  {
    Date=;
    Time=;
    Version List=;
  }
  PROPERTIES
  {
    Permissions=TableData 1518=rimd,
                TableData 1853=r;
    SingleInstance=Yes;
    OnRun=BEGIN
          END;

  }
  CODE
  {
    VAR
      NotificationTxt@1000 : TextConst '@@@="%1 = Item No., %2 = Item Name";ENU=You have run out of stock on items that this vendor usually supplies. Do you want to add them to this document?';
      YesPleaseTxt@1001 : TextConst 'ENU=Yes, please';
      NotificationForAdditionalLinesMsg@1004 : TextConst 'ENU=One or more lines have been added with restock suggestions. You can make any changes that you need.';
      AdditionalLinesNotificationToBeDisplayed@1005 : Boolean;
      ItemSalesForecastNotificationTxt@1006 : TextConst 'ENU=Items running low in inventory';
      ItemSalesForecastNotificationDescriptionTxt@1007 : TextConst 'ENU=Get notified if you are running low on stock for items that a vendor usually supplies, and get help re-stocking.';

    [EventSubscriber(Page,51,OnAfterGetCurrRecordEvent)]
    LOCAL PROCEDURE OnAfterCurrPurchaseInvoice@2(VAR Rec@1000 : Record 38);
    BEGIN
      OnAfterCurrPurchaseHeader(Rec);
    END;

    [EventSubscriber(Page,50,OnAfterGetCurrRecordEvent)]
    LOCAL PROCEDURE OnAfterCurrPurchaseOrder@13(VAR Rec@1000 : Record 38);
    BEGIN
      OnAfterCurrPurchaseHeader(Rec);
    END;

    LOCAL PROCEDURE OnAfterCurrPurchaseHeader@14(VAR PurchaseHeader@1000 : Record 38);
    BEGIN
      IF NOT PurchaseHeaderCommitted(PurchaseHeader) THEN
        EXIT;

      CreateStockoutNotification(PurchaseHeader);
      IF AdditionalLinesNotificationToBeDisplayed THEN
        ShowAdditionalLinesNotification;
    END;

    [EventSubscriber(Page,51,OnAfterValidateEvent,"Buy-from Vendor Name")]
    LOCAL PROCEDURE OnAfterBuyFromVendorNameValidate@3(VAR Rec@1000 : Record 38;VAR xRec@1001 : Record 38);
    BEGIN
      CreateStockoutNotification(Rec);
    END;

    [EventSubscriber(Page,51,OnInsertRecordEvent)]
    LOCAL PROCEDURE OnAfterInsertPurchaseHeader@4(VAR Rec@1000 : Record 38;BelowxRec@1001 : Boolean;VAR xRec@1002 : Record 38;VAR AllowInsert@1003 : Boolean);
    BEGIN
      CreateStockoutNotification(Rec);
    END;

    LOCAL PROCEDURE CreateStockoutNotification@1(PurchaseHeader@1002 : Record 38);
    VAR
      StockoutNotification@1000 : Notification;
    BEGIN
      IF ShouldNotificationBeShown(PurchaseHeader) THEN BEGIN
        StockoutNotification.ID(GetNotificationGuid(TRUE));
        CreateNotification(PurchaseHeader,StockoutNotification);
        StockoutNotification.SEND;
      END;
    END;

    LOCAL PROCEDURE ShouldNotificationBeShown@11(PurchaseHeader@1002 : Record 38) : Boolean;
    VAR
      ItemSalesForecastQuery@1001 : Query 1850;
    BEGIN
      IF NOT CheckPreconditions(PurchaseHeader) THEN
        EXIT(FALSE);

      IF NOT InitializeSalesForecastQuery(ItemSalesForecastQuery,PurchaseHeader) THEN
        EXIT(FALSE);

      IF NOT ItemSalesForecastQuery.OPEN THEN
        EXIT(FALSE);

      IF NOT ItemSalesForecastQuery.READ THEN
        EXIT(FALSE);

      REPEAT
        IF (NOT PurchaseLineWithItemExists(PurchaseHeader."Document Type",PurchaseHeader."No.",ItemSalesForecastQuery.ItemNo)) AND
           StockoutWarningForItemEnabled(ItemSalesForecastQuery.ItemNo) AND
           (ItemSalesForecastQuery.ExpectedSales > ItemSalesForecastQuery.Inventory)
        THEN
          EXIT(TRUE);
      UNTIL NOT ItemSalesForecastQuery.READ;

      EXIT(FALSE);
    END;

    LOCAL PROCEDURE CheckPreconditions@5(PurchaseHeader@1000 : Record 38) : Boolean;
    VAR
      SalesReceivablesSetup@1001 : Record 311;
      SalesInventoryForecastSetup@1002 : Record 1853;
      MyNotifications@1003 : Record 1518;
      Vendor@1004 : Record 23;
    BEGIN
      IF NOT Vendor.GET(PurchaseHeader."Buy-from Vendor No.") THEN
        EXIT(FALSE);

      IF NOT MyNotifications.IsEnabledForRecord(GetNotificationGuid(TRUE),Vendor) THEN
        EXIT(FALSE);

      IF NOT SalesInventoryForecastSetup.GET THEN
        EXIT(FALSE);

      SalesReceivablesSetup.GET;
      IF NOT SalesReceivablesSetup."Stockout Warning" THEN
        EXIT(FALSE);

      IF PurchaseHeader.Status <> PurchaseHeader.Status::Open THEN
        EXIT(FALSE);

      IF NOT (PurchaseHeader."Document Type" IN [PurchaseHeader."Document Type"::Invoice,PurchaseHeader."Document Type"::Order]) THEN
        EXIT(FALSE);

      EXIT(TRUE);
    END;

    LOCAL PROCEDURE StockoutWarningForItemEnabled@7(ItemNo@1000 : Code[20]) : Boolean;
    VAR
      Item@1001 : Record 27;
    BEGIN
      IF NOT Item.GET(ItemNo) THEN
        EXIT(FALSE);
      EXIT(Item."Stockout Warning" <> Item."Stockout Warning"::No);
    END;

    LOCAL PROCEDURE CreateNotification@23(PurchaseHeader@1002 : Record 38;VAR StockoutNotification@1000 : Notification);
    BEGIN
      StockoutNotification.MESSAGE := NotificationTxt;
      StockoutNotification.SETDATA('PurchaseHeaderType',FORMAT(PurchaseHeader."Document Type"));
      StockoutNotification.SETDATA('PurchaseHeaderNo',PurchaseHeader."No.");
      StockoutNotification.ADDACTION(YesPleaseTxt,CODEUNIT::"Item Sales Forecast Notifier",'CreatePurchaseLineAction');
    END;

    PROCEDURE CreatePurchaseLineAction@12(StockoutNotification@1000 : Notification);
    VAR
      PurchaseHeader@1004 : Record 38;
      ItemSalesForecastQuery@1005 : Query 1850;
      DocumentType@1003 : 'Quote,Order,Invoice,Credit Memo,Blanket Order,Return Order';
      DocumentNo@1002 : Code[20];
      ReorderQty@1009 : Decimal;
    BEGIN
      EVALUATE(DocumentType,StockoutNotification.GETDATA('PurchaseHeaderType'));
      DocumentNo := StockoutNotification.GETDATA('PurchaseHeaderNo');
      PurchaseHeader.GET(DocumentType,DocumentNo);

      IF NOT InitializeSalesForecastQuery(ItemSalesForecastQuery,PurchaseHeader) THEN
        EXIT;

      IF NOT ItemSalesForecastQuery.OPEN THEN
        EXIT;

      IF NOT ItemSalesForecastQuery.READ THEN
        EXIT;

      REPEAT
        ReorderQty := ItemSalesForecastQuery.ExpectedSales - ItemSalesForecastQuery.Inventory;
        IF ReorderQty > 0 THEN
          CreatePurchaseLine(DocumentType,DocumentNo,ItemSalesForecastQuery.ItemNo,ReorderQty);
      UNTIL NOT ItemSalesForecastQuery.READ;

      AdditionalLinesNotificationToBeDisplayed := TRUE;
    END;

    LOCAL PROCEDURE CreatePurchaseLine@37(DocumentType@1001 : 'Quote,Order,Invoice,Credit Memo,Blanket Order,Return Order';DocumentNo@1003 : Code[20];ItemNo@1000 : Code[20];DeltaQty@1002 : Decimal);
    VAR
      PurchaseLine@1005 : Record 39;
      Item@1004 : Record 27;
    BEGIN
      IF PurchaseLineWithItemExists(DocumentType,DocumentNo,ItemNo) THEN
        EXIT;

      PurchaseLine.INIT;
      PurchaseLine."Document Type" := DocumentType;
      PurchaseLine."Document No." := DocumentNo;
      PurchaseLine.VALIDATE("Line No.",GetNextLineNo(PurchaseLine));
      PurchaseLine.VALIDATE(Type,PurchaseLine.Type::Item);
      PurchaseLine.VALIDATE("No.",ItemNo);
      Item.GET(ItemNo);
      PurchaseLine.VALIDATE(Quantity,ROUND(DeltaQty,Item."Rounding Precision",'>'));
      PurchaseLine.INSERT(TRUE);
    END;

    LOCAL PROCEDURE GetNextLineNo@6(PurchaseLine@1000 : Record 39) : Integer;
    VAR
      NextLineNo@1001 : Integer;
    BEGIN
      PurchaseLine.SETRANGE("Document Type",PurchaseLine."Document Type");
      PurchaseLine.SETRANGE("Document No.",PurchaseLine."Document No.");
      NextLineNo := 10000;
      IF PurchaseLine.FINDLAST THEN
        NextLineNo += PurchaseLine."Line No.";
      EXIT(NextLineNo);
    END;

    LOCAL PROCEDURE PurchaseLineWithItemExists@9(DocumentType@1003 : 'Quote,Order,Invoice,Credit Memo,Blanket Order,Return Order';DocumentNo@1002 : Code[20];ItemNo@1001 : Code[20]) : Boolean;
    VAR
      PurchaseLine@1000 : Record 39;
    BEGIN
      PurchaseLine.SETRANGE("Document Type",DocumentType);
      PurchaseLine.SETRANGE("Document No.",DocumentNo);
      PurchaseLine.SETRANGE(Type,PurchaseLine.Type::Item);
      PurchaseLine.SETRANGE("No.",ItemNo);
      EXIT(NOT PurchaseLine.ISEMPTY);
    END;

    PROCEDURE CreateAndShowPurchaseInvoice@20(ItemNo@1000 : Code[20]);
    VAR
      DummyPurchaseHeader@1002 : Record 38;
    BEGIN
      CreateAndShowPurchaseDocument(ItemNo,DummyPurchaseHeader."Document Type"::Invoice);
    END;

    PROCEDURE CreateAndShowPurchaseOrder@21(ItemNo@1000 : Code[20]);
    VAR
      DummyPurchaseHeader@1002 : Record 38;
    BEGIN
      CreateAndShowPurchaseDocument(ItemNo,DummyPurchaseHeader."Document Type"::Order);
    END;

    LOCAL PROCEDURE CreateAndShowPurchaseDocument@10(ItemNo@1000 : Code[20];DocumentType@1004 : Option);
    VAR
      Item@1001 : Record 27;
      PurchaseHeader@1002 : Record 38;
      PurchaseLine@1003 : Record 39;
      ItemSalesForecastQuery@1005 : Query 1850;
      ReorderQty@1008 : Decimal;
    BEGIN
      Item.GET(ItemNo);
      Item.TESTFIELD("Vendor No.");

      PurchaseHeader.INIT;
      PurchaseHeader.VALIDATE("Document Type",DocumentType);
      PurchaseHeader.INSERT(TRUE);
      PurchaseHeader.VALIDATE("Buy-from Vendor No.",Item."Vendor No.");
      PurchaseHeader.MODIFY(TRUE);

      PurchaseLine.INIT;
      PurchaseLine.VALIDATE("Document Type",PurchaseHeader."Document Type");
      PurchaseLine.VALIDATE("Document No.",PurchaseHeader."No.");
      PurchaseLine.VALIDATE("Line No.",10000);
      PurchaseLine.INSERT(TRUE);

      PurchaseLine.VALIDATE(Type,PurchaseLine.Type::Item);
      PurchaseLine.VALIDATE("No.",ItemNo);
      InitializeSalesForecastQuery(ItemSalesForecastQuery,PurchaseHeader);
      ItemSalesForecastQuery.SETRANGE(ItemNo,ItemNo);
      IF ItemSalesForecastQuery.OPEN THEN
        IF ItemSalesForecastQuery.READ THEN BEGIN
          ReorderQty := ItemSalesForecastQuery.ExpectedSales - ItemSalesForecastQuery.Inventory;
          IF ReorderQty > 0 THEN
            PurchaseLine.VALIDATE(Quantity,ROUND(ReorderQty,Item."Rounding Precision",'>'));
        END;
      PurchaseLine.MODIFY(TRUE);

      IF DocumentType = PurchaseHeader."Document Type"::Invoice THEN
        PAGE.RUN(PAGE::"Purchase Invoice",PurchaseHeader);
      IF DocumentType = PurchaseHeader."Document Type"::Order THEN
        PAGE.RUN(PAGE::"Purchase Order",PurchaseHeader);

      IF ReorderQty > 0 THEN
        AdditionalLinesNotificationToBeDisplayed := TRUE;
    END;

    LOCAL PROCEDURE InitializeSalesForecastQuery@18(VAR ItemSalesForecastQuery@1000 : Query 1850;PurchaseHeader@1004 : Record 38) : Boolean;
    VAR
      SalesInventoryForecastSetup@1001 : Record 1853;
      PeriodFormManagement@1003 : Codeunit 359;
      StockoutWarningDate@1002 : Date;
    BEGIN
      IF NOT SalesInventoryForecastSetup.GET THEN
        EXIT(FALSE);

      StockoutWarningDate :=
        PeriodFormManagement.MoveDateByPeriod(WORKDATE,SalesInventoryForecastSetup."Period Type",
          SalesInventoryForecastSetup."Stockout Warning Horizon");

      ItemSalesForecastQuery.SETFILTER(VendorNo,PurchaseHeader."Buy-from Vendor No.");
      ItemSalesForecastQuery.SETFILTER(Date,'<=%1',StockoutWarningDate);
      ItemSalesForecastQuery.SETRANGE(Variance,0,SalesInventoryForecastSetup."Variance %");

      EXIT(TRUE);
    END;

    LOCAL PROCEDURE PurchaseHeaderCommitted@24(PurchaseHeader@1000 : Record 38) : Boolean;
    VAR
      CommittedPurchaseHeader@1001 : Record 38;
    BEGIN
      EXIT(CommittedPurchaseHeader.GET(PurchaseHeader."Document Type",PurchaseHeader."No."));
    END;

    LOCAL PROCEDURE ShowAdditionalLinesNotification@16();
    VAR
      AdditionalLinesNotification@1001 : Notification;
    BEGIN
      AdditionalLinesNotification.ID := GetNotificationGuid(FALSE);
      AdditionalLinesNotification.MESSAGE(NotificationForAdditionalLinesMsg);
      AdditionalLinesNotification.SEND;
    END;

    PROCEDURE GetNotificationGuid@19(IsStockoutNotification@1000: Boolean) : GUID;
    BEGIN
      IF IsStockoutNotification THEN
        EXIT('4842e366-3ef9-4741-b334-c0fc61d6fafc');
      EXIT('4842e366-3ef9-4741-b334-c0fc61d6fafd')
    END;

    [EventSubscriber(Page,1518,OnInitializingNotificationWithDefaultState)]
    LOCAL PROCEDURE OnInitializingNotificationWithDefaultState@8();
    VAR
      MyNotifications@1000 : Record 1518;
    BEGIN
      MyNotifications.InsertDefaultWithTableNum(GetNotificationGuid(TRUE),
        ItemSalesForecastNotificationTxt,
        ItemSalesForecastNotificationDescriptionTxt,
        DATABASE::Vendor);
    END;

    BEGIN
    END.
  }
}

