SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE procedure [dbo].[p_acc_transaction_delete_claim_prx]
	@transaction_id int,
	@type			ais_code_short		-- type de trainsaction: CLAIM_P, CLAIM_R, CLAIM_X
as 

	set nocount on;

	/*

	DGE

	Suppression d'une transaction de type CLAIM_P / CLAIM_R / CLAIM_X.


	Vérifications:
	- on vérifie que la transaction est de type CLAIM_P / CLAIM_R / CLAIM_X;
	- on vérifie que le règlement n'est pas contenu dans un bordereau

	Actions:
	- supprimer la ligne de transaction
	- passer le règlement / encaissement de recours en statut IS (Issued)

	*/

	-- validation du type 
	declare		@actor_id	int, 
				@lettering	int

	select	@actor_id = a.a_actor_id,
			@lettering = a.a_lettering
	from	acc_accounts a
			inner join acc_transactions t on t.atrn_transaction_id = a.a_account_id
	where	a.a_account_id = @transaction_id
	and		isnull(t.atrn_type_code, '') = @type


	if isnull(@actor_id, 0) <= 0
	begin
		
		raiserror('Type de transaction incorrect (CLAIM_P, CLAIM_R, CLAIM_X)', 16,1)
		return
	end

	-- vérifier que la transaction lettre uniquement des lignes CP/CR
	if exists ( select	1
				from	acc_accounts a
				where	a.a_actor_id = @actor_id
				and		a.a_lettering = @lettering
				and		a.a_account_id != @transaction_id
				and		a.a_type_code not in ('CP', 'CR') )
	begin

		raiserror('Cannot cancel this transaction.', 16,1)
		return
	
	end


	-- vérifier que les règlements ne se trouvent pas dans un bordereau
	if exists	(
				select	1
				from	acc_cl_bordereaux_accounts b
						inner join acc_accounts a on a.a_account_id = b.clba_account_id
				where	a.a_type_code in ('CP', 'CR')
				and		a.a_actor_id = @actor_id
				and		a.a_lettering = @lettering )
	begin

		raiserror('Payment linked to a bordereau.', 16,1)
		return
	
	end


	-- action	
	delete	acc_transactions where atrn_transaction_id = @transaction_id
	delete	acc_accounts where a_account_id = @transaction_id

	update	va
	set		va.clacc_operation_code = 'IS'
	from	claim_variables_accounts va
			inner join acc_accounts a on a.a_account_id = va.clacc_account_id
	where	a_actor_id = @actor_id
	and		a_lettering = @lettering
	and		a_type_code in ( 'CP', 'CR' )

	update	acc_accounts 
	set		a_lettering = null
	where	a_actor_id = @actor_id
	and		a_lettering = @lettering
	and		a_type_code in ( 'CP', 'CR' )


	
			



GO
