SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE procedure [dbo].[p_acc_transaction_delete_aco]
	@transaction_id int
as 

	set nocount on;

	/*

	DGE

	Suppression d'une transaction de type Aco.


	Vérifications:
	- on vérifie que la transaction est de type Aco;
	- on vérifie que l'acompte n'est pas repris (le trigger bloque la suppression des ces acomptes)

	Actions:
	- supprimer la ligne de transaction
	- supprimer l'acompte associé à cette transaction

	*/

	-- type != Aco
	if exists	(
				select	1
				from	acc_transactions
				where	atrn_transaction_id = @transaction_id
				and		isnull(atrn_type_code, '') != 'aco' )
	begin
		
		raiserror('Transaction type != ACO.', 16,1)
		return

	end

	-- identification de l'acompte
	declare		@advance_id	int

	select	@advance_id = adv.a_account_id
	from	acc_transactions trn
			inner join acc_accounts a		on	a.a_account_id = trn.atrn_transaction_id

			inner join vw_acc_advances adv	on	adv.a_actor_id = a.a_actor_id
											and	adv.adv_lettering = a.a_lettering
	where	trn.atrn_transaction_id = @transaction_id

		
	-- vérifier que l'acompte n'est pas repris	
	if exists	(
				select	1
				from	acc_advances
				where	adv_advance_id = @advance_id
				and		adv_taken != 0 )
	begin
		
		raiserror('Transaction linked to a taken advance.', 16,1)
		return

	end


	-- action
	delete	acc_advances where adv_advance_id = @advance_id
	delete	acc_transactions where atrn_transaction_id = @transaction_id
	delete acc_accounts where a_account_id in (@transaction_id, @advance_id)


								
			


GO
