unit uParseThread;

interface

uses
  System.Classes, xmldom, XMLIntf, msxmldom, XMLDoc, System.AnsiStrings,
  StdCtrls, Vcl.ComCtrls, Vcl.Dialogs, System.Variants, System.SysUtils, Data.DB,
  System.UITypes;

type
  TParseThread = class(TThread)
  private
    loaded: Integer;
    error: Integer;
    skip: Integer;
    KeyIndex: Integer;
    LBText: string;
    Enable: Boolean;
    UpdateOld: Boolean;
    EnableUpdateOldCB: TCheckBox;
    InvoiceXMLDocument: TXMLDocument;
    LogLB: TListBox;
    MainProgressBar: TProgressBar;
    SortBtn: TButton;
    CopyErrorsBtn: TButton;
    ParseInvoicesBtn: TButton;
    UpdateOldGB: TGroupBox;
    function GetDescriptionIndex(value: string): Byte;
    function GetProviderStatusIndex(value: string): Byte;
    function GetRecipientStatusIndex(value: string): Byte;
    function GetDocumentTypeIndex(value: string): Byte;
    function GetRateTypeIndex(value: string): Byte;
    procedure ChangeLBText;
    procedure ChangeLBItemIndex;
    procedure ChangeControlEnable;
    procedure SendDoneMessage;
    procedure ChangePGPos;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: Boolean; XmlDoc: TXMLDocument; LB:
      TListBox; PB: TProgressBar; UpdOld: Boolean; SortBtn, CopyErrorsBtn,
      ParseInvoicesBtn: TButton; UpdateOldGB: TGroupBox; EnableUpdateOld: TCheckBox); overload;
  end;

var
  ParseThread: TParseThread;

implementation

uses
  uDM;

{ ParseThread }

constructor TParseThread.Create(CreateSuspended: Boolean; XmlDoc: TXMLDocument;
  LB: TListBox; PB: TProgressBar; UpdOld: Boolean; SortBtn, CopyErrorsBtn,
  ParseInvoicesBtn: TButton; UpdateOldGB: TGroupBox; EnableUpdateOld: TCheckBox);
begin
  inherited Create(CreateSuspended);

  Self.InvoiceXMLDocument := XmlDoc;
  Self.LogLB := LB;
  Self.MainProgressBar := PB;
  Self.UpdateOld := UpdOld;
  Self.SortBtn := SortBtn;
  Self.CopyErrorsBtn := CopyErrorsBtn;
  Self.ParseInvoicesBtn := ParseInvoicesBtn;
  Self.UpdateOldGB := UpdateOldGB;
  Self.EnableUpdateOldCB := EnableUpdateOld;
end;

procedure TParseThread.ChangeLBText;
begin
  LogLB.Items[Self.KeyIndex] := LBText;
  ChangeLBItemIndex;
end;

procedure TParseThread.ChangeLBItemIndex;
begin
  LogLB.ItemIndex := Self.KeyIndex;
end;

procedure TParseThread.ChangeControlEnable;
begin
  SortBtn.Enabled := Self.Enable;
  CopyErrorsBtn.Enabled := Self.Enable;
  ParseInvoicesBtn.Enabled := Self.Enable;
  EnableUpdateOldCB.Enabled := Self.Enable;
  UpdateOldGB.Enabled := Self.Enable;
end;

procedure TParseThread.ChangePGPos;
begin
  Self.MainProgressBar.Position := Self.KeyIndex;
end;

procedure TParseThread.SendDoneMessage;
begin
  MessageDlg('Загрузка закончена.' + #10#13 + 'Загружено: ' + IntToStr(loaded) +
    #10#13 + 'Ошибки: ' + IntToStr(error) + #10#13 + 'Пропущено: ' + IntToStr(skip),
    mtInformation, [mbOk], 0);
end;

function TParseThread.GetDescriptionIndex(value: string): Byte;
begin
  Result := IndexStr(value, ['DEDUCTION_IN_FULL', 'VAT_EXEMPTION', 'OUTSIDE_RB',
    'IMPORT_VAT', 'EXCISE_MARK', 'CONTROL_MARK', 'CUSTOMS_EXCISE', 'IDENTIFIED_MARK', 'ANALYZED_DEAL']) + 1;
end;

function TParseThread.GetProviderStatusIndex(value: string): Byte;
begin
  Result := IndexStr(value, ['SELLER', 'CONSIGNOR', 'COMMISSIONAIRE', 'TRUSTEE',
    'TAX_DEDUCTION_PAYER', 'FOREIGN_ORGANIZATION', 'AGENT', 'DEVELOPER']) + 1;
end;

function TParseThread.GetRecipientStatusIndex(value: string): Byte;
begin
  Result := IndexStr(value, ['CUSTOMER', 'CONSIGNOR', 'COMMISSIONAIRE',
    'CONSUMER', 'TAX_DEDUCTION_RECIPIENT', 'FOREIGN_ORGANIZATION_BUYER']) + 1;
end;

function TParseThread.GetDocumentTypeIndex(value: string): Byte;
begin
  Result := IndexStr(value, ['ORIGINAL', 'ADDITIONAL', 'FIXED', 'ADD_NO_REFERENCE']) + 1;
end;

function TParseThread.GetRateTypeIndex(value: string): Byte;
begin
  Result := IndexStr(value, ['DECIMAL', 'ZERO', 'NO_VAT', 'CALCULATED']) + 1;
end;

procedure TParseThread.Execute;
var
  i, j, keypar, key: Integer;
//  IListConsignor, IListConsignee,
  IListDoc, IListRost, IListDesc: IXMLNodeList;
//  INodeConsignor, INodeConsignee,
  INodeDoc, INodeRost, INodeDesc: IXMLNode;
  SenderUNN, compilingYear, number, err, dopUNN: string;
  Find, isAdditional: Boolean;
begin
  Self.Enable := False;
  Synchronize(ChangeControlEnable);

  loaded := 0;
  skip := 0;
  error := 0;

  with DM do
    for key := 0 to LogLB.Count - 1 do
    begin
      InvoiceXMLDocument.FileName := LogLB.Items[key];
      Self.KeyIndex := key;
      Synchronize(ChangePGPos);

      try
        //============================ invoices  =================================
        InvoiceXMLDocument.Active := True;
        SenderUNN := InvoiceXMLDocument.DocumentElement.Attributes['sender'];

        with InvoiceXMLDocument.DocumentElement do
        begin
          for keypar := 0 to InvoicesInsert.Parameters.Count - 1 do
            InvoicesInsert.Parameters.Items[keypar].value := NULL;

          for keypar := 0 to RosterInsert.Parameters.Count - 1 do
            RosterInsert.Parameters.Items[keypar].value := NULL;

          for keypar := 0 to DocumentsInsert.Parameters.Count - 1 do
            DocumentsInsert.Parameters.Items[keypar].value := NULL;

          isAdditional := ChildNodes['general'].ChildNodes['documentType'].Text = 'ADDITIONAL';

          if isAdditional then
          begin
            SelectVariousPredprs.Close;
            SelectVariousPredprs.SQL.Clear;
            SelectVariousPredprs.SQL.Add('Select idPredpr from tbPredpr');
            SelectVariousPredprs.SQL.Add('where (idPredpr=idPlat or idPlat is NULL) and UNN='
              + QuotedStr(SenderUNN));
            SelectVariousPredprs.Open;
            Find := False;

            if not SelectVariousPredprs.IsEmpty then
            begin
              SelectVariousPredprs.First;

              while not SelectVariousPredprs.Eof do
              begin
                FindOriginal.Close;
                FindOriginal.Parameters.ParamByName('idSender').value :=
                  SelectVariousPredprs.FieldByName('idPredpr').AsInteger;
                FindOriginal.Parameters.ParamByName('compilingYear').value :=
                  Copy(ChildNodes['general'].ChildNodes['invoice'].Text, 11, 4);
                FindOriginal.Parameters.ParamByName('number').value := Copy(ChildNodes
                  ['general'].ChildNodes['invoice'].Text, 16, 10);
                FindOriginal.Open;

                if not FindOriginal.IsEmpty then
                begin
                  Find := True;
                  Break;
                end;

                SelectVariousPredprs.Next;
              end;
            end;

            if (not Find) then
            begin
              LBText := InvoiceXMLDocument.DocumentElement.ChildNodes['general'].ChildNodes
                ['number'].Text + ' - Не найдена исходная ЭСЧФ - ' + ChildNodes['general'].ChildNodes
                ['invoice'].Text;
              Synchronize(ChangeLBText);
              inc(error);
              Continue;
            end;
          end
          else
          begin
            SelectVariousPredprs.Close;
            SelectVariousPredprs.SQL.Clear;
            SelectVariousPredprs.SQL.Add('Select idPredpr from tbPredpr');

            if (not ChildNodes['provider'].ChildNodes['branchCode'].HasChildNodes)
              or (ChildNodes['provider'].ChildNodes['branchCode'].Text = '') then
              SelectVariousPredprs.SQL.Add('where (idPredpr=idPlat or idPlat is NULL) and (DopUNN=1 or DopUNN is NULL) and UNN='
                + QuotedStr(SenderUNN))
            else
            begin // 22.09.2021
              dopUNN := Trim(ChildNodes['provider'].ChildNodes['branchCode'].Text);

              with qSelectInvPredpr do
              begin
                Close;
                Parameters.ParamByName('unn').value := SenderUNN;
                Parameters.ParamByName('dopUnn').value := StrToInt(dopUNN);
                Open;
              end;

              if not qSelectInvPredpr.IsEmpty then
                dopUNN := qSelectInvPredprnewDopUnn.AsString;

              if dopUNN = '1' then
                SelectVariousPredprs.SQL.Add('where (idPredpr=idPlat or idPlat is NULL) and (DopUNN=1 or DopUNN is NULL) and UNN='
                  + QuotedStr(SenderUNN))
              else
                SelectVariousPredprs.SQL.Add('where (idPredpr=idPlat or idPlat is NULL) and DopUNN='
                  + dopUNN + ' and UNN=' + QuotedStr(SenderUNN));
            end;

            SelectVariousPredprs.Open;
          end;

          if SelectVariousPredprs.IsEmpty then
          begin
            if (not ChildNodes['provider'].ChildNodes['branchCode'].HasChildNodes) then
              dopUNN := ''
            else
              dopUNN := ChildNodes['provider'].ChildNodes['branchCode'].Text;

            LBText := InvoiceXMLDocument.DocumentElement.ChildNodes['general'].ChildNodes
              ['number'].Text + ' - Не найдено организации с УНП - ' +
              ChildNodes['provider'].ChildNodes['unp'].Text + ' - Код филиала(доп УНП) - ' + dopUNN;
            inc(error);
            Synchronize(ChangeLBText);
            Continue;
          end
          else
            InvoicesInsert.Parameters.ParamByName('idProvider').value :=
              SelectVariousPredprs.FieldByName('idPredpr').AsInteger;

          compilingYear := Copy(ChildNodes['general'].ChildNodes['number'].Text, 11, 4);
          number := Copy(ChildNodes['general'].ChildNodes['number'].Text, 16, 10);

          err := '';
          err := SelectVariousPredprs.FieldByName('idPredpr').AsString;

          if UpdateOld then
          begin
            DeleteInvoice.Parameters.ParamByName('idSender').value :=
              SelectVariousPredprs.FieldByName('idPredpr').AsInteger;
            DeleteInvoice.Parameters.ParamByName('compilingYear').value := compilingYear;
            DeleteInvoice.Parameters.ParamByName('number').value := number;
            DeleteInvoice.ExecSQL;
          end;

          InvoicesInsert.Parameters.ParamByName('idSender').value :=
            SelectVariousPredprs.FieldByName('idPredpr').AsInteger;
          InvoicesInsert.Parameters.ParamByName('compilingYear').value := compilingYear;
          InvoicesInsert.Parameters.ParamByName('number').value := number;
          InvoicesInsert.Parameters.ParamByName('invoice').value := ChildNodes['general'].ChildNodes
            ['invoice'].Text;

          if ChildNodes['general'].ChildNodes['dateCancelled'].HasChildNodes then
            InvoicesInsert.Parameters.ParamByName('dateCancelled').value :=
              ChildNodes['general'].ChildNodes['dateCancelled'].Text;

          InvoicesInsert.Parameters.ParamByName('documentType').value :=
            GetDocumentTypeIndex(ChildNodes['general'].ChildNodes['documentType'].Text);
          InvoicesInsert.Parameters.ParamByName('dateTransaction').value := Copy
            (Trim(ChildNodes['general'].ChildNodes['dateTransaction'].Text), 1, 10);

          if ChildNodes['deliveryCondition'].HasChildNodes then
            with ChildNodes['deliveryCondition'] do
            begin
              with ChildNodes['contract'] do
              begin
                if ChildNodes['number'].HasChildNodes then
                  InvoicesInsert.Parameters.ParamByName('contractNumber').value
                    := Trim(ChildNodes['number'].Text);

                if ChildNodes['date'].HasChildNodes then
                  InvoicesInsert.Parameters.ParamByName('contractDate').value :=
                    Copy(Trim(ChildNodes['date'].Text), 1, 10);
              end;

              if ChildNodes['description'].HasChildNodes then
                InvoicesInsert.Parameters.ParamByName('description').value := ChildNodes['description'].Text;
            end;

          if not isAdditional then
          begin
            // Проверка наличия документа в счёт-фактуре
            with ChildNodes['deliveryCondition'].ChildNodes['contract'] do
              if (not ChildNodes['documents'].HasChildNodes) or ((ChildNodes['documents'].ChildNodes
                ['document'].ChildNodes['docType'].ChildNodes['code'].Text =
                '600') and (Length(ChildNodes['documents'].ChildNodes['document'].ChildNodes
                ['number'].Text) = 0)) then
              begin
                LBText := 'У ЭСЧФ - ' + InvoiceXMLDocument.DocumentElement.ChildNodes
                  ['general'].ChildNodes['number'].Text + ' - нет документа для сверки.';
                inc(error);
                Synchronize(ChangeLBText);
                Continue;
              end;

            // Обработка данных о поставщике
            with ChildNodes['provider'] do
            begin
              InvoicesInsert.Parameters.ParamByName('providerStatus').value :=
                GetProviderStatusIndex(ChildNodes['providerStatus'].Text);

              if ChildNodes['specialDealGoods'].Text = 'true' then
                InvoicesInsert.Parameters.ParamByName('specialDealGoods').value := 1
              else
                InvoicesInsert.Parameters.ParamByName('specialDealGoods').value := 0;

              if ChildNodes['principal'].HasChildNodes then
              begin
                SelPredprByUnn.Close;
                SelPredprByUnn.Parameters.ParamByName('UNN').value := QuotedStr(Copy
                  (ChildNodes['principal'].ChildNodes['number'].Text, 1, 9));
                SelPredprByUnn.Open;

                if SelPredprByUnn.IsEmpty then
                  InvoicesInsert.Parameters.ParamByName('principalId').value := null
                else
                  InvoicesInsert.Parameters.ParamByName('principalId').value :=
                    SelPredprByUnnidPredpr.AsInteger;

                InvoicesInsert.Parameters.ParamByName('principalYear').value :=
                  Copy(ChildNodes['principal'].ChildNodes['number'].Text, 11, 4);
                InvoicesInsert.Parameters.ParamByName('principalNumber').value
                  := Copy(ChildNodes['principal'].ChildNodes['number'].Text, 16, 10);

                if ChildNodes['principal'].ChildNodes['date'].HasChildNodes then
                  InvoicesInsert.Parameters.ParamByName('principalDate').value
                    := ChildNodes['principal'].ChildNodes['date'].Text;
              end;

              if ChildNodes['vendor'].HasChildNodes then
              begin
                SelPredprByUnn.Close;
                SelPredprByUnn.Parameters.ParamByName('UNN').value := QuotedStr(Copy
                  (ChildNodes['vendor'].ChildNodes['number'].Text, 1, 9));
                SelPredprByUnn.Open;

                if SelPredprByUnn.IsEmpty then
                  InvoicesInsert.Parameters.ParamByName('vendorId').value := null
                else
                  InvoicesInsert.Parameters.ParamByName('vendorId').value := SelPredprByUnnidPredpr.AsInteger;

                InvoicesInsert.Parameters.ParamByName('vendorYear').value :=
                  Copy(ChildNodes['vendor'].ChildNodes['number'].Text, 11, 4);
                InvoicesInsert.Parameters.ParamByName('vendorNumber').value :=
                  Copy(ChildNodes['vendor'].ChildNodes['number'].Text, 16, 10);

                if ChildNodes['vendor'].ChildNodes['date'].HasChildNodes then
                  InvoicesInsert.Parameters.ParamByName('vendorDate').value :=
                    ChildNodes['vendor'].ChildNodes['date'].Text;
              end;

              if ChildNodes['declaration'].HasChildNodes then
                InvoicesInsert.Parameters.ParamByName('pDeclaration').value := ChildNodes['declaration'].Text;
              if ChildNodes['dateRelease'].HasChildNodes then
                InvoicesInsert.Parameters.ParamByName('dateRelease').value := ChildNodes['dateRelease'].Text;
              if ChildNodes['dateActualExport'].HasChildNodes then
                InvoicesInsert.Parameters.ParamByName('dateActualExport').value
                  := ChildNodes['dateActualExport'].Text;

              if ChildNodes['taxes'].HasChildNodes then
              begin
                InvoicesInsert.Parameters.ParamByName('pTaxesNumber').value :=
                  ChildNodes['taxes'].ChildNodes['number'].Text;

                if ChildNodes['taxes'].ChildNodes['date'].HasChildNodes then
                  InvoicesInsert.Parameters.ParamByName('pTaxesDate').value :=
                    ChildNodes['taxes'].ChildNodes['date'].Text;
              end;
            end;

          // Обработка данных о получателе
            with ChildNodes['recipient'] do
            begin
            // В филиалах облпо код филиала облпо = 8000
              if (SelNastrUNN.AsString = '600037767') or (SelNastrUNN.AsString = '391855888') then
                dopUNN := '8000'
              else
                dopUNN := '1';

              SelectVariousPredprs.Close;
              SelectVariousPredprs.SQL.Clear;
              SelectVariousPredprs.SQL.Add('Select idPredpr from tbPredpr');

              if (not ChildNodes['branchCode'].HasChildNodes) or (ChildNodes['branchCode'].Text = '') then
                SelectVariousPredprs.SQL.Add('where (idPredpr=idPlat or idPlat is NULL) and (DopUNN='
                  + dopUNN + ' or DopUNN is NULL) and UNN=' + QuotedStr(ChildNodes['unp'].Text))
              else
                SelectVariousPredprs.SQL.Add('where (idPredpr=idPlat or idPlat is NULL) and DopUNN='
                  + ChildNodes['branchCode'].Text + ' and UNN=' + QuotedStr(ChildNodes['unp'].Text));

              SelectVariousPredprs.Open;

              if SelectVariousPredprs.IsEmpty then
              begin
                if (not ChildNodes['branchCode'].HasChildNodes) then
                  dopUNN := ''
                else
                  dopUNN := ChildNodes['branchCode'].Text;

                LBText := InvoiceXMLDocument.DocumentElement.ChildNodes['general'].ChildNodes
                  ['number'].Text + ' - Не найдено организации с УНП - ' +
                  ChildNodes['unp'].Text + ' - Код филиала(доп УНП) - ' + dopUNN;
                inc(error);
                Synchronize(ChangeLBText);
                Continue;
              end
              else
                InvoicesInsert.Parameters.ParamByName('idRecipient').value :=
                  SelectVariousPredprs.FieldByName('idPredpr').AsInteger;

              InvoicesInsert.Parameters.ParamByName('recipientStatus').value :=
                GetRecipientStatusIndex(ChildNodes['recipientStatus'].Text);

              if ChildNodes['declaration'].HasChildNodes then
                InvoicesInsert.Parameters.ParamByName('rDeclaration').value := ChildNodes['declaration'].Text;

              if ChildNodes['taxes'].HasChildNodes then
              begin
                InvoicesInsert.Parameters.ParamByName('rTaxesNumber').value :=
                  ChildNodes['taxes'].ChildNodes['number'].Text;
                if ChildNodes['taxes'].ChildNodes['date'].HasChildNodes then
                  InvoicesInsert.Parameters.ParamByName('rTaxesDate').value :=
                    ChildNodes['taxes'].ChildNodes['date'].Text;
              end;

              if ChildNodes['dateImport'].HasChildNodes then
                InvoicesInsert.Parameters.ParamByName('dateImport').value := ChildNodes['dateImport'].Text;
            end;
          end;

          InvoicesInsert.Parameters.ParamByName('totalCostVat').value :=
            StringReplace(ChildNodes['roster'].Attributes['totalCostVat'], '.', ',', [rfReplaceAll]);
          InvoicesInsert.Parameters.ParamByName('totalExcise').value :=
            StringReplace(ChildNodes['roster'].Attributes['totalExcise'], '.', ',', [rfReplaceAll]);
          InvoicesInsert.Parameters.ParamByName('totalVat').value :=
            StringReplace(ChildNodes['roster'].Attributes['totalVat'], '.', ',', [rfReplaceAll]);
          InvoicesInsert.Parameters.ParamByName('totalCost').value :=
            StringReplace(ChildNodes['roster'].Attributes['totalCost'], '.', ',', [rfReplaceAll]);

          InvoicesInsert.ExecSQL;
        {
        //=========================== consignors  ==============================
        IListConsignor := ChildNodes['senderReceiver'].ChildNodes['consignors'].ChildNodes;
        for i := 0 to IListConsignor.Count - 1 do
          if IListConsignor[i].NodeName = 'consignor' then
          begin
            INodeConsignor:=IListConsignor[i];
            SelectVariousPredprs.Close;
            SelectVariousPredprs.SQL.Clear;
            SelectVariousPredprs.SQL.Add('Select idPredpr from tbPredpr');
            SelectVariousPredprs.SQL.Add('where UNN='+INodeConsignor.ChildNodes['unp'].Text);
            SelectVariousPredprs.Open;

            ConsignorsInsert.Parameters.ParamByName('idSender').Value:=InvoicesInsert.Parameters.ParamByName('idSender').Value;
            ConsignorsInsert.Parameters.ParamByName('compilingYear').Value:=InvoicesInsert.Parameters.ParamByName('compilingYear').Value;
            ConsignorsInsert.Parameters.ParamByName('number').Value:=InvoicesInsert.Parameters.ParamByName('number').Value;
            ConsignorsInsert.Parameters.ParamByName('idPredpr').Value:=SelectVariousPredprs.FieldByName('idPredpr').AsInteger;
            ConsignorsInsert.ExecSQL;
          end;

        //============================ consignees ==============================
        IListConsignee := ChildNodes['senderReceiver'].ChildNodes['consignees'].ChildNodes;
         for i := 0 to IListConsignee.Count - 1 do
           if IListConsignee[i].NodeName = 'consignee' then
           begin
            INodeConsignee:=IListConsignee[i];
            SelectVariousPredprs.Close;
            SelectVariousPredprs.SQL.Clear;
            SelectVariousPredprs.SQL.Add('Select idPredpr from tbPredpr');
            SelectVariousPredprs.SQL.Add('where UNN='+INodeConsignee.ChildNodes['unp'].Text);
            SelectVariousPredprs.Open;

            ConsigneesInsert.Parameters.ParamByName('idSender').Value:=InvoicesInsert.Parameters.ParamByName('idSender').Value;
            ConsigneesInsert.Parameters.ParamByName('compilingYear').Value:=InvoicesInsert.Parameters.ParamByName('compilingYear').Value;
            ConsigneesInsert.Parameters.ParamByName('number').Value:=InvoicesInsert.Parameters.ParamByName('number').Value;
            ConsigneesInsert.Parameters.ParamByName('idPredpr').Value:=SelectVariousPredprs.FieldByName('idPredpr').AsInteger;
            ConsigneesInsert.ExecSQL;
           end;
           }
        //=========================== roster ===================================
          IListRost := ChildNodes['roster'].ChildNodes;

          for i := 0 to IListRost.Count - 1 do
            if IListRost[i].NodeName = 'rosterItem' then
            begin
              INodeRost := IListRost[i];

              RosterInsert.Close;
              RosterInsert.Parameters.ParamByName('idSender').value :=
                InvoicesInsert.Parameters.ParamByName('idSender').value;
              RosterInsert.Parameters.ParamByName('compilingYear').value :=
                InvoicesInsert.Parameters.ParamByName('compilingYear').value;
              RosterInsert.Parameters.ParamByName('number').value :=
                InvoicesInsert.Parameters.ParamByName('number').value;
              RosterInsert.Parameters.ParamByName('pnt').value := null;

              if INodeRost.ChildNodes['number'].HasChildNodes then
                RosterInsert.Parameters.ParamByName('itemNumber').value :=
                  INodeRost.ChildNodes['number'].Text;

              RosterInsert.Parameters.ParamByName('[name]').value := Trim(INodeRost.ChildNodes['name'].Text);
              RosterInsert.Parameters.ParamByName('code').value := INodeRost.ChildNodes['code'].Text;
              RosterInsert.Parameters.ParamByName('code_oced').value :=
                INodeRost.ChildNodes['code_oced'].Text;
              RosterInsert.Parameters.ParamByName('units').value := null;

              if INodeRost.ChildNodes['count'].HasChildNodes then
                RosterInsert.Parameters.ParamByName('[count]').value :=
                  StringReplace(INodeRost.ChildNodes['count'].Text, '.', ',', [rfReplaceAll]);

              if INodeRost.ChildNodes['price'].HasChildNodes then
                RosterInsert.Parameters.ParamByName('price').value :=
                  StringReplace(INodeRost.ChildNodes['price'].Text, '.', ',', [rfReplaceAll]);

              RosterInsert.Parameters.ParamByName('cost').value := StringReplace
                (INodeRost.ChildNodes['cost'].Text, '.', ',', [rfReplaceAll]);

              if INodeRost.ChildNodes['summaExcise'].HasChildNodes then
                RosterInsert.Parameters.ParamByName('summaExcise').value :=
                  StringReplace(INodeRost.ChildNodes['summaExcise'].Text, '.', ',', [rfReplaceAll]);

              RosterInsert.Parameters.ParamByName('rate').value := StringReplace
                (INodeRost.ChildNodes['vat'].ChildNodes['rate'].Text, '.', ',', [rfReplaceAll]);
              RosterInsert.Parameters.ParamByName('idRateType').value :=
                GetRateTypeIndex(INodeRost.ChildNodes['vat'].ChildNodes['rateType'].Text);
              RosterInsert.Parameters.ParamByName('summaVat').value :=
                StringReplace(INodeRost.ChildNodes['vat'].ChildNodes['summaVat'].Text,
                '.', ',', [rfReplaceAll]);
              RosterInsert.Parameters.ParamByName('costVat').value :=
                StringReplace(INodeRost.ChildNodes['costVat'].Text, '.', ',', [rfReplaceAll]);
              RosterInsert.Open;

              if INodeRost.ChildNodes['descriptions'].HasChildNodes then
              begin
                IListDesc := INodeRost.ChildNodes['descriptions'].ChildNodes;
                for j := 0 to IListDesc.Count - 1 do
                  if IListDesc[j].NodeName = 'description' then
                  begin
                    INodeDesc := IListDesc[j];
                    DescriptionsInsert.Parameters.ParamByName('idDesc').value :=
                      GetDescriptionIndex(INodeDesc.Text);
                    DescriptionsInsert.Parameters.ParamByName('idStr').value :=
                      RosterInsert.FieldByName('IdentValue').AsInteger;
                    DescriptionsInsert.ExecSQL;
                  end;
              end;
            end;

        //========================= documents  =================================
          DocCheck.Close;
          DocCheck.Parameters.ParamByName('idSen').value := err;
          DocCheck.Parameters.ParamByName('Year').value := compilingYear;
          DocCheck.Parameters.ParamByName('numb').value := number;
          DocCheck.Open;

          if (DocCheck.IsEmpty) and (ChildNodes['deliveryCondition'].HasChildNodes) then
          begin
            IListDoc := ChildNodes['deliveryCondition'].ChildNodes['contract'].ChildNodes
              ['documents'].ChildNodes;

            for i := 0 to IListDoc.Count - 1 do
              if IListDoc[i].NodeName = 'document' then
              begin
                INodeDoc := IListDoc[i];

                if isAdditional and ((not INodeDoc.ChildNodes['number'].HasChildNodes)
                  or (INodeDoc.ChildNodes['docType'].ChildNodes['code'].Text = '600')) then
                  Break;

                DocumentsInsert.Parameters.ParamByName('idSender').value :=
                  InvoicesInsert.Parameters.ParamByName('idSender').value;
                DocumentsInsert.Parameters.ParamByName('compilingYear').value :=
                  InvoicesInsert.Parameters.ParamByName('compilingYear').value;
                DocumentsInsert.Parameters.ParamByName('number').value :=
                  InvoicesInsert.Parameters.ParamByName('number').value;

                DocumentsInsert.Parameters.ParamByName('code').value := INodeDoc.ChildNodes
                  ['docType'].ChildNodes['code'].Text;

                if INodeDoc.ChildNodes['date'].HasChildNodes then
                  DocumentsInsert.Parameters.ParamByName('docDate').value :=
                    Copy(Trim(INodeDoc.ChildNodes['date'].Text), 1, 10);

                DocumentsInsert.Parameters.ParamByName('blankCode').value :=
                  Trim(INodeDoc.ChildNodes['blankCode'].Text);
                DocumentsInsert.Parameters.ParamByName('seria').value := Trim(INodeDoc.ChildNodes
                  ['seria'].Text);
                DocumentsInsert.Parameters.ParamByName('docNumber').value :=
                  INodeDoc.ChildNodes['number'].Text;

                if SenderUNN = SelNastrUNN.AsString then
                begin
                  FindSkl.Close;

                  if InvoicesInsert.Parameters.ParamByName('documentType').value = 1 then
                    DocumentsInsert.Parameters.ParamByName('vidDoc').value := 2
                  else
                    DocumentsInsert.Parameters.ParamByName('vidDoc').value := 1;

                  FindSkl.Parameters.ParamByName('DocNumber').value := INodeDoc.ChildNodes['number'].Text;
                  FindSkl.Parameters.ParamByName('VidDoc').value :=
                    DocumentsInsert.Parameters.ParamByName('vidDoc').value;

                  if INodeDoc.ChildNodes['date'].HasChildNodes then
                    FindSkl.Parameters.ParamByName('DocDate').value :=
                      DocumentsInsert.Parameters.ParamByName('docDate').value
                  else
                    FindSkl.Parameters.ParamByName('DocDate').value := NULL;

                  FindSkl.Open;
                  DocumentsInsert.Parameters.ParamByName('kodSkl').value :=
                    FindSkl.FieldByName('KodSkl').value;

                  SelectVariousPredprs.Close;
                  SelectVariousPredprs.SQL.Clear;
                  SelectVariousPredprs.SQL.Add('Select idPredpr from tbPredpr');
                  SelectVariousPredprs.SQL.Add('where UNN=' + QuotedStr(ChildNodes
                    ['senderReceiver'].ChildNodes['consignees'].ChildNodes['consignee'].ChildNodes
                    ['unp'].Text));
                  SelectVariousPredprs.Open;
                  DocumentsInsert.Parameters.ParamByName('idPredpr').value :=
                    SelectVariousPredprs.FieldByName('idPredpr').AsInteger;
                end
                else
                begin
                  DocumentsInsert.Parameters.ParamByName('vidDoc').value := 1;
                  DocumentsInsert.Parameters.ParamByName('kodSkl').value := null;
                  DocumentsInsert.Parameters.ParamByName('idPredpr').value := null;
                end;

                DocumentsInsert.ExecSQL;

                Break; //17.01.2020 загрузка только первого документа для сверки
              end;
          end;
        end;

        compilingYear := Copy(InvoiceXMLDocument.DocumentElement.ChildNodes['general'].ChildNodes
          ['number'].Text, 11, 4);
        number := Copy(InvoiceXMLDocument.DocumentElement.ChildNodes['general'].ChildNodes
          ['number'].Text, 16, 10);

        UpdateAsComplete.Parameters.ParamByName('idSender').value :=
          InvoicesInsert.Parameters.ParamByName('idSender').value;
        UpdateAsComplete.Parameters.ParamByName('compilingYear').value := compilingYear;
        UpdateAsComplete.Parameters.ParamByName('number').value := number;
        UpdateAsComplete.ExecSQL;

        if (deleteFile(LogLB.Items[key])) then
        begin
          Inc(loaded);
          LBText := 'Загружен в базу - удалён';
          Synchronize(ChangeLBText);
        end;
      except
        if (err <> '') or (err <> 'NULL') then
        begin
          Check.Parameters.ParamByName('idSen').value := err;
          Check.Parameters.ParamByName('Year').value := compilingYear;
          Check.Parameters.ParamByName('numb').value := StrToInt64(number);
          Check.Open;

          if (Check.FieldByName('completed').AsBoolean) and (deleteFile(LogLB.Items[key])) then
          begin
            LBText := 'Уже существует - удалён';
            Inc(skip);
            Self.KeyIndex := key;
            Synchronize(ChangeLBText);
          end;

          Check.Close;
        end
        else
          inc(error);
      end;

      Synchronize(ChangeLBItemIndex);
    end;

  Synchronize(SendDoneMessage);

  Self.Enable := True;
  Synchronize(ChangeControlEnable);
end;

end.

