CREATE DEFINER=`root`@`localhost` PROCEDURE `SPRegistrar_BalanceLibroLiq-IVA`()
BEGIN
	declare done int default 0;
	declare balance_libro_id,person_id, periodo_id, period_liquidation_id, plan_cuenta_id, saldo_id, comprobante_id,retention_type_id, zone_id int;
    declare fecha date;
    declare total decimal(20,2) default 0.00;
    
    DECLARE liq_iva CURSOR FOR 
	select pl.person_id,pl.period_id, pl.period_liquidation_id,pl.created_at, sum(pl.total_debit+pl.positive_amount+pl.total_free_availability) as total
	from period_liquidation_iva pl
	join period_liquidations pli on pl.period_liquidation_id = pli.id
	where pli.status = 2
	GROUP BY pl.person_id,pl.period_id,pl.period_liquidation_id,pl.created_at
	order by period_liquidation_id;


	DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

	OPEN liq_iva;
	REPEAT

	FETCH liq_iva INTO person_id, periodo_id, period_liquidation_id,fecha,total;
	-- este if tiene que estar sino agrega un registro mas
	IF NOT done THEN
		
   


		insert into balance_libro 
			(person_id, period_id, conta_tipo_asiento_id, period_liquidation_id,fecha_registracion, total )
				VALUES
            (person_id, periodo_id, 15, period_liquidation_id,fecha, total );
            

    END IF; -- Fin If Done

	UNTIL done END REPEAT; -- fin del loop

  	CLOSE liq_iva;
  	
  
  END