
var
  vOrgAccountGetter_SQL1: string;


function GetOrgAccountGetter( var aTo: variant;
                                 aParams: string = '';
                                 aParamValues: Variant = NULL): integer;
var
  xResultXML: variant;
  xWhere: string;
  SL: TStringList;
  xLS_BS: string;
  xValues: Variant;
  xOrgRoles: string;
  s: string;
  xFillResultMode: string;
begin

    try
      // формируем единый набор значений параметров
      xValues:= NULL;
      if NOT VarIsNull( aParamValues)
        then VarArrayUnion( xValues, aParamValues);

      // разбор параметров
      SL:= TStringList.Create;
      try
        SL.Text := aParams;

        // режим заполнения результата в aTo
        xFillResultMode := TRIM( SL.Values[ 'FillResultMode']);

        // в начале описываем раздел where. это основа для раздела where
        // в запросе SQL.
        xWhere := TRIM( SL.Values[ 'where']);
        // дополнительный фильтр к параметру where
        s := TRIM( SL.Values[ 'filter']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          xWhere := xWhere + ' ' + s;
        end;

        // доп параметры
        xLS_BS := TRIM( SL.Values[ 'ls_bs']);

        // если требуется применить фильтр ролей организации, для которой
        // находится л/с, добавляем фильтр ролей организаций
        xOrgRoles := TRIM( SL.Values[ 'org_a_roles']);
        if (LENGTH( xOrgRoles)> 0)
          then xOrgRoles :=
                  FORMAT( ' Left Join OrgRoles org_a_rls'
                         +' on org_a_rls.org_id = org_a.Id'
                         +' and org_a_rls.OrgRole_Id in (%s) ',
                          [ xOrgRoles]);

        // поиск по идентификатору
        s := TRIM( SL.Values[ 'id']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          xWhere := xWhere +' a.id=?';
          // добавляем параметр - номер счета
          VarArrayUnion( xValues, s);
        end;

        // exchange #2960
        // добавлена привязка в\к организации
        s := TRIM( SL.Values[ 'org_id']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          xWhere := xWhere +' a.org_id=?';
          // добавляем параметр - номер счета
          VarArrayUnion( xValues, s);
        end;

        // exchange #2960
        // искать по номеру счета, нераспорядительный, с типом 5
        s := TRIM( SL.Values[ 'accountA1']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          xWhere := xWhere
                    +' (a.orgacctype_id=5 and a.ACCOUNT_NUMBER = ?'
                    +' and a.DISTRIBUTIVE_FLAG = 0)';
          // добавляем параметр - номер счета
          VarArrayUnion( xValues, s);
        end;

        // поиск по номеру счета
        s := TRIM( SL.Values[ 'account']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
(*
          xWhere := xWhere +' a.account_number=?';
          // добавляем параметр - номер счета
          VarArrayUnion( xValues, s);
*)
          if (LENGTH( TRIM( SL.Values[ 'account1'])) > 0)
            then begin
              // exchange #2581
              // проблема в том, что для счета первого типа, счет, который ищется
              // с параметром account1 должен проверяться со счетом финоргана.
              // поэтому, проверяем, если указана опция account1, то проверяем
              // совпадение номера счета в карточке счета и счета в карточке
              // финоргана
              xWhere := xWhere +' ((a.account_number=? and a.orgacctype_id=5)'
                               +'  or (ofk_a.account_number=? and a.orgacctype_id=1))';
              // добавляем параметр - номер счета
              VarArrayUnion( xValues, s);
              VarArrayUnion( xValues, s);
            end else
          if (LENGTH( TRIM( SL.Values[ 'account2'])) > 0)
            then begin
              // exchange #2581
              // проблема в том, что для счета первого типа, счет, который ищется
              // с параметром account2 должен проверяться со счетом финоргана.
              // поэтому, проверяем, если указана опция account2, то проверяем
              // совпадение номера счета в карточке счета и счета в карточке
              // финоргана
              xWhere := xWhere +' ((a.account_number=? and a.orgacctype_id=7)'
                               +'  or (ofk_a.account_number=? and a.orgacctype_id=6))';
              // добавляем параметр - номер счета
              VarArrayUnion( xValues, s);
              VarArrayUnion( xValues, s);
{            end else
          if (LENGTH( TRIM( SL.Values[ 'accountA1'])) > 0)
            then begin
              // exchange #2960 - ожидается счет с типом 5
              xWhere := xWhere +' (a.account_number=? and a.orgacctype_id=5)';
              // добавляем параметр - номер счета
              VarArrayUnion( xValues, s);
            end else
          if (LENGTH( TRIM( SL.Values[ 'accountA2'])) > 0)
            then begin
              // exchange #2960 - ожидается счет с типом 7
              xWhere := xWhere +' (a.account_number=? and a.orgacctype_id=7)';
              // добавляем параметр - номер счета
              VarArrayUnion( xValues, s);}
            end else begin
              xWhere := xWhere +' a.account_number=?';
              // добавляем параметр - номер счета
              VarArrayUnion( xValues, s);
            end;
        end;

        { тип счета }
        s := TRIM( SL.Values[ 'account_type']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          // здесь в запрос вставляется перечисление типов счета
          xWhere := xWhere + FORMAT( ' a.orgacctype_id in (%s)', [ s]);
        end;

        { exchange #2581
          состояние закрытия счета }
        s := TRIM( SL.Values[ 'closed']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          // здесь в запрос вставляется либо is null, либо is not null.
          // явное значение даты (например: =xx.xx.xxxx) не рекомендуется!
          xWhere := xWhere + FORMAT( ' a.CLOSE_DATE %s', [ s]);
        end;

        { Лицевой счет
          Искать с номером, равным л/с, нераспорядительный, среди счетов
          организации с типом 1 или 5.}
        s := TRIM( SL.Values[ 'account1']);
        if (LENGTH( s) > 0) then begin
//          if (LENGTH( TRIM( SL.Values[ 'account'])) <= 0) then begin
            if ( LENGTH( xWhere) > 0)
              then xWhere := xWhere + ' and ';
            xWhere := xWhere +' a.org_id=? and a.orgacctype_id in (1,5)'
                             +' and a.DISTRIBUTIVE_FLAG=0';
            // добавляем параметр - ид.организации
            VarArrayUnion( xValues, s);
          end;

        { Лицевой счет
          Искать с номером, равным л/с, нераспорядительный, среди счетов
          организации с типом 6 или 7.}
        s := TRIM( SL.Values[ 'account2']);
        if (LENGTH( s) > 0) then begin
//          if (LENGTH( TRIM( SL.Values[ 'account'])) <= 0) then begin
            if ( LENGTH( xWhere) > 0)
              then xWhere := xWhere + ' and ';
            xWhere := xWhere +' a.org_id=? and a.orgacctype_id in (6,7)'
                             +' and a.DISTRIBUTIVE_FLAG=0';
            // добавляем параметр - ид.организации
            VarArrayUnion( xValues, s);
          end;

        { Лицевой счет
          Искать с номером, равным л/с, нераспорядительный, среди счетов
          организации с типом 8 или 9.}
        s := TRIM( SL.Values[ 'account3']);
        if (LENGTH( s) > 0) then begin
          if ( LENGTH( xWhere) > 0)
            then xWhere := xWhere + ' and ';
          xWhere := xWhere +' a.org_id=? and a.orgacctype_id in (8,9)'
                           +' and a.DISTRIBUTIVE_FLAG=0';
          // добавляем параметр - ид.организации
          VarArrayUnion( xValues, s);
        end;
        finally
          SL.Free;
      end;

      xResultXML := QueryXml( vOrgAccountGetter_SQL1
      (*
 'select '
+' a.id,'
+' a.org_id,'
+' a.account_number,'
+' a.orgacctype_id,'
+' a.keeperacc_id,'
+' a.CLOSE_DATE,'
+' a.OPEN_DATE'
+' a.keeper_id,'
      +IfThenElse( (CompareVersionEx( AzkVersion, '2.28') >= 0),
                   ' a.CREDENTIALS_FLAG,',
                   ' null CREDENTIALS_FLAG,')
+' org_a.kpp org_kpp,'
+' org_a.taxcode org_taxcode,'
+' org_a.description org_description,'
+' a.budget_flag, a.distributive_flag, a.cash_flag, a.other_receiver_flag,'
+' (case when a.orgacctype_id in (2,4) then b.bic'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.bic'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.bic else executer_b.bic end)'
+'       else null end) bank_bic,'
+' (case when a.orgacctype_id in (2,4) then b.coraccount'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.coraccount'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.coraccount else executer_b.coraccount end)'
+'       else null end) bank_coraccount,'
+' (case when a.orgacctype_id in (2,4) then b.description'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.description'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.description else executer_b.description end)'
+'       else null end) bank_description,'
+' (case when a.orgacctype_id in (2,4) then b.city_type'
+'        when a.orgacctype_id in (3,5,7,8,9) then ufk_b.city_type'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then ofk_b.city_type else executer_b.city_type end)'
+'        else null end) bank_city_type,'
+' (case when a.orgacctype_id in (2,4) then b.city_name'
+'        when a.orgacctype_id in (3,5,7,8,9) then ufk_b.city_name'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then ofk_b.city_name else executer_b.city_name end)'
+'        else null end) bank_city_name,'
+' (case when a.orgacctype_id in (2,4) then f.code'
+'        when a.orgacctype_id in (3,5,7,8,9) then f_ufk.code'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.code else f_executer.code end)'
+'        else null end) bank_filial_code,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_o.description else executer_o.description end)'
+'       else ufk_o.description end) ufk_description,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_o.caption else executer_o.caption end)'
+'       else ufk_o.caption end) ufk_caption,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_a.account_number else executer_a.account_number end)'
+'    else ufk_a.account_number end) ufk_account_number,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_a.id else executer_a.id end)'
+'    else ufk_a.id end) ufk_acc_id,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.caption'
+'    when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.caption'
+'    else null end) ofk_caption,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.description'
+'    when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.description'
+'    else null end) ofk_description,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.id'
+'   when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.id'
+'   else null end) ofk_id,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.name'
+'   when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9)  then keeper_o.name'
+'   else null end) ofk_code,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then f_ufk.name'
+'       when a.orgacctype_id in (1,6) then'
+'         (case when ofk_a.orgacctype_id=2 then f_ofk.name else f_executer.name end)'
+'       else f.name end) filial_name,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then f_ufk.code'
+'      when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.code else f_executer.code end)'
+'      else f.code end) filial_code,'
//        -- для типа 7,8 - счет учета поступлений
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.account_number'
+'   else null end) inc_account_number,'
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.org_id'
+'   else null end) inc_org_id,'
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.id'
+'   else null end) inc_acc_id,'
+'  (case when a.orgacctype_id in (7,8)'
+'    then org_i.description'
+'    else null end) inc_description,'
+'  (case when a.orgacctype_id in (7,8)'
+'    then org_i.caption'
+'    else null end) inc_caption,'
//        -- для типа 9 - единый счет спецсредств
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.account_number'
+'   else null end) spec_account_number,'
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.org_id'
+'   else null end) spec_org_id,'
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.id'
+'   else null end) spec_acc_id,'
+'  (case when a.orgacctype_id in (9)'
+'    then ufksf_a.description'
+'    else null end) spec_description,'
{            +'  (case when a.orgacctype_id in (9)'
+'    then ufksf_a.caption'
+'    else null end) spec_caption,'}
//------------------------ описание ТОФК ----------------------------------
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.CAPTION'
+'       else null'
+'     end) TOFK_CAPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.DESCRIPTION'
+'       else null'
+'     end) TOFK_DESCRIPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.ID'
+'       else null'
+'     end) TOFK_ID,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.NAME'
+'       else null'
+'     end) TOFK_CODE,'
//--------------------- описание организации УФК --------------------------
// это описание организации УФК, только для типов счетов ФК и УФК
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.NAME'
+'       else null'
+'     end) UFK_ORG_CODE,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.DESCRIPTION'
+'       else null'
+'     end) UFK_ORG_DESCRIPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.ID'
+'       else null'
+'     end) UFK_ORG_ID,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.CAPTION'
+'       else null'
+'     end) UFK_ORG_CAPTION'
*)

+' from orgaccount a'
+'   Left Join Org org_a on org_a.Id = A.org_id'
// если требуется применить фильтр ролей организации, для которой
// находится л/с, добавляем фильтр ролей организаций
+xOrgRoles
+'   left join bank b on a.bank_id=b.id'
+'   left join orgaccount ufk_a on a.executeracc_id = ufk_a.id'
+'   left join bank ufk_b on ufk_a.bank_id = ufk_b.id'
+'   left join org ufk_o on ufk_a.org_id = ufk_o.id'
//   +'   --(ufkjoinacc == SPECIALFUNDSACC ? specialfundsacc_id :
//-- +'       (ufkjoinacc == INCOME ? incomeacc_id : executeracc_id))   = ufk_a.id
+'   left join orgaccount ufksf_a on a.specialfundsacc_id = ufksf_a.id'
+'   left join orgaccount ofk_a on a.keeperacc_id = ofk_a.id'
+'   left join org ofk_o on ofk_a.org_id = ofk_o.id'
//     +'   left join org ofk_o on a.keeper_id = ofk_o.id'
+'   left join bank ofk_b on ofk_a.bank_id = ofk_b.id'
// если лицевой счет - в ФО с типом Ближний счет в органах ФК
// т.е. получаем организации ТОФК и орг УФК по одному л/с ТОФК
+'   left join org keeper_o on ofk_a.keeper_id = keeper_o.id'
+'   left join org executer_o on ofk_a.executer_id = executer_o.id'
//   -- для типа 7,8 - счет учета поступлений
+'   left join orgaccount oacc_i on oacc_i.id = a.INCOMEACC_ID'
+'   left join org org_i on org_i.id = oacc_i.org_id'
+'   left join orgaccount executer_a on ofk_a.executeracc_id = executer_a.id'
+'   left join bank executer_b on executer_a.bank_id = executer_b.id'
+'   left join filial f on a.filial_id = f.id'
+'   left join filial f_ufk on ufk_a.filial_id = f_ufk.id'
+'   left join filial f_ofk on ofk_a.filial_id = f_ofk.id'
+'   left join filial f_executer on executer_a.filial_id = f_executer.id'
// описание ТОФК для счета типа ... в ФК
+'   left join ORG TOFK on TOFK.ID = A.KEEPER_ID'
// описание организации УФК
// это описание организации УФК, только для типов счетов ФК и УФК
+'   left join ORG ufk_org on ufk_org.ID = A.EXECUTER_ID'
// если секция where описана, то добавлям секцию к запросу SQL
+IfThen( (LENGTH( xWhere) > 0), ' where ' + xWhere),
           xValues);

      Result := xResultXML.documentElement.ChildNodes.Length;
      if (Result = 0) then begin
        
        EXIT;
      end;

      if (Result > 1) then begin
        
        EXIT;
      end;

      
      // переходим в ветвь результата SQL: это ветвь внутри корневого узла.
      xResultXML := xResultXML.documentElement.childNodes.Item[0];
      // переносим описание л/с в документ

      if NOT VarIsNull( aTo) then
        try
          case xFillResultMode of
            'ED215R': begin
              aTo.setAttribute('ORG_ID', xResultXML.getAttribute('ORG_ID'));
              aTo.setAttribute('ORG_TAXCODE', xResultXML.getAttribute('ORG_TAXCODE'));
              aTo.setAttribute('ORG_KPP', xResultXML.getAttribute('ORG_KPP'));
              aTo.setAttribute('ORG_NAME', xResultXML.getAttribute('ORG_DESCRIPTION'));
              aTo.setAttribute('ORG_ACCOUNT', xResultXML.getAttribute('ACCOUNT_NUMBER'));
              aTo.setAttribute('ORGACCOUNT_ID', xResultXML.getAttribute('ID'));
              aTo.setAttribute('ORGACCOUNTTYPE', xResultXML.getAttribute('ORGACCTYPE_ID'));
              aTo.setAttribute('ORG_BIC', xResultXML.getAttribute('BANK_BIC'));
              aTo.setAttribute('ORG_B_NAME', xResultXML.getAttribute('BANK_DESCRIPTION'));
              aTo.setAttribute('ORG_FILIAL_CODE', xResultXML.getAttribute('BANK_FILIAL_CODE'));
              aTo.setAttribute('ORG_FILIAL_NAME', xResultXML.getAttribute('BANK_FILIAL_NAME'));
              aTo.setAttribute('ORG_CREDENTIALS_FLAG', xResultXML.getAttribute('CREDENTIALS_FLAG'));
              //aTo.setAttribute('CREDENTIALS_ID', xResultXML.getAttribute('CREDENTIALS_ID'));
              aTo.setAttribute('ORG_B_CORACCOUNT', xResultXML.getAttribute('BANK_CORACCOUNT'));

              aTo.setAttribute('ORG_OFK_NAME', xResultXML.getAttribute('OFK_DESCRIPTION'));
              aTo.setAttribute('ORG_OFK_CODE', xResultXML.getAttribute('OFK_CODE'));
              aTo.setAttribute('ORG_OFK_CAPTION', xResultXML.getAttribute('OFK_CAPTION'));
              // ТОФК
              aTo.setAttribute('ORG_TOFK_NAME', xResultXML.getAttribute('TOFK_DESCRIPTION'));
              aTo.setAttribute('ORG_TOFK_CODE', xResultXML.getAttribute('TOFK_CODE'));
              aTo.setAttribute('ORG_TOFK_CAPTION', xResultXML.getAttribute('TOFK_CAPTION'));
              aTo.setAttribute('ORG_TOFK_ID', xResultXML.getAttribute('TOFK_ID'));
              // УФК для типов 1,6
              aTo.setAttribute('ORG_UFK_ACCOUNT', xResultXML.getAttribute('UFK_ACCOUNT_NUMBER'));
              aTo.setAttribute('ORG_UFK_ACC_ID', xResultXML.getAttribute('UFK_ACC_ID'));
              aTo.setAttribute('ORG_UFK_NAME', xResultXML.getAttribute('UFK_DESCRIPTION'));
              aTo.setAttribute('ORG_UFK_CAPTION', xResultXML.getAttribute('UFK_CAPTION'));
              // описание организации УФК для типов 3,5,7,8,9
              aTo.setAttribute('UFK_ORG_CODE', xResultXML.getAttribute('UFK_ORG_CODE'));
              aTo.setAttribute('UFK_ORG_DESCRIPTION', xResultXML.getAttribute('UFK_ORG_DESCRIPTION'));
              aTo.setAttribute('UFK_ORG_ID', xResultXML.getAttribute('UFK_ORG_ID'));
              aTo.setAttribute('UFK_ORG_CAPTION', xResultXML.getAttribute('UFK_ORG_CAPTION'));
            end;

            else begin
              aTo.setAttribute('ORG_ID', xResultXML.getAttribute('ORG_ID'));
              aTo.setAttribute('ORG_TAXCODE', xResultXML.getAttribute('ORG_TAXCODE'));
              aTo.setAttribute('ORG_KPP', xResultXML.getAttribute('ORG_KPP'));
              aTo.setAttribute('ORG_NAME', xResultXML.getAttribute('ORG_DESCRIPTION'));
              aTo.setAttribute('ORG_ACCOUNT', xResultXML.getAttribute('ACCOUNT_NUMBER'));
              aTo.setAttribute('ORGACCOUNT_ID', xResultXML.getAttribute('ID'));
              aTo.setAttribute('ORGACCOUNTTYPE', xResultXML.getAttribute('ORGACCTYPE_ID'));
              aTo.setAttribute('ORG_BIC', xResultXML.getAttribute('BANK_BIC'));
              aTo.setAttribute('ORG_B_NAME', xResultXML.getAttribute('BANK_DESCRIPTION'));
              aTo.setAttribute('ORG_FILIAL_CODE', xResultXML.getAttribute('BANK_FILIAL_CODE'));
              aTo.setAttribute('ORG_FILIAL_NAME', xResultXML.getAttribute('BANK_FILIAL_NAME'));
              aTo.setAttribute('ORG_CREDENTIALS_FLAG', xResultXML.getAttribute('CREDENTIALS_FLAG'));
              aTo.setAttribute('CREDENTIALS_ID', xResultXML.getAttribute('CREDENTIALS_ID'));
              aTo.setAttribute('ORG_B_CORACCOUNT', xResultXML.getAttribute('BANK_CORACCOUNT'));
          //    aTo.setAttribute('', xResultXML.getAttribute('BANK_CITY_NAME'));
          //    aTo.setAttribute('', xResultXML.getAttribute('KEEPERACC_ID'));
          //    aTo.setAttribute('', xResultXML.getAttribute('OFK_CAPTION'));
              aTo.setAttribute('ORG_OFK_NAME', xResultXML.getAttribute('OFK_DESCRIPTION'));
              aTo.setAttribute('ORG_OFK_CODE', xResultXML.getAttribute('OFK_CODE'));
              aTo.setAttribute('ORG_OFK_CAPTION', xResultXML.getAttribute('OFK_CAPTION'));
              // ТОФК
              aTo.setAttribute('ORG_TOFK_NAME', xResultXML.getAttribute('TOFK_DESCRIPTION'));
              aTo.setAttribute('ORG_TOFK_CODE', xResultXML.getAttribute('TOFK_CODE'));
              aTo.setAttribute('ORG_TOFK_CAPTION', xResultXML.getAttribute('TOFK_CAPTION'));
              aTo.setAttribute('ORG_TOFK_ID', xResultXML.getAttribute('TOFK_ID'));
              // УФК для типов 1,6
              aTo.setAttribute('ORG_UFK_ACCOUNT', xResultXML.getAttribute('UFK_ACCOUNT_NUMBER'));
              aTo.setAttribute('ORG_UFK_ACC_ID', xResultXML.getAttribute('UFK_ACC_ID'));
              aTo.setAttribute('ORG_UFK_NAME', xResultXML.getAttribute('UFK_DESCRIPTION'));
              aTo.setAttribute('ORG_UFK_CAPTION', xResultXML.getAttribute('UFK_CAPTION'));
              // описание организации УФК для типов 3,5,7,8,9
              aTo.setAttribute('UFK_ORG_CODE', xResultXML.getAttribute('UFK_ORG_CODE'));
              aTo.setAttribute('UFK_ORG_DESCRIPTION', xResultXML.getAttribute('UFK_ORG_DESCRIPTION'));
              aTo.setAttribute('UFK_ORG_ID', xResultXML.getAttribute('UFK_ORG_ID'));
              aTo.setAttribute('UFK_ORG_CAPTION', xResultXML.getAttribute('UFK_ORG_CAPTION'));

              case xResultXML.getAttribute('ORGACCTYPE_ID') of
                // если тип л/с =7,8
                '7','8':
                    // если поле "Счет для учета поступлений" совпадает с полем ls_bs
                    if (LENGTH( xLS_BS) > 0) then
                      if (xResultXML.getAttribute('INC_ACCOUNT_NUMBER') = xLS_BS) then begin
                        // то в счет УФК подставляется поле "Счет для учета поступлений"
                        aTo.setAttribute('ORG_UFK_ACCOUNT', xResultXML.getAttribute('INC_ACCOUNT_NUMBER'));
                        aTo.setAttribute('ORG_UFK_ACC_ID', xResultXML.getAttribute('INC_ACC_ID'));
                        aTo.setAttribute('ORG_UFK_NAME', xResultXML.getAttribute('INC_DESCRIPTION'));
                      end;
                // если тип л/с =9
                '9':
                    // если поле "единый счет спецсредств" совпадает с полем ls_bs
                    if (LENGTH( xLS_BS) > 0) then
                      if (xResultXML.getAttribute('SPEC_ACCOUNT_NUMBER') = xLS_BS) then begin
                        // то в счет УФК подставляется поле "единый счет спецсредств"
                        aTo.setAttribute('ORG_UFK_ACCOUNT', xResultXML.getAttribute('SPEC_ACCOUNT_NUMBER'));
                        aTo.setAttribute('ORG_UFK_ACC_ID', xResultXML.getAttribute('SPEC_ACC_ID'));
                        aTo.setAttribute('ORG_UFK_NAME', xResultXML.getAttribute('SPEC_DESCRIPTION'));
                      end;
              end;//case//
            end;
          end;//case//
      //    aTo.setAttribute('', xResultXML.getAttribute('UFK_CAPTION'));

          except
            ExceptionLog( 'Сбой копирования параметров л/с в XML результата.');
        end;
      except
        ExceptionProc( 'GetOrgAccountGetter');
    end;

end;

{~GetOrgAccountGetter_ToXML
  работает как и GetOrgAccountGetter, отличие в том, что в результате
  формируется XML и возвращается в параметре aTo, а затем вызывается
  GetOrgAccountGetter. }
function GetOrgAccountGetter_ToXML( var aTo: variant;
                                       aParams: string = '';
                                       aParamValues: Variant = NULL): integer;
begin

    try
      // создаем документ XML с корневым элементом ORG
      aTo := CreateOleObject('Microsoft.XmlDom');
      aTo := aTo.appendChild( aTo.createElement('ORG'));
      Result := GetOrgAccountGetter( aTo, aParams, aParamValues);

      except
        ExceptionProc( 'GetOrgAccountGetter_ToXML');
    end;

end;

{~GetOrgAccountGetter_Initialize
  инициализация модуля запросов описания счетов организаций.
  тут подготавливаются запросы в зависимости от версии АЦК-Финансы.
  это дает ускорение, чтобы при выполнении запроса каждый раз не проверять
  версии.
  требуется вызывать только после модуля Un_VersionSupport.}
procedure GetOrgAccountGetter_Initialize;
begin

    try
// запрос для версии 2.27.6 и более ранних

      vOrgAccountGetter_SQL1 :=
 'select '
+' a.id,'
+' a.org_id,'
+' a.account_number,'
+' a.orgacctype_id,'
+' a.keeperacc_id,'
+' a.CLOSE_DATE,'
+' a.OPEN_DATE,'
+' a.keeper_id,'
+' null CREDENTIALS_FLAG,'    // поля CREDENTIALS_FLAG нет в версиях до 2.28
+' org_a.kpp org_kpp,'
+' org_a.taxcode org_taxcode,'
+' org_a.description org_description,'
+' a.budget_flag, a.distributive_flag, a.cash_flag, a.other_receiver_flag,'
+' (case when a.orgacctype_id in (2,4) then b.bic'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.bic'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.bic else executer_b.bic end)'
+'       else null end) bank_bic,'
+' (case when a.orgacctype_id in (2,4) then b.coraccount'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.coraccount'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.coraccount else executer_b.coraccount end)'
+'       else null end) bank_coraccount,'
+' (case when a.orgacctype_id in (2,4) then b.description'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.description'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.description else executer_b.description end)'
+'       else null end) bank_description,'
+' (case when a.orgacctype_id in (2,4) then b.city_type'
+'        when a.orgacctype_id in (3,5,7,8,9) then ufk_b.city_type'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then ofk_b.city_type else executer_b.city_type end)'
+'        else null end) bank_city_type,'
+' (case when a.orgacctype_id in (2,4) then b.city_name'
+'        when a.orgacctype_id in (3,5,7,8,9) then ufk_b.city_name'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then ofk_b.city_name else executer_b.city_name end)'
+'        else null end) bank_city_name,'
+' (case when a.orgacctype_id in (2,4) then f.code'
+'        when a.orgacctype_id in (3,5,7,8,9) then f_ufk.code'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.code else f_executer.code end)'
+'        else null end) bank_filial_code,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_o.description else executer_o.description end)'
+'       else ufk_o.description end) ufk_description,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_o.caption else executer_o.caption end)'
+'       else ufk_o.caption end) ufk_caption,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_a.account_number else executer_a.account_number end)'
+'    else ufk_a.account_number end) ufk_account_number,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_a.id else executer_a.id end)'
+'    else ufk_a.id end) ufk_acc_id,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.caption'
+'    when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.caption'
+'    else null end) ofk_caption,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.description'
+'    when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.description'
+'    else null end) ofk_description,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.id'
+'   when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.id'
+'   else null end) ofk_id,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.name'
+'   when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9)  then keeper_o.name'
+'   else null end) ofk_code,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then f_ufk.name'
+'       when a.orgacctype_id in (1,6) then'
+'         (case when ofk_a.orgacctype_id=2 then f_ofk.name else f_executer.name end)'
+'       else f.name end) filial_name,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then f_ufk.code'
+'      when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.code else f_executer.code end)'
+'      else f.code end) filial_code,'
//        -- для типа 7,8 - счет учета поступлений
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.account_number'
+'   else null end) inc_account_number,'
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.org_id'
+'   else null end) inc_org_id,'
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.id'
+'   else null end) inc_acc_id,'
+'  (case when a.orgacctype_id in (7,8)'
+'    then org_i.description'
+'    else null end) inc_description,'
+'  (case when a.orgacctype_id in (7,8)'
+'    then org_i.caption'
+'    else null end) inc_caption,'
//        -- для типа 9 - единый счет спецсредств
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.account_number'
+'   else null end) spec_account_number,'
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.org_id'
+'   else null end) spec_org_id,'
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.id'
+'   else null end) spec_acc_id,'
+'  (case when a.orgacctype_id in (9)'
+'    then ufksf_a.description'
+'    else null end) spec_description,'
{            +'  (case when a.orgacctype_id in (9)'
+'    then ufksf_a.caption'
+'    else null end) spec_caption,'}
//------------------------ описание ТОФК ----------------------------------
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.CAPTION'
+'       else null'
+'     end) TOFK_CAPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.DESCRIPTION'
+'       else null'
+'     end) TOFK_DESCRIPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.ID'
+'       else null'
+'     end) TOFK_ID,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.NAME'
+'       else null'
+'     end) TOFK_CODE,'
//--------------------- описание организации УФК --------------------------
// это описание организации УФК, только для типов счетов ФК и УФК
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.NAME'
+'       else null'
+'     end) UFK_ORG_CODE,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.DESCRIPTION'
+'       else null'
+'     end) UFK_ORG_DESCRIPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.ID'
+'       else null'
+'     end) UFK_ORG_ID,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.CAPTION'
+'       else null'
+'     end) UFK_ORG_CAPTION';

// запрос для версии 2.28

      if CompareVersionAZK_Finance(
                'Функция описаний кодов организаций SQL с доп. полями для 2.28',
                '2.28',
                FALSE,
                FALSE)
        then vOrgAccountGetter_SQL1 :=
 'select '
+' a.id,'
+' a.org_id,'
+' a.account_number,'
+' a.orgacctype_id,'
+' a.keeperacc_id,'
+' a.CLOSE_DATE,'
+' a.OPEN_DATE,'
+' a.keeper_id,'
+' a.CREDENTIALS_FLAG,'
+' org_a.kpp org_kpp,'
+' org_a.taxcode org_taxcode,'
+' org_a.description org_description,'
+' a.CREDENTIALS_ID,'
+' a.budget_flag, a.distributive_flag, a.cash_flag, a.other_receiver_flag,'
+' (case when a.orgacctype_id in (2,4) then b.bic'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.bic'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.bic else executer_b.bic end)'
+'       else null end) bank_bic,'
+' (case when a.orgacctype_id in (2,4) then b.coraccount'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.coraccount'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.coraccount else executer_b.coraccount end)'
+'       else null end) bank_coraccount,'
+' (case when a.orgacctype_id in (2,4) then b.description'
+'       when a.orgacctype_id in (3,5,7,8,9) then ufk_b.description'
+'       when a.orgacctype_id in (1,6) then'
+'       (case when ofk_a.orgacctype_id=2 then ofk_b.description else executer_b.description end)'
+'       else null end) bank_description,'
+' (case when a.orgacctype_id in (2,4) then b.city_type'
+'        when a.orgacctype_id in (3,5,7,8,9) then ufk_b.city_type'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then ofk_b.city_type else executer_b.city_type end)'
+'        else null end) bank_city_type,'
+' (case when a.orgacctype_id in (2,4) then b.city_name'
+'        when a.orgacctype_id in (3,5,7,8,9) then ufk_b.city_name'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then ofk_b.city_name else executer_b.city_name end)'
+'        else null end) bank_city_name,'
+' (case when a.orgacctype_id in (2,4) then f.code'
+'        when a.orgacctype_id in (3,5,7,8,9) then f_ufk.code'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.code else f_executer.code end)'
+'        else null end) bank_filial_code,'
+' (case when a.orgacctype_id in (2,4) then f.name'
+'        when a.orgacctype_id in (3,5,7,8,9) then f_ufk.name'
+'        when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.name else f_executer.name end)'
+'        else null end) bank_filial_name,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_o.description else executer_o.description end)'
+'       else ufk_o.description end) ufk_description,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_o.caption else executer_o.caption end)'
+'       else ufk_o.caption end) ufk_caption,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_a.account_number else executer_a.account_number end)'
+'    else ufk_a.account_number end) ufk_account_number,'
+' (case when a.orgacctype_id in (1,6) then'
+'    (case when ofk_a.orgacctype_id=2 then ofk_a.id else executer_a.id end)'
+'    else ufk_a.id end) ufk_acc_id,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.caption'
+'    when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.caption'
+'    else null end) ofk_caption,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.description'
+'    when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.description'
+'    else null end) ofk_description,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.id'
+'   when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9) then keeper_o.id'
+'   else null end) ofk_id,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then ofk_o.name'
+'   when a.orgacctype_id in (1,6) and ofk_a.orgacctype_id in (5,7,8,9)  then keeper_o.name'
+'   else null end) ofk_code,'
+' (case when a.orgacctype_id in (3,5,7,8,9) then f_ufk.name'
+'       when a.orgacctype_id in (1,6) then'
+'         (case when ofk_a.orgacctype_id=2 then f_ofk.name else f_executer.name end)'
+'       else f.name end) filial_name,'
+'(case when a.orgacctype_id in (3,5,7,8,9) then f_ufk.code'
+'      when a.orgacctype_id in (1,6) then'
+'        (case when ofk_a.orgacctype_id=2 then f_ofk.code else f_executer.code end)'
+'      else f.code end) filial_code,'
//        -- для типа 7,8 - счет учета поступлений
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.account_number'
+'   else null end) inc_account_number,'
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.org_id'
+'   else null end) inc_org_id,'
+' (case when a.orgacctype_id in (7,8)'
+'   then oacc_i.id'
+'   else null end) inc_acc_id,'
+'  (case when a.orgacctype_id in (7,8)'
+'    then org_i.description'
+'    else null end) inc_description,'
+'  (case when a.orgacctype_id in (7,8)'
+'    then org_i.caption'
+'    else null end) inc_caption,'
//        -- для типа 9 - единый счет спецсредств
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.account_number'
+'   else null end) spec_account_number,'
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.org_id'
+'   else null end) spec_org_id,'
+' (case when a.orgacctype_id in (9)'
+'   then ufksf_a.id'
+'   else null end) spec_acc_id,'
+'  (case when a.orgacctype_id in (9)'
+'    then ufksf_a.description'
+'    else null end) spec_description,'
{            +'  (case when a.orgacctype_id in (9)'
+'    then ufksf_a.caption'
+'    else null end) spec_caption,'}
//------------------------ описание ТОФК ----------------------------------
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.CAPTION'
+'       else null'
+'     end) TOFK_CAPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.DESCRIPTION'
+'       else null'
+'     end) TOFK_DESCRIPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.ID'
+'       else null'
+'     end) TOFK_ID,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then TOFK.NAME'
+'       else null'
+'     end) TOFK_CODE,'
//--------------------- описание организации УФК --------------------------
// это описание организации УФК, только для типов счетов ФК и УФК
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.NAME'
+'       else null'
+'     end) UFK_ORG_CODE,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.DESCRIPTION'
+'       else null'
+'     end) UFK_ORG_DESCRIPTION,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.ID'
+'       else null'
+'     end) UFK_ORG_ID,'
+'  (case'
+'     when A.ORGACCTYPE_ID in (3, 5, 7, 8, 9)'
+'       then ufk_org.CAPTION'
+'       else null'
+'     end) UFK_ORG_CAPTION';

      except
        ExceptionLog( 'Сбой Un_OrgAccountGetter.GetOrgAccountGetter_Initialize;');
    end;

end;

begin
end.
