// ñêðèïò ãåíåðèðóåò ïàêåòû îáìåíà arcsklad.zip ñ ïîëíûìè ñïðàâî÷íèêàìè òîâàðíûõ ãðóïï

const ExportDir = 'c:\mail_xprice\out\';

procedure CopyTable1(Fromtable :string ; ToDir :string);
var table :ttable;
    table1 :ttable;
begin
  table := ttable.create(nil);
  try
    table1 := ttable.create(table);

    table.databasename := 'dbkassa';

    table.close;
    table.tablename := FromTable;
    table.open;

    //table1.close;
    //table1.tablename := toDir + table.tablename;
    //table1.batchmove(table,BATCOPY);
    BDEBatchMoveToTMP(table, toDir + table.tablename);

  finally
    table.free
  end;
end;


function GenNN_GRPackage(ToDir :string) :string;
var Query :TQuery;
begin
  todir := includetrailingpathdelimiter(ToDir);
  result := ToDir + 'arcsklad.zip';
  forcedirectories(ToDir);
  ClearDir(ToDir);

  CopyTable1('nn_gr1.db',ToDir);
  ZipAdd(result,'nn_gr1.db',ToDir );
  CopyTable1('nn_gr2.db',ToDir);
  ZipAdd(result,'nn_gr2.db',ToDir );
  CopyTable1('nn_gr3.db',ToDir);
  ZipAdd(result,'nn_gr3.db',ToDir );
  CopyTable1('nn_gr4.db',ToDir);
  ZipAdd(result,'nn_gr4.db',ToDir );
  CopyTable1('nn_gr5.db',ToDir);
  ZipAdd(result,'nn_gr5.db',ToDir );
  CopyTable1('nn_gr6.db',ToDir);
  ZipAdd(result,'nn_gr6.db',ToDir );

  Query :=TQuery.create(nil);
  try
    Query.databasename := 'dbkassa';
    Query.sql.text := 'select nn,gr1,gr2,gr3,gr4,gr5,gr6 from tovar where notused is null or notused =0';
    Query.open;

    BDEBatchMoveToTMP(Query, ToDir+'exp_tgr.db');
    ZipAdd(result,'exp_tgr.db',ToDir );

  finally
    Query.free;
  end;

  //ZipAddDir(result,ToDir, ToDir);
end;


var
  cds :Tclientdataset;
  Query :TQuery;
  TMPDir :string;
  REsultFile :string;
  ExportDir1 :string;
begin

  tmpdir := '';
  cds := TClientdataset.create(Nil);
  with TMyWait.create('Èäåò ãåíåðàöèÿ äàííûõ') do
  try

    repeat
      tmpdir := includetrailingpathdelimiter(gettempdir+inttostr(randomrange(1,100000)));
    until not directoryexists(tmpdir);

    forcedirectories(tmpdir);


    Query := TQuery.create(cds);
    Query.databasename := 'dbkassa';
    Query.sql.text := 'select id,code,name '+
      ' from agents '+
      ' where issklad = 1 and code>'''' '+
      ' order by id';

    Query.open;
    readdataset(CDs,Query);
    Query.close;

    cds.first;
    progressbarmax := cds.recordcount;
    progressbarpos := 0;

    ResultFile := GenNN_GRPackage(TMPdir);

    while not cds.eof do
    begin
      incprogress;
      advancedtext := cds.fieldbyname('name').asstring;


      ExportDir1 := includetrailingpathdelimiter( includetrailingpathdelimiter(ExportDir)+CDS.fieldbyname('CODE').asstring);
      ForceDirectories(ExportDir1);

      CopyFile(ResultFile, ExportDir1+extractfilename(Resultfile),    false);
      //createhint(resultFile+#13+ExportDir1+extractfilename(Resultfile));


      cds.next;
    end;

    deletefile(ResultFile);

    deletedir(tmpdir);

    CreateHint('Ãåíåðàöèÿ äàííûõ îêîí÷åíà');
  finally
    free;
    cds.free;

  end;
end.
