CREATE OR REPLACE FUNCTION public.sp_deletetpfinclose(
	id uuid)
    RETURNS void
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
AS $BODY$
BEGIN

create temp table cmtValues
(MonthValuesID uuid);

insert into cmtValues
	select cmt.MonthValuesID
	from FIES.T_TP_FIN_CLOSED_MONTH_TARIFS cmt
		join FIES.T_TP_FIN_CLOSE_ITEM fci on fci.TpFinCloseItemID = cmt.TpFinCloseItem
	where fci.TpFinClose = ID;

	delete
	from FIES.T_TP_FIN_CLOSED_MONTH_TARIFS cmt
	where cmt.MonthValuesID in (select MonthValuesID from cmtValues);

	delete 
	from FIES.T_MONTH_VALUES mv
	where mv.MonthValuesID in (select MonthValuesID from cmtValues);

	drop table cmtValues;

	delete 
	from FIES.T_TP_FIN_CLOSED_VALUE  fcv
	using FIES.T_TP_FIN_CLOSE_ITEM fci where fci.TpFinCloseItemID = fcv.TpFinCloseItem
	and fci.TpFinClose = ID;

	delete 
	from FIES.T_TP_FIN_CLOSED_COEF fcc
	using FIES.T_TP_FIN_CLOSE_ITEM fci where fci.TpFinCloseItemID = fcc.TpFinCloseItem
	and fci.TpFinClose = ID;

create temp table fcmValues
(MonthValuesID uuid);

	insert into fcmValues
	select fcm.MonthValuesID
	from FIES.T_TP_FIN_CLOSED_MONTHS fcm
		join FIES.T_TP_FIN_CLOSE_ITEM fci on fci.TpFinCloseItemID = fcm.TpFinCloseItem
	where fci.TpFinClose = ID;

	delete 
	from FIES.T_TP_FIN_CLOSED_MONTHS fcm
	where fcm.MonthValuesID in (select MonthValuesID from fcmValues);

	delete 
	from FIES.T_MONTH_VALUES mv
	where mv.MonthValuesID in (select MonthValuesID from fcmValues);

	drop table fcmValues;

	delete 
	from FIES.T_TP_FIN_CLOSE_ITEM fci
	where fci.TpFinClose = ID;

	delete 
	from FIES.T_TP_FIN_CLOSE fc
	where fc.TpFinCloseID = ID;

END;
$BODY$;
