
// Ñêðèïò ýêñïîðòà ñïèñêà íàêëàäíûõ â XML-ôàéë èëè TXT-ôàéë. Ñêðèïò òðåáóåò íàëè÷èÿ âåðñèè ïðîãðàììû 5.8.0.8
// Ñêðèïò èñïîëüçóåòñÿ ôîðìîé "Îò÷åòû/Ýêñïîðò â 1Ñ ñïèñêîâ íàêëàäíûõ". Ïðîïèñûâàåòñÿ â ïàðàìåòðàõ
// (âûçûâàåìûõ ïî êíîïêå "Ïàðàìåòðû" â ñàìîé ôîðìå ýêñïîðòà), â ïàðàìåòðå "âûïîëíèòü ñêðèïò". Áîëüøå íèêàêèå
// íàñòðîéêè â ïàðàìåòðàõ ýêñïîðòà íå íóæíû.

// Â ñàìîé ôîðìå íóæíî âûáðàòü ïåðèîä íàêëàäíûõ, òèïû íàêëàäíûõ (ïðèõîäû è ðàñõîäû), ñêëàäû, îñíîâàíèÿ íàêëàäíûõ,
// êîòîðûå ó÷àñòâóþò â îò÷åòå.

// Ñòðóêòóðà ôàéëà XML:

//  <?xml version="1.0" encoding="utf-8" ?>
//  <root MinDate="28.11.2004" MaxDate="28.11.2007">
//  -- êîðåíü äåðåâà, Mindate è MaxDate - äèàïàçîí âûáèðàåìûõ äàò
//  <!-- Ïðèõîäíûå äîêóìåíòû  -->
//  <InputInvoices> -- Âåòêà ñî ñïèñêîì ïðèõîäíûõ íàêëàäíûõ
// <Invoice ID="89" DateDoc="22.12.05" NumberDoc="16984" ID_DOC="" Storage="2" Storage_Name="ÎÎÎ "Àïòåêà Ñóïåð+", ÒÎÐÃÎÂÛÉ ÇÀË" Agent="1" Agent_Name="ÎÎÎ "Àïòåêà Ñóïåð+", ÎÑÍÎÂÍÎÉ ÑÊËÀÄ" SummDoc="29197,6" SummRetail="29197,6" SummNDS="2654,3273" SummNDSRetail="2654,3273" Doc_Reason="Á" Doc_Reason_Name="Áåçíàëè÷íûé ðàñ÷åò">
// -- Íàêëàäíàÿ
// -- Íàêëàäíàÿ
// --  ID - âíóòðåííèé óíèêàëüíûé êîä ïðèõîäíîé íàêëàäíîé.
// --  DateDoc - äàòà íàêëàäíîé
// --  NumberDoc - âíóòðåííèé íîìåð, ïðèñâîåííûé íàêëàäíîé. Ìîæåò îáíóëÿòüñÿ ðàç â äåíü, ðàç â ìåñÿö, ðàç â êâàðòàë èëè ðàç â ãîä, â çàâèñèìîñòè
//     îò íàñòðîåê, óñòàíîâëåííûõ â àïòåêå
// --  ID_DOC - íîìåð íàêëàäíîé ïîñòàâùèêà.
// --  Storage - êîä ñêëàäà
// --  Storage_Name - íàèìåíîâàíèå ñêëàäà
// --  Agent - êîä êîíòðàãåíòà
// --  Agent_Name - íàèìåíîâàíèå êîíòðàãåíòà
// --  SummDoc - Ñóììà ïî äîêóìåíòó, ÍÄÑ â ò.÷.
// --  SummRetail - Ñóììà ïî äîêóìåíòó, â ðîçíè÷íûõ öåíàõ, ÍÄÑ â ò.÷.
// --  SummNDS - Ñóììà ÍÄÑ
// --  SummNDSRetail - Ñóììà ÍÄÑ â ðîçíèöå
// --  Doc_Reason - îñíîâàíèå â ïðèõîäíîé íàêëàäíîé, êîä
// --  Doc_Reason_Name - îñíîâàíèå â ïðèõîäíîé íàêëàäíîé, íàèìåíîâàíèå

//  <InvoiceRow ID="374" id_goods="2283290" name="Áóòîðôàíîëà òàðòðàò àìï 0.2% 1ìë N10" Quantity="80" Price="364,97" PriceRetail="364,97" nds="10" ndsout="10" />
// -- Ñòðîêà íàêëàäíîé
//  - ID - Êîä óíèêàëüíîé ñòðîêè ïðèõîäà
//  - ID_Goods - Êîä òîâàðíûé - óíèêàëüíûé êîä â íîìåíêëàòóðíîì ïåðå÷íå
//  - Name - íàèìåíîâàíèå òîâàðà
//  - Quantity - êîëè÷åñòâî åäèíèö
//  - Price - öåíà ïðèõîäíàÿ, ÍÄÑ â ò.÷.
//  - PriceRetail - Öåíà ðîçíèöû, ÍÄÑ â ò.÷.
//  - NDS - Ñòàâêà ÍÄÑ â ò.÷. â öåíå ïðèõîäà
//  - NDS - ñòàâêà ÍÄÑ â ò.÷. äëÿ ïðîäàæè

//  <!-- Ðàñõîäíûå äîêóìåíòû  -->
//  <OutputInvoices>
//  <Invoice ID="1" DateDoc="28.08.05" NumberDoc="1" ID_DOC="" Storage="1" Storage_Name="ÎÎÎ "Àïòåêà Ñóïåð+", ÎÑÍÎÂÍÎÉ ÑÊËÀÄ" Agent="0" Agent_Name="" SummDoc="556,8" SummWHS="386,6974" SummNDS="44,80" SummNDSWHS="31,1154" Doc_Reason="*" Doc_Reason_Name="Íàëè÷íûé ðàñ÷åò">
//   <InvoiceRow ID="1" id_goods="À31401" name="111111" Quantity="1" Price="192" nds="20" />

//   - ID - óíèêàëüíûé êîä ñòðîêè ðàñõîäà
//   - ID_GOODS - êîä òîâàðíûé
//   - name - íàèìåíîâàíèå òîâàðà
//   - Quantity - êîëè÷åñòâî â íàêëàäíîé
//   - Price - Öåíà â íàêëàäíîé
//   - NDS - ñòàâêà ÍÄÑ â ò.÷.


//  <!-- Ïðèõîäíûå îðäåðà  --> -- Íå èñïîëüçóåòñÿ â äàííû ìîìåíò
//   <InputMoney>


// Ñòðóêòóðà ôàéëà TXT
//  [root]
//  ;äèàïàçîí âûáèðàåìûõ äàò
//  Mindate =
//  MaxDate
//  ;Ïðèõîäíûå äîêóìåíòû
//  [InputInvoices] -- Âåòêà ñî ñïèñêîì ïðèõîäíûõ íàêëàäíûõ
//  [Header] - çàãîëîâîê
//  Invoice ID=89
//  DateDoc=22.12.05
//  NumberDoc=16984
//  ID_DOC=
//  Storage=2
//  Storage_Name=ÎÎÎ "Àïòåêà Ñóïåð+" ÒÎÐÃÎÂÛÉ ÇÀË"
//  Agent=1
//  Agent_Name=ÎÎÎ "Àïòåêà Ñóïåð+", ÎÑÍÎÂÍÎÉ ÑÊËÀÄ
//  SummDoc=29197,6
//  SummRetail=29197,6
//  SummNDS=2654,3273
//  SummNDSRetail=2654,3273
//  Doc_Reason=Á
//  Doc_Reason_Name=Áåçíàëè÷íûé ðàñ÷åò
//  ;Íàêëàäíàÿ (ïîëÿ ïåðå÷èñëåíû ÷åðåç çíàê òàáóëÿöèè, ïåðâàÿ ñòðîêà - ñïèñîê ïîëåé
//  [InvoiceRows]
//  ID   id_goods      name   ed Quantity Price  PriceRetail   nds ndsout    seria     sertif     srok_sertif       producer         name_producer id_sertif       name_sertif

//  ;Ñòðîêà íàêëàäíîé
//  374    2283290    Áóòîðôàíîëà òàðòðàò àìï 0.2% 1ìë N10  80 364,97      364,97  10      10
//  ;Ðàñõîäíûå äîêóìåíòû
//  [OutputInvoices]
//  [Invoice]
//  ID=1
//  DateDoc=28.08.05
//  NumberDoc=1
//  ID_DOC=
//  Storage=1
//  Storage_Name=ÎÎÎ "Àïòåêà Ñóïåð+", ÎÑÍÎÂÍÎÉ ÑÊËÀÄ
//  Agent=0
//  Agent_Name=
//  SummDoc=556,8
//  SummWHS=386,6974
//  SummNDS=44,80
//  SummNDSWHS=31,1154
//  Doc_Reason=*
//  Doc_Reason_Name=Íàëè÷íûé ðàñ÷åò
//  [InvoiceRows]
//  ID          id_goods     name    ed        Quantity  Price nds    id_pr
//  1           À31401       111111      1  192  20
//  ;Ïðèõîäíûå îðäåðà  --> -- Íå èñïîëüçóåòñÿ â äàííû ìîìåíò
//  [InputMoney]


// UseXML: 0 - ñãåíåðèðîâàòü XML, 1  - ñãåíåðèðîâàòü TXT
const UseFormat = 0;


// Íàêëàäíàÿ âûâîäèòñÿ ñ ïîëíîé äåòàëèçàöèåé, åñëè NeedDetailInvoices = true
const NeedDetailInvoices = true;



var // ïðåäîïðåäåëåííûå ïðîãðàììîé ïåðåìåííûå

  DATASET :TTable; // òàáëèöà ñ øàïêàìè íàêëàäíûõ ,êîòîðóþ ñîáèðàåò âûçûâàþùàÿ ôîðìà. Èç íåå ôîðìèðóåì âûõîäíîé ôàéë
  MinDate :tDateTime; // Ïåðâàÿ èç äàò â äèàïàçîíå
  MaxDate :tDateTime; // Âòîðàÿ (ìàêñèìàëüíàÿ) äàòà â äèàïàçîíå
  CheckOutput :boolean; // True, åñëè çàïðîñ îñóùåñòâëÿëñÿ ïî ðàñõîäíûì äîêóìåíòàì
  CheckInput  :boolean; // True, åñëè çàïðîñ îñóùåñòâëÿëñÿ ïî ïðèõîäíûì äîêóìåíòàì
  CheckInputMoney :boolean; // True, åñëè çàïðîñ îñóùåñòâëÿëñÿ ïî âûïëàòàì îò ïîêóïàòåëåé


  function ifstr(boolval :boolean; truestr :string; falsestr :string) :string;
  begin
    if boolval then result := truestr
    else result := falsestr;
  end;


  function FindField(table :tTable; KeyVAlue :Variant; SearchFieldName :string ) :string;
  begin
    if table.findkey([KeyValue])
    then result := Table.fieldbyname(searchfieldname).asstring
    else Result := '';
  end;


var
  Doc :Variant;
  DocTXT :TStringList;
  NodeIn,NodeOut,NodeMoneyIn :Variant;
  NodeInTXT,NodeOutTXT,NodeMoneyInTXT :TStringLIst;
  SaveDialog :TSaveDialog;
  FileName :string;

  Node,RootNode,NodeDetail :Variant;
  QueryPR,QueryRS :tQuery;

  TaPR_Tovar,TaRS_Tovar,TaTovar,TaPRoducer,TaSertif,TaCountry,TaAgents :TTAble;

begin
  Filename := '';

  // çàïðàøèâàåì ôàéë, êóäà áóäåì êëàñòü äàííûå. Ó÷èòûâàþòñÿ äàííûå ïðåäûäóùåãî ñåàíñà
  SaveDialog := TSaveDialog.create(nil);
  try
     SaveDialog.Title := 'Óêàæèòå ôàéë';
     SaveDialog.FileName  := AppIniFile.readstring('plugin_export1c','filename','');
     SaveDialog.defaultext := 'XML';
     if UseFormat = 0 then
       SaveDialog.Filter := 'XML-ôàéëû(*.xml)|*.xml'
     else
       SaveDialog.Filter := 'TXT-ôàéëû(*.txt)|*.txt';

     SaveDialog.filter := SaveDialog.Filter + '|Âñå ôàéëû(*.*)|*.*';

     if  SaveDialog.execute then
     begin
         Filename := SaveDialog.FileName;
         AppIniFile.writestring('plugin_export1c','filename',SaveDialog.filename);
     end;
  finally
    SaveDialog.free;
  end;


  // Ñóäÿ ïî âñåìó, íàì äàëè îòáîé, óõîäèì, ïîíóðèâ ãîëîâó...
  if filename = '' then exit;


  QueryPR := TQuery.create(nil);
  with TMyWait.create('Èäåò ýêñïîðò íàêëàäíûõ') do
  try
      QueryRS := TQuery.create(QueryPR);
      TaPR_Tovar := TTable.create(QueryPR);
      TaRS_Tovar := Ttable.create(QueryPR);
      TaTovar := Ttable.create(QueryPR);
      TaPRoducer := Ttable.create(QueryPR);
      TaSertif := Ttable.create(QueryPR);
      TaCountry := Ttable.create(QueryPR);
      TaAgents := Ttable.create(QueryPR);

      QueryPR.databasename := 'dbkassa';
      QueryRS.databasename := 'dbkassa';

      TaPR_tovar.databasename := 'dbkassa';
      TaRS_tovar.databasename := 'dbkassa';
      TaTovar.databasename := 'dbkassa';
      TaProducer.databasename := 'dbkassa';
      TaSertif.databasename := 'dbkassa';
      TaCountry.databasename := 'dbkassa';
      TaAgents.databasename := 'dbkassa';

      TaPR_tovar.TAblename :='pr_tovar';
      tapr_tovar.open;
      TaRS_tovar.TAblename :='rs_tovar';
      tars_tovar.open;
      TaTovar.TAblename :='tovar';
      tatovar.open;
      TaProducer.TAblename :='producer';
      taproducer.open;
      TaSertif.TAblename :='sertif';
      tasertif.open;
      TaCountry.TAblename :='country';
      taCountry.open;
      TaAgents.TAblename :='agents';
      taAgents.open;

      (*
      QueryPR.sql.text := 'select a.id,a.nn,b.name,b.ed,a.kol,a.cena,a.rs_cena,a.nds,a.ndsout,a.seria,a.sertif,a.sroksertif,a.producer,c.name as name_producer,a.idsertif,d.name as name_sertif '+
                          ' from pr_tovar a join tovar b on a.nn = b.nn '+
                          ' left join producer c on c.id = a.producer '+
                          ' left join sertif d on d.id = a.idsertif '+
                          ' where a.id_nakl  = :id_n';

      QueryRS.sql.text := 'select a.id,a.id_pr,a.nn,b.name,b.ed,a.kol,a.cena,a.nds,pr.seria,pr.sertif,pr.sroksertif,pr.producer,c.name as name_producer,pr.idsertif,d.name as name_sertif  '+
                          ' from rs_tovar a join tovar b on a.nn = b.nn '+
                          ' left join  pr_tovar pr on a.id_pr = pr.id '+
                          ' left join producer c on c.id = pr.producer '+
                          ' left join sertif d on d.id = pr.idsertif '+
                          ' where a.id_nakl  = :id_n';
      *)

      QueryPR.sql.text := 'select a.id,a.nn,a.kol,a.cena,a.rs_cena,a.nds,a.ndsout,a.seria'+
                          ',a.sertif,a.sroksertif,a.producer,a.idsertif'+
                          ' from pr_tovar a '+
                          ' where a.id_nakl  = :id_n'+
                          ' order by a.ID';

      QueryRS.sql.text := 'select a.id,a.id_pr,a.nn,a.kol,a.cena,a.nds'+
                          ' from rs_tovar a'+
                          ' where a.id_nakl  = :id_n'+
                          ' order by a.id';

      if UseFormat = 0
      then begin
        Doc := CreateOleObject('MSXML2.DOMDocument');
        Doc.Async := false;
        Doc.setProperty('SelectionLanguage', 'XPath');

        // òàê âñå äåëàþò çà÷åì-òî :)
        Doc.AppendChild(Doc.CreateProcessingInstruction('xml', 'version=''1.0'' encoding=''utf-8'''));
      end
      else begin
        DocTXT := TStringlIst.create;
      end;



      // çàäàåì ãëîáàëüíûå ñâîéñòâà îò÷åòà

      if UseFormat = 0
      then begin
        RootNode := Doc.CreateElement('root');
        Doc.appendchild(RootNode);
        RootNode.Attributes.SetNamedItem(Doc.CreateAttribute('MinDate')).Value := formatdatetime('dd/mm/yyyy', Mindate);
        RootNode.Attributes.SetNamedItem(Doc.CreateAttribute('MaxDate')).Value := formatdatetime('dd/mm/yyyy', Maxdate);

        //NodeDocAttributes.AppendChild(Doc.CreateElement('MinDate')).Text := '222';
      end
      else begin
        DocTXT.add('[root]');
        DocTXT.add('MinDate='+formatdatetime('dd/mm/yyyy', Mindate));
        DocTXt.add('MaxDate='+formatdatetime('dd/mm/yyyy', Maxdate));
      end;



      if CheckInput then begin
        if UseFormat = 0 then begin
          RootNode.AppendChild(Doc.CreateComment('Ïðèõîäíûå äîêóìåíòû'));
          NodeIn := RootNode.AppendChild(Doc.CreateElement('InputInvoices'));
        end
        else begin
          NodeInTXT :=TStringlist.create;
        end
      end;

      if CheckOutput then begin
        if useFormat = 0 then begin
          RootNode.AppendChild(Doc.CreateComment('Ðàñõîäíûå äîêóìåíòû'));
          NodeOut := RootNode.AppendChild(Doc.CreateElement('OutputInvoices'));
        end
        else begin
          NodeOutTXT := tstringlist.create;
        end;
      end;

      if CheckInputMoney then begin
        if useFOrmat = 0 then begin
          RootNode.AppendChild(Doc.CreateComment('Ïðèõîäíûå îðäåðà'));
          NodeMoneyIn := RootNode.AppendChild(Doc.CreateElement('InputMoney'));
        end
        else begin
          NodeMOneyInTXT := Tstringlist.create;
        end;
      end;

      progressbarpos := 0;
      progressbarmax := dataset.recordcount;
      advancedtext := 'çàïèñåé: '+inttostr(dataset.recordcount);
      dataset.first;
      while not dataset.eof do
      begin


        if (dataset.fieldbyname('po').asstring = '+') and CheckInput
        then begin
          if useformat = 0
          then begin
              Node := NodeIn.AppendChild(Doc.createElement('Invoice'));
              Node.Attributes.SetNamedItem(Doc.createAttribute('ID')).Value := dataset.fieldbyname('ID_NAKL').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('DateDoc')).Value := dataset.fieldbyname('data').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('NumberDoc')).Value := dataset.fieldbyname('nomer').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('FacturaDoc')).Value :=
                ifstr(dataset.fieldbyname('factura').asinteger=0,'', dataset.fieldbyname('factura').asstring);
              Node.Attributes.SetNamedItem(Doc.createAttribute('ID_DOC')).Value := dataset.fieldbyname('id_doc').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Storage')).Value := dataset.fieldbyname('sklad').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Storage_Name')).Value := dataset.fieldbyname('skladname').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Agent')).Value := dataset.fieldbyname('agent').asstring;

              Node.Attributes.SetNamedItem(Doc.createAttribute('AgentINN')).Value :=
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'inn');
                //vartostr( BDEQueryValue(' select inn from agents where id = :id', [dataset.fieldbyname('agent').asinteger]));
              Node.Attributes.SetNamedItem(Doc.createAttribute('AgentDogovor')).Value :=
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'dogovor');
                //vartostr( BDEQueryValue(' select dogovor from agents where id = :id', [dataset.fieldbyname('agent').asinteger]));

              Node.Attributes.SetNamedItem(Doc.createAttribute('Agent_Name')).Value := dataset.fieldbyname('agentname').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummDoc')).Value := dataset.fieldbyname('summaz').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummRetail')).Value := dataset.fieldbyname('summa').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummNDS')).Value := FormatFloat('0.00##', dataset.fieldbyname('nds10z').asfloat + dataset.fieldbyname('nds18z').asfloat);
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummNDSRetail')).Value := FormatFloat('0.00##',dataset.fieldbyname('nds10').asfloat + dataset.fieldbyname('nds18').asfloat);
              Node.Attributes.SetNamedItem(Doc.createAttribute('Doc_Reason')).Value := dataset.fieldbyname('osnov').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Doc_Reason_Name')).Value := dataset.fieldbyname('osnovname').asstring;
          end
          else begin
              NodeInTXT.add('[Invoice]');
              NodeInTXT.add('ID='+ dataset.fieldbyname('ID_NAKL').asstring);
              NodeInTXT.add('DateDoc='+ dataset.fieldbyname('data').asstring);
              NodeInTXT.add('NumberDoc='+ dataset.fieldbyname('nomer').asstring);
              NodeInTXT.add('FacturaDoc=' +
                ifstr(dataset.fieldbyname('factura').asinteger=0,'', dataset.fieldbyname('factura').asstring));
              NodeInTXT.add('ID_DOC='+ dataset.fieldbyname('id_doc').asstring);
              NodeInTXT.add('Storage='+ dataset.fieldbyname('sklad').asstring);
              NodeInTXT.add('Storage_Name='+ dataset.fieldbyname('skladname').asstring);
              NodeInTXT.add('Agent='+ dataset.fieldbyname('agent').asstring);

              NodeInTXT.add('AgentINN='+
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'inn'));
                //vartostr( BDEQueryValue(' select inn from agents where id = :id', [dataset.fieldbyname('agent').asinteger])));
              NodeInTXT.add('AgentDogovor='+
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'dogovor'));

                //vartostr( BDEQueryValue(' select dogovor from agents where id = :id', [dataset.fieldbyname('agent').asinteger])));

              NodeInTXT.add('Agent_Name='+ dataset.fieldbyname('agentname').asstring);
              NodeInTXT.add('SummDoc='+ dataset.fieldbyname('summaz').asstring);
              NodeInTXT.add('SummRetail='+ dataset.fieldbyname('summa').asstring);
              NodeInTXT.add('SummNDS='+ FormatFloat('0.00##', dataset.fieldbyname('nds10z').asfloat + dataset.fieldbyname('nds18z').asfloat));
              NodeInTXT.add('SummNDSRetail='+ FormatFloat('0.00##',dataset.fieldbyname('nds10').asfloat + dataset.fieldbyname('nds18').asfloat));
              NodeInTXT.add('Doc_Reason='+ dataset.fieldbyname('osnov').asstring);
              NodeInTXT.add('Doc_Reason_Name='+ dataset.fieldbyname('osnovname').asstring);
          end;

          if needDetailInvoices then
          begin
            QueryPR.close;
            QueryPR.parambyname('id_n').asInteger := dataset.fieldbyname('id_nakl').asinteger;
            QueryPR.open;
            QueryPR.first;
            //CreateHintI('id_n='+inttostr(dataset.fieldbyname('id_nakl').asinteger)+', recordcount = '+inttostr(Querypr.recordcount));

            if UseFormat<>0 then begin
              NodeInTXT.add('[InvoiceRows]');
              NodeInTXT.add('ID'+#9+'id_goods'+#9+'name'+#9+'ed'+#9+'Quantity'+#9+'Price'+#9+'PriceRetail'+#9+'nds'+#9+'ndsout'
                      +#9+'seria'+#9+'sertif'+#9+'srok_sertif'+#9+'producer'+#9+'name_producer'+#9+'id_sertif'+#9+'name_sertif'+#9+'Summ'+#9+'SummRetail'+#9+'SummNDS'+#9+'SummNDSRetail');
            end;


            while not QueryPR.eof do begin
              //CreateHintI('Record='+inttostr(Querypr.recno));



              if UseFormat = 0
              then begin
                  NOdeDetail := Node.appendChild(Doc.CreateElement('InvoiceRow'));
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('ID')).Value := QueryPR.Fieldbyname('id').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('id_goods')).Value := QueryPR.Fieldbyname('nn').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('name')).Value :=
                    FindField(taTovar,QueryPR.fieldbyname('nn').asstring,'name');
                    //QueryPR.Fieldbyname('name').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('ed')).Value :=
                    FindField(taTovar,QueryPR.fieldbyname('nn').asstring,'ed');
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('Quantity')).Value := QueryPR.Fieldbyname('kol').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('Price')).Value := formatfloat('0.00##', QueryPR.Fieldbyname('cena').ascurrency);
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('PriceRetail')).Value := formatfloat('0.00##', QueryPR.Fieldbyname('rs_cena').ascurrency);
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('nds')).Value := QueryPR.Fieldbyname('nds').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('ndsout')).Value := QueryPR.Fieldbyname('ndsout').asstring;

                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('Summ')).Value := formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('cena').asfloat); ;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('SummRetail')).Value := formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('rs_cena').asfloat); ;

                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('SummNDS')).Value := formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('cena').asfloat * QueryPR.fieldbyname('NDS').asinteger/(100 + QueryPR.fieldbyname('nds').asinteger)) ;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('SummNDSRetail')).Value := formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('rs_cena').asfloat * QueryPR.fieldbyname('NDSout').asinteger/(100 + QueryPR.fieldbyname('ndsout').asinteger));


                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('seria')).Value := QueryPR.Fieldbyname('seria').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('sertif')).Value := QueryPR.Fieldbyname('sertif').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('srok_sertif')).Value := QueryPR.Fieldbyname('sroksertif').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('producer')).Value := QueryPR.Fieldbyname('producer').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('name_producer')).Value :=
                    FindField(taProducer,QueryPR.fieldbyname('producer').asinteger,'name');
                    //QueryPR.Fieldbyname('name_producer').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('id_sertif')).Value := QueryPR.Fieldbyname('idsertif').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('name_sertif')).Value :=
                    FindField(tasertif,QueryPR.fieldbyname('idsertif').asstring,'name');
                    //QueryPR.Fieldbyname('name_sertif').asstring;
              end
              else begin
                  NodeInTXT.add(QueryPR.Fieldbyname('id').asstring+#9+
                                QueryPR.Fieldbyname('nn').asstring+#9+
                                FindField(taTovar,QueryPR.fieldbyname('nn').asstring,'name')+#9+
                                FindField(taTovar,QueryPR.fieldbyname('nn').asstring,'ed')+#9+
                                QueryPR.Fieldbyname('kol').asstring+#9+
                                formatfloat('0.00##', QueryPR.Fieldbyname('cena').ascurrency)+#9+
                                formatfloat('0.00##', QueryPR.Fieldbyname('rs_cena').ascurrency)+#9+
                                QueryPR.Fieldbyname('nds').asstring+#9+
                                QueryPR.Fieldbyname('ndsout').asstring+#9+
                                QueryPR.Fieldbyname('seria').asstring+#9+
                                QueryPR.Fieldbyname('sertif').asstring+#9+
                                QueryPR.Fieldbyname('sroksertif').asstring+#9+
                                QueryPR.Fieldbyname('producer').asstring+#9+
                                FindField(taProducer,QueryPR.fieldbyname('producer').asstring,'name')+#9+
                                QueryPR.Fieldbyname('idsertif').asstring+#9+
                                FindField(taSertif,QueryPR.fieldbyname('idsertif').asstring,'name')+#9+
                                formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('cena').asfloat)+#9+
                                formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('rs_cena').asfloat)+#9+
                                formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('cena').asfloat * QueryPR.fieldbyname('NDS').asinteger/(100 + QueryPR.fieldbyname('nds').asinteger))+#9+
                                formatfloat('0.00##', QueryPR.Fieldbyname('kol').asfloat *QueryPR.fieldbyname('rs_cena').asfloat * QueryPR.fieldbyname('NDSout').asinteger/(100 + QueryPR.fieldbyname('ndsout').asinteger))
                                );
              end;
              QueryPR.next;
            end;
          end;
        end
        else
        if (dataset.fieldbyname('po').asstring = '-') and CheckOutput
        then begin
          if UseFormat = 0
          then begin
              Node := NodeOut.AppendChild(Doc.createElement('Invoice'));
              Node.Attributes.SetNamedItem(Doc.createAttribute('ID')).Value := dataset.fieldbyname('ID_NAKL').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('DateDoc')).Value := dataset.fieldbyname('data').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('NumberDoc')).Value := dataset.fieldbyname('nomer').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('FacturaDoc')).Value :=
                ifstr(dataset.fieldbyname('factura').asinteger=0,'', dataset.fieldbyname('factura').asstring);
              Node.Attributes.SetNamedItem(Doc.createAttribute('ID_DOC')).Value := dataset.fieldbyname('id_doc').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Storage')).Value := dataset.fieldbyname('sklad').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Storage_Name')).Value := dataset.fieldbyname('skladname').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Agent')).Value := dataset.fieldbyname('agent').asstring;

              Node.Attributes.SetNamedItem(Doc.createAttribute('AgentINN')).Value :=
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'inn');
                //vartostr( BDEQueryValue(' select inn from agents where id = :id', [dataset.fieldbyname('agent').asinteger]));
              Node.Attributes.SetNamedItem(Doc.createAttribute('AgentDogovor')).Value :=
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'dogovor');

              Node.Attributes.SetNamedItem(Doc.createAttribute('Agent_Name')).Value := dataset.fieldbyname('agentname').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummDoc')).Value := dataset.fieldbyname('summa').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummWHS')).Value := dataset.fieldbyname('summaz').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummNDS')).Value := FormatFloat('0.00##', dataset.fieldbyname('nds10').asfloat + dataset.fieldbyname('nds18').asfloat);
              Node.Attributes.SetNamedItem(Doc.createAttribute('SummNDSWHS')).Value := FormatFloat('0.00##',dataset.fieldbyname('nds10z').asfloat + dataset.fieldbyname('nds18z').asfloat);
              Node.Attributes.SetNamedItem(Doc.createAttribute('Doc_Reason')).Value := dataset.fieldbyname('osnov').asstring;
              Node.Attributes.SetNamedItem(Doc.createAttribute('Doc_Reason_Name')).Value := dataset.fieldbyname('osnovname').asstring;
          end
          else begin
              NodeOutTXT.add('[Invoice]');
              NodeOutTXT.add('ID='+ dataset.fieldbyname('ID_NAKL').asstring);
              NodeOutTXT.add('DateDoc='+ dataset.fieldbyname('data').asstring);
              NodeOutTXT.add('NumberDoc='+ dataset.fieldbyname('nomer').asstring);
              NodeOutTXT.add('FacturaDoc=' +
                ifstr(dataset.fieldbyname('factura').asinteger=0,'', dataset.fieldbyname('factura').asstring));
              NodeOutTXT.add('ID_DOC='+ dataset.fieldbyname('id_doc').asstring);
              NodeOutTXT.add('Storage='+ dataset.fieldbyname('sklad').asstring);
              NodeOutTXT.add('Storage_Name='+ dataset.fieldbyname('skladname').asstring);
              NodeOutTXT.add('Agent='+ dataset.fieldbyname('agent').asstring);

              NodeOutTXT.add('AgentINN='+
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'inn'));
                //vartostr( BDEQueryValue(' select inn from agents where id = :id', [dataset.fieldbyname('agent').asinteger])));
              NodeOutTXT.add('AgentDogovor='+
                FindField(TaAgents,dataset.fieldbyname('agent').asinteger,'dogovor'));

              NodeOutTXT.add('Agent_Name='+ dataset.fieldbyname('agentname').asstring);
              NodeOutTXT.add('SummDoc='+ dataset.fieldbyname('summa').asstring);
              NodeOutTXT.add('SummWHS='+ dataset.fieldbyname('summaz').asstring);
              NodeOutTXT.add('SummNDS='+ FormatFloat('0.00##', dataset.fieldbyname('nds10').asfloat + dataset.fieldbyname('nds18').asfloat));
              NodeOutTXT.add('SummNDSWHS='+ FormatFloat('0.00##',dataset.fieldbyname('nds10z').asfloat + dataset.fieldbyname('nds18z').asfloat));
              NodeOutTXT.add('Doc_Reason='+ dataset.fieldbyname('osnov').asstring);
              NodeOutTXT.add('Doc_Reason_Name='+ dataset.fieldbyname('osnovname').asstring);
          end;
          if needDetailInvoices then
          begin
            QueryRS.close;
            QueryRS.parambyname('id_n').asInteger := dataset.fieldbyname('id_nakl').asinteger;
            QueryRS.open;
            QueryRS.first;

            if UseFormat<>0 then begin
              NodeOutTXT.add('[InvoiceRows]');
              NodeOutTXT.add('ID'+#9+'id_goods'+#9+'name'+#9+'ed'+#9+'Quantity'+#9+'Price'+#9+'nds'+#9+'id_pr'+#9+'seria'+#9+'sertif'+#9+'sroksertif'+#9+'producer'+#9+'name_producer'+#9+'id_sertif'+#9+'name_sertif'+#9+'summ'+#9+'summnds');
            end;

            while not QueryRS.eof do begin
              if UseFormat = 0 then begin
                  NodeDetail := Node.appendChild(Doc.CreateElement('InvoiceRow'));
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('ID')).Value := QueryRS.Fieldbyname('id').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('id_goods')).Value := QueryRS.Fieldbyname('nn').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('id_pr')).Value := QueryRS.Fieldbyname('id_pr').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('name')).Value :=
                    FindField(taTovar,Queryrs.fieldbyname('nn').asstring,'name');
                    //QueryRS.Fieldbyname('name').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('ed')).Value :=
                    FindField(taTovar,Queryrs.fieldbyname('nn').asstring,'ed');
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('Quantity')).Value := QueryRS.Fieldbyname('kol').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('Price')).Value := formatfloat('0.00##', QueryRS.Fieldbyname('cena').ascurrency);
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('nds')).Value := QueryRS.Fieldbyname('nds').asstring;


                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('seria')).Value :=
                    FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'seria');
                    //Queryrs.Fieldbyname('seria').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('sertif')).Value :=
                    FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'sertif');
                    //Queryrs.Fieldbyname('sertif').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('srok_sertif')).Value :=
                    FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'sroksertif');
                    //QueryRS.Fieldbyname('sroksertif').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('producer')).Value :=
                    FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'producer');
                    //QueryRS.Fieldbyname('producer').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('name_producer')).Value :=
                    FindField(taproducer,FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'producer'),'name');
                    //QueryRS.Fieldbyname('name_producer').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('id_sertif')).Value :=
                    FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'idsertif');
                    //QueryRS.Fieldbyname('idsertif').asstring;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('name_sertif')).Value :=
                    FindField(tasertif,FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'idsertif'),'name');
                    //QueryRS.Fieldbyname('name_sertif').asstring;

                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('Summ')).Value := formatfloat('0.00##', Queryrs.Fieldbyname('kol').asfloat *Queryrs.fieldbyname('cena').asfloat); ;
                  NodeDetail.Attributes.SetNamedItem(Doc.CreateAttribute('SummNDS')).Value := formatfloat('0.00##', Queryrs.Fieldbyname('kol').asfloat *Queryrs.fieldbyname('cena').asfloat * Queryrs.fieldbyname('NDS').asinteger/(100 + Queryrs.fieldbyname('nds').asinteger)) ;

              end
              else begin
                  NodeOutTXT.add(Queryrs.Fieldbyname('id').asstring+#9+
                                Queryrs.Fieldbyname('nn').asstring+#9+
                                FindField(taTovar,Queryrs.fieldbyname('nn').asstring,'name')+#9+
                                //Queryrs.Fieldbyname('name').asstring+#9+
                                FindField(taTovar,Queryrs.fieldbyname('nn').asstring,'ed')+#9+
                                //Queryrs.Fieldbyname('ed').asstring+#9+
                                Queryrs.Fieldbyname('kol').asstring+#9+
                                formatfloat('0.00##', Queryrs.Fieldbyname('cena').ascurrency)+#9+
                                Queryrs.Fieldbyname('nds').asstring+#9+
                                Queryrs.Fieldbyname('id_pr').asstring+#9+
                                FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'seria')+#9+
                                FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'sertif')+#9+
                                FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'sroksertif')+#9+
                                FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'producer')+#9+
                                FindField(taproducer,FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'producer'),'name')+#9+
                                FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'idsertif')+#9+
                                FindField(tasertif,FindField(tapr_tovar,Queryrs.fieldbyname('id_pr').asstring,'idsertif'),'name')+#9+
                                formatfloat('0.00##', QueryRS.Fieldbyname('kol').asfloat *QueryRS.fieldbyname('cena').asfloat)+#9+
                                formatfloat('0.00##', QueryRS.Fieldbyname('kol').asfloat *Queryrs.fieldbyname('cena').asfloat * QueryRS.fieldbyname('NDS').asinteger/(100 + QueryRS.fieldbyname('nds').asinteger))


                                );
                    //QueryRS.Fieldbyname('name_sertif').asstring;
              end;

              QueryRS.next;
            end;
          end;
        end
        else
        if (dataset.fieldbyname('po').asstring = '1') and CheckInputMoney
        then begin
          // do nothing çà íåíàäîáíîñòüþ
        end;

        dataset.next;
        IncProgress;
      end;

      if UseFormat=0 then begin
        Doc.Save(FileName);
      end
      else begin
        If checkInput then begin
          DocTXT.add('[InputInvoices]');
          DocTXT.add(NodeInTXT.text);
          NodeInTXT.free
        end;
        If checkOutput then begin
          DocTXT.add('[OutputInvoices]');
          DocTXT.add(NodeOutTXT.text);
          NodeOutTXT.free;
        end;
        If checkinputmoney then begin
          DocTXT.add('[InputMoney]');
          DocTXT.add(NodeMoneyInTXT.text);
          NodeMoneyInTXT.Free
        end;

        DocTXT.SaveToFile(FileName);
        DocTXT.free;

      end;

      CreateHintI('Îïåðàöèÿ ýêñïîðòà äàííûõ çàâåðøåíà');
  finally
    free;
    QueryPR.free;
  end;

end.

