ModuleQueries.xml 29.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
<?xml version="1.0" encoding="utf-8"?>
<queries>
  <query key="CreateProcedureGetHeadRecipientsByEmployee">
    <mssql><![CDATA[if exists (select * from sys.objects WHERE type = 'P' AND name = '{0}')
  drop procedure {0};
exec('create procedure {0}
  @currentEmployee int

as
begin
  set nocount on;
    declare @allMyRecipients table (Id int primary key clustered)
    
    -- Получить список подразделений сотрудника.
    insert into @allMyRecipients (Id) 
    select distinct r.Id
      from Sungero_Core_Recipient r
      join Sungero_Core_RecipientLink l
        on r.Id = l.Recipient
      where r.Status = ''Active''
        and l.Member = @currentEmployee 
     
	 insert into @allMyRecipients values (@currentEmployee)
	    
    -- Добавить подразделения, в которых сотрудник руководитель.
    insert @allMyRecipients
    select r.Id
        from Sungero_Core_Recipient r
        where r.Manager_Company_Sungero = @currentEmployee
        and not exists (select 1 from @allMyRecipients dd where dd.Id = r.Id)
    
	declare @allMyRecipientsCount int = 0
    -- Поднять вверх по иерархии до головных подразделений. 
    while ((select count(1) from @allMyRecipients) <> @allMyRecipientsCount)
    begin
	    set @allMyRecipientsCount = (select count(1) from @allMyRecipients)

	    -- Вверх по RecipientLink
        insert @allMyRecipients
        select distinct l.Recipient
          from Sungero_Core_RecipientLink l
          join @allMyRecipients d
            on d.Id= l.Member
          where not exists (select 1 from @allMyRecipients dd where dd.Id = l.Recipient)

		-- Вверх по Parent
        insert @allMyRecipients
        select distinct r.Parent
          from Sungero_Core_Recipient r
          join @allMyRecipients d
            on d.Id= r.Id
          where r.Parent is not null
            and not exists (select 1 from @allMyRecipients dd where dd.Id = r.Parent)

		-- Вверх по HeadOffice (головные подразделение)
        insert @allMyRecipients
        select distinct r.HeadOffice_Company_Sungero
          from Sungero_Core_Recipient r
          join @allMyRecipients d
            on d.Id= r.Id
          where r.HeadOffice_Company_Sungero is not null
            and not exists (select 1 from @allMyRecipients dd where dd.Id = r.HeadOffice_Company_Sungero)

		-- Вверх по НОР
        insert @allMyRecipients
        select distinct r.BusinessUnit_Company_Sungero
          from Sungero_Core_Recipient r
          join @allMyRecipients d
            on d.Id= r.Id
          where r.BusinessUnit_Company_Sungero is not null
            and not exists (select 1 from @allMyRecipients dd where dd.Id = r.BusinessUnit_Company_Sungero)

    end
    
    -- Добавить НОРы, в которых сотрудник руководитель.
    insert into @allMyRecipients
    select r.Id
      from Sungero_Core_Recipient r
      where r.CEO_Company_Sungero = @currentEmployee
        and not exists (select 1 from @allMyRecipients bb where bb.Id = r.Id)

    -- Добавить Всех пользователей
	insert into @allMyRecipients 
	select top 1 Id from Sungero_Core_Recipient
	 where Sid = ''440103EA-A766-47A8-98AD-5260CA32DE46''

  select Id from @allMyRecipients
end')]]></mssql>
    <postgres><![CDATA[create or replace function public.{0}(
    currentemployee integer)
    returns setof integer 
    language 'plpgsql'
as $body$
declare 
   allMyRecipients integer array;
	 allMyRecipientsCount int = 0;
begin    
    -- Получить список подразделений сотрудника.
    allMyRecipients := array( 
    select distinct r.Id
      from Sungero_Core_Recipient r
      join Sungero_Core_RecipientLink l
        on r.Id = l.Recipient
      where r.Status = 'Active'
        and l.Member = currentEmployee);
     
	 allMyRecipients := array_cat(allMyRecipients, array[currentEmployee]);
	    
    -- Добавить подразделения, в которых сотрудник руководитель.
    allMyRecipients := array_cat(allMyRecipients, array(
    select r.Id
        from Sungero_Core_Recipient r
        where r.Manager_Company_Sungero = currentEmployee
        and not exists (select 1 from unnest(allMyRecipients) dd where dd = r.Id)));
    
	
    -- Поднять вверх по иерархии до головных подразделений. 
    while ((select count(1) from unnest(allMyRecipients)) <> allMyRecipientsCount) loop
    begin
	    allMyRecipientsCount = (select count(1) from unnest(allMyRecipients));

	    -- Вверх по RecipientLink
        allMyRecipients := array_cat(allMyRecipients, array(
        select distinct l.Recipient
          from Sungero_Core_RecipientLink l
          join unnest(allMyRecipients) d
            on d = l.Member
          where not exists (select 1 from unnest(allMyRecipients) dd where dd = l.Recipient)));

		-- Вверх по Parent
        allMyRecipients := array_cat(allMyRecipients, array(
        select distinct r.Parent
          from Sungero_Core_Recipient r
          join unnest(allMyRecipients) d
            on d= r.Id
          where r.Parent is not null
            and not exists (select 1 from unnest(allMyRecipients) dd where dd = r.Parent)));

		-- Вверх по HeadOffice (головные подразделение)
        allMyRecipients := array_cat(allMyRecipients, array(
        select distinct r.HeadOffice_Company_Sungero
          from Sungero_Core_Recipient r
          join unnest(allMyRecipients) d
            on d= r.Id
          where r.HeadOffice_Company_Sungero is not null
            and not exists (select 1 from unnest(allMyRecipients) dd where dd = r.HeadOffice_Company_Sungero)));

		-- Вверх по НОР
        allMyRecipients := array_cat(allMyRecipients, array(
        select distinct r.BusinessUnit_Company_Sungero
          from Sungero_Core_Recipient r
          join unnest(allMyRecipients) d
            on d= r.Id
          where r.BusinessUnit_Company_Sungero is not null
            and not exists (select 1 from unnest(allMyRecipients) dd where dd = r.BusinessUnit_Company_Sungero)));

    end;
	end loop;
    
    -- Добавить НОРы, в которых сотрудник руководитель.
    allMyRecipients := array_cat(allMyRecipients, array(
    select r.Id
      from Sungero_Core_Recipient r
      where r.CEO_Company_Sungero = currentEmployee
        and not exists (select 1 from unnest(allMyRecipients) bb where bb = r.Id)));

    -- Добавить Всех пользователей
	allMyRecipients := array_cat(allMyRecipients, array(
	select Id from Sungero_Core_Recipient
	 where Sid = '440103EA-A766-47A8-98AD-5260CA32DE46' limit 1));

  return query select * from unnest(allMyRecipients);
end;
$body$;]]></postgres>
  </query>
  <query key="CreateProcedureGetAllVisibleRecipients">
    <mssql><![CDATA[if exists (select * from sys.objects WHERE type = 'P' AND name = '{0}')
  drop procedure {0};
exec('
create procedure {0}
  @recipientId int,
  @resultRecipientsTypeGuid uniqueidentifier
as
begin
  set nocount on
  
  create table #headRecipients (Id int primary key clustered)
  create table #ruleRecipients (Id int, ruleId int, primary key clustered (Id, ruleId))
  create table #EmployeeRules (Id int, ruleId int)
  create table #ExcudeEmployeeRules (Id int, ruleId int)
  create table #rules (Id int primary key clustered)
  create table #ruleExcludeRecipients (Id int, ruleId int, primary key clustered (Id, ruleId))
  
  declare @ruleRecipientsCount int = 0
  declare @ruleExcludeRecipientsCount int = 0
  create table  #rulestepRecipients (Id int, ruleId int)
  
  -- Разворачиваем вышестоящие группы.
  insert into #headRecipients (Id) 
    exec Sungero_Company_GetHeadRecipientsByEmployee @recipientId
  
  -- Добавляем моноправило с ид = 0.
  insert into #ruleRecipients
    select distinct h.Id, 0
      from #headRecipients h
      join Sungero_Core_Recipient r
        on r.Id = h.Id
      where r.Discriminator in (''EFF95720-181F-4F7D-892D-DEC034C7B2AB'', ''61B1C19F-26E2-49A5-B3D3-0D3618151E12'')
  
  -- Исключить "невидимок".
  insert into #ruleExcludeRecipients
    select distinct e.Recipient, 0 
      from Sungero_Company_VSHidden e
      where e.Recipient != @recipientId
    order by e.Recipient 
  
  insert into #rules
    select distinct vr.Id
      from Sungero_Company_VisibRule vr
      join Sungero_Company_RuleRecipients r
        on r.VisibRule = vr.Id
      join #headRecipients h
        on h.Id = r.Recipient
      where vr.Status = ''Active''
  
  -- Подгружаем правила видимости.
  insert into #ruleRecipients
    select distinct v.Recipient, v.VisibRule 
      from Sungero_Company_RuleVisblMembs v
      join #rules r
        on r.Id = v.VisibRule
    order by v.Recipient, v.VisibRule
  
  -- Подгружаем исключения из правил видимости.
  insert into #ruleExcludeRecipients
    select distinct e.Recipient, e.VisibRule 
      from Sungero_Company_RuleExcldMembs e
      join #rules r
        on r.Id = e.VisibRule
    order by e.Recipient, e.VisibRule  
  
  -- В цикле разворачиваем до конечных групп.
  while (select count(1) from #ruleRecipients) <> @ruleRecipientsCount
  begin
    set @ruleRecipientsCount = (select count(1) from #ruleRecipients)
  
    -- RecipientLinks.
    insert into #rulestepRecipients
      select l.Member, rr.ruleId
        from Sungero_Core_RecipientLink l
        join #ruleRecipients rr
          on l.Recipient = rr.Id
        join Sungero_Core_Recipient r
          on l.Member = r.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
       
    -- Parent.  
    insert into #rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join #ruleRecipients rr
          on r.Parent = rr.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
    
    -- НОР. 
    insert into #rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join #ruleRecipients rr
          on r.BusinessUnit_Company_Sungero = rr.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
  
    -- Подчиненные подразделения. 
    insert into #rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join #ruleRecipients rr
          on r.HeadOffice_Company_Sungero = rr.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
    
    insert into #ruleRecipients
      select distinct Id, ruleId
        from #rulestepRecipients rs
        where not exists (select 1 from #ruleRecipients rr where rr.Id = rs.Id and rr.ruleId = rs.ruleId)
  
    delete from #rulestepRecipients
  end
  
  
  while (select count(1) from #ruleExcludeRecipients) <> @ruleExcludeRecipientsCount
  begin
    set @ruleExcludeRecipientsCount = (select count(1) from #ruleExcludeRecipients)
  
    -- RecipientLinks.
    insert into #rulestepRecipients
      select l.Member, rr.ruleId
        from Sungero_Core_RecipientLink l
        join #ruleExcludeRecipients rr
          on l.Recipient = rr.Id
        join Sungero_Core_Recipient r
         on l.Member = r.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
       
    -- Parent.  
    insert into #rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join #ruleExcludeRecipients rr
          on r.Parent = rr.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
    
    -- НОР.
    insert into #rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join #ruleExcludeRecipients rr
          on r.BusinessUnit_Company_Sungero = rr.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
  
    -- Подчиненные подразделения.
    insert into #rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join #ruleExcludeRecipients rr
          on r.HeadOffice_Company_Sungero = rr.Id
        where r.Discriminator <> ''B7905516-2BE5-4931-961C-CB38D5677565''
    
    insert into #ruleExcludeRecipients
      select distinct Id, ruleId
        from #rulestepRecipients rs
        where not exists (select 1 from #ruleExcludeRecipients rr where rr.Id = rs.Id and rr.ruleId = rs.ruleId)
  
    delete from #rulestepRecipients
  end
  
  -- Если запрашивали только НОР или подразделения, то разворачивать не нужно.
  if (@resultRecipientsTypeGuid = ''EFF95720-181F-4F7D-892D-DEC034C7B2AB'' or @resultRecipientsTypeGuid = ''61B1C19F-26E2-49A5-B3D3-0D3618151E12'')
  begin
    select distinct rr.Id
      from #ruleRecipients rr
      join Sungero_Core_Recipient r
        on r.Id = rr.Id
      where r.Discriminator = @resultRecipientsTypeGuid
        and not exists (select 1 from #ruleExcludeRecipients e where e.Id = rr.Id and e.ruleId = rr.RuleId)
  end
  else
  begin  
    declare @AllRecipientsId int = (select t.Id from Sungero_Core_Recipient t where t.Sid = ''440103EA-A766-47A8-98AD-5260CA32DE46'') 
  
    insert into #EmployeeRules
      select l.Member as Id, rr.RuleId as RuleId
        from Sungero_Core_RecipientLink l
        join #ruleRecipients rr
          on rr.Id = l.Recipient
        join Sungero_Core_Recipient r
          on r.Id = l.Member
        where r.Discriminator = @resultRecipientsTypeGuid
  
    insert into #EmployeeRules
      select rr.Id as Id, rr.RuleId as RuleId
        from #ruleRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Discriminator = @resultRecipientsTypeGuid
    
    insert into #EmployeeRules
      select r.Manager_Company_Sungero as Id, rr.RuleId as RuleId
        from #ruleRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Manager_Company_Sungero is not null
      
    insert into #EmployeeRules
      select r.CEO_Company_Sungero as Id, rr.RuleId as RuleId
        from #ruleRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.CEO_Company_Sungero is not null
      
    if exists (select 1 from #ruleRecipients where Id = @AllRecipientsId)
    begin
      insert into #EmployeeRules  
        select r.Id as Id, rr.RuleId as RuleId
          from #ruleRecipients rr
          join Sungero_Core_Recipient r
            on rr.Id = @AllRecipientsId
          where r.Discriminator = ''B7905516-2BE5-4931-961C-CB38D5677565''
    end
  
    insert into #ExcudeEmployeeRules
      select l.Member as Id, rr.RuleId as RuleId
        from Sungero_Core_RecipientLink l
        join #ruleExcludeRecipients rr
          on rr.Id = l.Recipient
        join Sungero_Core_Recipient r
          on r.Id = l.Member
        where r.Discriminator = @resultRecipientsTypeGuid
    
    insert into #ExcudeEmployeeRules
      select rr.Id as Id, rr.RuleId as RuleId
        from #ruleExcludeRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Discriminator = @resultRecipientsTypeGuid
     
    insert into #ExcudeEmployeeRules
      select r.Manager_Company_Sungero as Id, rr.RuleId as RuleId
        from #ruleExcludeRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Manager_Company_Sungero is not null
          
    insert into #ExcudeEmployeeRules
      select r.CEO_Company_Sungero as Id, rr.RuleId as RuleId
        from #ruleExcludeRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.CEO_Company_Sungero is not null
     
    if exists (select 1 from #ruleExcludeRecipients where Id = @AllRecipientsId)
    begin
      insert into #ExcudeEmployeeRules
        select r.Id as Id, rr.RuleId as RuleId
          from #ruleExcludeRecipients rr
          join Sungero_Core_Recipient r
            on rr.Id  = @AllRecipientsId
          where r.Discriminator = ''B7905516-2BE5-4931-961C-CB38D5677565''
    end
  
    select distinct em.Id
      from #EmployeeRules em
      where not exists (select 1 from #ExcudeEmployeeRules ex where ex.Id = em.Id and ex.RuleId = em.RuleId)
       
  end

end')]]></mssql>
    <postgres><![CDATA[create or replace function public.{0}(
	  recipientid integer,
	  resultrecipientstypeguid uuid)
    returns setof integer 
    language 'plpgsql'
as $body$
declare 
  ruleRecipientsCount integer = 0;
  ruleExcludeRecipientsCount integer = 0;
  AllRecipientsId integer; 
begin	
  create temp table headRecipients (Id int primary key);
  create temp table ruleRecipients (Id int, ruleId int, primary key (Id, ruleId));
  create temp table EmployeeRules (Id int, ruleId int);
  create temp table ExcudeEmployeeRules (Id int, ruleId int);
  create temp table rules (Id int primary key);
  create temp table ruleExcludeRecipients (Id int, ruleId int, primary key (Id, ruleId)); 
  create temp table rulestepRecipients (Id int, ruleId int);
  
  -- Разворачиваем вышестоящие группы.
  insert into headRecipients
    select * from {1}(recipientid);
  
  -- Добавляем моноправило с ид = 0.
  insert into ruleRecipients
    select distinct h.Id, 0
      from headRecipients h
      join Sungero_Core_Recipient r
        on r.Id = h.Id
      where r.Discriminator in ('EFF95720-181F-4F7D-892D-DEC034C7B2AB', '61B1C19F-26E2-49A5-B3D3-0D3618151E12');
  
  -- Исключить "невидимок".
  insert into ruleExcludeRecipients
    select distinct e.Recipient, 0 
      from Sungero_Company_VSHidden e
      where e.Recipient != recipientid
    order by e.Recipient;
  
  insert into rules
    select distinct vr.Id
      from Sungero_Company_VisibRule vr
      join Sungero_Company_RuleRecipients r
        on r.VisibRule = vr.Id
      join headRecipients h
        on h.Id = r.Recipient
      where vr.Status = 'Active';
  
  -- Подгружаем правила видимости.
  insert into ruleRecipients
    select distinct v.Recipient, v.VisibRule 
      from Sungero_Company_RuleVisblMembs v
      join rules r
        on r.Id = v.VisibRule
    order by v.Recipient, v.VisibRule;
  
  -- Подгружаем исключения из правил видимости.
  insert into ruleExcludeRecipients
    select distinct e.Recipient, e.VisibRule 
      from Sungero_Company_RuleExcldMembs e
      join rules r
        on r.Id = e.VisibRule
    order by e.Recipient, e.VisibRule;  
  
  -- В цикле разворачиваем до конечных групп.
  while ((select count(1) from ruleRecipients) <> ruleRecipientsCount) loop
  begin
    ruleRecipientsCount = (select count(1) from ruleRecipients);
  
    -- RecipientLinks.
    insert into rulestepRecipients
      select l.Member, rr.ruleId
        from Sungero_Core_RecipientLink l
        join ruleRecipients rr
          on l.Recipient = rr.Id
        join Sungero_Core_Recipient r
          on l.Member = r.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
       
    -- Parent.  
    insert into rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join ruleRecipients rr
          on r.Parent = rr.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
    
    -- НОР. 
    insert into rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join ruleRecipients rr
          on r.BusinessUnit_Company_Sungero = rr.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
  
    -- Подчиненные подразделения. 
    insert into rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join ruleRecipients rr
          on r.HeadOffice_Company_Sungero = rr.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
    
    insert into ruleRecipients
      select distinct Id, ruleId
        from rulestepRecipients rs
        where not exists (select 1 from ruleRecipients rr where rr.Id = rs.Id and rr.ruleId = rs.ruleId);
  
    delete from rulestepRecipients;
  end;
  end loop;
  
  
  while ((select count(1) from ruleExcludeRecipients) <> ruleExcludeRecipientsCount) loop
    ruleExcludeRecipientsCount = (select count(1) from ruleExcludeRecipients);
  
    -- RecipientLinks.
    insert into rulestepRecipients
      select l.Member, rr.ruleId
        from Sungero_Core_RecipientLink l
        join ruleExcludeRecipients rr
          on l.Recipient = rr.Id
        join Sungero_Core_Recipient r
         on l.Member = r.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
       
    -- Parent.  
    insert into rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join ruleExcludeRecipients rr
          on r.Parent = rr.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
    
    -- НОР.
    insert into rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join ruleExcludeRecipients rr
          on r.BusinessUnit_Company_Sungero = rr.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
  
    -- Подчиненные подразделения.
    insert into rulestepRecipients
      select r.Id, rr.ruleId
        from Sungero_Core_Recipient r
        join ruleExcludeRecipients rr
          on r.HeadOffice_Company_Sungero = rr.Id
        where r.Discriminator <> 'B7905516-2BE5-4931-961C-CB38D5677565';
    
    insert into ruleExcludeRecipients
      select distinct Id, ruleId
        from rulestepRecipients rs
        where not exists (select 1 from ruleExcludeRecipients rr where rr.Id = rs.Id and rr.ruleId = rs.ruleId);
  
    delete from rulestepRecipients;
  end loop;
  
  -- Если запрашивали только НОР или подразделения, то разворачивать не нужно.
  if (resultRecipientsTypeGuid = 'EFF95720-181F-4F7D-892D-DEC034C7B2AB' or resultRecipientsTypeGuid = '61B1C19F-26E2-49A5-B3D3-0D3618151E12')
  then
    return query select distinct rr.Id
      from ruleRecipients rr
      join Sungero_Core_Recipient r
        on r.Id = rr.Id
      where r.Discriminator = resultRecipientsTypeGuid
        and not exists (select 1 from ruleExcludeRecipients e where e.Id = rr.Id and e.ruleId = rr.RuleId);
  else
  begin  
    AllRecipientsId = (select t.Id from Sungero_Core_Recipient t where t.Sid = '440103EA-A766-47A8-98AD-5260CA32DE46');
  
    insert into EmployeeRules
      select l.Member as Id, rr.RuleId as RuleId
        from Sungero_Core_RecipientLink l
        join ruleRecipients rr
          on rr.Id = l.Recipient
        join Sungero_Core_Recipient r
          on r.Id = l.Member
        where r.Discriminator = resultRecipientsTypeGuid;
  
    insert into EmployeeRules
      select rr.Id as Id, rr.RuleId as RuleId
        from ruleRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Discriminator = resultRecipientsTypeGuid;
    
    insert into EmployeeRules
      select r.Manager_Company_Sungero as Id, rr.RuleId as RuleId
        from ruleRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Manager_Company_Sungero is not null;
      
    insert into EmployeeRules
      select r.CEO_Company_Sungero as Id, rr.RuleId as RuleId
        from ruleRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.CEO_Company_Sungero is not null;
      
    if exists (select 1 from ruleRecipients where Id = AllRecipientsId)
	then
      insert into EmployeeRules  
        select r.Id as Id, rr.RuleId as RuleId
          from ruleRecipients rr
          join Sungero_Core_Recipient r
            on rr.Id = AllRecipientsId
          where r.Discriminator = 'B7905516-2BE5-4931-961C-CB38D5677565';
    end if;
  
    insert into ExcudeEmployeeRules
      select l.Member as Id, rr.RuleId as RuleId
        from Sungero_Core_RecipientLink l
        join ruleExcludeRecipients rr
          on rr.Id = l.Recipient
        join Sungero_Core_Recipient r
          on r.Id = l.Member
        where r.Discriminator = resultRecipientsTypeGuid;
    
    insert into ExcudeEmployeeRules
      select rr.Id as Id, rr.RuleId as RuleId
        from ruleExcludeRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Discriminator = resultRecipientsTypeGuid;
     
    insert into ExcudeEmployeeRules
      select r.Manager_Company_Sungero as Id, rr.RuleId as RuleId
        from ruleExcludeRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.Manager_Company_Sungero is not null;
          
    insert into ExcudeEmployeeRules
      select r.CEO_Company_Sungero as Id, rr.RuleId as RuleId
        from ruleExcludeRecipients rr
        join Sungero_Core_Recipient r
          on r.Id = rr.Id
        where r.CEO_Company_Sungero is not null;
     
    if exists (select 1 from ruleExcludeRecipients where Id = AllRecipientsId)
    then
      insert into ExcudeEmployeeRules
        select r.Id as Id, rr.RuleId as RuleId
          from ruleExcludeRecipients rr
          join Sungero_Core_Recipient r
            on rr.Id  = AllRecipientsId
          where r.Discriminator = 'B7905516-2BE5-4931-961C-CB38D5677565';
    end if;
  
    return query select distinct em.Id
      from EmployeeRules em
      where not exists (select 1 from ExcudeEmployeeRules ex where ex.Id = em.Id and ex.RuleId = em.RuleId);
       
  end;
  end if;
  drop table headrecipients;
  drop table rulerecipients;
  drop table employeerules;
  drop table excudeemployeerules;
  drop table rules;
  drop table ruleexcluderecipients; 
  drop table rulesteprecipients;  
end;
$body$;]]></postgres>
  </query>
  <query key="ExecuteStoredProcedure">
    <mssql><![CDATA[exec {0} {1}]]></mssql>
    <postgres><![CDATA[select {0}({1})]]></postgres>
  </query>
  <query key="CreateIndexForRecipientVisibility">
    <mssql><![CDATA[if (not exists (select 1 from sys.indexes
                where object_id = (select object_id from sys.objects where name = 'Sungero_Company_RuleExcldMembs')
                and name = 'idx_RuleExcldMembs_Recipient_VisibRule'))
begin
  create nonclustered index idx_RuleExcldMembs_Recipient_VisibRule ON Sungero_Company_RuleExcldMembs
  (
  	Recipient ASC
  )
  include (VisibRule) 
end;

if (not exists (select 1 from sys.indexes
                where object_id = (select object_id from sys.objects where name = 'Sungero_Company_RuleRecipients')
                and name = 'idx_RuleRecipients_Recipient_VisibRule'))
begin
  create nonclustered index idx_RuleRecipients_Recipient_VisibRule ON Sungero_Company_RuleRecipients
  (
  	Recipient ASC
  )
  include (VisibRule) 
end;

if (not exists (select 1 from sys.indexes
                where object_id = (select object_id from sys.objects where name = 'Sungero_Company_RuleVisblMembs')
                and name = 'idx_RuleVisblMembs_Recipient_VisibRule'))
begin
  create nonclustered index idx_RuleVisblMembs_Recipient_VisibRule ON Sungero_Company_RuleVisblMembs
  (
  	Recipient ASC
  )
  include (VisibRule) 
end;

if (not exists (select 1 from sys.indexes
                where object_id = (select object_id from sys.objects where name = 'Sungero_Company_VisibRule')
                and name = 'idx_VisibRule_Status_Id'))
begin
  create nonclustered index idx_VisibRule_Status_Id ON Sungero_Company_VisibRule
  (
  	Status ASC
  )
  include (Id) 
end;]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS  idx_RuleExcldMembs_Recipient_VisibRule ON Sungero_Company_RuleExcldMembs
  (
  	Recipient ASC,
  	VisibRule
  );

CREATE INDEX IF NOT EXISTS idx_RuleRecipients_Recipient_VisibRule ON Sungero_Company_RuleRecipients
  (
  	Recipient ASC,
  	VisibRule
  );

CREATE INDEX IF NOT EXISTS idx_RuleVisblMembs_Recipient_VisibRule ON Sungero_Company_RuleVisblMembs
  (
  	Recipient ASC,
  	VisibRule
  );

CREATE INDEX IF NOT EXISTS idx_VisibRule_Status_Id ON Sungero_Company_VisibRule
  (
  	Status ASC,
  	Id
  );]]></postgres>
  </query>
  <query key="CreateIndexDiscriminatorParentId">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  Discriminator,
  Parent
)
INCLUDE (Id)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0}
(
  Discriminator,
  Parent,
  Id
)]]></postgres>
  </query>
  <query key="CreateIndexDiscriminatorBusinessUnitId">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  Discriminator,
  BusinessUnit_Company_Sungero
)
INCLUDE (Id)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0}
(
  Discriminator,
  BusinessUnit_Company_Sungero,
  Id
)]]></postgres>
  </query>
  <query key="CreateIndexDiscriminatorHeadOfficeId">
    <mssql><![CDATA[CREATE NONCLUSTERED INDEX {1} ON {0}
(
  Discriminator,
  HeadOffice_Company_Sungero
)
INCLUDE (Id)]]></mssql>
    <postgres><![CDATA[CREATE INDEX IF NOT EXISTS {1} ON {0}
(
  Discriminator,
  HeadOffice_Company_Sungero,
  Id
)]]></postgres>
  </query>
</queries>