Delimiter //
/**
    In batchnum Int : num du lot
*/

Drop Procedure if exists LOADER_SUMMARIES_SUMMARIES_INSERT//

Create Procedure LOADER_SUMMARIES_SUMMARIES_INSERT (
    In batchnum int
)
Begin

	-- @todo créer un P.S de mappage

	Set @lssi_idAdminParams = GET_LOADER_INFO('ID_ADMIN_PARAMS', batchnum);

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


	-- insertion
	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 Distinct
		ARD.ACCOUNTS_ID_ACCOUNTS, ARD.ENTRIES_ID_ENTRIES, NULL AS ID_RECLAIMS
		, ARD.DF_SUMMARIES_ID_DF_SUMMR, ARD.DF_PRIORITY_ID_DF_PRIORITY
		, @lssi_IdMEmber AS ID_MEMBERS, Coalesce(ARD.SUMMARIES_DATE, now()) SUMDATE
		, ARD.SUMMARIES_SUBJECT, ARD.SUMMARIES_COMMENTS
		, ARD.SUMMARIES_OUTSTANDING, ARD.SUMMARIES_OVERDUE
    From LOADER_STATUS S
        Inner Join
            LOADER_SUMMARIES ARD
            On ARD.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
    Where 
        S.LOADER_STATUS_BATCH_NUM = batchnum
        AND S.LOADER_STATUS_ERRCOUNT = 0
		And ARD.ID_SUMMARIES Is Null
    ;
End //

Delimiter ;
