unit Unit21;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, DBCtrlsEh,
  Vcl.Buttons, Vcl.ExtCtrls, DBGridEh, DBLookupEh, Vcl.ComCtrls, Vcl.ToolWin,
  DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, EhLibVCL,
  GridsEh, DBAxisGridsEh, Data.DB, Data.Win.ADODB, Vcl.DBCtrls, Vcl.Imaging.jpeg,
  IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack,
  IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdSSL,
  IdSSLOpenSSL;

type
  TfMainEdit = class(TForm)
    Panel1: TPanel;
    bbOk: TBitBtn;
    bbCancel: TBitBtn;
    Panel2: TPanel;
    GroupBox2: TGroupBox;
    Panel3: TPanel;
    Panel4: TPanel;
    Panel5: TPanel;
    GroupBox1: TGroupBox;
    DBDateTimeEditEh1: TDBDateTimeEditEh;
    DBEditEh1: TDBEditEh;
    GroupBox6: TGroupBox;
    Panel6: TPanel;
    GroupBox3: TGroupBox;
    Panel7: TPanel;
    GroupBox4: TGroupBox;
    DBEditEh3: TDBEditEh;
    DBEditEh4: TDBEditEh;
    DBLookupComboboxEh1: TDBLookupComboboxEh;
    DBLookupComboboxEh2: TDBLookupComboboxEh;
    DBEditEh5: TDBEditEh;
    DBEditEh6: TDBEditEh;
    DBMemoEh1: TDBMemoEh;
    Splitter1: TSplitter;
    DBLookupComboboxEh3: TDBLookupComboboxEh;
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    TabSheet3: TTabSheet;
    ToolBar1: TToolBar;
    tbAddWork: TToolButton;
    tbEditWork: TToolButton;
    tbDelWork: TToolButton;
    DBGridEh2: TDBGridEh;
    dsClient: TDataSource;
    dsDevType: TDataSource;
    dsBrand: TDataSource;
    TabSheet4: TTabSheet;
    DBMemoEh3: TDBMemoEh;
    DBComboBoxEh1: TDBComboBoxEh;
    dsWorks: TDataSource;
    dsStockMove: TDataSource;
    ToolBar2: TToolBar;
    tbAddValue: TToolButton;
    tbEditValue: TToolButton;
    tbDelValue: TToolButton;
    qStockMove: TADOQuery;
    qStockMoveid: TAutoIncField;
    qStockMovestock_id: TIntegerField;
    qStockMovevalue_id: TIntegerField;
    qStockMovequantity: TIntegerField;
    qStockMovebuyPrice: TFloatField;
    qStockMoveprice: TFloatField;
    qStockMovename: TWideStringField;
    qStockMovevendor: TWideStringField;
    DBGridEh1: TDBGridEh;
    qStockMovemain_id: TIntegerField;
    qSumma: TADOQuery;
    GroupBox5: TGroupBox;
    DBText1: TDBText;
    DBText2: TDBText;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    DBText3: TDBText;
    DBEditEh2: TDBEditEh;
    dsSumma: TDataSource;
    qWorks: TADOQuery;
    qWorksid: TAutoIncField;
    qWorksmain_id: TIntegerField;
    qWorksfixprice_id: TIntegerField;
    qWorksprice: TFloatField;
    qWorksquantity: TSmallintField;
    qWorkssumma: TFloatField;
    ToolBar3: TToolBar;
    tbAddPhoto: TToolButton;
    tbEditPhoto: TToolButton;
    tbDelPhoto: TToolButton;
    qPhoto: TADOQuery;
    dsPhoto: TDataSource;
    qPhotoid: TAutoIncField;
    qPhotoname: TWideStringField;
    qPhotomain_id: TIntegerField;
    DBGridEh3: TDBGridEh;
    Image1: TImage;
    Splitter2: TSplitter;
    qWorksfixprice: TWideStringField;
    qDevType: TADOQuery;
    qDevTypeid: TAutoIncField;
    qDevTypename: TWideStringField;
    qDevTypeparent_id: TIntegerField;
    qSummaid: TAutoIncField;
    qSummasumWork: TFloatField;
    qSummasumStock: TFloatField;
    qSummasumAll: TFloatField;
    qStockMovesumma: TFloatField;
    qMainEdit: TADOQuery;
    dsMainEdit: TDataSource;
    qMainEditid: TAutoIncField;
    qMainEditdate: TDateTimeField;
    qMainEditbrand_id: TIntegerField;
    qMainEditdevtype_id: TIntegerField;
    qMainEditstatus: TWideStringField;
    qMainEditclient_id: TIntegerField;
    qMainEditmodel: TWideStringField;
    qMainEditserial: TWideStringField;
    qMainEdituser_id: TIntegerField;
    qMainEditdate_end: TDateTimeField;
    qMainEditdefect: TWideMemoField;
    qMainEditcomment: TWideMemoField;
    qMainEditwarranty: TIntegerField;
    IdHTTP: TIdHTTP;
    SSL: TIdSSLIOHandlerSocketOpenSSL;
    procedure tbAddWorkClick(Sender: TObject);
    procedure tbDelWorkClick(Sender: TObject);
    procedure tbAddValueClick(Sender: TObject);
    procedure tbDelValueClick(Sender: TObject);
    procedure tbEditValueClick(Sender: TObject);
    procedure qStockMoveAfterPost(DataSet: TDataSet);
    procedure tbEditPhotoClick(Sender: TObject);
    procedure tbAddPhotoClick(Sender: TObject);
    procedure tbDelPhotoClick(Sender: TObject);
    procedure qPhotoAfterScroll(DataSet: TDataSet);
    procedure tbEditWorkClick(Sender: TObject);
    procedure qWorksAfterPost(DataSet: TDataSet);
    procedure qPhotoAfterOpen(DataSet: TDataSet);
    procedure DBComboBoxEh1Change(Sender: TObject);
    procedure DBComboBoxEh1EditButtons0Click(Sender: TObject;
      var Handled: Boolean);
    procedure DBLookupComboboxEh3EditButtons0Click(Sender: TObject;
      var Handled: Boolean);
  private
    function addStock(main_id:integer) : integer;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  fMainEdit: TfMainEdit;

implementation

{$R *.dfm}

uses Unit1, Unit2, Unit24, Unit25, Unit9, Unit17;

function TfMainEdit.addStock(main_id:integer) : integer;
begin
   if DM.qRequest.Active then
      DM.qRequest.Close;
   DM.qRequest.SQL.Text := 'SELECT * FROM stock WHERE main_id='+IntToStr(main_id);
   DM.qRequest.Open;
   if DM.qRequest.RecordCount > 0 then begin
      addStock := DM.qRequest.FieldByName('id').AsInteger;
   end
   else begin
      DM.qRequest.Append;
      DM.qRequest.FieldByName('date').AsDateTime  := now();
      DM.qRequest.FieldByName('moveIn').AsInteger := 0;
      DM.qRequest.FieldByName('main_id').AsInteger := main_id;
      DM.qRequest.FieldByName('user_id').AsInteger := fMain.user_id;
      if DM.qRequest.Modified then
         DM.qRequest.Post;
      addStock := DM.qRequest.FieldByName('id').AsInteger;
   end;
   DM.qRequest.Close;
   DM.qStock.Requery();
end;

procedure TfMainEdit.DBComboBoxEh1Change(Sender: TObject);
begin
   if fMainEdit.qMainEditstatus.AsString <> 'Выдан' then begin
      if (DBComboBoxEh1.Text = 'Выдан') AND (fMainEdit.qMainEditdate_end.AsString = '') then begin
         if Application.MessageBox('Установить дату выдачи?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
            fMainEdit.qMainEditdate_end.AsDateTime := now();
         end
         else begin
            fMainEdit.qMainEditdate_end.AsString := '';
         end;
      end;
   end;
   if ( (DBComboBoxEh1.Text = 'Готово') OR (DBComboBoxEh1.Text = 'Выдан') ) then begin
      DBComboBoxEh1.EditButtons[0].Visible := True;
   end
   else begin
      DBComboBoxEh1.EditButtons[0].Visible := False;
   end;
end;

procedure TfMainEdit.DBComboBoxEh1EditButtons0Click(Sender: TObject; var Handled: Boolean);
   var
      data:TStringList;
      s,t,text:string;
      i:integer;
begin
   if Application.MessageBox('Отправить смс уведомление об изменении статуса?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
      if not DM.tConfig.Active then
         DM.tConfig.Open;
      if DM.tConfigsmsApi.AsString <> '' then begin
         t := DBEditEh4.Text;
         for i:=length(t) downto 1 do begin
             if not(t[i] in ['0'..'9']) then
                delete(t,i,1);
         end;
         if DBComboBoxEh1.Text = 'Готово' then begin
            text := 'Ваш '+qMainEditmodel.AsString+' отремонтирован! '+DM.tConfigname.AsString+', '+DM.tConfigaddress.AsString+', '+DM.tConfigphone.AsString;
         end;
         if (DBComboBoxEh1.Text = 'Выдан') then begin
            text := 'Благодарим за обращение в сервисный центр '+DM.tConfigname.AsString+'! '+DM.tConfigaddress.AsString+', '+DM.tConfigphone.AsString;
         end;

         data:=TStringList.Create;
         data.Add('api_id='+DM.tConfigsmsApi.AsString);
         data.Add('to='+t);
         data.Add('msg='+text);

         s := IdHTTP.Post('https://sms.ru/sms/send', data);
         if pos('100', s) <> 0 then begin
            Application.MessageBox('Сообщение успешно отправлено', 'Информация', MB_ICONINFORMATION);
         end
         else
            Application.MessageBox(PWideChar('Ошибка отправки сообщения. Код ошибки '+s), 'Ошибка', MB_ICONERROR);
      end
      else begin
         Application.MessageBox('У вас нет ключа API для отправки смс. Введите ключ в настройках программы', 'Ошибка', MB_ICONERROR);
      end;
      DM.tConfig.Close;
   end;
end;

procedure TfMainEdit.DBLookupComboboxEh3EditButtons0Click(Sender: TObject;
  var Handled: Boolean);
begin
  DM.tClient.Append;
  if fClientEdit.ShowModal = mrOk then begin
    if DM.tClient.Modified then
      DM.tClient.Post;
   end;
   DM.tClient.Cancel;
   DM.tClient.Requery();
   DM.tClient.Last;
end;

procedure TfMainEdit.qPhotoAfterOpen(DataSet: TDataSet);
   var
      curDir : string;
begin
   if fMainEdit.qPhotoname.AsString <> '' then begin
      curDir := GetCurrentDir + '\photo';
      Image1.Picture.LoadFromFile(curDir+'\'+fMainEdit.qPhotoname.AsString);
   end
   else begin
      Image1.Picture := nil;
   end;
end;

procedure TfMainEdit.qPhotoAfterScroll(DataSet: TDataSet);
   var
      curDir : string;
begin
   if qPhotoname.AsString <> '' then begin
      curDir := GetCurrentDir + '\photo';
      Image1.Picture.LoadFromFile(curDir+'\'+qPhotoname.AsString);
   end
   else begin
     Image1.Picture := nil;
   end;
end;

procedure TfMainEdit.qStockMoveAfterPost(DataSet: TDataSet);
begin
   fMainEdit.qSumma.Requery();
end;

procedure TfMainEdit.qWorksAfterPost(DataSet: TDataSet);
begin
   fMainEdit.qSumma.Requery();
end;

procedure TfMainEdit.tbAddWorkClick(Sender: TObject);
begin
   if fMainEdit.qMainEditid.AsInteger > 0 then begin
      qWorks.Append;
      qWorksmain_id.AsInteger := fMainEdit.qMainEditid.AsInteger;
      if fMainWorkEdit.ShowModal = mrOk then begin
         if qWorks.Modified then
            qWorks.Post;
      end;
      qWorks.Cancel;
      qWorks.Requery();
      qWorks.Last;
   end
   else begin
      if Application.MessageBox('Для продолжения необходимо сохранить текущую запись. Сохранить?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
         if fMainEdit.qMainEdit.Modified then
            fMainEdit.qMainEdit.Post;
         fMainEdit.qMainEdit.Edit;
         qWorks.Append;
         qWorksmain_id.AsInteger := fMainEdit.qMainEditid.AsInteger;
         if fMainWorkEdit.ShowModal = mrOk then begin
            if qWorks.Modified then
               qWorks.Post;
            qWorks.Parameters[0].Value := fMainEdit.qMainEditid.AsInteger;
         end;
         qWorks.Cancel;
         qWorks.Requery();
         qWorks.Last;
      end;
   end;
end;

procedure TfMainEdit.tbAddPhotoClick(Sender: TObject);
begin
   if fMainEdit.qMainEditid.AsInteger > 0 then begin
      qPhoto.Append;
      qPhotomain_id.AsInteger := fMainEdit.qMainEditid.AsInteger;
      if fPhotoEdit.ShowModal = mrOk then begin
         if qPhoto.Modified then
            qPhoto.Post;
      end;
      qPhoto.Cancel;
      qPhoto.Requery();
      qPhoto.Last;
   end
   else begin
      if Application.MessageBox('Для продолжения необходимо сохранить текущую запись. Сохранить?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
         if fMainEdit.qMainEdit.Modified then
            fMainEdit.qMainEdit.Post;
         fMainEdit.qMainEdit.Edit;
         qPhoto.Append;
         qPhotomain_id.AsInteger := fMainEdit.qMainEditid.AsInteger;
         if fPhotoEdit.ShowModal = mrOk then begin
            if qPhoto.Modified then
               qPhoto.Post;
            qPhoto.Parameters[0].Value := fMainEdit.qMainEditid.AsInteger;
         end;
         qPhoto.Cancel;
         qPhoto.Requery();
         qPhoto.Last;
      end;
   end;
end;

procedure TfMainEdit.tbEditPhotoClick(Sender: TObject);
  var
    id:integer;
begin
   id := qPhoto.RecNo;
   qPhoto.Edit;
   if fPhotoEdit.ShowModal = mrOk then begin
      if qPhoto.Modified then
         qPhoto.Post;
   end;
   qPhoto.Cancel;
   qPhoto.Requery();
   qPhoto.MoveBy(id-1);
end;

procedure TfMainEdit.tbDelPhotoClick(Sender: TObject);
begin
   if Application.MessageBox('Удалить запись?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
      DM.qRemove.SQL.Text := 'SELECT * FROM photo WHERE id='+qPhotoid.AsString;
      DM.qRemove.Open;
      DM.qRemove.Delete;
      DM.qRemove.Close;
      qPhoto.Requery;
   end;
end;

procedure TfMainEdit.tbDelWorkClick(Sender: TObject);
begin
   if Application.MessageBox('Удалить запись?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
      DM.qRemove.SQL.Text := 'SELECT * FROM works WHERE id='+qWorksid.AsString;
      DM.qRemove.Open;
      DM.qRemove.Delete;
      DM.qRemove.Close;
      qWorks.Requery;
   end;
   fMainEdit.qSumma.Requery();
end;

procedure TfMainEdit.tbAddValueClick(Sender: TObject);
   var
      stock_id : integer;
begin
   if fMainEdit.qMainEditid.AsInteger > 0 then begin
      stock_id := addStock(fMainEdit.qMainEditid.AsInteger);
      qStockMove.Append;
      qStockMovestock_id.AsInteger := stock_id;
      if fMainStockMoveEdit.ShowModal = mrOk then begin
         if qStockMove.Modified then
            qStockMove.Post;
         qStockMove.Parameters[0].Value := fMainEdit.qMainEditid.AsInteger;
      end;
      qStockMove.Cancel;
      qStockMove.Requery();
      qStockMove.Last;
   end
   else begin
      if Application.MessageBox('Для продолжения необходимо сохранить текущую запись. Сохранить?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
         if fMainEdit.qMainEdit.Modified then
            fMainEdit.qMainEdit.Post;
         fMainEdit.qMainEdit.Edit;
         stock_id := addStock(fMainEdit.qMainEditid.AsInteger);
         qStockMove.Append;
         qStockMovestock_id.AsInteger := stock_id;
         qStockMove.Parameters[0].Value := stock_id;
         if fMainStockMoveEdit.ShowModal = mrOk then begin
            if qStockMove.Modified then
               qStockMove.Post;
            qStockMove.Parameters[0].Value := fMainEdit.qMainEditid.AsInteger;
         end;
         qStockMove.Cancel;
         qStockMove.Requery();
         qStockMove.Last;
      end;
   end;
end;

procedure TfMainEdit.tbEditValueClick(Sender: TObject);
  var
    id:integer;
begin
   id := qStockMove.RecNo;
   fMainStockMoveEdit.qStockMove.Parameters[0].Value := qStockMovevalue_id.Value;
   fMainStockMoveEdit.qStockMove.Open;
   qStockMove.Edit;
   fMainStockMoveEdit.qResidues.Parameters[0].Value := qStockMovevalue_id.Value;
   fMainStockMoveEdit.qResidues.Open;
   if fMainStockMoveEdit.ShowModal = mrOk then begin
      if qStockMove.Modified then
         qStockMove.Post;
   end;
   fMainStockMoveEdit.qStockMove.Close;
   qStockMove.Cancel;
   qStockMove.Requery();
   qStockMove.MoveBy(id-1);
end;

procedure TfMainEdit.tbEditWorkClick(Sender: TObject);
  var
    id:integer;
begin
   id := qWorks.RecNo;
   qWorks.Edit;
   if fMainWorkEdit.ShowModal = mrOk then begin
      if qWorks.Modified then
         qWorks.Post;
   end;
   qWorks.Cancel;
   qWorks.Requery();
   qWorks.MoveBy(id-1);
end;

procedure TfMainEdit.tbDelValueClick(Sender: TObject);
begin
   if Application.MessageBox('Удалить запись?', 'Подтверждение', MB_ICONQUESTION+MB_YESNO) = idYes then begin
      DM.qRemove.SQL.Text := 'SELECT * FROM stockmove WHERE id='+qStockMoveid.AsString;
      DM.qRemove.Open;
      DM.qRemove.Delete;
      DM.qRemove.Close;
      qStockMove.Requery;
   end;
   fMainEdit.qSumma.Requery();
end;

end.
