SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[p_acc_cts_update_fees]
	@table_id			type_table_id READONLY,			-- liste des id quittances (inv_invoice_id)
	@cts_fee			ais_decimal2,					-- frais de contentieux
	@date_operation		datetime,
	@user_code			ais_code_medium,
	@obs				nvarchar(64),
	@branch_id			int,
	@department_code	ais_code_medium
AS

	/*
	DGE 27/04/2017
	Merci de penser à la modification de la procédure p_acc_cts_update_type_code__cts_invoices
	*/

	-- modification des frais ctx
	update	a
	set		a_amount = isnull(a.a_amount, 0) - isnull(i.inv_cts_fee, 0) + @cts_fee
	from	acc_accounts a
			inner join @table_id t		on	t.id = a.a_account_id 
			inner join acc_invoices i	on	i.inv_invoice_id = a.a_account_id

	update	i
	set		i.inv_cts_fee = ISNULL(@cts_fee, inv_cts_fee)
	from	acc_invoices i 
			inner join @table_id t on t.id = i.inv_invoice_id


	INSERT INTO [dbo].[acc_invoices_operations]
			   ([invop_invoice_id]
			   ,[invop_operation_utc_date]
			   ,[invop_operation_code]
			   ,[invop_user_code]
			   ,[invop_obs]
			   ,[invop_branch_id]
			   ,[invop_department_code])
	select	t.id,
			@date_operation,
			'RF',
			@user_code,
			@obs,
			@branch_id,
			@department_code
	from	@table_id t
GO
