Delimiter //
/**
 * move entreis reclaims from one entity to another
 * @author Armen
 */
Drop Procedure if Exists BUSINESS_ENTITIES_MOVE_RECLAIMS//

Create Procedure BUSINESS_ENTITIES_MOVE_RECLAIMS(
    In srcEntityId Int Unsigned
    , In tarEntityId Int Unsigned
    , In inTransaction smallint
)
Begin
    bemr_Main: begin
        Declare bemr_transactionStarted int default 0 ;
        DECLARE Exit HANDLER FOR SQLEXCEPTION
            Begin
                if bemr_transactionStarted  <> 0 then
                    rollback;
                    set bemr_transactionStarted  = 0;
                End if;
                resignal;
            end ;
        if Coalesce(inTransaction, 0) = 0 Then
            Start Transaction;
            Set bemr_transactionStarted  = 1;
        else
            Set bemr_transactionStarted  = 0;
        end if;

        Set @bemr_srcEntityId = srcEntityId;
        Set @bemr_tarEntityId = tarEntityId;
#
        bemr_reclaim: BEGIN
            -- explain
            Update
                RECLAIMS_DETAILS tar
                Inner Join RECLAIMS rc
                    On tar.RECLAIMS_ID_RECLAIMS = rc.ID_RECLAIMS
                Inner Join ACCOUNTS acc1
                    On rc.ACCOUNTS_ID_ACCOUNTS = acc1.ID_ACCOUNTS
                Inner Join ENTRIES_has_ACCOUNTS eha
                    On tar.ENTRIES_ID_ENTRIES = eha.ENTRIES_ID_ENTRIES
                    And eha.ENTRIES_PERMANENT_ATTACHEMENT = 1
                Inner Join ACCOUNTS acc2
                    On eha.ACCOUNTS_ID_ACCOUNTS = acc2.ID_ACCOUNTS
                Inner Join DF_RECLAIMS srcrc
                    On tar.DF_RCLM_ID_DF_RCLM = srcrc.ID_DF_RECLAIMS
                Inner Join DF_RECLAIMS_STATUS srcst
                    On tar.DF_RCLM_STT_ID_DF_RCLM_STT = srcst.ID_DF_RECLAIMS_STATUS
            Set
                tar.DF_RCLM_STT_ID_DF_RCLM_STT = (
                        Select tarst.ID_DF_RECLAIMS_STATUS
                        From DF_RECLAIMS_STATUS tarst
                        Where tarst.ENTITIES_ID_ENTITIES = @bemr_tarEntityId
                            And tarst.DF_RECLAIMS_STATUS_CODE = srcst.DF_RECLAIMS_STATUS_CODE
                        Limit 1
                    )
                , tar.DF_RCLM_ID_DF_RCLM = (
                       Select tarrc.ID_DF_RECLAIMS
                       From DF_RECLAIMS tarrc
                       Where tarrc.ENTITIES_ID_ENTITIES = @bemr_tarEntityId
                           And tarrc.DF_RECLAIMS_CODE = srcrc.DF_RECLAIMS_CODE
                       Limit 1
                   )
            Where
                @bemr_srcEntityId  In (acc1.ENTITIES_ID_ENTITIES, acc2.ENTITIES_ID_ENTITIES)
            ;
        end ;
        if(bemr_transactionStarted <> 0 ) Then
            -- pour dev / debug
#             rollback ;
            commit;
            Set bemr_transactionStarted = 0;
        End if;


    end ;
End //
Delimiter ;