SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE procedure [dbo].[p_claim_variables_update_payment]
	@claim_id		int,
	@variable_id	int,
	@amount			ais_decimal2,		-- montant du règlement. Il faut considérer la valeur absolue.
	@action			smallint,			-- 0 = set to 0, 1 = update, 2 = do not update
	@repr			bit,				-- règlement mandataire
	@injury			bit,				-- règlement corporel
	@disable_accounting BIT
as

	/*
	DGE : MAJ de la table claims_variables après l'enregistrement d'un règlement
	*/

	SET NOCOUNT ON;



	update	cv
	set		cv.clv_payment		=	ISNULL(cv.clv_payment, 0) + CASE 
																WHEN @disable_accounting = 0 THEN  ABS(@amount)
																ELSE 0
																END,
			clv_provision		=	case		
									when @repr = 0 and @injury = 0 and @variable_id > 0 and @action = 0 then 0
									when @repr = 0 and @injury = 0 and @variable_id > 0 and @action = 1 and ISNULL(clv_provision, 0) <= ABS(@amount) then 0
									when @repr = 0 and @injury = 0 and @variable_id > 0 and @action = 1 and ISNULL(clv_provision, 0) > ABS(@amount) then ISNULL(clv_provision, 0) - ABS(@amount)
									else clv_provision
									end,
			clv_provision_injury=	case		
									when @repr = 0 and @injury != 0 and @variable_id > 0 and @action = 0 then 0
									when @repr = 0 and @injury != 0 and @variable_id > 0 and @action = 1 and ISNULL(clv_provision_injury, 0) <= ABS(@amount) then 0
									when @repr = 0 and @injury != 0 and @variable_id > 0 and @action = 1 and ISNULL(clv_provision_injury, 0) > ABS(@amount) then ISNULL(clv_provision_injury, 0) - ABS(@amount)
									else clv_provision_injury
									end,
			clv_provision_repr	=	case	
									when @injury = 0 and (@repr != 0 or @variable_id < 0) and @action = 0 then 0
									when @injury = 0 and (@repr != 0 or @variable_id < 0) and @action = 1 AND ISNULL(clv_provision_repr, 0) <= ABS(@amount) then 0
									when @injury = 0 and (@repr != 0 or @variable_id < 0) and @action = 1 AND ISNULL(clv_provision_repr, 0) > ABS(@amount) then ISNULL(clv_provision_repr, 0) - ABS(@amount)
									else clv_provision_repr
									end
	from	dbo.claim_variables cv
	where	cv.clv_claim_id = @claim_id
	and		cv.clv_variable_id = @variable_id

GO
