///////////////////////////////////////////////////////////
// МОдуль импорта накладных от поставщиков в реестр импортируемых приходных накладных
///////////////////////////////////////////////////////////

const LogName ='import_invoices.log'; // лог ошибок импорта. Хранится около solaris.ini, согласно настройкам программы

// каталог импорта. 
// Если пусто, то берется из локальной настройки ImportInvoicesDirName
// если пусто, то берется из глобальной настройкки ImportInvoicesDirname
// если пусто, то берется из каталога обмена с другими программами, подкаталог IN
// иначе скрипт выдаст ошибку
var DirName :string =  '';

var WF :TMyWait;

procedure AddToLog(StrVAlue :string);
var FName :string;
    List :tstringlist;
    
const maxcnt =10000; // макс.количество строк 
begin
  list := tstringlist.create;
  try
    FName := getAppLocalDataFolder+LogName; 
    if fileexists(fname) then List.loadfromfile(FName);
    
    while list.count>maxcnt do list.Delete(0);
    
    List.add(formatdatetime('dd/mm/yyyy hh:nn',now)+' : '+ StrValue);
    List.SaveToFile(FName);
  finally
    List.free
  end;
end;  

function ExtractOrigFilename(FName :string) :string;
var iPos:integer;
begin
      Result := Extractfilenamewithoutext(FName);
      if pos('_',result)>0
      then begin
        for ipos:= length(result) downto 2 do
        begin
          if not isdigit(result[ipos])
          then begin
            if (result[ipos] = '_')
            then
              result := copy(result,1,ipos-1);
            break;
          end;
        end;
      end;

    result := Result + extractfileext(fname);
end;


procedure import_invoices_from_dir;
var
  FList :TSTringList;
  i :integer;

  CodeOrg :string;

  ID_org :int64;

  StrVAlue :string;
  ScriptName :string;

  FName :string;
  FOrigName :string;
  iPos :integer;
  DateFromDir :tdatetime;
  
  CNT1 :integer =0;
  
  handle :integer;

begin


   if DirName = '' then DirName := AppIniFile.readstring('advanced','ImportInvoicesDirName','');
   if DirName = '' then DirName := DBIniFile.readstring('advanced','ImportInvoicesDirName','');
   if DirName = '' then begin
     DirName := dbinifile.readstring('COMMON','INOUTDIR','');
     if DirName >'' then DirName := includetrailingpathdelimiter(DirName)+'IN\'; 
   end;
   if DirName = '' then begin
     AddToLog('Ошибка: не указан каталог импорта');
     createhinte('Не указан каталог импорта!');
     exit;
   end;
   
   DirName := includetrailingpathdelimiter(DirName);
   if not DirectoryExists(DirName) then begin
     AddToLog('Ошибка: не найден каталог импорта: '+DirName);
     createhinte('Не найден каталог импорта: '+DirName);
     exit;
   end;
  

  // прием файлов из каталога почты
  FList := TStringlist.create;
  try
    GetFileList(DirName,FList,'*.*',true,true);
    FList.Sorted := true;

    wf.progressbarpos := 0;
    wf.progressbarmax := flist.count;
    

    for i := 0 to FList.count-1 do
    begin
      wf.incprogress;
      application.processmessages;
      if wf.stopped then exit;

      if not fileexists(FList[i]) then continue; // файла уже нет
          
      FName := ExtractFilename(FList[i]);
      FOrigName := ExtractOrigFilename(FList[i]);

      CodeOrg := extractfilepath(FList[i]); // находим первый подкаталог, это есть код даты
      if (codeorg>'') and (codeorg[length(codeorg)]='\') then delete(codeorg,length(codeorg),1);

      StrValue := copy( extractfilename(CodeOrg),1,30);

      DateFromDir := 0;
      if (length(strvalue)=10)
         and isdigit(strvalue[1])
         and isdigit(strvalue[2])
         and isdigit(strvalue[3])
         and isdigit(strvalue[4])

         and (strvalue[5]='-')

         and isdigit(strvalue[6])
         and isdigit(strvalue[7])

         and (strvalue[8]='-')

         and isdigit(strvalue[9])
         and isdigit(strvalue[10])
      then begin

       try
         {
         datefromdir := encodedate(strtoint(copy(strvalue,1,4)),
                        strtoint(copy(strvalue,6,2)),
                        strtoint(copy(strvalue,9,2))
                        );
         }
         CodeOrg := extractfilepath(codeorg); // находим  подкаталог выше, это есть код организации
         if (codeorg>'') and (codeorg[length(codeorg)]='\') then delete(codeorg,length(codeorg),1);
       except
       end;
      end;


      CodeOrg := copy( extractfilename(CodeOrg),1,30);
      
      
      ID_org := asint64( bdeQueryValue(
                    'select id from agents  where ispost=1 and upper(code)= upper(:code)',
                    [CodeOrg]));
                    
      if ID_ORG = 0 then continue;              

      if not asboolean(GetOrgParamValue(ID_ORG,'ImportInvoicesAutoImport')) then continue;

      if asBoolean(GetOrgParamValue(ID_ORG,'ImportInvoicesSolarisSolaris')) then StrValue := '%.ZIP'
      else  strvalue := asstring(getorgparamvalue(id_org,'ImportInvoicesFilePattern'));

      if (StrvAlue='') or not StrInTemplate(stringreplace(StrValue,'*','%',true),FOrigName) then continue;

      if ID_org = 0
      then begin
        continue;
      end;

      begin
        try


          //Loader.waittext := 'Загрузка файлов: '+inttostr(flist.count-i+1)+'/'+inttostr(flist.count)+' - '+CODEORG;
          //Handle := FileOpen(flist[i],fmOpenRead + fmShareExclusive);
          //if handle = 0 then continue; // Не могу открыть файл, он заблокирован, пропускаем просто
          try
            importinvoice(id_org ,{scriptname,} FList[i]);
          finally
            //fileclose(handle); // Разблокируем файла
          end;

          createhinti(Flist[i],'Накладная импортирована',30);
          deletefile(flist[i]); // согласно новому exe deletefile(extractfilepath(fList[i])+'ARCSKLAD.ZIP');
          
          inc(cnt1);

        except
          createhinte('Файл: '+Flist[i]+#13+ExceptMessage,'Ошибка импорта');
          AddToLog('Ошибка: '+exceptMessage+', Файл: '+FList[i]);
        end;
      end;
    end;

    CreateHint('Обработано файлов: '+inttostr(FList.Count)+', принято накладных: '+inttostr(cnt1));

  finally
    FList.free
  end;
end;

procedure import_invoices_from_http;
var
  FName :string;
  id_org :int64;
  code_org :string;
  httpfile :string;
  FDate :tdatetime;

  CDS:tclientdataset;
  Query :tQuery;
  
  strVAlue :string;
  MailMessage :Variant;
  List :Tstringlist;
  i :integer;
begin

  // прием файлов из http://, адреса указаны в поле "шаблон файла" в шапках (prices_headers.import_filepattern);

  List := tstringlist.create;
  Query := TQuery.create(selfscript);
  cds := tclientdataset.create(selfscript);
  try
  
   Query.databasename := 'dbkassa';
   
   Query.sql.text := 
      'select a.id,a.name,a.code,c.FieldValue as import_filepattern'+
      ' from agents a '+
      ' left join org_adv b on a.id=b.id_org and b.fieldname=''ImportInvoicesAutoImport'''+
      ' left join org_adv c on a.id=c.id_org and c.fieldname=''ImportInvoicesFilePattern'''+
      ' where a.ispost=1 and a.code is not null and a.code>'''' and b.fieldvalue =''True'' and upper(c.FieldValue) like ''HTTP://%''';
   
   Query.open;
   readdataset(cds,Query);
   Query.close;

   wf.progressbarpos := 0;
   wf.progressbarmax := cds.recordcount;
   
   cds.first;
   while not cds.eof do
   begin

   
      wf.incprogress;
      application.processmessages;
      if wf.stopped then exit;
   
      id_org := cds.fieldbyname('id').aslargeint;
      code_org := cds.fieldbyname('code').asstring;
      httpfile := cds.fieldbyname('import_filepattern').asstring;

      //Loader.ImportCDS.close;
      //Loader.ClearFields;

      try

        //Loader.waittext := 'Загрузка прайс-листов с ресурсов: '+inttostr(cds.recno)+'/'+inttostr(cds.recordcount)+#13+httpfile;

        fname := GetUniqueFileName(gettempdir,'tempimportfile'+extractfileext(httpfile));
        if fileexists(fname) then deletefile(fname);

        with tmywait.create1('Идет загрузка файла '+httpfile, selfscript) do
        try
           URLDownloadToFileSimple( httpfile, fname);
          //SynHttpGetBinary(const URL: string; const Response: TStream): Boolean
        finally
          free
        end;

        if fileexists(fname)
        then begin
          importinvoice(id_org , fname);
        end;

        createhinti(httpfile,'Накладная импортирована',30);

        deletefile(fname);

      except
          createhinte('Файл: '+httpfile+#13+ExceptMessage,'Ошибка импорта',0);
          AddToLog('Ошибка: '+exceptMessage+', Файл: '+httpFile);
      end;
      cds.next;
   end;
   
   //createHint('http:// - обработано файлов: '+inttostr(cds.recordcount));
   
  finally
   cds.free;
   list.free;
  end;
end;

procedure import_invoices_from_ftp;

  //ftp://ИмяПользователя:Пароль@АдресУзла:порт/Путь/ИмяФайла;ТипРесурса
  procedure ParseFTPSTring1(Source :string; var IP,Port,Filepath,Filename,Username,Password :string);
  var strvalue :string;
      intval :integer;
      intval1 :integer;
  begin
    IP :='';
    Port  := '21';
    Filepath := '';
    Filename := '';
    Username := '';
    Password := '';


    source := trim(source);
    if source='' then exit;

    if uppercase(copy(source,1,6))<>'FTP://' then exit;

    delete(source,1,6);


    intval := pos(';',source);
    if intval>0 then delete(source,intval,length(source));


    intval := pos('@',source);
    if intval>0
    then begin
      strvalue := copy(source,1,intval-1);
      intval1 := pos(':',strvalue);
      if intval1 = 0 then username := strvalue
      else begin
        username := copy(strvalue,1,intval1-1);
        password := copy(strvalue,intval1+1,length(strvalue));
      end;


      delete(source,1,intval);
    end;

    intval := pos('/',source);
    if intval=0 then exit;

    filename := copy(source,intval+1,length(source));
    intval1 := pos('/',filename);
    while intval1>0
    do begin
      filepath := filepath+copy(filename,1,intval1);
      filename := copy(filename,intval1+1,length(filename));
      intval1 := pos('/',filename);
    end;

    strvalue := copy(source,1,intval-1);
    intval1 := pos(':',strvalue);
    if intval1>0
    then begin
      ip := copy(strvalue,1,intval1-1);
      port := copy(strvalue,intval1+1,length(strvalue));
    end
    else
      ip := strvalue;
  end;

var
  FName :string;
  id_org :int64;
  code_org :string;
  ftpstring :string;
  FDate,FDATE1 :tdatetime;
  tmpdir :string;

  CDS:tclientdataset;
  
  StrValue :string;
  List :Tstringlist;
  i :integer;
  
  Query :TQuery;

var
  IP,Port,Filepath,Filename,Username,Password :string;

begin

  // прием файлов из ftp://, адреса указаны в поле "шаблон файла" в шаблоне файла импорта;
  //шаблон FTP-схемы: ftp://ИмяПользователя:Пароль@АдресУзла:порт/Путь/ИмяФайла;ТипРесурса


  list := tstringlist.create;
  Query := TQuery.create(selfscript);
  cds := tclientdataset.create(selfscript);
  try
  
   Query.databasename := 'dbkassa';
   Query.sql.text := 
      'select a.id,a.name,a.code,c.FieldValue as import_filepattern'+
      ' from agents a '+
      ' left join org_adv b on a.id=b.id_org and b.fieldname=''ImportInvoicesAutoImport'''+
      ' left join org_adv c on a.id=c.id_org and c.fieldname=''ImportInvoicesFilePattern'''+
      ' where a.ispost=1 and a.code is not null and a.code>'''' and b.fieldvalue =''True'' and upper(c.FieldValue) like ''FTP://%''';
   
   Query.open;
   readdataset(cds,Query);
   Query.close;

   wf.progressbarpos := 0;
   wf.progressbarmax := cds.recordcount;
         
   cds.first;
   while not cds.eof do
   begin

   
      wf.incprogress;
      application.processmessages;
      if wf.stopped then exit;

      id_org := cds.fieldbyname('id').aslargeint;
      code_org := cds.fieldbyname('code').asstring;
      ftpstring := cds.fieldbyname('import_filepattern').asstring;

      //Loader.ImportCDS.close;
      //Loader.ClearFields;

      try

        tmpdir := '';
        //Loader.waittext := 'Загрузка прайс-листов с ресурсов: '+inttostr(cds.recno)+'/'+inttostr(cds.recordcount)+#13+ftpstring;

        with tmywait.create1('Идет загрузка файла '+ftpstring, selfscript) do
        try

          ParseFTPSTring1(ftpstring,
                      IP,Port,filepath,Filename,Username,Password);

          if (ip>'') and (filename>'')
          then begin

             tmpdir := includetrailingpathdelimiter(createuniquedir);

             advancedtext := 'проверка обновлений';

             fdate := SynFtpGetFileDateTime(ip,
                                   port,
                                   filepath+filename,
                                   username,
                                   password);

             //fdate1 := asdatetime(dbQueryvalue('select update_org from prices_headers_upd where id = :id',[id_header]));

             if (fdate<>0) //and (fdate1<fdate) 
             then begin
               advancedtext := 'чтение нового файла';

               SynFtpGetFile(ip,
                                     port,
                                     filepath+filename,
                                     tmpdir+filename,
                                     username,
                                     password);


               if fileexists(tmpdir+filename)
               then begin
                  importinvoice(id_org , tmpdir+filename);
               end;
               createhinti(ftpstring,'Накладная импортирована',30);
             end;
          end;
        finally
          free
        end;

        if tmpdir<>''
        then begin
          deletedir(tmpdir);
        end;


      except
          createhinte('Файл: '+ftpstring+#13+ExceptMessage,'Ошибка импорта',0);
          AddToLog('Ошибка: '+exceptMessage+', Файл: '+ftpstring);
      end;

      cds.next;
   end;
   //createHint('ftp:// - обработано файлов: '+inttostr(cds.recordcount));

  finally
   cds.free;
   list.free;
  end;
end;

begin
   Wf := TMyWait.create('Идет проверка импортируемых документов',selfscript,nil,true);
   wf.advancedtext := 'Импорт из http://';
   import_invoices_from_http;
   application.processmessages; if wf.stopped then exit;
   wf.advancedtext := 'Импорт из ftp://';
   import_invoices_from_ftp;
   application.processmessages; if wf.stopped then exit;
   wf.advancedtext := 'Импорт из каталога обмена';
   import_invoices_from_dir;
end.


