Delimiter $$
/**
 *  BUSINESS_COPY_LINKED_ACCOUNTS_ENTRIES
 * copie les ecritures des compte lié vers le compte principal
 */ 
Drop Procedure if Exists BUSINESS_COPY_LINKED_ACCOUNTS_ENTRIES $$
Create Procedure BUSINESS_COPY_LINKED_ACCOUNTS_ENTRIES(In refdate DateTime, In idaccounts Int unsigned)
Begin
	if refdate is null Then
		set refdate = AMO_BAL_REFDATE();
	End if ;

	Set @blae_bclae_withoutEntriesCopy = 1;

	-- pour eviter d'avoir une table temporaire ou une requeste constuite
	-- on utilise la permissivité de MySql pour avoir une peuseudo requete dynamique
	-- on va utilisé un like % ou l'id du compte pour filter les données
-- 	set @blae_accFilter = ifnull(idaccounts, '%');
    if idaccounts Is null Then
        Set @blae_accMinVal = 0;
        Set @blae_accMaxVal = 4e7;
    Else
        Set @blae_accMinVal = idaccounts;
        Set @blae_accMaxVal = idaccounts;
    End if;
--     Drop TEMPORARY TABLE IF Exists TMP_ENTRIES_has_ACCOUNTS_DBL_CHK;
--     Create TABLE TMP_ENTRIES_has_ACCOUNTS_DBL_CHK (
--         ENTRIES_ID_ENTRIES Int Unsigned Not Null
--         , ACCOUNTS_ID_ACCOUNTS Int Unsigned Not Null
--         , ENTRIES_ACC_EXT_REF Int Unsigned Not Null
--         , ENTRIES_PERMANENT_ATTACHEMENT SmallInt(5) Not Null
--     );



	Insert Into ENTRIES_has_ACCOUNTS(
-- 	Insert Into TMP_ENTRIES_has_ACCOUNTS_DBL_CHK(
		ENTRIES_ID_ENTRIES, ACCOUNTS_ID_ACCOUNTS, ENTRIES_ACC_EXT_REF, ENTRIES_PERMANENT_ATTACHEMENT
	)
	-- toutes les ecritures des compte lié
	-- non présent dans la table principal
	Select DISTINCT
		
		LNKED_ACC_ENT.ENTRIES_ID_ENTRIES
		, AHA.ACCOUNTS_ID_ACCOUNTS
		, LNKED_ACC_ENT.ENTRIES_ACC_EXT_REF
		, 0 ENTRIES_PERMANENT_ATTACHEMENT
-- 		, LNKED_ACC_ENT.ENTRIES_PERMANENT_ATTACHEMENT
	From
		ENTRIES_has_ACCOUNTS LNKED_ACC_ENT
		Inner Join ACCOUNTS_has_ACCOUNTS AHA
			On LNKED_ACC_ENT.ACCOUNTS_ID_ACCOUNTS = AHA.ACCOUNTS_ID_ACCOUNTS_LINK

	Where
        AHA.ACCOUNTS_ID_ACCOUNTS between @blae_accMinVal And @blae_accMaxVal
-- 		AHA.ACCOUNTS_ID_ACCOUNTS like @blae_accFilter -- ici like sur un int volontaire pour eviter une requete dynamique
		And LNKED_ACC_ENT.ENTRIES_ID_ENTRIES Not In (
			Select 
				MAIN_ACC_ENT.ENTRIES_ID_ENTRIES
			From
				ENTRIES_has_ACCOUNTS MAIN_ACC_ENT
				Inner Join ENTRIES ENT
					On ENT.ID_ENTRIES = MAIN_ACC_ENT.ENTRIES_ID_ENTRIES
			Where
				AHA.ACCOUNTS_ID_ACCOUNTS = MAIN_ACC_ENT.ACCOUNTS_ID_ACCOUNTS
				And LNKED_ACC_ENT.ENTRIES_ID_ENTRIES = MAIN_ACC_ENT.ENTRIES_ID_ENTRIES
				And ENT.ENTRIES_DATE <= refdate
		)
        -- test unicité ref unique ecriture
        And Not Exists (    
            Select 
				ENTEXTREFCHK.ENTRIES_ACC_EXT_REF
			From
				ENTRIES_has_ACCOUNTS ENTEXTREFCHK
			Where
				LNKED_ACC_ENT.ENTRIES_ACC_EXT_REF = ENTEXTREFCHK.ENTRIES_ACC_EXT_REF
            Limit 1
        )

		-- #8186
		-- test flag rapatriment automatique des ecritres
		And Coalesce(AHA.ACCOUNTS_has_ACCOUNTS_STATUS, 0) <> @blae_bclae_withoutEntriesCopy
	;

    
end $$
Delimiter ;

