Delimiter //
/**
 * Author:  armen
 * Created: 26 juil. 2017
 * renvoi l'id de compte avec permenant attachement = 1 
 * des écritures qui correspondent à la référence fournis
 * on prend de préférence les écriture au débit (factures) la plus ancienne
 */

drop function if exists CASH_BUSINESS_FIND_ACCOUNTS_WITH_ENTRIES_REF //

Create Function CASH_BUSINESS_FIND_ACCOUNTS_WITH_ENTRIES_REF(
		entries_ref varchar(60)
		, id_entities Int unsigned
	)
	returns Int unsigned
Begin
	return (
			Select
				acc.ID_ACCOUNTS
			From
				ACCOUNTS acc
				Inner Join ENTRIES_has_ACCOUNTS eha 
					On acc.ID_ACCOUNTS = eha.ACCOUNTS_ID_ACCOUNTS
                    AND ENTRIES_PERMANENT_ATTACHEMENT = 1
				Inner Join ENTRIES ent
					On ent.ID_ENTRIES = eha.ENTRIES_ID_ENTRIES
			Where
				acc.ENTITIES_ID_ENTITIES = id_entities
				And ent.ENTRIES_REF = entries_ref
				And eha.ENTRIES_PERMANENT_ATTACHEMENT = 1
			Order By
				ent.ENTRIES_DATE, ent.ENTRIES_ENT_CREDIT 
			Limit 1
		)
	;
End //
Delimiter ;