-- =============================================
-- Author:		Anatoliy Pokus
-- Create date: 2017-06-13
-- Description:	Удаление пустого остатка на складе
-- =============================================
DROP PROCEDURE IF EXISTS stor.sp_deleteremain;

CREATE PROCEDURE stor.sp_deleteremain
(
	"remainsID" uuid
)
    language plpgsql
as
$$
Begin 
	if not exists (select * from stor.T_STORAGE_REST_ON_DAY rest where rest.Remain = "remainsID")
	then
        delete 
		from stor.T_REMAINS_LINK_PACKAGE_TYPE pt
        where exists(select* from stor.T_REMAINS r where r.RemainsID = ptt.Remains and r.RemainsID = "remainsID" and r.Amount = 0)
        and not exists(select * from stor.T_INVOICE_ITEM ii where ii.remains = "remainsID" or ii.PrepareRemains = "remainsID");

        delete from stor.T_REMAINS
        Where RemainsID = "remainsID"
        and Amount = 0
        and not exists(select* from stor.T_INVOICE_ITEM ii where ii.remains = "remainsID" or ii.PrepareRemains = "remainsID");
    end if;

	if exists(select* from VCLib.T_OBJECT_MODIFICATION_ACTION where Name = 'SP_GetSetStorRemains' and Active = '1')
	then
		call SP_GetSetStorRemains(null, 0,0, "remainsID");
	end if;
End;
$$;
