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;
    btnSave: 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;
    edtOrderNum: TWebEdit;
    btnDelete: TWebButton;
    btnClose: TWebButton;
    btn_confirm_delete: TWebButton;
    btnCopy: TWebButton;
    tmrReturn: TWebTimer;
    btnEdit: TWebButton;
    btnAdd: TWebButton;
    WebButton2: TWebButton;
    procedure btnSaveClick(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;
    procedure SendOrderToServer();
    function VerifyOrder(): boolean;
    procedure btnDeleteClick(Sender: TObject);
    [async] procedure delOrder();
    procedure btnCloseClick(Sender: TObject);
    procedure btnCopyClick(Sender: TObject);
    procedure btn_confirm_deleteClick(Sender: TObject);
    procedure tmrReturnTimer(Sender: TObject);
    procedure btnAddClick(Sender: TObject);
    procedure xdwdsShipToAfterEdit(DataSet: TDataSet);
    procedure EditMode();
    procedure xdwdsQBItemAfterEdit(DataSet: TDataSet);
    procedure XDataWebDataSet1AfterEdit(DataSet: TDataSet);
    procedure dtpOrderDateChange(Sender: TObject);
    procedure btnEditClick(Sender: TObject);
    procedure ViewMode();
    procedure WebButton2Click(Sender: TObject);
    procedure ShowAddAddressForm();
    [async] procedure SendAddressToServer(AddressJSON: TJSONObject);
  private
    FAgencyCode: string;
    FCurrentReportType: string;
    FSelectProc: TSelectProc;
    orderID: string;
    customerID: string;
    mode: string;
    notification: string;
  public
    class function CreateForm(AElementID, orderInfo, customerInfo, mode, info: string): TWebForm;
  end;

var
  FOrderEntryCuttingDie: TFOrderEntryCuttingDie;

implementation

{$R *.dfm}

uses
  View.Home, View.Main, View.AddOrder, View.AddAddress;

procedure TFOrderEntryCuttingDie.WebButton2Click(Sender: TObject);
begin
  ShowAddAddressForm();
end;

procedure TFOrderEntryCuttingDie.SendAddressToServer(AddressJSON: TJSONObject);
var
  Response: TXDataClientResponse;
  notification: TJSObject;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddShippingAddress',
              [AddressJSON.ToString]));

  notification := TJSObject(Response.Result);
  ShowNotification(string(notification['status']));
  xdwdsShipTo.Close;
  xdwdsShipTo.SetJSONData(notification['ADDRESS']);
  xdwdsShipTo.Open;
end;

procedure TFOrderEntryCuttingDie.ShowAddAddressForm;
// displays the search pop-up that allows the user to filter the order list
var
  newform: TFViewAddAddress;
  AddressJSON: TJSONObject;
  ship_block: string;
begin
  newform := TFViewAddAddress.CreateNew;

  newform.Caption := 'Shipping Information';
  newForm.Popup := True;
  newForm.Border := fbDialog;

  // used to manage Back button handling to close subform
  window.location.hash := 'subform';

  newform.ShowModal(
    procedure(AValue: TModalResult)
    var
      searchOptions: string;
    begin
      if newform.confirm then
      begin
        AddressJSON := TJSONObject.Create;

        AddressJSON.AddPair('address', newform.edtAddress.Text);
        AddressJSON.AddPair('city', newform.edtCity.Text);
        AddressJSON.AddPair('state', newform.edtState.Text);
        AddressJSON.AddPair('zip', newform.edtZip.Text);
        AddressJSON.AddPair('contact', newform.edtContact.Text);
        AddressJSON.AddPair('customer_id', customerID);

        ship_block := newform.edtFirstLine.Text + slinebreak +
                      edtCompanyName.Text + slinebreak +
                      newform.edtContact.Text + slinebreak +
                      newform.edtAddress.Text + slinebreak +
                      newform.edtCity.Text + ', ' + newform.edtState.Text + ' ' + newform.edtZip.Text;
        AddressJSON.AddPair('ship_block', ship_block);

        AddressJSON.AddPair('mode', 'ADD');
        sendAddressToServer(AddressJSON);
      end;
    end
  );
end;

function TFOrderEntryCuttingDie.VerifyOrder: Boolean;
var
  input: TJSHTMLInputElement;
begin
  result := true;

  input := TJSHTMLInputElement(document.getElementById('edtcompanyname'));
  if edtCompanyName.Text = '' then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');


  input := TJSHTMLInputElement(document.getElementById('edtaccountcompanyname'));
  if edtCompanyAccountName.Text = '' then
  begin

    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');

  input := TJSHTMLInputElement(document.getElementById('edtinvoiceto'));
  if edtInvoiceTo.Text = '' then
  begin
    console.log('hot');
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');


  input := TJSHTMLInputElement(document.getElementById('wcbshipto'));
  if wdbcbShipTo.Text = '' then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');

  input := TJSHTMLInputElement(document.getElementById('dtporderdate'));
  if dtpOrderDate.Date = 0 then
  begin
    input.classList.add('is-invalid');
    result := false;
  end
  else
    input.classList.remove('is-invalid');
end;

procedure TFOrderEntryCuttingDie.SendOrderToServer;
var
  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);

  if mode = 'ADD' then
    ShowNotification('Success:Order Added Successfully!')
  else
    ShowNotification('Success:Order Edited Successfully');

  AddCuttingDieOrder(orderJSON);

end;

procedure TFOrderEntryCuttingDie.btnSaveClick(Sender: TObject);
// Converts all the information on the page into a JSON to then send to the server
begin
  if VerifyOrder() then
  begin
    sendOrderToServer();
    ViewMode();
  end;
  window.scrollTo(0, 0);
end;

procedure TFOrderEntryCuttingDie.btnCopyClick(Sender: TObject);
begin
  mode := 'ADD';
  dtpOrderDate.Date := 0;
  dtpProofDate.Date := 0;
  edtOrderNum.Text := '';
  ShowNotification('Success:Order Successfully Copied');
  EditMode();
  window.scrollTo(0, 0);
end;

procedure TFOrderEntryCuttingDie.btnDeleteClick(Sender: TObject);
begin
  asm
    var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
    keyboard: false });
    confirmationModal.show();
  end;
end;
procedure TFOrderEntryCuttingDie.btnEditClick(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryCuttingDie.DelOrder();
var
  Response: TXDataClientResponse;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.DelOrder',
              [OrderID, 'corrugated', JS.toString(AuthService.TokenPayload.Properties['user_id'])]));
end;

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

procedure TFOrderEntryCuttingDie.btn_confirm_deleteClick(Sender: TObject);
begin
  if  document.getElementById('btn_confirm_delete').innerText = 'Yes' then
  begin
    FViewMain.change := false;
    if OrderID <> '' then
    begin
      FViewMain.ViewOrderEntryCuttingDie(OrderID, '', 'EDIT', 'Failure:Changes Discarded');
    end
    else
      FViewMain.ViewOrders('');
  end
  else
  begin
    asm
      var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
      keyboard: false });
      confirmationModal.hide();
      startSpinner();
    end;
    delOrder();
    tmrReturn.Enabled := true;
  end;
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;
  jsObj: TJSObject;
begin
  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddCuttingDieOrder',
              [orderJSON.ToString]));
  jsObj := JS.TJSObject(Response.Result);
  if mode = 'ADD' then
    OrderID := String(jsObj.Properties['OrderID']);
  mode := 'EDIT';
end;

class function TFOrderEntryCuttingDie.CreateForm(AElementID, orderInfo, customerInfo, mode, info: 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;
        TFOrderEntryCuttingDie(AForm).notification := info;
      end;
    end
  );

end;

procedure TFOrderEntryCuttingDie.btnAddClick(Sender: TObject);
var
  newform: TFAddOrder;
  orderType: string;
begin
  newform := TFAddOrder.CreateNew;

  newform.Caption := 'Select Customer and Order Type';
  newForm.Popup := True;
  newForm.Border := fbDialog;

  // used to manage Back button handling to close subform
  window.location.hash := 'subform';

  newform.ShowModal(
    procedure(AValue: TModalResult)
    begin
      if newform.confirm then
      begin
        if newform.cbCorrugatedPlate.Checked then
          orderType := 'corrugated'
        else if newform.cbWebPlate.Checked then
          orderType := 'web'
        else
          orderType := 'cutting';

        if orderType = 'corrugated' then
          FViewMain.ViewOrderEntryCorrugated('', newForm.DBID, 'ADD', '')
        else if orderType = 'web' then
          FViewMain.ViewOrderEntryWeb('', newForm.DBID, 'ADD', '')
        else
          FViewMain.ViewOrderEntryCuttingDie('', newForm.DBID, 'ADD', '');
      end;
    end
  );
end;

procedure TFOrderEntryCuttingDie.btnCancelClick(Sender: TObject);
begin
  document.getElementById('modal_body').innerHTML := 'Are you sure you want to cancel all changes?';
  document.getElementById('btn_confirm_cancel').innerText := 'No';
  document.getElementById('btn_confirm_delete').innerText := 'Yes';
  asm
    var confirmationModal = new bootstrap.Modal(document.getElementById('confirmation_modal'), {
    keyboard: false });
    confirmationModal.show();
  end;
end;

procedure TFOrderEntryCuttingDie.btnCloseClick(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;
  items: TJSObject;
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);

  dtpOrderDate.Date := 0;
  dtpProofDate.Date := 0;
  dtpShipDate.Date := 0;

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

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

end;

procedure TFOrderEntryCuttingDie.WebFormShow(Sender: TObject);
begin
  if mode <> 'ADD' then
  begin
    getCuttingDieOrder(orderID);
    ViewMode();
  end
  else
  begin
    getCustomer(customerID);
    EditMode();
  end;
  edtOrderNum.Text := OrderID;
  if notification = '' then
  begin
    HideNotification;
  end
  else
  begin
    ShowNotification(notification);
  end;
end;

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

procedure TFOrderEntryCuttingDie.ShowNotification(Notification: string);
var
  splitNotification: TArray<string>;
begin
  if Notification <> '' then
  begin
    splitNotification := Notification.Split([':']);
    if(splitNotification[0] = 'Success') then
    begin
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-danger');
        messageDiv.classList.add('alert-success');
      end;
    end
    else
    begin
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-success');
        messageDiv.classList.add('alert-danger');
      end;
    end;
    lblMessage.Caption := splitNotification[1];
    pnlMessage.ElementHandle.hidden := False;
  end;
end;


procedure TFOrderEntryCuttingDie.tmrReturnTimer(Sender: TObject);
begin
  asm
    endSpinner();
  end;
  tmrReturn.Enabled := false;
  FViewMain.ViewOrders('Success: Order Successfully Deleted');
end;

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

procedure TFOrderEntryCuttingDie.EditMode;
begin
  FViewMain.change := true;
  btnCopy.Enabled := false;
  btnPDF.Enabled := false;
  btnDelete.Enabled := false;
  btnClose.Enabled := false;
  btnSave.Enabled := true;
  btnCancel.Enabled := True;
  btnEdit.Enabled := false;
  btnAdd.Enabled := false;
end;

procedure TFOrderEntryCuttingDie.xdwdsQBItemAfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

procedure TFOrderEntryCuttingDie.xdwdsShipToAfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

procedure TFOrderEntryCuttingDie.XDataWebDataSet1AfterEdit(DataSet: TDataSet);
begin
  EditMode();
end;

procedure TFOrderEntryCuttingDie.dtpOrderDateChange(Sender: TObject);
begin
  EditMode();
end;

procedure TFOrderEntryCuttingDie.ViewMode;
begin
  btnPDF.Enabled := true;
  btnDelete.Enabled := true;
  btnClose.Enabled := true;
  btnCopy.Enabled := true;
  btnSave.Enabled := false;
  btnCancel.Enabled := false;
  btnEdit.Enabled := true;
  btnAdd.Enabled := true;
  FViewMain.change := false;
end;

initialization
  RegisterClass(TFOrderEntryCuttingDie);

end.