--liquibase formatted sql
-- This code generated was by RbacViewPostgresGenerator at 2024-03-15T17:17:00.864301165.


-- ============================================================================
--changeset hs-office-relation-rbac-OBJECT:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRelatedRbacObject('hs_office_relation');
--//


-- ============================================================================
--changeset hs-office-relation-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacRoleDescriptors('hsOfficeRelation', 'hs_office_relation');
--//


-- ============================================================================
--changeset hs-office-relation-rbac-insert-trigger:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

/*
    Creates the roles, grants and permission for the AFTER INSERT TRIGGER.
 */

create or replace procedure buildRbacSystemForHsOfficeRelation(
    NEW hs_office_relation
)
    language plpgsql as $$

declare
    newHolderPerson hs_office_person;
    newAnchorPerson hs_office_person;
    newContact hs_office_contact;

begin
    call enterTriggerForObjectUuid(NEW.uuid);

    select * from hs_office_person as p where p.uuid = NEW.holderUuid    INTO newHolderPerson;
    assert newHolderPerson.uuid is not null, format('newHolderPerson must not be null for NEW.holderUuid = %s', NEW.holderUuid);

    select * from hs_office_person as p where p.uuid = NEW.anchorUuid    INTO newAnchorPerson;
    assert newAnchorPerson.uuid is not null, format('newAnchorPerson must not be null for NEW.anchorUuid = %s', NEW.anchorUuid);

    select * from hs_office_contact as c where c.uuid = NEW.contactUuid    INTO newContact;
    assert newContact.uuid is not null, format('newContact must not be null for NEW.contactUuid = %s', NEW.contactUuid);


    perform createRoleWithGrants(
        hsOfficeRelationOwner(NEW),
            permissions => array['DELETE'],
            incomingSuperRoles => array[globalAdmin()],
            userUuids => array[currentUserUuid()]
    );

    perform createRoleWithGrants(
        hsOfficeRelationAdmin(NEW),
            permissions => array['UPDATE'],
            incomingSuperRoles => array[
            	hsOfficeRelationOwner(NEW),
            	hsOfficePersonAdmin(newAnchorPerson)]
    );

    perform createRoleWithGrants(
        hsOfficeRelationAgent(NEW),
            incomingSuperRoles => array[
            	hsOfficePersonAdmin(newHolderPerson),
            	hsOfficeRelationAdmin(NEW)]
    );

    perform createRoleWithGrants(
        hsOfficeRelationTenant(NEW),
            permissions => array['SELECT'],
            incomingSuperRoles => array[
            	hsOfficeRelationAgent(NEW),
            	hsOfficeContactAdmin(newContact),
            	hsOfficePersonAdmin(newHolderPerson)],
            outgoingSubRoles => array[
            	hsOfficeContactReferrer(newContact),
            	hsOfficePersonReferrer(newHolderPerson),
            	hsOfficePersonReferrer(newAnchorPerson)]
    );

    call leaveTriggerForObjectUuid(NEW.uuid);
end; $$;

/*
    AFTER INSERT TRIGGER to create the role+grant structure for a new hs_office_relation row.
 */

create or replace function insertTriggerForHsOfficeRelation_tf()
    returns trigger
    language plpgsql
    strict as $$
begin
    call buildRbacSystemForHsOfficeRelation(NEW);
    return NEW;
end; $$;

create trigger insertTriggerForHsOfficeRelation_tg
    after insert on hs_office_relation
    for each row
execute procedure insertTriggerForHsOfficeRelation_tf();
--//


-- ============================================================================
--changeset hs-office-relation-rbac-update-trigger:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

/*
    Called from the AFTER UPDATE TRIGGER to re-wire the grants.
 */

create or replace procedure updateRbacRulesForHsOfficeRelation(
    OLD hs_office_relation,
    NEW hs_office_relation
)
    language plpgsql as $$

declare
    oldHolderPerson hs_office_person;
    newHolderPerson hs_office_person;
    oldAnchorPerson hs_office_person;
    newAnchorPerson hs_office_person;
    oldContact hs_office_contact;
    newContact hs_office_contact;

begin
    call enterTriggerForObjectUuid(NEW.uuid);

    select * from hs_office_person as p where p.uuid = OLD.holderUuid    INTO oldHolderPerson;
    assert oldHolderPerson.uuid is not null, format('oldHolderPerson must not be null for OLD.holderUuid = %s', OLD.holderUuid);

    select * from hs_office_person as p where p.uuid = NEW.holderUuid    INTO newHolderPerson;
    assert newHolderPerson.uuid is not null, format('newHolderPerson must not be null for NEW.holderUuid = %s', NEW.holderUuid);

    select * from hs_office_person as p where p.uuid = OLD.anchorUuid    INTO oldAnchorPerson;
    assert oldAnchorPerson.uuid is not null, format('oldAnchorPerson must not be null for OLD.anchorUuid = %s', OLD.anchorUuid);

    select * from hs_office_person as p where p.uuid = NEW.anchorUuid    INTO newAnchorPerson;
    assert newAnchorPerson.uuid is not null, format('newAnchorPerson must not be null for NEW.anchorUuid = %s', NEW.anchorUuid);

    select * from hs_office_contact as c where c.uuid = OLD.contactUuid    INTO oldContact;
    assert oldContact.uuid is not null, format('oldContact must not be null for OLD.contactUuid = %s', OLD.contactUuid);

    select * from hs_office_contact as c where c.uuid = NEW.contactUuid    INTO newContact;
    assert newContact.uuid is not null, format('newContact must not be null for NEW.contactUuid = %s', NEW.contactUuid);


    if NEW.contactUuid <> OLD.contactUuid then

        call revokeRoleFromRole(hsOfficeRelationTenant(OLD), hsOfficeContactAdmin(oldContact));
        call grantRoleToRole(hsOfficeRelationTenant(NEW), hsOfficeContactAdmin(newContact));

        call revokeRoleFromRole(hsOfficeContactReferrer(oldContact), hsOfficeRelationTenant(OLD));
        call grantRoleToRole(hsOfficeContactReferrer(newContact), hsOfficeRelationTenant(NEW));

    end if;

    call leaveTriggerForObjectUuid(NEW.uuid);
end; $$;

/*
    AFTER INSERT TRIGGER to re-wire the grant structure for a new hs_office_relation row.
 */

create or replace function updateTriggerForHsOfficeRelation_tf()
    returns trigger
    language plpgsql
    strict as $$
begin
    call updateRbacRulesForHsOfficeRelation(OLD, NEW);
    return NEW;
end; $$;

create trigger updateTriggerForHsOfficeRelation_tg
    after update on hs_office_relation
    for each row
execute procedure updateTriggerForHsOfficeRelation_tf();
--//


-- ============================================================================
--changeset hs-office-relation-rbac-INSERT:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

/*
    Creates INSERT INTO hs_office_relation permissions for the related hs_office_person rows.
 */
do language plpgsql $$
    declare
        row hs_office_person;
        permissionUuid uuid;
        roleUuid uuid;
    begin
        call defineContext('create INSERT INTO hs_office_relation permissions for the related hs_office_person rows');

        FOR row IN SELECT * FROM hs_office_person
            LOOP
                roleUuid := findRoleId(hsOfficePersonAdmin(row));
                permissionUuid := createPermission(row.uuid, 'INSERT', 'hs_office_relation');
                call grantPermissionToRole(permissionUuid, roleUuid);
            END LOOP;
    END;
$$;

/**
    Adds hs_office_relation INSERT permission to specified role of new hs_office_person rows.
*/
create or replace function hs_office_relation_hs_office_person_insert_tf()
    returns trigger
    language plpgsql
    strict as $$
begin
    call grantPermissionToRole(
            createPermission(NEW.uuid, 'INSERT', 'hs_office_relation'),
            hsOfficePersonAdmin(NEW));
    return NEW;
end; $$;

create trigger z_hs_office_relation_hs_office_person_insert_tg
    after insert on hs_office_person
    for each row
execute procedure hs_office_relation_hs_office_person_insert_tf();

/**
    Checks if the user or assumed roles are allowed to insert a row to hs_office_relation.
*/
create or replace function hs_office_relation_insert_permission_missing_tf()
    returns trigger
    language plpgsql as $$
begin
    if ( not hasInsertPermission(
        ( SELECT anchorPerson.uuid FROM

            (select * from hs_office_person as p where p.uuid = NEW.anchorUuid) AS anchorPerson

        ), 'INSERT', 'hs_office_relation') ) then
            raise exception
                '[403] insert into hs_office_relation not allowed for current subjects % (%)',
                currentSubjects(), currentSubjectsUuids();
    end if;
    return NEW;
end; $$;

create trigger hs_office_relation_insert_permission_check_tg
    before insert on hs_office_relation
    for each row
        execute procedure hs_office_relation_insert_permission_missing_tf();
--//

-- ============================================================================
--changeset hs-office-relation-rbac-IDENTITY-VIEW:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

call generateRbacIdentityViewFromProjection('hs_office_relation', $idName$
         (select idName from hs_office_person_iv p where p.uuid = anchorUuid)
     || '-with-' || target.type || '-'
     || (select idName from hs_office_person_iv p where p.uuid = holderUuid)

    $idName$);
--//

-- ============================================================================
--changeset hs-office-relation-rbac-RESTRICTED-VIEW:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacRestrictedView('hs_office_relation',
    $orderBy$
        (select idName from hs_office_person_iv p where p.uuid = target.holderUuid)
    $orderBy$,
    $updates$
                contactUuid = new.contactUuid
    $updates$);
--//

