Delimiter //
/**
*/
Drop Procedure if exists LOADER_EDMINDEX_SUMMARIES_INSERT//

Create Procedure LOADER_EDMINDEX_SUMMARIES_INSERT (
    In batchnum int
)
Begin
	Set @dfSumCode = 'AGED-C';
	Set @admin = GET_LOADER_INFO('ID_ADMIN_PARAMS', batchnum);
	Set @dfSummaries = (Select ID_DF_SUMMARIES From DF_SUMMARIES Where ADMIN_ID_ADMIN = @admin  and DF_SUMMARIES_CODE = @dfSumCode);
	Set @dfPriority = (Select DF_PRIORITY_ID_DF_PRIORITY From DF_SUMMARIES Where ADMIN_ID_ADMIN = @admin  and DF_SUMMARIES_CODE = @dfSumCode);

	Set @IdMEmber  = (Select ID_MEMBERS From MEMBERS Where UNIVERS_ID_UNIVERS = @admin And MEMBERS_ADMIN_RIGHTS = 1 and MEMBERS_LOGIN like '%batch%' limit 1);
	if @IdMEmber Is Null Then
		Set @IdMEmber  = (Select ID_MEMBERS From MEMBERS Where UNIVERS_ID_UNIVERS = @admin And MEMBERS_ADMIN_RIGHTS = 1 limit 1);
	End if;

-- 	/*
-- 	Set @IdMEmber  = (Select ID_MEMBERS From MEMBERS Where UNIVERS_ID_UNIVERS = @admin And MEMBERS_ADMIN_RIGHTS = 1 and MEMBERS_LOGIN like '%batch%' );
-- 	if @IdMEmber Is Null Then
-- 		(Select ID_MEMBERS From MEMBERS Where UNIVERS_ID_UNIVERS = @admin And MEMBERS_ADMIN_RIGHTS = 1 );
-- 	End if;
-- 	*/
-- 
		Insert Into SUMMARIES (
            ACCOUNTS_ID_ACCOUNTS, ENTRIES_ID_ENTRIES, RECLAIMS_ID_RECLAIMS, DF_SUMMARIES_ID_DF_SUMMR
			, DF_PRIORITY_ID_DF_PRIORITY, SUMMARIES_MEMBER_AUTHOR, SUMMARIES_DATE, SUMMARIES_SUBJECT
			, SUMMARIES_COMMENTS, SUMMARIES_OUTSTANDING, SUMMARIES_OVERDUE 
        )
        Select
			src.ACCOUNTS_ID_ACCOUNTS, LEEHD.ENTRIES_ID_ENTRIES, null, @dfSummaries
			, @dfPriority, @IdMEmber, curdate(), null
			, null, null, null
			
        From
                LOADER_EDMINDEX src  
                Inner Join LOADER_STATUS lst  
                    On src.LOADER_STATUS_ID_LOADER_STATUS = lst.ID_LOADER_STATUS  
				Left Join LOADER_EDMINDEX_ENTRIES_HAS_DOCUMENTS LEEHD
					On lst.ID_LOADER_STATUS = LEEHD.LOADER_STATUS_ID_LOADER_STATUS
--         Select
-- 			src.ACCOUNTS_ID_ACCOUNTS, null, null, @dfSummaries
-- 			, @dfPriority, null, curdate(), null
-- 			, null, null, null
-- 			
--         From
--                 LOADER_EDMINDEX src  
--                 Inner Join LOADER_STATUS lst  
--                     On src.LOADER_STATUS_ID_LOADER_STATUS = lst.ID_LOADER_STATUS  

        Where 1 = 1  
            And lst.LOADER_STATUS_ERRCOUNT = 0  
            And lst.LOADER_STATUS_BATCH_NUM = batchnum
            And Coalesce(src.ID_DOCUMENTS_NEW, 0) <> 0 
        ;
End //

Delimiter ;