/****** Object:  StoredProcedure [dbo].[DeleteFactorAndRelations]    Script Date: 17/11/2022 10:03:27 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Azimi
-- Create date: s
-- Description:	
-- =============================================
ALTER PROCEDURE [dbo].[DeleteFactorAndRelations] 
	@FactorID bigint = 0,
	@OnlyRelation bit = 0
AS
BEGIN
	if @FactorID <= 0 
		return 	SET NOCOUNT ON;
	
	BEGIN TRANSACTION

	IF CURSOR_STATUS('global','FactorCursor')>=-1
		DEALLOCATE FactorCursor

	DECLARE @ID as BIGINT
	DECLARE FactorCursor CURSOR FOR select WareOutID from AccFactor where ID = @FactorID
	Open FactorCursor
	
	FETCH NEXT FROM FactorCursor INTO @ID
	WHILE @@FETCH_STATUS = 0 
	BEGIN
		print 'DeleteWarehouseAndRelations @WarehouseID='+Str(@ID)
		EXEC DeleteWarehouseAndRelations @WarehouseID=@ID, @FromFactorID = @FactorID
		FETCH NEXT FROM FactorCursor INTO @ID
	END
	CLOSE FactorCursor
	DEALLOCATE FactorCursor

	DECLARE WareCursor CURSOR FOR select ID from AccWarehouse where FromForm in (0,1) AND FormID = @FactorID
	Open WareCursor
	
	FETCH NEXT FROM WareCursor INTO @ID
	WHILE @@FETCH_STATUS = 0 
	BEGIN
		print 'DeleteWarehouseAndRelations @WarehouseID='+Str(@ID)
		EXEC DeleteWarehouseAndRelations @WarehouseID=@ID, @FromFactorID = @FactorID
		FETCH NEXT FROM WareCursor INTO @ID
	END
	CLOSE WareCursor
	DEALLOCATE WareCursor


	Delete AccDocItem where RelationTable=12 and RelationTableID in (select id from AccFactorDetail where FactorID = @FactorID)

	if @OnlyRelation=0
	BEGIN
		Delete AccFactorDetail where  FactorID = @FactorID
		Delete AccFactor where ID = @FactorID
	END
	ELSe
	BEGIN
		update AccFactorDetail SET DocItemID=0 WHERE FactorID = @FactorID
		update AccFactor SET WareOutID=0 where ID = @FactorID
		update AccFactor SET [Type] = [Type]+100 where ID = @FactorID and [Type] < 100
	END

	COMMIT

END