-- =============================================
-- Author:      Vitacore Anatoliy
-- Create date: 2021 03 09
-- =============================================
DROP PROCEDURE IF EXISTS stor.sp_DeleteInvoiceItemProcess;

CREATE PROCEDURE stor.sp_DeleteInvoiceItemProcess
(
	"InvoiceId" uuid, 
	"All" boolean
)
    language plpgsql
as
$$
Begin 
	if exists(select * from STOR.T_STORAGE_INVOICE where InvoiceID = "InvoiceId" and State = 0)
	then
		create temp table TmpDELETE(ElementID uuid);

		if "All" = '1'
		then
			INSERT INTO TmpDELETE(ElementID)
			select ii.ElementID
			from STOR.T_INVOICE_ITEM ii
			where ii.StorageInvoice = "InvoiceId";
		else
			INSERT INTO TmpDELETE(ElementID)
			select ii.ElementID
			from STOR.T_INVOICE_ITEM ii
			where ii.StorageInvoice = "InvoiceId" 
			and (ii.Amount is null or ii.Amount = 0);
		end if;


		delete from STOR.T_DESTRUCTION_ITEM_INFO where exists(select * from TmpDELETE d where d.ElementID = InvoiceItem);
		
		ANALYZE TmpDELETE;

		update STOR.T_MARK_MESSAGE mm
		set ObjId = null
		from TmpDELETE d 
		where d.ElementID = mm.ObjId;

		update STOR.T_PATIENT_DRUG_DELIVERY pdd
		set InvoiceItem = null
		from TmpDELETE d 
		where d.ElementID = pdd.InvoiceItem;

		delete from STOR.T_INVOICE_ITEM where exists(select* from TmpDELETE d where d.ElementID = ElementID);

		drop table TmpDELETE;
	end if;
End;
$$;