unit View.OrderEntryCuttingDie;

interface

uses
  System.SysUtils, System.Generics.Collections, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, WEBLib.Menus, WEBLib.ExtCtrls, WEBLib.StdCtrls,
  WEBLib.JSON, Auth.Service, XData.Web.Client, WebLib.Storage,
  ConnectionModule, App.Types, Vcl.StdCtrls, Vcl.Controls, WEBLib.DBCtrls,
  Data.DB, XData.Web.JsonDataset, XData.Web.Dataset, WEBLib.DB;

type
  TFOrderEntryCuttingDie = class(TWebForm)
    WebDataSource1: TWebDataSource;
    XDataWebDataSet1: TXDataWebDataSet;
    XDataWebDataSet1COMPANY_ID: TIntegerField;
    XDataWebDataSet1USER_ID: TIntegerField;
    XDataWebDataSet1ORDER_DATE: TDateField;
    XDataWebDataSet1ORDER_STATUS: TStringField;
    XDataWebDataSet1SHORT_NAME: TStringField;
    XDataWebDataSet1staff_fields_ship_via: TStringField;
    XDataWebDataSet1staff_fields_price: TStringField;
    XDataWebDataSet1staff_fields_invoice_to: TStringField;
    XDataWebDataSet1staff_fields_invoice_attention: TStringField;
    XDataWebDataSet1staff_fields_ship_to: TStringField;
    XDataWebDataSet1staff_fields_ship_attention: TStringField;
    XDataWebDataSet1staff_fields_po_number: TStringField;
    XDataWebDataSet1staff_fields_job_name: TStringField;
    XDataWebDataSet1staff_fields_order_date: TStringField;
    XDataWebDataSet1staff_fields_proof_date: TStringField;
    XDataWebDataSet1staff_fields_ship_date: TStringField;
    XDataWebClient1: TXDataWebClient;
    tmrScrollTop: TWebTimer;
    WebLabel2: TWebLabel;
    edtCompanyAccountName: TWebDBEdit;
    edtInQuickBooks: TWebDBEdit;
    WebLabel1: TWebLabel;
    dtpOrderDate: TWebDateTimePicker;
    dtpProofDate: TWebDateTimePicker;
    dtpShipDate: TWebDateTimePicker;
    edtShipVia: TWebDBEdit;
    edtQuantity: TWebDBEdit;
    edtPrice: TWebDBEdit;
    edtInvoiceTo: TWebDBEdit;
    wdbcbShipTo: TWebDBComboBox;
    edtPONumber: TWebDBEdit;
    edtJobName: TWebDBEdit;
    wdsShipTo: TWebDataSource;
    xdwdsShipTo: TXDataWebDataSet;
    xdwdsShipToADDRESS: TStringField;
    WebLabel9: TWebLabel;
    edtSpecialInstructions: TWebDBEdit;
    btnConfirm: TWebButton;
    btnCancel: TWebButton;
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    edtCompanyName: TWebDBEdit;
    XDataWebDataSet1NAME: TStringField;
    XDataWebDataSet1staff_fields_quickbooks_item: TStringField;
    XDataWebDataSet1general_special_instructions: TStringField;
    XDataWebDataSet1staff_fields_quantity: TStringField;
    wdsQBItem: TWebDataSource;
    xdwdsQBItem: TXDataWebDataSet;
    xdwdsQBItemname: TStringField;
    wcbQBItem: TWebDBComboBox;
    btnPDF: TWebButton;
    procedure btnConfirmClick(Sender: TObject);
    procedure btnCancelClick(Sender: TObject);
     procedure WebFormCreate(Sender: TObject);
    procedure HideNotification();
    procedure ShowNotification(Notification: string);
    procedure WebFormShow(Sender: TObject);
    [async] procedure GetCuttingDieOrder(Order_ID: string);
    [async] procedure GetCustomer(customerID: string);
    procedure tmrScrollTopTimer(Sender: TObject);
    [async] procedure AddCuttingDieOrder(orderJSON: TJSONObject);
    procedure btnPDFClick(Sender: TObject);
    [async] procedure GenerateReportPDF;
  private
    FAgencyCode: string;
    FCurrentReportType: string;
    FSelectProc: TSelectProc;
    orderID: string;
    customerID: string;
    mode: string;
  public
    class function CreateForm(AElementID, orderInfo, customerInfo, mode: string): TWebForm;
  end;

var
  FOrderEntryCuttingDie: TFOrderEntryCuttingDie;

implementation

{$R *.dfm}

uses
  View.Home, View.Main;

procedure TFOrderEntryCuttingDie.btnConfirmClick(Sender: TObject);
// Converts all the information on the page into a JSON to then send to the server
var
  I, J: integer;
  orderJSON: TJSONObject;
  fieldNames: TStringList;
  itemList: TJSNodeList;
  header, value: string;
  Field: TField;
  Response: TXDataClientResponse;
begin
  orderJSON := TJSONObject.Create;
  XDataWebDataSet1.Edit;

  //Convert all dates to strings because I was having less issues with that data type.
  XDataWebDataSet1staff_fields_proof_date.Value := DateTimeToStr(dtpProofDate.Date);
  XDataWebDataSet1staff_fields_ship_date.Value := DateTimeToStr(dtpShipDate.Date);
  XDataWebDataSet1staff_fields_order_date.Value := DateTimeToStr(dtpOrderDate.Date);

  XDataWebDataSet1.Post;
  XDataWebDataSet1.First;
  while not XDataWebDataSet1.Eof do
  begin
    for Field in XDataWebDataSet1.Fields do
    begin
      if Field is TStringField then
      begin
        if Field.AsString = '' then
          orderJSON.AddPair(Field.FieldName, '')
        else
          orderJSON.AddPair(Field.FieldName, Field.AsString);  // Add all other fields
      end
      else if Field is TBooleanField then
      begin
        if Field.AsBoolean then
          orderJSON.AddPair(Field.FieldName, 'T')
        else
          orderJSON.AddPair(Field.FieldName, '');
      end;
    end;
    XDataWebDataSet1.Next;
  end;
  orderJSON.AddPair('COMPANY_ID', customerID);
  orderJSON.AddPair('USER_ID', JS.toString(AuthService.TokenPayload.Properties['user_id']));
  orderJSON.AddPair('mode', mode);
  if mode = 'EDIT' then
    orderJSON.AddPair('ORDER_ID', orderID);
  console.log(orderJSON.GetValue('ORDER_ID'));
  console.log(orderJSON);
  AddCuttingDieOrder(orderJSON);
  FViewMain.ViewOrders('Success');
end;

procedure TFOrderEntryCuttingDie.btnPDFClick(Sender: TObject);
begin
  GenerateReportPDF;
end;

[async] procedure TFOrderEntryCuttingDie.GenerateReportPDF;
// sends the search to the server which then sends back a pdf of the results
var
  xdcResponse: TXDataClientResponse;
  searchOptions, pdfURL: string;
  jsObject: TJSObject;
begin

  // Call the server method to generate the PDF
  console.log(orderID);
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GenerateOrderCuttingPDF', [orderID]));
  jsObject := JS.TJSObject(xdcResponse.Result);
  pdfURL := JS.toString(jsObject.Properties['value']);

  // Open the PDF in a new browser tab without needing a different form
  // This method is much faster too, even for large datasets
  window.open(pdfURL, '_blank');
end;

procedure TFOrderEntryCuttingDie.AddCuttingDieOrder(orderJSON: TJSONObject);
// sends the order JSON object to the server
var
Response: TXDataClientResponse;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddCuttingDieOrder',
              [orderJSON.ToString]));
end;

class function TFOrderEntryCuttingDie.CreateForm(AElementID, orderInfo, customerInfo, mode: string): TWebForm;
var
  localMode: string;
begin
  localMode := mode;
  Application.CreateForm(TFOrderEntryCuttingDie, AElementID, Result,
    procedure(AForm: TObject)
    begin
      with TFOrderEntryCuttingDie(AForm) do
      begin
        HideNotification;
        TFOrderEntryCuttingDie(AForm).customerID := customerInfo;
        TFOrderEntryCuttingDie(AForm).orderID := orderInfo;
        TFOrderEntryCuttingDie(AForm).mode := localMode;
      end;
    end
  );

end;

procedure TFOrderEntryCuttingDie.btnCancelClick(Sender: TObject);
begin
  FViewMain.ViewOrders('');
end;

procedure TFOrderEntryCuttingDie.WebFormCreate(Sender: TObject);
begin
   if not DMConnection.ApiConnection.Connected then
   begin
    DMConnection.ApiConnection.OpenAsync;
    console.log('report requirements connection open')
   end;
end;

procedure TFOrderEntryCuttingDie.getCuttingDieOrder(Order_ID: string);
// retrieves an order from the server then loads the info into the page
var
  xdcResponse: TXDataClientResponse;
  orderList : TJSObject;
  i: integer;
  data: TJSArray;
  order, items: TJSObject;
begin
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GetCuttingDieOrder',
        [Order_ID]));
  order :=  TJSObject(xdcResponse.Result);
  data := TJSArray(order['data']);
  XDataWebDataSet1.Close;
  XDataWebDataSet1.SetJsonData(order);
  XDataWebDataSet1.Open;

  // Check boxes and dates need to be manually set

  if not (XDataWebDataSet1staff_fields_order_date.AsString = '') then
    dtpOrderDate.Date := StrToDateTime(XDataWebDataSet1staff_fields_order_date.Value)
  else
    dtpOrderDate.Date := 0;
  if not (XDataWebDataSet1staff_fields_proof_date.AsString = '') then
    dtpProofDate.Date := StrToDateTime(XDataWebDataSet1staff_fields_proof_date.AsString)
  else
    dtpProofDate.Date := 0;
  if not (XDataWebDataSet1staff_fields_ship_date.AsString = '') then
    dtpShipDate.Date := StrToDateTime(XDataWebDataSet1staff_fields_ship_date.AsString)
  else
    dtpShipDate.Date := 0;

  console.log(mode);
  console.log(XDataWebDataSet1COMPANY_ID.AsString);
  if mode = 'EDIT' then
    CustomerID := XDataWebDataSet1COMPANY_ID.AsString;
  console.log(CustomerID);

  if mode = 'EDIT' then
  begin
    CustomerID := XDataWebDataSet1COMPANY_ID.AsString;
    xdwdsShipTo.Close;
    xdwdsShipTo.SetJSONData(order['ADDRESS_LIST']);
    xdwdsShipTo.Open;
  end;

  xdwdsQBItem.Close;
  items := TJSObject(order['ITEMS']);
  xdwdsQBItem.SetJsonData(items['data']);
  xdwdsQBITEM.Open;

end;

procedure TFOrderEntryCuttingDie.getCustomer(customerID: string);
// gets a customer from the database then loads the appropiate fields
var
  xdcResponse: TXDataClientResponse;
  customer : TJSObject;
  address: string;
begin

  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GetCustomer',
        [customerID]));
  customer :=  TJSObject(xdcResponse.Result);
  console.log(customer);
  XDataWebDataSet1.Close;
  XDataWebDataSet1.SetJsonData(customer);
  XDataWebDataSet1.Open;
  console.log(XDataWebDataSet1NAME.AsString);

  xdwdsShipTo.Close;
  xdwdsShipTo.SetJSONData(customer['ADDRESS_LIST']);
  xdwdsShipTo.Open;

end;

procedure TFOrderEntryCuttingDie.WebFormShow(Sender: TObject);
begin
  if mode <> 'ADD' then
    getCuttingDieOrder(orderID)
  else
    getCustomer(customerID);
  HideNotification();
end;

procedure TFOrderEntryCuttingDie.HideNotification;
begin
  pnlMessage.ElementHandle.hidden := True;
end;

procedure TFOrderEntryCuttingDie.ShowNotification(Notification: string);
begin
  if Notification <> '' then
  begin
    lblMessage.Caption := Notification;
    pnlMessage.ElementHandle.hidden := False;
  end;
end;


procedure TFOrderEntryCuttingDie.tmrScrollTopTimer(Sender: TObject);
begin
  tmrScrollTop.Enabled := False;
  window.scrollTo(0, 0);
end;

initialization
  RegisterClass(TFOrderEntryCuttingDie);

end.