///////////////////////////////////////////////////////////
// МОдуль импорта данных в варианте solaris-solaris
///////////////////////////////////////////////////////////

// DirName должно быть определено одним из следующих способов
const DirName = 'c:\mail\in\'; // на случай жесткого запуска по таймеру
//var DirName :string; // Имя базового каталога, в котором происходит поиск, если настроено через сканирование каталогов

const IsOffice = true; // true, если это офис, false, если это аптечный пункт
      Storage = 0;  //  фильтрующий склад. Если мы в аптечном пункте, то лучше фильтровать, чтобы застраховать себя от получения данных по другим складам

      FilterReasons = true; // false - принимать все, что дают.
                            // true - принимать только чеки тз, если принимающий является офисом, а данные - из ТЗ,
                            // а если принимающая база - ТЗ, то принять все приходы и расходы, не являющиеся чеками ТЗ


const
  MaxInterval = 365;
                            
procedure import_invoices;
var
  FList :TSTringList;
  i :integer;
  SRV :variant;
  InReasons :string;
  OutReasons :string;
  Table :TTable;

  ErrList :TstringList;
  ErrFName :string;



begin

  FList := TStringlist.create;
  Table := tTable.create(nil);
  try
    GetFileList(DirName,FList,'ArcSklad*.zip',true,true);
    FList.Sorted := true;

    if not FilterReasons
    then begin
      InREasons :=  'DEFAULT';
      OutReasons := 'DEFAULT';
    end
    else begin

      Table.databasename := 'dbkassa';
      table.tablename := 'osnov.db';

      Table.open;

      if isoffice
      then begin
        InReasons := '';
        outreasons := '';

        table.filter := 'iscash = 1';
        table.filtered := true;
        table.first;
        while not table.eof do
        begin
          if outreasons >'' then outreasons := outreasons + ',';
          outReasons := OutReasons + table.fieldbyname('id').asstring;
          table.next;
        end;
      end
      else begin
        InReasons := 'DEFAULT';

        outreasons := '';

        table.filter := 'iscash <> 1';
        table.filtered := true;
        table.first;
        while not table.eof do
        begin
          if outreasons >'' then outreasons := outreasons + ',';
          outReasons := OutReasons + table.fieldbyname('id').asstring;
          table.next;
        end;
      end;
    end;

      //showmessage('Files = '+FList.text);

    for i := 0 to FList.count-1 do //for i := 0 to FList.count-1 do
    begin
      (* новый вариант exe может жрать сразу имена файлов в качестве аргумента DirName
      if uppercase(extractfilename(Flist[i])) <> 'ARCSKLAD.ZIP'
      then begin
        //ShowMessage('F='+FList[i]);
        MoveFile(FList[i],extractfilepath(FList[i])+'ARCSKLAD.ZIP');
        deletefile(fList[i]);
      end;*)

      try
        STDInOutReadFile({extractfilepath( по новому exe} FList[i] {)},date()-MaxInterval,date(),Storage,not IsOffice,InReasons,OutReasons);
        //STDInOutReadFile(const DirName :string; FromDate :TDateTime; ToDate :TDateTime; const Storage :Integer = -1; CheckRef :Boolean = true; InReasons :string = 'DEFAULT'; OutReasons :string = 'DEFAULT')

        CreateHInt('delete : '+FList[i]);
        deletefile(flist[i]); // согласно новому exe deletefile(extractfilepath(fList[i])+'ARCSKLAD.ZIP');
        if pos('ARCSKLADTMP',uppercase(extractfilepath(FList[i])))>0
        then DeleteDir(Extractfilepath(FList[i]));
      except
        try
          createhinte(ExceptMessage,'Ошибка импорта',0);

          ErrList := tstringlist.create;
          try
            ErrFName :=  extractfilepath(application.exename)+'mailerrlog.log';
            if fileexists(errFName)
            then errlist.loadfromfile(errfname);

            ErrList.add(datetimetostr(now)+' : файл : '+flist[i]+' : Ошибка : '+exceptmessage);
            errlist.savetofile(errfname);
          finally
            errlist.free;
          end;


          //SRV := CreateOleObject('mailprocessor.SRV');
          //SRV.Connectwp('Пользователь','1');
          //SRV.CreateNotify(ExceptMessage);

          //CreateNotify(IDMessage: Integer; Msg: string; Sender: string = ''; Subject: string = ''; NOtifyLogType: TNotifyLogTypes = atInformation)

        except
          createhinte(ExceptMessage,'Сохранение уведомления в MailProcessor',0);
        end;

      end;
    end;

    CreateHint('Обработано файлов: '+inttostr(FList.Count));
    if flist.count>0 then MainCalculation;

  finally
    Table.free;
    FList.free
  end;
end;

begin
  try
    import_invoices;
  finally
   // Application.terminate;
  end;

end.

