
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE procedure [dbo].[p_acc_account_regularization_invoices_by_policies_ids]
    @policies_ids_table type_table_id readonly,
    @return_account_data bit = 1,     
    @return_policies_last_situations bit = 0

as 
	set nocount on;

	declare @invoices_ids TABLE
	(
		account_id int not null primary key,
		pols_policy_id int not null
	)

	------------------------------------------------------------------------------------------
	-- traitement des quittances

	insert into @invoices_ids(  account_id,		  pols_policy_id)
	select				  ai.inv_invoice_id,  pols_policy_id
	from	acc_invoices ai
		inner join pol_policies_situations pps on pps.pols_policy_situation_id = ai.inv_policy_situation_id
		inner join @policies_ids_table pit on pit.id = pps.pols_policy_id
	where  inv_operation_code__last = 'AWR'

	------------------------------------------------------------------------------------------

    if @return_account_data = 1
    begin
	   SELECT	*
	   from	vw_acc_account_clients vaac
			 inner join @invoices_ids ids on	ids.account_id = vaac.a_account_id
    end
    else
    begin
	   select	 ai.*,
			 pps.pols_policy_id	
	   from  @invoices_ids ii 
		  inner join acc_invoices ai on ai.inv_invoice_id = ii.account_id
		  inner join pol_policies_situations pps on pps.pols_policy_situation_id = ai.inv_policy_situation_id
    end


    if @return_policies_last_situations = 1 
    BEGIN
	   
	   EXEC p_policies_last_situation_children 
		  @policies_ids_table = @policies_ids_table, 
		  @return_variables = 1, 
	       @return_risks = 0, 
	       @return_also_retired_risks = 0

    END 


GO
